blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3b9965ccbe74e26724be2e501a127ac24eab28ff
kyeparedes/python
/convesion.py
521
3.84375
4
def ascii_to_bin(char): ascii = ord(char) bin = [] while (ascii > 0): if (ascii & 1) == 1: bin.append("1") else: bin.append("0") ascii = ascii >> 1 bin.reverse() binary = "".join(bin) zerofix = (8 - len(binary)) * '0' return zerofix + binary # Ejemplo: def ingreso(): String...
610d32b4f28ca13465e4296e8005a4941c0f7299
inwnote154/Python
/Chapter7Test3.py
1,065
3.796875
4
from random import randint def Read_Scores(): Scores=() Done=True count=1 while Done: score=int(input(f"Enter score #{count} (-1 to exit) : ")) if score>=0 and score<=100: Scores+=(score,) count+=1 elif score==-1: break count-...
592fdabed088572a4a1a17bad2958688f8110fb6
inwnote154/Python
/Chapter4Test4.py
350
4.125
4
num1 = int(input('Enter number 1 : ')) num2 = int(input('Enter number 2 : ')) num3 = int(input('Enter number 3 : ')) Max=0 print() if num1>num2: if num1>num3: Max=num1 else: Max=num3 else: if num2>num3: Max=num2 else: Max=num3 print(f"Maximum number of {num...
a49ce89e2bb8d2d17ef6c9f3f6105173f68374c7
inwnote154/Python
/Chapter1Test3.py
327
4.03125
4
int1 = input("Enter float number 1 : ") int2 = input("Enter float number 2 : ") int3 = input("Enter float number 3 : ") print("Value number 1 : " +str(float(int1))) print("Value number 2 : " +str(float(int2))) print("Value number 3 : " +str(float(int3))) print("Total all : "+str(float(int1)+float(int2)+float(in...
03b6a7e209d934c791c1134bbf498ccadc8965d4
inwnote154/Python
/Chapter2Test4.py
256
4.15625
4
Sum = 0 Sum += int(input("Enter number 1 : ")) Sum += int(input("Enter number 2 : ")) Sum += int(input("Enter number 3 : ")) Sum += int(input("Enter number 4 : ")) Average = Sum / 4 print() print("Summation =",Sum) print("Average =",Average)
08766b8299a49a0b06456d4a09a062cab808ff94
aarsalannazeer/Palindrome-Code-in-Python
/palindrome.py
201
3.921875
4
def checkk(w): return w == w[::-1] w = input("Enter the string: ") w= w.lower() answer = checkk(w) if answer: print("Yes, it is Palindrome") else: print("No, try anaother word")
ce965d446b153819f9aceafec33352d7298f941d
scretch28/ITEA
/lesson_9.py
2,960
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 12 19:04:10 2020 @author: nia """ #import string as string_lib #string = 'абракадабра' #print(repr(string_lib.punctuation)) #import lesson_OOP # #car1 = lesson_OOP.Car() ##print(car1) #car1.price = 10 #car1.color = 'white' # #car2 = Car(model_name...
bb47b11b2344061d19ee955405c3629c60c82670
scretch28/ITEA
/hw_1_1_2.py
1,494
4.25
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 23:48:59 2020 @author: nia """ def get_dates(): day1=int(input('Enter the day of birsday: ')) month1=int(input('Enter the month of birsday: ')) year1=int(input('Enter the year of birsday: ')) day2=int(input('Enter the current day: ')) month2=int(i...
7654b019b816ed1cc89deeeb2cf61edcba73c238
scretch28/ITEA
/hw_3_2.py
937
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 2 23:41:12 2020 @author: nia """ #Задача №2 (Статистика слов с сортировкой)¶ #filename: hw_3_2.py #Изменить программу из Задачи №1 для сортировки слов из текста. #Пользователь вводит с клавиатуры строки, состоящие из слов. #Пустая строка означает ...
9f2b31ee6122fb90a8b453c9c7fa79b6ce73ec9a
tnydg99/practice_python
/blackjack/deck.py
1,015
4.125
4
""" This module is for defining the deck of cards """ import random class Card(): def __init__(self, suit='X', rank='X', value=0): self.suit = suit self.rank = rank self.value = value def __str__(self): return f'{self.rank} of {self.suit}' class Deck(): values = {'Ace':...
d5898efa44a2456500fee6d64f9bfc0994c58691
tnydg99/practice_python
/twosum.py
620
3.53125
4
def twoSum(nums: list, target: int) -> list: indexes = [] indexes_nums = list(enumerate(nums)) indexes_nums.sort(key=lambda x: x[1]) for index_num in indexes_nums: index, num = index_num for match_index in range(index + 1, len(indexes_nums)): print(f'{indexes_nums[match_...
6a082c535d0c2d4a55f81269db986e6f148c874a
tnydg99/practice_python
/remove_element.py
331
3.6875
4
def removeElement(nums, val): if len(nums): index = 0 while index < len(nums): if nums[index] == val: del nums[index] else: index += 1 return len(nums) if __name__ == "__main__": nums = [0,1,2,2,3,0,4,2] removeElement(nums, 2) ...
fc82fe576e031e6e9f2ceac2661e20d7eebb1c3e
naumovda/python
/daria.py
490
3.734375
4
class base: def get_name(self): raise NotImplementedError def get_cost(self): raise NotImplementedError class coffee(base): def get_name(self): return 'coffee' def get_cost(self): return 10 class tea(base): def get_name(self): return 'tea' def add_mil...
44b2ec9bac8b5f436d717106fe9614d14c119c6c
masonicGIT/two1
/two1/lib/bitcoin/hash.py
2,137
3.828125
4
import hashlib from two1.lib.bitcoin.utils import bytes_to_str class Hash(object): """ Wrapper around a byte string for handling SHA-256 hashes used in bitcoin. Specifically, this class is useful for disambiguating the required hash ordering. This assumes that a hex string is in RPC order...
e4ac6b7495e3c6c9c8fae418eb944151c9d15a17
keupa/python101
/src/script.py
782
3.515625
4
import csv def read_csv(): with open('../data/mascotas.csv') as f: reader = csv.reader(f) for row in reader: print("Nombre: {0}, Especie: {1}, Color: {2}, Sexo: {3}".format(row[0], row[1], row[2], row[3])) def leer_csv(): path_archivo = '../data/mascotas.csv' with open(path_arc...
499b0143dceb18cc573fda7237ae94f81e7aa819
Kingslayer124856/inbetween_semesters
/free_Code_Camp.org/calculator.py
671
4.1875
4
""" Getting users numbers and adding them togther and returning the result """ # Basic Calculator num1 = input("Enter a number: ") num2 = input("Enter another number: ") result = float(num1) + float(num2) # int() in results or float(). int() used for whole numbers whereas float allows decimals print(result) # Better C...
7d1b7f3ef97ee725f60df2770884cee17e91202f
Kingslayer124856/inbetween_semesters
/free_Code_Camp.org/app.py
1,167
4.28125
4
""" Multiple different apps(name in comments above code) By: Cassandra King Date: Note: """ # Testing the water print("Hello World") # drawing a shape with print statements print(" /| ") print(" / |") print(" / |") print("/___|") # # Varibles and Data Types character_name = 'John' character_age = '35' is_male =...
a37b89015c3b9309d74496d7a85bdf4da6e490cd
raghav136411/Python-Training
/Assignment Solution Day 2/PythonFunction_9.py
536
4.15625
4
#9. Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). # That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") # should return the string "tothohisos isos fofunon". def translate(d): l=0 ...
afd7af959cba1846c5936488c0be713d92db962d
raghav136411/Python-Training
/Assignment Solution Day 1/ForLoopsandTuplesProblems solution.py
1,234
4.53125
5
#Tuples #1.create a 4 element tuple that consists of a float, an integer, a Boolean value, and a string. Assingn this tuple to a variable a = ('hello', True, 1, 1.5) #2.print the tuple from step print(a) # 3.print the the second element from the tuple you made in step 1 print(a[1]) # 4.print the first ...
fac235bae714dd93ca76584def5955cd1d114ea0
RaquelO/Python-Projects
/guiTipCalculator.py
2,584
4.28125
4
""" This graphical program allows the user to enter an amount for a bill, select a tip percentage and calculate the total amount due including the tip. """ #Import the tkinter module import tkinter #Main Function def main() : #Creates the window test_window = tkinter.Tk() #Sets the window's ti...
1007d7ada9ccf4c3a3ce4d991d40fe03c31021a1
credencelabs/pythonworks
/Tests/Strings/Eg2.py
224
3.65625
4
def testString(): string = input() if string < 'Mango': print(string, 'comes before Mango alphabetically') dir(string) else: print(string, 'comes after Mango alphabetically') testString()
1ed1b5cf6a923ec8f1cb77ef74000a29ceb9436d
kopok2/DeepLearning
/ANN/MNIST_Classifier/MNIST_model.py
2,151
3.53125
4
# coding=utf-8 """MNIST dataset classifier using simple multilayer dense perceptron.""" from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.optimizers import SGD, Adam, RMSprop from keras import regularizers from keras.utils import np...
73539860cb36417a00775a7ca73d275fbbeb0ec6
sumiem01/Sorting-Algorithms
/bubblesort.py
958
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 9 18:55:40 2019 @author: mateusz """ def bubble_sort(A: list) -> None: n = len(A) while n > 1: for i in range(0, n-1): if A[i] > A[i+1]: A[i], A[i+1] = A[i+1], A[i] n = n-1 def bidirection...
5507f237155bd8b280dff7ec8def8f0c27ea95fc
TransmissibleCancerGroup/Mixed
/search_fastq/search_fastq.py
2,777
3.546875
4
#!/usr/bin/env python import os, re, sys def readfq(fp): # this is a generator function """ Function comes from Heng Li: https://raw.githubusercontent.com/lh3/readfq/master/readfq.py parameter fp = open file object """ last = None # this is a buffer keeping the last unprocessed line while...
ef62cf7c05a7d60c915ef2ad7a90d226d19432c4
gittygitgit/python-sandbox
/sandbox/practicepython/e6.py
500
4.40625
4
#!/usr/bin/python ''' Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) ''' s=raw_input("Enter a string.") l=len(s) print len(s) isPalindrome=True for i in range(len(s)): a=i b=len(s)-1-i if a < b: print...
c9a7ac2e770bbeb27b0db2916d721f68a1217f63
gittygitgit/python-sandbox
/stdlib/02-built-in_functions/getattr.py
137
3.75
4
#!/usr/bin/python """ getattr retrieves the value of a given attribute """ class Test: f="foo" t=Test() print getattr(t, "f") # foo
9a409744b53cba2e816ac5c7a054216d9196a025
gittygitgit/python-sandbox
/stdlib/05-built-in_types/sequence_types/mutable/operations.py
1,174
3.921875
4
#!/usr/bin/python """ What sequence types are mutable? bytearray and List """ ba=bytearray(10) # new bytearray having size 10, each position initialized to null l=range(0,10) # new list initialized with ints 1 through 10 """ all the following operations are valid for both bytearray and list """ print len(l) # prints...
5f31d82ab73c0a01a274e3f542fce7a166965efa
gittygitgit/python-sandbox
/stdlib/05-built-in_types/file_objects/file.py
581
3.53125
4
#!/usr/bin/python ''' files objects can be created manually, and may also be returned from various calls. files are created manually with the built in open method. ''' f=open('names.txt') content=f.read() # read content into memory content2=f.read(10) # read 10 bytes into memory ''' invoking read moves an internal...
4c131eda36e324c018ac4689100c97a23e6e00a7
gittygitgit/python-sandbox
/stdlib/02-built-in_functions/enumerate.py
416
3.9375
4
#!/usr/bin/python """ enumerate enumerate object? an object that supports iterating over a sequence using the next function. """ s="string" e=enumerate(s) list(e) # [(0,'s'),(1,'t'),(2,'r'),(3,'i'),(4,'n'),(5,'g')] list(e) # [] // passing an enumerate obj to list has the side-effect of having next invoked for all ite...
2e8f3e1d00de82c3e223746d2d49fbf88b4a1002
gittygitgit/python-sandbox
/stdlib/02-built-in_functions/setattr.py
227
3.9375
4
#!/usr/bin/python """ setattr used to set an attribute value on an object useful mainly when the attribute name is obtained dynamically """ class Foo: val=3 f=Foo() a="val" setattr(f,a, "bar") print f.val # prints "bar"
2f5afe8c4bc0e6a419d449010dab46a5a74b94d6
gittygitgit/python-sandbox
/sandbox/practicepython/e17.py
464
3.65625
4
#!/usr/bin/python ''' Use the BeautifulSoup and requests Python packages to print out a list of all the article titles on the New York Times homepage. http://www.nytimes.com ''' import requests from BeautifulSoup import BeautifulSoup r=requests.get("http://www.nytimes.com") bs=BeautifulSoup(r.text) stories=bs.findAll...
cfa0201f19f6cea753682f8ddff888ce5373234b
gittygitgit/python-sandbox
/stdlib/15-generic_os_svcs/argparse1.py
852
3.96875
4
#!/usr/bin/python import argparse from datetime import date import sys parser = argparse.ArgumentParser(description="Process a range of dates.") parser.add_argument("--start_date", help="The date to start from (format YYYYmmdd)") parser.add_argument("end_date", help="The date to end with (format YYYYmmdd)") args=par...
63493244c13161b2464f561f46633dba190e1d9e
gittygitgit/python-sandbox
/tutorial/4-more_control_flows/if.py
214
4.0625
4
#!/usr/bin/python x=input("enter a number") print('Got a number [number={}]'.format(x)) if x > 100: print("greater than 100") elif x > 50: print("greater than 50") else: print("less than or equal to 10")
1048f650f78067eb16a58359f97a362952d4878d
gittygitgit/python-sandbox
/stdlib/02-built-in_functions/sorted.py
108
3.859375
4
#!/usr/bin/python d={1:[1,5,3],4:[23],9:[4,5,21]} k=d.keys() print sorted(k) print sorted(k, reverse=True)
586e9ff2e32e47492eb831d9d489eb56fed19075
pmanolak/computer-8bits
/scripts/save_rom.py
678
3.5
4
# Saves the codes table in a ROM file. # file_name: the ROM file name # codes_table: the code table to be saved into the ROM file # instruction_size: the instruction size in bytes # cols: the number of columns def save_file(file_name, codes_table, instruction_size, cols = 8): file = open(file_name, "w+", encoding...
3083e2719ad17cd452eb3190ae48996dfb49f9ba
pointworld/python
/learning_by_code/错误调试与测试/错误调试与测试.py
27,837
4.03125
4
• 在程序运行过程中,总会遇到各种各样的错误。 '错误' 'bug' • 有的错误是程序编写有问题造成的,比如本来应该输出整数结果输出了字符串,这种错误我们通常称之为'bug',bug是必须修复的。 '用户输入错误 IOError' • 有的错误是用户输入造成的,比如让用户输入email地址,结果得到一个空字符串,这种错误可以通过检查'用户输入'来做相应的处理。 '异常' • 还有一类错误是完全无法在程序运行过程中预测的,比如写入文件的时候,磁盘满了,写不进去了,或者从网络抓取数据,网络突然断掉了。 这类错误也称为'异常',在程序中通常是必须处理的,否则,程序会因为各种...
46465500fcd64b9c80c677b23f3c2d5ec50ef1f0
pointworld/python
/MySQL数据库命令.py
6,630
3.515625
4
编程常见命令集合 MySQL数据库命令 登录到MySQL mysql -h localhost -u root -p localhost:IP地址; root:用户名; database:数据库名(可以省略,如果有,跟在-p面) 删除数据库: mysqladmin -u root -pwrf956750621 drop awesome 初始化数据库: mysql –u root –p密码 <D:\computer_learning\backup\schema.sql mysql -u root -p 2.mysql -h localhost -u root -p database...
c68485cc690a9c093821f21c472a45c5c93ca052
JohanHansen-Hub/PythonProjects
/Arkiv/SøkeAlgoritmer/sequential_search.py
317
3.6875
4
eksamplelist = [5,3,8,1,9,2] def sequentialSearch(the_list, item): position = 0 found = False while position < len(the_list) and not found: if the_list[position] == item: found == True else: position += 1 return found print(sequentialSearch(eksamplelist, 9))
c6662bc2185249c6bad7b28b246367aff7b1fca7
Sxp835/PythonCode
/RockPaperScissors/Sofia_Portillo_RPS
7,212
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 17 17:51:12 2019 @author: sofiaportillo """ """ Course: Introduction to Python Programming Student Name: Sofia Portillo """ #%% from random import randint #note: x=randint(0, 10) will generate a random integer x and 0<=x<=10 # %% def HumanPlayer(G...
cc6f47afd98bc0340e7eb6bbd018b3488cf3611b
jromanz/jQuery
/python/primero.py
379
3.984375
4
# -*- encoding: utf-8 -*- import random; numero = random.randint(1,100); tentativas = 0; escolha = 0; print numero; while escolha != numero: escolha = input("Informe un numero de 1 a 100: "); tentativas+=1; if escolha > numero: print "Menor"; elif escolha < numero: print "Mayor"; print "Acerto el numero era...
dce4ed4560b014f469e656ee0e525c3c14c0b08e
jromanz/jQuery
/python/test.py
473
3.65625
4
print "Hola Mundo!" variable = 45 otra_variable = True; if variable != 45 or otra_variable: print "Si vale eso" print "No vale eso" lista = [1,3,4,6,7,8,"dato",True,3.4] for i in lista: print "The data is ", i print '\n' cad = "El veloz " + "Murcielago" print cad[3:8] print "un buen numero " + str(variable) ...
0bc2d288e43aa4aba98a7e7cdc67e64236880106
EmineYksk/globalaihub-introduction-to-python
/Project_Homework.py
6,699
3.859375
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 27 22:11:01 2020 @author: okkes """ class Student(object): def __init__(self,name,surname): self.name=name.lower() self.surname=surname.lower() self.course_list=["Python Programming","Java Programming","Linear Algebra","Physics","Ma...
2c391b06b9cfb6c9054407b4b1645d4568e1d181
AndreeaBucur1/TemeIA
/Tema.py
16,324
3.5
4
class NodParcurgere: def __init__(self, info, parinte, cost=0, h=0): self.info = info self.parinte = parinte # parintele din arborele de parcurgere self.g = cost # consider cost=1 pentru o mutare self.h = h self.f = self.g + self.h def obtineDrum(self): ...
3bbeedb2cba172f9ad769a4e1571c35ad191a35f
tinlevn/HackerRank30DaysofCodePython
/simpleBookClass.py
821
4.03125
4
from abc import ABCMeta, abstractmethod\n", class Book(object, metaclass=ABCMeta):\n", def __init__(self,title,author):\n", self.title=title\n", self.author=author \n", @abstractmethod\n", def display(): pass\n", \n", #Write MyBook class\n", class MyBook...
f152bf5c8979456a5357e8c3607cfcae344cba0b
davidmcclure/tdiff
/tdiff/utils.py
608
3.59375
4
import networkx as nx from collections import OrderedDict from textplot.utils import sort_dict def dijkstra(graph, cutoff): """ Compute the path distance between all nodes in a graph. Args: graph (nx.Graph) cutoff (int) Returns: dict: A map of node (str) -> neighbors (Ord...
c35428a63bfb23f3634678e6c5cf38cafc611d5c
JosephFasogbon/pythonassignment
/pythonassignemt/rotate2.py
689
3.859375
4
def print_rotate(word = 'rotate', direction=4): if (direction >= 1) and (direction <= 4): word = word[::-1] centering = 0 if direction % 2 == 0: if direction % 4 == 0: for letter in word: print(' '*len(word) + letter) ...
c756eac972eac786a6ad55cefdc5f7f3e5badd36
Lambda-CS/Graphs
/projects/graph/graph1.py
2,157
3.953125
4
class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) class Graph: d...
5b1e95a1a1bb62242b4096f26f61915d138deb94
RahulMR42/pythonTest
/ifelse.py
168
4.125
4
val = input('enter a value :') if val > 10: print ('more than 10') else: if val < 5: print ('less than 5') else: print ('between 5 and 10')
14cded499415658ab75e23ce11f7a5e9a4db086d
rianePL/Python-2018-06-05
/kolekcje 6 - zamiana miejscami.py
896
3.5
4
# znajdz najwiekszy i najmniejszy element # i zamien je miejscami lista = [2, 90, 4, -2, 17, -200, -3, 30, 1] # dwa sposoby chodzenia po listach: #1 for i,x in enumerate(lista): print(i,x) #2 for i in range(len(lista)): print(i, lista[i]) # sposób na sprawdzenie czy wartość 90 jest na liscie # a jeśli tak to...
07a64941b67a06413f845ce2456b08047a52037f
rianePL/Python-2018-06-05
/zadanie 14 - while cd.py
808
3.625
4
# przed pętlą # zapytaj użytkownika o a # jeśli a nie jest liczbą to zakończ # w przeciwnym przypadku a staje się pierwszym min i pierwszym max # w pętli # wejdź do pętli jeśli a jest liczbą # sprawdź czy a jest większa od najwiekszej # jeśli tak to podmień # analogicznie z minimum # zapytaj o następną lic...
aabb0b7c0917e376045923f52eb6bdd883f325f1
rianePL/Python-2018-06-05
/obiektowosc/obiekty6.py
1,776
4.1875
4
# Zaimplementuj klase Vector dostarczajaca funkcjonalnosc wektora # swobodnego na dwuwymiarowej płaszczyznie. Wektory powinny # miec mozliwosc dodawania, odejmowania, mnozenia (przez liczbe), # porównywania (po długosci) oraz powinny posiadac czytelna # reprezentacje napisowa. # Przykład uzycia: # vector_1 = Vect...
dba8f437e03243f4592561a124c7263a8ea8e47c
rianePL/Python-2018-06-05
/tabliczka mnożenia.py
536
3.96875
4
# zadanie: wypisz tabliczkę mnożenia 10x10 # 1 2 3 4 5 ... 10 # 2 4 6 8 10 ... 20 # ... # 10 20 30 40 50... 100 print('tabliczka mnożenia za pomocą while:') x = 1 while x <= 10: y = 1 while y <= 10: print(f'{x*y:5}', end=' ') y+=1 print() x+=1 print('to samo za pomocą for:') ...
5a600090f87eaedd28f6d1634a53774869d24fcd
rianePL/Python-2018-06-05
/zadanie 10 - elif.py
662
3.84375
4
liczba1 = float(input('podaj pierwszą liczbę: ')) liczba2 = float(input('podaj drugą liczbę: ')) operacja = input('co wykonać? (+ - * /) ') if operacja == '+' : print(f'wynik dodawania {liczba1} + {liczba2} = {liczba1+liczba2}') elif operacja == '-': print(f'wynik odejmowania {liczba1} - {liczba2} = {liczba1...
545a970343655ba1f548361bc94a8e74b1af8f68
rianePL/Python-2018-06-05
/zadanie 13 while.py
838
3.859375
4
# jak sprawdzić czy napis jest liczbą (całkowitą) # # if 'ala ma kota'.isdecimal(): # print('to jest liczba') # else: # print('to nie jest liczba') # # if '12345'.isdecimal(): # print('to jest liczba') # else: # print('to nie jest liczba') # przed pętlą # licznik na -1 # suma na 0 # ustaw pierwszą licz...
62beb3a3e2d7a440946209f5e60e1c2cca50ae7c
qizongjun/prep
/addtwonum.py
1,319
3.8125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def get_val(self): return self.val def get_next(self): return self.next def set_next(self, node): self.next = node class Solution(object): de...
75e595e8f4e3c1b9cfbf0f396a54398e55feea42
wilkeraziz/smtutils
/atools/list_minimal_biphrases.py
701
3.65625
4
import sys import minphrases as mp # here we read the bilingual corpus (with word alignments) into a list of triples [(F, E, A)] D = mp.read_corpus(sys.stdin) for F, E, A in D: # here we get minimal phrases for each sentence pair biphrases = mp.minimal_biphrases(F, E, A) # this is just a header print '# ...
afcb2d51515bef53a59560787262d099f50f77a1
uthirab/Algorithm
/Diagonal Difference
401
3.75
4
#!/bin/python3 import sys def diagonalDifference(n,a): f=0 s=0 for i in range(n): f+=a[i][i] s+=a[i][n-1-i] return(abs(f-s)) if __name__ == "__main__": n = int(input().strip()) a = [] for a_i in range(n): a_t = [int(a_temp) for a_temp in input().strip().split(' ...
b3e735c609fb792f9c71f1cc8dbe9c6b24931723
ingkoon/2020-s
/AI/sources/sources/chap13/grad_descent2.py
493
3.78125
4
x = 20 learning_rate = 0.01 precision = 0.00001 max_iterations = 100 # 손실 함수를 람다식으로 정의한다. loss_func = lambda x: (0.33*x)**3 + (50*x)**2 - 100*x -30 # 그래디언트를 람다식으로 정의한다. 손실 함수의 1차 미분값이다. gradient = lambda x: (0.99*x)**2 + 100 * x - 100 # 그래디언트 강하법 for i in range(max_iterations): x = x - learning_rate * gradient(x...
261a7e9f587a8e7a75f355d07a567240f1657109
melagirisriharirao/se
/folders_files_se.py
1,192
3.71875
4
""" folders-files-se.py creates the necessary folders and files required for se. """ import os import csv # separate folder for each and every website def create_folder(folder): if not os.path.exists(folder): os.makedirs(folder) print("\n'{}' folder created.\n".format(folder)) else: ...
3146edc2e0a13c580f90fbce864d0c5e6ea8fd03
Stas-Krasnagir/Tasks
/string.py
1,321
3.84375
4
def len_string(string): i = 0 while string[i:]: i += 1 return i def charAt(string, char): count = 0 for value in string: if value == char: return count count += 1 return -1 def trim(string): new_string = "" for i, ch in enumerate(string): if...
b82dd56c53bddf61adf847301935ac24d2fc0f8c
navneetjo/python-workspace
/Python_book_eg/exception_eg.py
179
3.546875
4
try: text = input("Enter a Name :") except EOFError: print("EOF file error") except KeyboardInterrupt: print("cancel the operation") else: print('Name is ' + text)
613c75e99bf3d3d9b20a4351049c07a72cab3cf2
itactuk/isc-206
/testing_python_script/ejemplo_for_range_1.py
147
3.921875
4
acc = 0 for i in range(5): nota = int(input('Digite nota examen ' + str(i+1) + ' :' )) acc += nota print('El promedio es: ' + str(acc/5))
35d47c246ce0f9af90e6a3e219403386904efe8a
itactuk/isc-206
/P2/torneo/suma_mult_div.py
95
3.625
4
suma = 0 for x in range(0, 1001): if x % 5 == 0 or x %3 == 0: suma+=x print(suma)
23abcd5eed602b3cf1c90a273d1a47dc5213491a
itactuk/isc-206
/testing_python_script/ejemplo_switch_meses.py
399
4.03125
4
meses = { 1:'Enero', 2:'Febrero', 3:'Marzo', 4:'Abril', 5:'Mayo', 6:'Junio', 7:'Julio', 8:'Agosto', 9:'Septiembre', 10: 'Octubre', 11: 'Noviembre', 12: 'Diciembre', } mes_numerico = int(input("Digita mes numerico: ")) if mes_numerico in meses: mes_texto = meses[mes...
ce6465865690426c35b84921e9cca5e73d5a91ee
lemonLayla/string_methods
/primary.py
2,945
4.5625
5
# author:Layla # date:7/13/2021 # --------------- Section 1 --------------- # # 1 | String Methods # # 1 - Save your name to a variable named name. # a. Center that variable within 30 characters. Print it. # b. Print the variable in all upper case. # c. Print the variable in all lower case. # d. Print the var...
4322642c578015afda278d6873899669b434b492
shrinkhlaGatech/CodingChallenges
/Tree/preOrderIterative.py
559
3.84375
4
#!/usr/bin/env python3 #https://leetcode.com/problems/n-ary-tree-preorder-traversal/ class Node: def __init__(self, val, children): self.val = val self.children = children class Solution: def preorder(self, root: 'Node') -> List[int]: preorder_list = [] if root: st...
c06a188b7c533491231ac66e6b16c74e44a5c35f
shrinkhlaGatech/CodingChallenges
/Stack/ValidParanthesis.py
1,111
3.671875
4
#https://leetcode.com/problems/valid-parentheses/ class Solution: def isValid(self, s: str) -> bool: stack=[] dictionary ={')':'(','}':'{',']':'['} #O(1) space """opening brackets are stored as values so that they can be retrieved for comparison with the last element of the stack"...
4adf4f38da7d4a77e72aaf089634f320b75a7c05
shrinkhlaGatech/CodingChallenges
/Sort/IntersectionTwoArraysSet.py
359
3.59375
4
#https://leetcode.com/problems/intersection-of-two-arrays/ class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: set1 = set(nums1) set2 = set(nums2) return set1 & set2 #O(m+n) time average and 0(m*n) worst case when load factor is high #0(m+n) space for wor...
661944b9f9826085233e6fd59dab142728180bce
shrinkhlaGatech/CodingChallenges
/Stack/ValidParenthesisStringStack.py
552
3.71875
4
class Solution: def isValid(self,s): stack=[] opening_bracket = '({[' closing_bracket = ')}]' if len(s) == 0: return True for i in s: if i in opening_bracket: stack.append(i) else: if not stack: return False elif opening_bracket.index(stack[-1...
64e7ddbff34ba9281377ceee24b1173e2d6b65cb
shrinkhlaGatech/CodingChallenges
/Hash Table/FizzBuss.py
3,436
4.0625
4
#Soultion I class Solution: def fizzBuzz(self, n: int) -> List[str]: string_representation = [None]*n # start by checking if the number is multiple of both because if we'll start by checking if number is multiple of either one then if there is a number which is a multiple of both then it will first...
9bc0d428598276f73be03d0001382c9c2f0c06ab
shrinkhlaGatech/CodingChallenges
/Tree/increasingBST.py
716
3.765625
4
#!/usr/bin/env python3 #https://leetcode.com/problems/increasing-order-search-tree/ class Node: def __init__(self, val, children): self.val = val self.children = children #using inorder traversal class Solution: def __init__(self): self.dummy_head = TreeNode(0) self.current = s...
6148ffe7711284f3a4eb8120e88035592d5a8ecb
shrinkhlaGatech/CodingChallenges
/Sort/mergeIntervals.py
558
3.59375
4
#https://leetcode.com/problems/merge-intervals/ class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort(key = lambda x : x[0]) res = [] for i in intervals: if res and i[0] <= res[-1][1]: res[-1][1] = max(i[1],res[-1][1]) ...
3b17294aceb1c7b892719500ee474fdf84076189
giseldo/chatbottutor
/exe1sol.py
1,103
4.53125
5
# https://campus.datacamp.com/courses/building-chatbots-in-python/ # EchoBot I # Hello, World! # You'll begin learning how to build chatbots in Python by writing two functions to build the simplest bot possible: EchoBot. EchoBot just responds by replying with the same message it receives. # In this exercise, you'll de...
08a79862409d89c9e882f2c981e64d0a730b650b
prateekkish/monte-carlo-strategy
/program.py
1,449
3.78125
4
import random def switching_player(): doors = [1,2,3] car_behind_door = random.choice(doors) player_first_choice = random.choice(doors) if car_behind_door != player_first_choice: # get the door which will be eliminated by the show host doors_to_eliminate_by_host = doors.copy() doors_to_eliminate...
6af69cb5babf08cc4cc50c1d11af22a75763751f
Dev4life007/Python_codes
/User input.py
227
4
4
name = input("What is your name? ") age = input("please enter your age? ") state_of_origin = input("what is your state of origin? ") print("Your Name is:" ,name, "You age is:" ,age, "Your State of origin is:" ,state_of_origin)
1b74de32018e040c335c0360ac34cd906c3f7605
Dev4life007/Python_codes
/Playing.py
333
3.796875
4
# Name = input("Enter your name: ") # age = input("Enter your age: ") # print("Hello", (Name) + "!", "You are", age) # hobbies = input("Enter are your hobbies?: ") # print("Your", hobbies, "are awesome!\nYou must be fun to be with!") # Naughty = input("what are your guilty pleasures?: ") # print("wow! thats cool, am a...
f0e65bf4b5e538b4c17baf9489a1eea9109c5e9f
Dev4life007/Python_codes
/For_loops.py
2,103
4.09375
4
for x in "Banana": print(x) _list = [1,2,3,"Banana",5] count = 0 for element in _list: print(element) count += 1 if str(element).isalpha(): for letter in (element): print(letter) print("Total count is:", count) Name = input("Please enter name: ") count = 0 for characters in Na...
cd7c0a22b878e058b9e60fc0764408b0ace0196d
ramscarv/codigos_python_imperativo
/intervalo numérico, pares e impares.py
544
3.9375
4
n=int(input("Digite um valor inteiro: ")) m=int(input("Digite um valor inteiro diferente: ")) par=0 impar=0 if n < m: c=n+1 while c <= m+1: c=c+1 if c%2==0: par=par+1 elif c%2!=0: impar=impar+1 print("pares:",par) print("impares:",impar) el...
26bc153552cfb0ef83c7171b446e93c409f62a04
ramscarv/codigos_python_imperativo
/calculadora2 em python.py
899
4.15625
4
def soma(x,y): print(x,"+",y,"=",x+y) def subtração(x,y): print(x,"-",y,"=",x-y) def multiplicação(x,y): print(x,"*",y,"=",x*y) def divisão(x,y): print(x,"/",y,"=",x/y) n=float(input(" digite o primeiro número: ")) n1=float(input(" digite o segundo número: ")) print("digite 1 para somar,2 pa...
3c4ac95351c59f74801c483b6984f02f4f508186
ramscarv/codigos_python_imperativo
/conta espacos e vogais.py
424
3.765625
4
nome = str(input("Digite um baguio ae, irmao: ")) cont = 0 c = 0 letra = str for letra in nome: if letra == "a": cont += 1 if letra == "e": cont += 1 elif letra == "i": cont += 1 elif letra == "o": cont += 1 elif letra == "u": cont += 1 print("V...
d813d6cbf99fb0d3e8224b71317b3d7ac279e5c6
experimental-software/reminder
/lib/seconds_until_timestamp.py
427
3.953125
4
#!/usr/bin/env python3 import sys import time import re import datetime def to_seconds(t): return int(datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second).total_seconds()) t = sys.argv[1] m = re.match("(\d+):(\d+)", t) hour = int(m.group(1)) minute = int(m.group(2)) later = datetime.time(hour, ...
f69b57b1dd33118b85ff50e31b5b19428ae9561a
praveenmundkar/Python_Projects
/Snake_Water_Gun.py
3,579
3.953125
4
import random import sys list_1 = ["snake", "gun", "water"] try : print("Shall we begin the Game\n") x = input("PRESS yes or no :::: IF U PRESS 'no' GAME APPLICATION will be EXITED") print("_________________________________________________") if x == "no": print("Thank YOU for Visiting the ga...
5e5bcc6ab37d40005c17e5d1565708236db230f8
connie-liou/powersimstore
/classes/binarysearch.py
1,087
3.5625
4
def binarySearch(data, val): lo, hi = 0, len(data) - 1 best_ind = lo while lo <=hi: mid = int(lo + (hi - lo) / 2) if data[mid] < val: lo = mid + 1 elif data[mid] > val: hi = mid - 1 else: best_ind = mid break # check if ...
ddfeca7fa83602d4572033f200fa49ba643f7239
david-pok/Graphs
/projects/ancestor/ancestor.py
2,373
4.03125
4
class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex): """ Add a vertex to the graph. """ self.vertices[vertex] = set() def get_neighbors(self, vertex_id): ...
221d4212df3dbb1f2bd1bff9caf71f3c45fd3f77
profepato/clases_estructura_2018
/clase_020418/edades.py
503
4.1875
4
# Autor: Patricio Pérez # Fecha: 2 de abril de 2018 # Pedir una edad y que diga si es menor o mayor de edad print("Ingrese su nombre:") # Leer nombre nombre = input() # Entero --> Integer --> int # Reales --> Float --> float # Cadenas --> String --> ? # Leer edad print("Ingrese su edad: ") ...
a7804f4f6bf083ebffa2eceef87f8c0a16a6d0cf
profepato/clases_estructura_2018
/clase_240418/main.py
685
3.671875
4
from baseDeDatos import * from mensajes import * from os import system import sys def main(): so = sys.platform bienvenido() intentos = 0 while(True): rut = input("Ingrese rut:") password = input("Ingrese pass:") nombre = verificar(rut, password) if(nombre != -1): ...
2e6546b7f58a499a94403845deea3adc1da162ac
profepato/clases_estructura_2018
/clase_230418/ejercicio_5.py
239
3.875
4
def ciclo(limite, mensaje): # ciclo(3, "hola") --> hola hola hola # ??????????? vueltas = 0 while(True): vueltas += 1 print(mensaje) if(limite == vueltas): break ciclo(12, "puntos")
4091258aa0497e0f8b6bfa0b1a47e319445ad939
profepato/clases_estructura_2018
/clase_140518_2/Main3.py
373
3.921875
4
# Desarrollar un sistema que permita # Pedir un producto. # Los datos del producto son nombre, precio # y cantidad. # Al finalizar el ingreso, mostrar el total. from Producto import * p1 = Producto() p1.nombre = input("nombre: ") p1.precio = int(input("precio: ")) p1.cantidad = int(input("cantidad: ")) p1.total = ...
97acac4778f00bd1dc6fe4c9701fc12c483a3c4c
profepato/clases_estructura_2018
/test_listas/main.py
510
3.734375
4
# Autor: Patricio Pérez Pinto # Fecha: 2 de mayo de 2018 lista_notas = list() cont_rojos = 0 # Notas de Ismael en Religión lista_notas.append(7) lista_notas.append(1.3) lista_notas.append(7) lista_notas.append(4) """ print(lista_notas) print("La segunda nota de Ismael es:") print(lista_notas[1]) print("La tercera n...
69c34a516614eac2392677d4b586378d6c80695e
profepato/clases_estructura_2018
/clase_020418/rangos.py
674
4.125
4
# Autor: Pato # Fecha: 02 abril 2018 """ Ingresar una temperatura y enviar los siguientes mensajes entre 1 y 15 grados, mucho frío entre 16 y 25 grados, tibio entre 26 y 30 grados, calido mas de 30, mucho calor """ temp = int(input("Temperatura: ")) if(temp >= 1 and temp <= 15): print("Mucho Frío...
fb5aade7b2f71f6f92641d6e1f05db05203eedf5
profepato/clases_estructura_2018
/test_listas/main2.py
643
3.984375
4
# Autor: Patricio Pérez Pinto # Fecha: 2 de mayo de 2018 lista_edades = list() # promedio de edades (suma / cantidad) suma = 0 lista_edades.append(12) lista_edades.append(20) lista_edades.append(21) lista_edades.append(19) print("-------------------------") print("Las edades") for e in lista_edades: print(e) pri...
9763e27058db157d0fc02b588b898c7c398c0ef5
profepato/clases_estructura_2018
/lusho/ejercicio2.py
648
3.96875
4
# reprobados, si esta reprobado, mensaje reprobados = list() aprobados = list() reprobados.append("Max Moraga") reprobados.append("Roberto Guzmán") reprobados.append("Flavio Toro") reprobados.append("Luis Arellano") aprobados.append("Rodrigo Serrano") aprobados.append("Alex Vargas") aprobados.append("Camilo Vergara"...
df3a637ded35b78acd4ea6ebbc128dcfec0a2049
profepato/clases_estructura_2018
/codificador_decodificador/main.py
795
3.796875
4
from funciones import * cont_decod = 0 cont_cod = 0 lis_mensajes = list() while(True): mensaje = input("Mensaje: ") if (mensaje.lower() == "salir"): print("se han codificado " + str(cont_cod) + " mensajes") print("se han decodificado " + str(cont_decod) + " mensajes") raise SystemExit...
ea861e3b63d0f3fd2da869d918779b3de99447fb
profepato/clases_estructura_2018
/test_listas/main4.py
495
3.953125
4
# Ingresar sueldos # hasta que el sueldo sea -1 # y mostrar el promedio # mostrar el listado de sueldos al final # lista_sueldos = list() suma = 0 cantidad = 0 # __len__ while(True): sueldo = int(input("Sueldo:")) if(sueldo == -1): # if de corte break lista_sueldos.append(sueldo) print("Listado ...
13efcac69ea355a9041eef771db8cb9938172688
IDotan/Python2020
/slides 5-7/itai6.py
5,719
4.25
4
from random import randint def psw(length,upper,lower,numbers,symbols): new_psw = "" i = 0 # loop to fill the password while i < length: # fill with random when no parameters are given or left if upper == 0 and lower == 0 and numbers == 0 and symbols == 0: temp_char...
9003ace2067fa14d72367c17800ec7950ad80885
ZeinabMahmoud20/python
/lab2/person.py
3,400
3.5625
4
class Person: moods=('happy','tired','lazy') def __init__(self,name,money,mood,health_rate): self.name=name self.money=money self.mood=mood self.health_rate=health_rate def sleep(self,hours): if hours==7: print ("Happy") elif hours<7: ...
7844dd6a379640a5a61b4be5680d50dddd58e486
Ngiong/Indonesian_Parser
/python/src/utils/CharMachine.py
601
3.640625
4
class CharMachine(object): BLANK_SPACE = ' ' def __init__(self, str): self.str = str self.idx = 0 def has_remaining(self): return self.idx < len(self.str) def next_char(self): if self.idx == len(self.str): raise IndexError('Unable to get next char.') ...
84db7fc965c39e1d7fc9266409a7038bbc49bdfe
Gavin-Song/99CardGame
/game/player.py
1,538
3.703125
4
#!/usr/bin/env python # # -*- coding: utf-8 -*- """ player.py Base class for a player. AI and Human extend this class """ from abc import abstractmethod, ABCMeta from deck import Deck class Player(object): __metaclass__ = ABCMeta def __init__(self, name, tokens): self.name = name self.card...
e578e4d47503163a9407e1e22dedf20ab0719d02
edwardUL99/python-practise
/Arrays.py
524
3.609375
4
import random class Arrays: def __init__(self, array = []): self.array = array def add(self, element): self.array.append(element) def length(self): return len(self.array) def shuffle(self): for x in range(0, self.length()): temp = self.array[...
86b2059cbf4314977e5d9e2487828174ee613b02
abdimohamud/Guided-Projects-Answers-
/Week 2/Day 4/find_rotation_point.py
3,132
4.28125
4
""" I was bored one day and decided to look at last names in the phonebook for my area. I flipped open the phonebook to a random page near the middle and started perusing. I wrote each last name that I was unfamiliar with down on paper in increasing order. When I got to the end of the phonebook, I was having so much f...