blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a9a02bab5f2a12dfd0d6b32a5a76c116006de19c
allekmott/longestsentence
/sentence.py
1,533
3.9375
4
import re """Container for a sentence, stored in a string""" class Sentence(object): """Create new sentence object""" def __init__(self, text): self._text = None self.text = text """Get the sentence's text""" @property def text(self): return self._text """Set the sentence's text Validates for length, termination, words, etc. Assumes text is not high-bit unicode, and only one sentence is to be contained. Will not attempt to deduce if two sentences are present. Text must be terminated with '.', '?', or '!'""" @text.setter def text(self, text): if type(text) is not str: raise TypeError("Sentence text must be of type str") elif not len(text) or text[-1] not in [ ".", "?", "!" ]: raise ValueError( "Sentence must be terminated with a period") elif not len(text) or not len(self.parse_words(text)): raise ValueError("Sentence text must contain words") self._text = text """Parse all words from a string of text. Filters out everything but word chars.""" @staticmethod def parse_words(text): pieces = re.split("\W+", text) words = filter(lambda piece: len(piece), pieces) return words """Get longest word, along with length, contained in the sentence's text. Returns tuple: (word, word_length)""" def get_longest_word(self): words = self.parse_words(self.text) def longer_word(word_a, word_b): if len(word_b) > len(word_a): return word_b else: return word_a longest_word = reduce(longer_word, words) return (longest_word, len(longest_word),)
08116ea949e55a064c14e16a1567011803514a77
Nahia9/COMP301-Python-Assignment03
/copyfile.py
461
3.5
4
#!/usr/bin/env python3 ''' Filename: copyfile.py Author: Nahia Akter Student no.: 301106956 Description: Copies the source file content to the specified destination ''' infile = input("Enter the source file name: ") outfile = input("Enter the destination file name: ") source_file = open(infile, "r"); target_file = open(outfile, "w"); content = source_file.read(); target_file.write(content); print("The source file is successfully copied to destination file")
0a31524fb775f07633ce9858b633afdd9d2bf80b
albert4git/bTest
/bPot/Py3Robot/pendulum.py
378
3.78125
4
def firstn(g, n): for i in range(n): yield next(g) def abc(): for ch in "abcde": yield ch def pendulum(g): while True: reverse = [] for el in g(): reverse.insert(0,el) yield el for el in reverse: yield el if __name__ == "__main__": for i in pendulum(abc): print(i, end=" ")
bf2dced76a087396202427c189174e35eedadf80
AshTiwari/Standard-DSA-Topics-with-Python
/Array/Array_Union_and_Intersection_of_Sorted_Array.py
300
3.515625
4
# Union And Intersection of sorted Array: from sortedArrays import Union from sortedArrays import Intersection if __name__ == "__main__": sorted_array_1 = [1,1,3,5,7] sorted_array_2 = [0,1,1,2,4,6,7] print(Union(sorted_array_1,sorted_array_2)) print(Intersection(sorted_array_1,sorted_array_2))
a94a2d78b122b1d9dfb68ba25853f4ed9dd69ce2
onestarshang/leetcode
/reconstruct-original-digits-from-english.py
3,520
3.625
4
''' https://leetcode.com/problems/reconstruct-original-digits-from-english/ Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted. Input length is less than 50,000. Example 1: Input: "owoztneoer" Output: "012" Example 2: Input: "fviefuro" Output: "45" ''' class Solution(object): def originalDigits(self, s): # Gaussian elimination """ :type s: str :rtype: str """ words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] n, m = 26, len(words) a = [[0.0 for j in xrange(m + 1)] for i in xrange(n)] for i, w in enumerate(words): for c in w: a[ord(c) - 97][i] += 1 for c in s: a[ord(c) - 97][m] -= 1 def find_row_by_max_abs(x, y): max_i = max_v = 0 for i in xrange(x, n): if max_v < abs(a[i][y]): max_v = a[i][y] max_i = i return max_i if max_v > 1e-4 else None def swap_row(i, k): for j in xrange(m + 1): tmp = a[i][j] a[i][j] = a[k][j] a[k][j] = tmp i = j = 0 while i < n and j < m: while j < m: k = find_row_by_max_abs(i, j) if k is not None: break j += 1 swap_row(i, k) for k in xrange(i + 1, n): if abs(a[k][j]) > 1e-4: p = a[i][j] / a[k][j] for t in xrange(j, m + 1): a[k][t] = p * a[k][t] - a[i][t] i += 1 j += 1 f = [0 for i in xrange(m)] j = m - 1 for i in reversed(xrange(m)): if abs(a[i][i]) < 1e-4: continue f[i] = -a[i][m] for t in xrange(i + 1, m): f[i] -= a[i][t] * f[t] f[i] /= a[i][i] return ''.join(chr(i + 48) * int(f[i] + 1e-4) for i in xrange(m)) def originalDigits_bfs(self, s): # TLE """ :type s: str :rtype: str """ words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] a = [None for i in xrange(10)] for i, w in enumerate(words): a[i] = {} for c in w: a[i][c] = a[i].get(c, 0) + 1 d = {} for c in s: d[c] = d.get(c, 0) + 1 q = [(d, '')] head = tail = 0 while head <= tail: d, n = q[head] last = 0 if not n else int(n[-1]) for i in xrange(last, 10): x = {c: v - a[i].get(c, 0) for c, v in d.iteritems()} if all(v >= 0 for v in x.itervalues()): nn = n + str(i) tail += 1 q.append((x, nn)) if all(v == 0 for v in x.itervalues()): return nn head += 1 if __name__ == '__main__': f = Solution().originalDigits assert f('owoztneoer') == '012' assert f("zeroonetwothreefourfivesixseveneightnine") == '0123456789' assert f('fviefuro') == '45'
7a276e337f8928d3f8ae6a7dfc9d6bc971ea0205
barua-anik/python_tutorials
/break.py
275
4.1875
4
#Example 1: Type exit to break print("Example 1: ") while True: command = input("type 'exit' to exit \n") if (command == "exit"): break #Example 2: exit from the program with a certain value print("Example 2: ") for x in range(1,101): print(x) if x==30: break
f84cb4f84081acf104912f7da38bf02c20a20467
vcaitite/hangman
/read_txt_archive.py
441
3.625
4
from pathlib import Path import random path = Path('./word_list.txt') def archive_lines(): if path.is_file(): with open(path, 'r') as f: lines = (f.readlines()) return lines else: raise Exception("Word list archive doesn't exist 😞") def read_random_word(): lines = archive_lines() n_words = len(lines) word_line = random.randint(0, n_words) return lines[word_line]
c4fa8ad7e557142e6a911223da9cdc52d93aa596
bharatvarmap/Python
/Algorithms/Sorting/bubbleSort.py
364
4
4
# -*- coding: utf-8 -*- """ Created on Tue May 28 12:13:21 2019 @author: Bharath """ def bubbleSort(alist): n = len(alist) for num in range(n-1,0,-1): for i in range(num): if alist[i]>alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp return alist
a77cbac124a0fe733088145e62eee368c9a179ef
het1613/CCC-Solutions-1996-to-2005
/1997/Nasty Numbers Problem B CCC 1997.py
763
3.625
4
def NastyNumber(num): factor_limit=round(num**0.5)+2 factors=[] for factor_1 in range(1,factor_limit): if (num%factor_1==0): factor_2=int(num/factor_1) factors.append([factor_1,factor_2]) for pair_1 in factors: for pair_2 in factors: if (abs(pair_1[0]-pair_1[1])==pair_2[0]+pair_2[1]): return True return False num_of_tests=int(input('Enter number of tests: ')) outputs=[] for test in range(num_of_tests): num=int(input('Enter number: ')) status='{0:d} is not nasty'.format(num) if NastyNumber(num): status='{0:d} is nasty'.format(num) outputs.append(status) print() print('\n'.join(outputs))
76e5191b05f41cb110dd6222655fc2692f2640c9
armijoalb/CRIP
/Práctica 2/siguientePrimoFUerte.py
1,996
3.703125
4
import random as rnd def potencia(a,b,m): x = 1 while( b > 0): if (b%2 ==1): x = (x*a)%m a = (a**2)%m b = b//2 return x def PrimalidadMillerRabin(p,lista): """ Descripción: devuelve si p es posible primo o no Argumentos: p:(int)Número sobre el que se realiza el test n:(int)Número de veces que se realiza el test """ if type(lista) is int: n = lista l_cond = False #si no es una lista lo guardamos elif type(lista) is list: n = len(lista) l_cond = True #Si es una lista lo guardamos else: print("Se esperaba una lista o un entero como segundo argumento") return False s = p-1 u = 0 while(s%2==0): u+=1 s = s//2 #Iterator almacena la potencia de 2 y s el producto de forma que p-1 = (2^u)*s for i in range(n):#Para cada experimento if l_cond: a = lista[i] else: a = rnd.randrange(2,p-2)#Se crea un a aleatorio a = potencia(a,s,p) if(a != 1 and a != p-1): probFound = False for j in range(1,u): a = potencia(a,2,p) if(a == p-1): #print("Es probable primo porque a = -1") probFound = True break elif(a == 1): #print("No es primo porque a = 1") return False probFound = False if(not probFound):#Si sale del bucle(habiendo entrado en él) devuelve false return False return True def siguientePrimoFuerte(n): number = n+3-(n%4) while(not(PrimalidadMillerRabin(number,100)) or not(PrimalidadMillerRabin((number-1)//2,100))): number+=4 return number primoFuerte = siguientePrimoFuerte(24) print(primoFuerte) p = 19 for i in range(1,p): a = i l = [1] while a != 1: l.append(a) a = (a*i)%p print (str(i)+": "+str(len(l)))
85ac500649d9431a6eb627474ddd64a1099dfd5e
RomanenkoRIS/PythonStudying
/ex.py
681
3.890625
4
#types_of_people = 10 #x = f"Существует {types_of_people} типов людей" #print(x) #w = "зачем это {}" #r = "отак" #print(w.format(r)) print("У Мери был маленький барашек.") print("Его шерсть была белой как {}.".format('снег')) print("И всюду, куда Мери шла,") print("Маленький барашек всегда следовал за ней.") print("."*10)#что это могло значить ? end1 = "Б" end2 = "а" end3 = "д" end4 = "д" end5 = "и" end6 = "г" end7 = "а" end8 = "й" print(end1+end2+end3+end4+end5, end ='') print(end6+end7+end8) m = 10 print(bin(m))
d2d7f16c9fbe184e29b5a45263bc8ca93c273583
szfwl/J_TEST
/old/test20180530.py
1,258
4.0625
4
# a=0 # b=0 # while a <= 4: # a += 1 # if a==3: # continue # print (a) # b += a # # # print (b) # # row=1 # while row<=5: # # print("*"* row) # # row+=1 # row = 1 # while row<=5: # col=1 # while col<=row: # print ("*",end="") # col+=1 # print ("") # row += 1 # def get_a(): # a = 1 # while a <= 9: # b = 1 # while b <= a: # print ("%d * %d = %d" % (a, b, a * b), end="\t") # b += 1 # print ("") # a += 1 # name="小明" # # # def hello(): # """打招呼""" # # print ("Say hello!") # print ("Say hello!") # # print (name) # hello() # # print (name) # # # def sum_a(a,b): # # print ("请输入A和B的值") # # print ("A:") # # #a=int(input()) # # print ("B:") # # b=int(input()) # # c=a+b # # print ("%d + %d = %d"%(a,b,c)) # c=a+b # return c # # q=sum_a(10,11) # print (q) # def x(char, times): # """单行分隔""" # print (char * times) # # # def line(char, times): # """多行分隔线 # # :param char: 分隔字符 # :param times: 分隔次数 # """ # row = 0 # while row < 5: # x(char, times) # row += 1 # # line("*", 50)
977474f56fedf488bfcfdeca86205c357faa8348
esfoliante/python_class_final_project
/main.py
2,962
4.21875
4
import random # ? This sys right here (not step sis, sadly) will let us # ? close the program import sys import os options = ["Dizer olá", "Calculadora", "Sair"] # ? After getting the data from other functions we greet the user, as asked def greetings(): name = getName() print(chooseGreeting() + " " + name) # ? This function is lame, we just get the user's name and return it def getName(): name = input("Olá! Por favor introduz o teu nome: ") while name.strip() == "": print("Por favor introduza um nome válido!") name = input("Olá! Por favor introduz o teu nome: ") return name # ? Choosing in an array of greetings, we will return a random one # ? and append it in the text from the function getName() def chooseGreeting(): greetings = ["Hello", "Hola", "Olá!", "Heyooo", "こんにちは"] # ? With the help of the "random" library we select a random greeting by index greetingIndex = random.randint(0, 4) return greetings[greetingIndex] # ? Pffffftttt easy one # ? Here we will just display the menu according to the options array def showMenu(): i = 0 for option in options: i += 1 print(str(i) + " - " + option + "\n") # ? This cute function will only be called by other function (executeOption()) # ? and here we are just asking for which option the user wants to execute def chooseOption(): option = input("Escolhe uma opção (1, 2, ...) » ").strip() # ? We use this while loop just to verify if the option is valid while int(option) < 1 or int(option) > len(options): print("Por favor seleciona uma opção válida") option = input("Escolhe uma opção (1, 2, ...) » ").strip() return int(option) # ? The following function will ask which function the user typed # ? and then it will execute it, calling other functions def executeOption(): selectedOption = chooseOption() - 1 if selectedOption == 0: greetings() input() os.system('cls' if os.name == 'nt' else 'clear') main() elif selectedOption == 1: calculadora() input() os.system('cls' if os.name == 'nt' else 'clear') main() else: print("Obrigador por usares o nosso programa") sys.exit() # ? Uuuu this function is pretty simple. # ? We just get two input numbers (without verification ehehe) # ? and an operation. After that we just do the math def calculadora(): num1 = input("Por favor introduz o primeiro número » ") num2 = input("Por favor introduz o segundo número » ") operation = input("Por favor introduz uma operação » ") if operation == "+": print(str(int(num1) + int(num2))) elif operation == "-": print(str(int(num1) - int(num2))) elif operation == "*": print(str(int(num1) * int(num2))) else: print(str(int(num1) / int(num2))) def main(): showMenu() executeOption() main()
09dcb97644ff6f2346d6c4c61607b51f4fc48898
bhavya-singh/Algorithmic-Toolbox
/Week1 - Introductory Challenges/1-2 sum_of_two_digits.py
143
3.546875
4
# python3 def sum_digits(a, b): return a+ b if __name__ == '__main__': p, q = map(int, input().split()) print(sum_digits(p, q))
79eb248b4eedf1bc69a435af4b8b01b4588f5f7e
kamieliz/Udemy_Python_Projects
/Lecture 9 - Sorts/insertion_sort.py
1,246
4.4375
4
# starting with a list and a key that starts at index 1. keep track of key # if condition for a swap is reached, keep track of the current item bc it will be compared over and over # Assignment implement insertion sort algorithm using Python # Test it for lists of various sizes # See if you can work out why it has O(n**2) complexity def insertion_sort(arr): print("Starting array: {}".format(arr)) for key in range(1, len(arr)): print("Key is set to {}".format(key)) print("Integer at key of {} is {}".format(key, arr[key])) print("Integer in place before {} is {}".format(arr[key], arr[key-1])) print("Comparing {} with {}".format(arr[key],arr[key-1])) if arr[key] < arr[key-1]: print("Swap condition reached since {} is less than {}".format(arr[key], arr[key-1])) j = key while j > 0 and arr[j] < arr[j-1]: arr[j], arr[j-1] = arr[j-1], arr[j] print("Swap performed") j-= 1 else: print("{} is in its correct place, moving key to next item".format(arr[key])) print("Current array state: {}".format(arr)) print("Sorting complete...") l = [6,1,8,4,10] insertion_sort(l) print(l)
596261800b198f7f946513cf4b6ecc0a34291d21
dankodak/Programmierkurs
/Abgaben/Blatt 3/Aufgabe 1/Team 44141/Shirokikh_Emil_EmilShirokikh_1761423/Aufgabe1.py
492
3.6875
4
# Kurzform der Mengen- und Listenoperationen in Python Emil Shirokikh # a. # Werte Selber auswaehlen, wobei a der Anfang und B das Ende des Intervalls ist. a = 3 b = 6 n = 4 deltaX = (b - a) / n seq = [] for i in range(0, n + 1): seq.append(a + i * deltaX) print(seq) #b. N = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Teiler ={(a,b)for a in N for b in N if a%b ==0 } print(Teiler) #c. Pythagoras ={(a,b,c)for a in N for b in N for c in N if a*a + b*b == c*c} print(Pythagoras)
9f99211d0fe01a065be615a0cdc582dcfbd0a504
thenixan/CourseraPythonStarter
/src/week4/task3.py
335
4
4
x1 = float(input()) y1 = float(input()) x2 = float(input()) y2 = float(input()) x3 = float(input()) y3 = float(input()) def distance(x1, y1, x2, y2): return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 s1 = distance(x1, y1, x2, y2) s2 = distance(x2, y2, x3, y3) s3 = distance(x3, y3, x1, y1) print("{0:.6f}".format(s1 + s2 + s3))
9fdc0eefc771ff3625fa6d67d5cf4955a53370be
abaez004/Python-Assignments
/Assignment1/Assignment1.py
818
3.9375
4
#Angel Baez 9:30 AM This is the updated version import math minutes = 42; seconds = 42; totalTime = minutes * 60 + seconds; print("The total time is:", totalTime); radius = 6; radius2 = 4; volume = 4 / 3 * math.pi * (math.pow(radius,3)); volume2 = 4 / 3 * math.pi * (math.pow(radius2,3)); print("The volume of the sphere with radius 6 is:", volume); print("The volume of the sphere with radius 4 is:", volume2); farenheit = -40; fToC = (farenheit - 32) * 5/9; print("-40 degrees farenheit to celsius is:", fToC); celsius = -40; cToF = (celsius * 9/5) + 32; print("-40 degrees celsius to farenheit is:", cToF); a_str = input("Enter the value for a:"); a_int = int(a_str); rPrism = a_int * 2 * a_int * 3 * a_int; cube = math.pow(a_int, 3); print("The prism can fit: ", rPrism//cube, "cubes");
3ecdbb87bd71ee44a1e3e9de2fb685cc3f13a935
redkad/100-Days-Of-Code
/Day 7/Challenges/replace.py
871
3.921875
4
import random import hangman, hangmanWords print(hangman.logo) blanks = [] lives = 0 chosen_word = random.choice(hangmanWords.word_list) for _ in range(len(chosen_word)): blanks.append('_') while '_' in blanks and lives < 7: entered = input('\nEnter a letter: ').lower() if entered in blanks : print(f'You have already guessed the letter {entered}') count = 0 for char in chosen_word: if entered == char: blanks[count] = entered count+=1 if entered not in chosen_word: print(' '.join(blanks)) print(f'Wrong guess. You have {6 - lives} tries left\n') print(hangman.HANGMANPICS[lives]) lives += 1 else: print(' '.join(blanks)) if '_' not in blanks: print("You've Won") else: print(f"You've lost. The word was {chosen_word}")
8991fb819b58bb250852e26a0d0852427e1f58fb
mantoshkumar1/interview_preparation
/design/find_median_from_data_stream.py
2,251
4.125
4
""" Find Median from Data Stream ----------------------------- Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. For example, [2,3,4], the median is 3 [2,3], the median is (2 + 3) / 2 = 2.5 Design a data structure that supports the following two operations: void addNum(int num) - Add a integer number from the data stream to the data structure. double findMedian() - Return the median of all elements so far. Example: addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2 Follow up: If all integer numbers from the stream are between 0 and 100, how would you optimize it? If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it? """ import heapq class MedianFinder: def __init__(self): self.max_heap = [] self.min_heap = [] def addNum(self, num): if not self.min_heap: heapq.heappush(self.min_heap, num) return if num >= self.min_heap[0]: heapq.heappush(self.min_heap, num) else: heapq.heappush(self.max_heap, -num) if len(self.max_heap) + 2 == len(self.min_heap): n = heapq.heappop(self.min_heap) heapq.heappush(self.max_heap, -n) elif len(self.max_heap) == len(self.min_heap) + 2: n = heapq.heappop(self.max_heap) heapq.heappush(self.min_heap, -n) def findMedian(self): if len(self.max_heap) == len(self.min_heap): return (-self.max_heap[0] + self.min_heap[0]) / 2.0 if len(self.max_heap) + 1 == len(self.min_heap): return self.min_heap[0] return -self.max_heap[0] # test case 1 obj = MedianFinder() obj.addNum(1) obj.addNum(2) assert 1.5 == obj.findMedian() obj.addNum(3) assert 2 == obj.findMedian() # test case 2 obj = MedianFinder() obj.addNum(1) assert 1 == obj.findMedian() # test case 3 obj = MedianFinder() obj.addNum(-1) assert -1 == obj.findMedian() obj.addNum(-2) assert -1.5 == obj.findMedian() obj.addNum(-3) assert -2 == obj.findMedian() obj.addNum(-4) assert -2.5 == obj.findMedian() obj.addNum(-5) assert -3 == obj.findMedian()
6724d381f952b55c7ec7d26262c45c94cfc48ea7
gomesgr/python-conversor
/zenit_polar.py
1,257
3.640625
4
class ZenitPolar: def __init__(self): self.zenit_polar_dict = {'Z': 'P', 'E': 'O', 'N': 'L', 'I': 'A', 'T': 'R', 'Í': 'Á', 'É': 'Ó', 'z': 'p', 'e': 'o', 'n': 'l', 'i': 'a', 't': 'r'} def encriptar(self, palavra): """ # Criado por Gabriel R. Gomes # Conversor de textos para Zenit Polar # O método coleta a palavra individual e letra por letra o converte se existir no # dicionário 'zenit_polar_dict', para que não haja a conversão da mesma letra # múltiplas vezes, usa-se 'enumerate()' para identificar cada # letra, mesmo que repetida, única no loop (contraditório porém é verdade). # Através do indice é possível então, identificar a posição da letra em questão """ letras = list(palavra) for indice, objeto in enumerate(letras): for zenit, polar in self.zenit_polar_dict.items(): if zenit in objeto: letras[indice] = polar if polar in objeto: letras[indice] = zenit return ''.join(letras) if __name__ == '__main__': zenit_polar = ZenitPolar() print(zenit_polar.encriptar('qUeIjO'))
a3bb9f15abdc945ff754a0e906164820082e063c
ryanjames1729/computer-programming-python
/Unit 1 Python Files/is-odd.py
184
3.796875
4
# CDS - Programming # Is Odd Assignment # # Student Name: # Ask for input # Determine if the number is even or odd odd = False # Print a statement with the result
5f4d87c2d3a4097a35026dd24bf21c8a09b3fd2f
hiei17/Crawler_Learning_Record
/用python3原生的urllib/1.1百度返回二进制转成str.py
1,207
3.796875
4
# coding=utf-8 import urllib.request def load_data(): url = "http://www.baidu.com/" # response:http相应的对象 mark urllib.request 是 python3 自带了 是一切的基础 response = urllib.request.urlopen(url) # http请求 没传参 就是 mark get的请求 如果有data=? 就是post print(response) # 读取内容 bytes类型 data = response.read() # 将字符串类型转换成bytes # str_name = "baidu" # bytes_name = str_name.encode("utf-8") # print(bytes_name) # python爬取的类型:str bytes # 如果爬取回来的是bytes类型:但是你写入的时候需要字符串 decode("utf-8") # 如果爬取过来的是str类型:但你要写入的是bytes类型 encode(""utf-8") # mark 百度返回的二进制(bytes) 需要转成字符串 str_data = data.decode("utf-8") # ,mark utf-8 会写在网页<head>里面 # < head > # # < meta http - equiv = "content-type" content = "text/html;charset=utf-8" > print(str_data) # mark 将数据写入文件 # w stands for writing permission for the opened file with open("baidu.html", "w", encoding="utf-8")as f: f.write(str_data) load_data()
c0cdf588c040a9e887d020137b2550bf62887bab
lee362/Learn-Python-3-the-Hard-Way
/codes/ex44.py
2,018
3.859375
4
#Inheritance vesus Composition #summary: #When you are doing this kind of specialization, there are three ways that the parent and child classes can interact: # 1. Actions on the child imply an action on the parent. # 2. Actions on the child override the action on the parent. # 3. Actions on the child alter the action on the parent. # #If both solutions solve the problem of reuse, then which one is appropriate in which situations? The answer is incredibly subjective, but I’ll give you my three guidelines for when to do which: # 1. Avoid multiple inheritance at all costs, as it’s too complex to be reliable. If you’re stuck with it, then be prepared to know the class hierarchy and spend time finding where everything is coming from. # 2. Use composition to package code into modulesthatareusedinmanydifferentunrelatedplaces and situations. # 3. Use inheritance only when there are clearly related reusable pieces of code that fit under a single common concept or if you have to because of something you’re using. # # # ex44a.py implicit inheritance class Parent(object): """docstring for Parent""" def implicit(): print("PARENT implicit():") class Child(Parent): pass dad = Parent() son = Child() dad.implicit() son.implicit() # ex44b.py Override Explicitly class Parent(object): """docstring for Parent""" def override(self): print("PARENT override()") class Child(Parent): def override(slef): print("CHILD override") dad = Parent() son = Child() dad.override() son.override() # ex44c.py Aleter Before of After class Parent(object): """docstring for Parent""" def altered(self): print("PARENT altered()") class Child(Parent): def altered(slef): print("CHILD, BEFORE PARENT altered()") super(Child, self).altered() print("CHILD, AFTER PARENT altered()") dad = Parent() son = Child() dad.altered() son.altered() class ClassName(object): """docstring for ClassName""" def __init__(self, arg): super(ClassName, self).__init__() self.arg = arg
d54ee3b14c4e0d355ceada5abf0307177e7c42db
it57070028/The-Examer
/Project.py
1,495
4.46875
4
''' This program can help you create the examination How to use: 1.Enter the number of your question 2.Enter your question 3.Enter you answer choices 4.Enter the correct answer You can reset your question by enter "_reset" in question You can submit all of your question when you finish it by enter "_submit" Author : Yaya & Tonpho @ITKMITL Last Modified Date : 24/11/2014 Time : 14:50 Language : Python 2.7.8 ''' import Tkinter as tk root = tk.Tk() root.resizable(True, True) ##root.geometry('500x200') root.title('The-Examer') tk.Label(root, text='Please Enter The Number of Your Question :').grid() num = tk.IntVar() entry = tk.Entry(root, textvariable=num) entry.grid(pady=5) ##space = tk.Label(root, text=" ") ##space.grid() def question(): root = tk.Tk() root.resizable(True, True) ## root.geometry('500x200') root.title('The-Examer') quest = {} global num num = num.get() col = 0 row = 1 for i in xrange(1, num+1): quest_name = tk.StringVar() tk.Label(root, text='Please Enter Your Question %d :' % i).grid(pady=5, row=(row-1)*2, column=col) entry = tk.Entry(root, textvariable=quest_name) entry.grid(row=(row*2)-1, column=col) row += 1 if i%10 == 0: if num % 2 == 0: col += 2 else: col += 1 row = 1 tk.Button(root, text='Submit').grid(pady=5) tk.Button(root, text='Create', command=question).grid(pady=5) root.mainloop()
50895c35c54f4f4fae4bb008a2c39f6d45d94ef0
INT-NIT/generateGUID
/doc/test_duplicates/TEST_GUID_Python2.py
5,605
3.65625
4
#!/usr/bin/python # Test possibilty of Duplication of GUID for first 10 characters of hash # Dipankar Bachar # Written in 29/10/2019 # Updated Version # Runs with Python 2 """This scripts produces more then 1million unique combination of name,surname,dateofbirth,sex from the file name.csv which is a tsv file and produces GUID for each combination, and checks whether there is any repetation of GUID ( That is Duplicate GUID ) """ """Written in python 2.7 Users can add, or remove more test data in the name.csv file and run this script to check the possibility of duplication of GUID For running the program: Keep the file name.csv and this python script in the same folder and run with python 2.7 from command line """ import hashlib import sys import os.path import re import unicodedata # Function to remove special characters and convert them in lower case from typical french names def strip_accents(text): """ Strip accents from input String. :param text: The input string. :type text: String. :returns: The processed String. :rtype: String. """ try: text = unicode(text, 'utf-8') except (TypeError, NameError): # unicode is a default on python 3 pass text = unicodedata.normalize('NFD', text) text = text.encode('ascii', 'ignore') text = text.decode("utf-8") return str(text) # Function to remove special characters from typical french names def text_to_id(text): """ Convert input text to id. :param text: The input string. :type text: String. :returns: The processed String. :rtype: String. """ #print text text = strip_accents(text) text = re.sub('[ ]+', '_', text) text = re.sub('[^0-9a-zA-Z_-]', '', text) text = re.sub('-', '', text) text = re.sub('_', '', text) text = text.replace('\/', '') text = text.replace('\\', '') #text = re.sub('\\', '', text) #text = re.sub('\/', '', text) #text = text.replace('-', '') #text = text.replace('_', '') #print text return text.upper() container_final={} C1=[] C2=[] C3=[] C4=[] C5=[] C6=[] # reads the csv file in tsv format and stores each columns in a separate list infile="./name.csv" #infile="./test.csv" inf=open(infile,"r",encoding="latin-1") for l in inf: k=l.strip().split() C1.append(k[0]) C2.append(k[1]) C3.append(k[2]) C4.append(k[3]) C5.append(k[4]) C6.append(k[5]) inf.close() # Produces the combination from the 6 columns data ( 6 lists ) to use as a input for hash alogorithm SHA #print "-------------------------- \n" for i in range(0,len(C1)): if C1[i]!="NULL": for j in range(0,len(C2)): new_string=text_to_id(C1[i])+text_to_id(C2[j])+text_to_id(C3[j])+text_to_id(C4[j])+text_to_id(C5[j])+text_to_id(C6[j]).lower() #print new_string if not container_final.has_key(new_string): container_final[new_string]=1 #print "-------------------------- \n" # More combination for i in range(0,len(C1)): if C1[i]!="NULL": for j in range(0,len(C2)): new_string=text_to_id(C1[i]+"abcd")+text_to_id(C2[j]+"bc")+text_to_id(C3[j])+text_to_id(C4[j])+text_to_id(C5[j])+text_to_id(C6[j]).lower() #print new_string if not container_final.has_key(new_string): container_final[new_string]=1 #print "-------------------------- \n" # More combination for i in range(0,len(C1)): if C1[i]!="NULL": for j in range(0,len(C2)): new_string=text_to_id(C1[i]+"cd")+text_to_id(C2[j]+"ef")+text_to_id(C3[j])+text_to_id(C4[j])+text_to_id(C5[j])+text_to_id(C6[j]).lower() #print new_string if not container_final.has_key(new_string): container_final[new_string]=1 #print "-------------------------- \n" # More combination for i in range(0,len(C1)): if C1[i]!="NULL": for j in range(0,len(C2)): new_string=text_to_id(C1[i]+"gh")+text_to_id(C2[j]+"ij")+text_to_id(C3[j])+text_to_id(C4[j])+text_to_id(C5[j])+text_to_id(C6[j]).lower() #print new_string if not container_final.has_key(new_string): container_final[new_string]=1 #print "-------------------------- \n" # More combination for i in range(0,len(C1)): if C1[i]!="NULL": for j in range(0,len(C2)): new_string=text_to_id(C1[i]+"kl")+text_to_id(C2[j]+"mn")+text_to_id(C3[j])+text_to_id(C4[j])+text_to_id(C5[j])+text_to_id(C6[j]).lower() #print new_string if not container_final.has_key(new_string): container_final[new_string]=1 #print "-------------------------- \n" # More combination for i in range(0,len(C1)): if C1[i]!="NULL": for j in range(0,len(C2)): new_string=text_to_id(C1[i]+"op")+text_to_id(C2[j]+"qr")+text_to_id(C3[j])+text_to_id(C4[j])+text_to_id(C5[j])+text_to_id(C6[j]).lower() #print new_string if not container_final.has_key(new_string): container_final[new_string]=1 print "Total Number of Combination = "+str(len(container_final)) print "------------------------------------------------- \n " newGUIDlist={} # Produces hash and takes the first 10 characters and checks for the Duplicates for key,value in container_final.items(): k=hashlib.sha256(key).hexdigest() pk=k[0:10] print pk if not newGUIDlist.has_key(pk): newGUIDlist[pk]=1 else: #If duplicate is found print the message and exit the program print "BINGO: A Duplicate GUID has been found " print "Exiting the Program " exit() # No Duplicate found print "\n Program terminated normally \n" print "Total Number of Combination Tested for Duplicate GUID hash = "+str(len(container_final)) print "------------------------------------------------- \n " print " No duplicate GUID found in "+str(len(container_final))+" combination \n"
7160dccef02e156cb33332f7ed1087fb8d67d84c
CatchTheDog/py
/py/logiccontrol.py
316
3.5
4
#!/usr/bin/python # -*- coding: UTF-8 -*- flag = False name = 'luren' if name == 'python': flag = True print('welcome boss') else: print(name) # python 不支持switch num = 5 if num == 3: print('boss') elif num == 2: print('user') elif num == 1: print('worker') else: print('roadman')
6514d77e2a163f60bfc57e9c4aa89ae3c298332f
michaelyzq/Python-Algorithm-Challenges
/021mergeTwoLists.py
1,278
4.09375
4
""" Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 """ class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l1next = l1 l2next = l2 new_node = ListNode(100) ret = new_node while l1 or l2: if l1== None and l2 == None: return None elif l1 == None and l2 !=None: new_node.next = ListNode(l2.val) new_node = new_node.next l2 = l2.next elif l2 == None and l1 !=None: new_node.next = ListNode(l1.val) new_node = new_node.next l1 = l1.next else: if l1.val > l2.val: new_node.next = ListNode(l2.val) new_node = new_node.next l2 = l2.next elif l2.val >= l1.val: new_node.next = ListNode(l1.val) new_node = new_node.next l1 = l1.next return ret.next
4923adfb43f82c7efde7c82676a6d80e84756751
mikolajwr/Projects
/My Projects/e to n.py
384
3.6875
4
import math from decimal import Decimal from decimal import getcontext n = input('Enter how many decimal points of e you want to view: ') max = 100 e = Decimal(1) getcontext().prec = 40 def fact(p): silnia =1 for i in range(1, int(p)+1): silnia *= i return (int(silnia)) for k in range(1, max): e += Decimal(1/(fact(k))) print (round(e ,int(n))) ##silnia
96bc61d92c71f9e641a0948b82f330b8821117ab
alievgithub/MIPT_advanced_python_fall
/w1/Dictionary.py
288
4.15625
4
#3 dict1 = {'A': 1, 'B': 2, 'C': 3} # (2 вариант) #dict2 = dict([(value, key) for (key, value) in zip(dict1.keys(), dict1.values())]) dict2 = {value: key for key, value in dict1.items()} # (1 вариант) #for key, value in dict1.items(): # dict2[value] = key print(dict2)
ec23149d5fd3826a8afeaad36872d19ee7e55800
liuminzhao/pythoncourse
/guessnumber.py
2,036
4.125
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import random import simplegui import math # initialize global variables used in your code secret = 0 myguess = 0 num_range = 100 count = 0 maxcount = 0 # define event handlers for control panel def init(): global num_range, count, maxcount, secret count = 0 secret = random.randrange(0, num_range) maxcount = math.ceil(math.log(num_range)/math.log(2)) print 'New game. Range is frome 0 to', num_range print 'Number of remaining guesses is', maxcount print 'True value: ' , secret, '\n' def range100(): # button that changes range to range [0,100) and restarts global num_range num_range = 100 init() def range1000(): # button that changes range to range [0,1000) and restarts global num_range num_range = 1000 init() def get_input(guess): # main game logic goes here global secret, count, maxcount count += 1 myguess = int(guess) if myguess == secret: print 'Guess was', myguess print 'Number of remaining guesses is', maxcount - count print 'Correct! \n' init() elif myguess > secret: print 'Guess was', myguess print 'Number of remaining guesses is', maxcount - count print 'Lower!', '\n' else: print 'Guess was', myguess print 'Number of remaining guesses is', maxcount - count print 'Higher', '\n' if count == maxcount: print 'You lose! No more trial! \n' init() # create frame frame = simplegui.create_frame("Guess the number", 300, 300) # register event handlers for control elements b100 = frame.add_button("Range: 0 - 100", range100, 200) b1000 = frame.add_button("Range: 0 - 1000", range1000, 200) inp = frame.add_input("My guess", get_input, 200) init() # start frame frame.start() # always remember to check your completed program against the grading rubric
469b1e8822ec80e20ef2c9c110a4b969a6709584
aritse/practice
/palindrome_linked_list.py
1,819
3.78125
4
# Approach 1 class Solution(object): def isPalindrome(self, head): rev = None slow = fast = head while fast and fast.next: fast = fast.next.next rev, rev.next, slow = slow, rev, slow.next if fast: slow = slow.next while rev and rev.val == slow.val: slow = slow.next rev = rev.next return not rev # # Approach 2 # class Solution(object): # def isPalindrome(self, head): # if not head or not head.next: # return True # last = self.lastLink(head) # if head.val != last.next.val: # return False # last.next = None # return self.isPalindrome(head.next) # def lastLink(self, head): # while head.next.next: # head = head.next # return head # # Approach 3 # class Solution(object): # def isPalindrome(self, head): # if head is None or head.next is None: # return True # length = 0 # link = head # while link: # length += 1 # link = link.next # half = length // 2 # print length, half # i = 1 # first = head # while i < half: # first = first.next # i += 1 # if length % 2: # second = first.next.next # else: # # print first.next.val # second = first.next # while second: # # print first.val, second.val # if first.val != second.val: # return False # second = second.next # print second # link = head # while link.next and link.next != first: # link = link.next # first = link # return True
50988873c2393c330b1ee5c96d5be0389f6dd5b4
CateGitau/Python_programming
/Packt_Python_programming/Chapter_3/exercise50.py
137
3.71875
4
def countdown(n): if n == 0: return "Liftoff!!" else: print(n) return countdown(n-1) print(countdown(3))
1fe6e6d14f2464fb5b550635afe66acf0beec88e
Geokenny23/Basic-python-batch5-c
/Tugas-2/Soal-1.py
2,009
3.96875
4
semuakontak = [] kontak = [] def menu(): print("----menu---") print("1. Daftar Kontak") print("2. Tambah Kontak") print("3. Keluar") def tampilkankontak(): print("Daftar Kontak: ") for kontak in semuakontak: print("Nama : " + kontak["nama"]) print("No. Telepon : " + kontak["telpon"]) def tambahkontak(): nama = str(input("\nMasukkan Data\nNama : ")) telpon = str(input("No Telepon : ")) kontak = { "nama" : nama, "telpon" : telpon, } semuakontak.append(kontak) print("Kontak berhasil ditambahkan") print("Selamat datang!!!") while True: menu() pilihan = int(input("Pilih menu: ")) if pilihan == 1: tampilkankontak() elif pilihan == 2: tambahkontak() elif pilihan == 3: print("program selesai, sampai jumpa") break else: print("menu tidak tersedia, silahkan menginput No. yang benar") print("-------------------------------------------------------") # print("Selamat datang!") # while True: # print("---Menu---") # print("1. Daftar Kontak") # print("2. Tambah Kontak") # print("3. Keluar") # pilih = int(input("Pilih menu: ")) # if pilih == 1: # #print("Amal") # #print("0834267588") # Nama = { # "nama" : "Amal" # "No. telepon" : "0834267588" # } # } # daftar_kontak = [Nama].append(x) # print(daftar_kontak) # #print(Nama) # #print(Nomor) # #print(x) # #print(y) # elif pilih == 2: # x = str(input("Nama: ")) # y = int(input("No. Telepon: ")) # print("Kontak berhasil ditambahkan") # elif pilih == 3: # print("program selesai, sampai jumpa") # break # else: # print("menu tidak tersedia, silahkan menginput No. yang benar") # print("------------------------------------------------------")
65e950537d3adc987c720d33da21ecbef38f3f83
jaiprakashrenukumar/mypython_lab
/python_basic/013_split_join.py
533
4.0625
4
names = 'jai, suresh, vikram, santhosh' print(names) # this prints as a long string print("\n") # now we are going to split this string l = names.split(", ") # we are spliting using , and space print(l) print("\n") print("another example") newlist = 'jai1suresh1vikram1santhosh' print(newlist) print("\n") nl = newlist.split("1") print(nl) print("\n") ############################ now joining a string ###################### print("example for joining the string") csv = ','.join(nl) print(csv) print("\n") friends = ' and '.join(nl) print(friends)
f9abcdd993a09c0e3078ce172007652744fd6ec2
Maria105/python_lab
/lab4_1.py
194
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math a=float(input('enter a>=0: ')) b=float(input('enter b>0: ')) e=math.e x=math.sqrt(a*b)/(math.exp(a)*b)+a*math.exp(2*a/b) print(x)
34e7af40d5c01d9a8802be5731f16d11049b3f51
FilipMohyla/Cycles-in-Python
/pentagon_to_octagon.py
266
3.671875
4
from turtle import forward, left, right, shape, exitonclick, penup, pendown, pencolor shape("turtle") for h in range(4): for i in range(8-h): forward(45) left(360/(8-h)) penup() forward(110) pendown() exitonclick()
a6c4220ce76f5574a5078a7455efc7efbf96bf95
TimLeeTY/compPhyEx
/ex1/numInt.py
2,510
3.953125
4
""" =================================================== Ex.1 Numerical Integration using Monte-Carlo method =================================================== """ import numpy as np import matplotlib.pyplot as plt def MCint(N, n): # N holds number of samples and n is the number of trials per N D, s = 8, np.pi/8 V = s**8 fmean, fsqmean = np.zeros(n), np.zeros(n) for i in range(n): # sums 8 uniformly distributed random numbers in [0,s] r = (np.random.rand(D, N)).sum(axis=0)*s f = np.sin(r)*V*10**6 # evaluates sin(x0+x1+...+x7) fmean[i] = f.mean() # evaluates <f> fsqmean[i] = (f**2).mean() # evaluates <f^2> sigma = np.sqrt((fsqmean-fmean**2)/N) # finds error in estimate # return the best estimate of the integral in n trials, the standard deviation # of that mean, and the mean of the error estimate return(fmean.mean(), fmean.std(), sigma.mean()) #%% """ ----------------------- §1. Evaluating integral ----------------------- Repeats the integral n times for each value of N samples. Take mean of n trials as the best estimate for the integral. """ n = 25 vMC = np.vectorize(MCint) target = 10**6*(70-16*np.sin(np.pi/8)+56*np.sin(np.pi/4)-112*np.sin(3*np.pi/8)) sample = (2**np.arange(5, 22)) lsamp = np.log(sample) [y, yerr, zerr] = vMC(sample, n) plt.figure() plt.semilogx() plt.ylim(525, 545) plt.yticks(np.arange(525, 551, 5)) plt.xlabel(r'$N$') plt.ylabel(r'Integral value') plt.errorbar(sample, y, yerr, fmt='+', color='#1f77b4', lw=0.8, capsize=3) plt.plot(sample, np.ones(len(sample))*target, '-', color='#2ca02c', lw=0.8) plt.savefig("est.pdf", format="pdf") #%% """ --------------------- §2. Evaluating errors --------------------- Comparing the error obtained from the standard deviation of n trials to the average error from equation (3) of the handout """ fig, ax = plt.subplots() ax.loglog(basex=2) plt.ylim(10**(-5), 10**(-1)) yfit = np.polyfit(lsamp, np.log(yerr/target), 1) yffit = np.poly1d(yfit) ax.plot(sample, yerr/target, '+', color='#1f77b4', label=r'S.D. in mean') ax.plot(sample, np.exp(yffit(lsamp)), '-', color='#1f77b4', linewidth=0.8) zfit = np.polyfit(lsamp, np.log(zerr/target), 1) zffit = np.poly1d(zfit) ax.plot(sample, zerr/target, 'x', color='#ff7f0e', label=r'$\sigma (N)$') ax.plot(sample, np.exp(zffit(lsamp)), '-', color='#ff7f0e', linewidth=0.8) plt.xlabel(r'$N$') plt.ylabel(r'Fractional Error, $\Delta$') plt.grid(True) ax.legend() fig.savefig("err.pdf", format="pdf")
7bc3443e285952e129c6161066448e516f3fbf0b
abriggs914/Coding_Practice
/Python/Resource/textprint.py
2,723
3.8125
4
import pygame import datetime # Class to print text to a pygame window. # Borrowed from: # https://stackoverflow.com/questions/49887874/pygame-xbox-one-controller # Version............1.0 # Date........2022-03-05 # Author....Avery Briggs pygame.init() BLACK = pygame.Color('black') WHITE = pygame.Color('white') # This is a simple class that will help us print to the screen. # It has nothing to do with the joysticks, just outputting the # information. class TextPrint(object): def __init__(self): self.reset() self.font = pygame.font.Font(None, 20) def tprint(self, screen, textString): new_line_split = textString.split("\n") for new_line in new_line_split: tab_split = new_line.split("\t") for line in tab_split: if line or 1: textBitmap = self.font.render(line, True, BLACK) screen.blit(textBitmap, (self.x, self.y)) width = textBitmap.get_width() if len(line) == 0: self.x += width self.indent() self.new_line() for i in range(len(tab_split)): self.unindent() def reset(self): self.x = 10 self.y = 10 self.line_height = 15 def indent(self): self.x += 10 def unindent(self): self.x -= 10 def new_line(self): self.y += self.line_height if __name__ == "__main__": # Set the width_canvas and height_canvas of the screen (width_canvas, height_canvas). screen = pygame.display.set_mode((500, 700)) pygame.display.set_caption("My Game") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates. clock = pygame.time.Clock() # Get ready to print. textPrint = TextPrint() while not done: # # EVENT PROCESSING STEP # # Possible joystick actions: JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN, # JOYBUTTONUP, JOYHATMOTION for event in pygame.event.get(): # User did something. if event.type == pygame.QUIT: # If user clicked close. done = True # Flag that we are done so we exit this loop. # # DRAWING STEP # # First, clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. screen.fill(WHITE) textPrint.reset() textPrint.tprint(screen, f"new line string: {datetime.datetime.now()}\nTesting new line") textPrint.new_line() textPrint.tprint(screen, f"new tab string: {datetime.datetime.now()}\tTesting tab") textPrint.new_line() textPrint.indent() textPrint.tprint(screen, f"new split tab string: {datetime.datetime.now()}\nhere's the new line\tfollowed by tab") textPrint.tprint(screen, f"new split tab string: {datetime.datetime.now()}\n\n\n\t\tTricky Test:\n1\t-\tTab\n2\t-\tTab") pygame.display.flip() # Limit to 20 frames per second. clock.tick(20)
c481ee852934f1e8625d7849130aa5b7859125f8
burakhanaksoy/PythonOOP
/corey_schafer/magic_methods.py
1,545
3.875
4
# magic methods help us change built in methods and/or operations from datetime import timedelta import math class Employee: raise_amt = 1.04 def __init__(self, f_name, l_name, pay): self.f_name = f_name self.l_name = l_name self.email = self.f_name.lower() + '.' + self.l_name.lower() + '@company.com' self.pay = pay def fullname(self): return f"{self.f_name} {self.l_name}" def apply_raise(self): self.pay = int(self.pay * self.raise_amt) def __repr__(self): return f"Employee('{self.f_name}', '{self.l_name}', {self.pay})" def __str__(self): return f"Employee('{self.fullname()} -- {self.email}')" def __add__(self, other): return self.pay + other.pay def __sub__(self, other): return self.pay - other.pay # override __len__() method to calculate length of employee full name def __len__(self): # didn't use fullname() since it contains space return len(self.f_name + self.l_name) # It's good to have at least __repr__() method since if we don't define __str__() method and call it, # Python will automatically look for __repr__() method... emp1 = Employee('burak', 'aksoy', 2000) emp2 = Employee('Marash', 'Raghev', 5700) print(emp1) print(repr(emp1)) print(str(emp1)) print(emp1 + emp2) print(emp1 - emp2) print(len(emp2)) # same as print(emp2.__len__()) time1 = timedelta(1, 2, 3, 4, 5, 6, 1) time2 = timedelta(1, 3, 5, 2, 1, 3, 4) print(timedelta.__add__(time1, time2))
93a3dfb2bb3c27f5308a6688a05437c85a380903
wellingtond2271/old-files
/practice2.py
395
3.96875
4
print(" Give Me Numbers. ") Num1 = input(" Whats your first number?! ") Num2 = input(" Whats The Second One? ") Num1 = int(Num1) Num2 = int(Num2) print(str(Num1) + "+" + str(Num2) + "=" + str(Num1 + Num2)) print(str(Num1) + "-" + str(Num2) + "=" + str(Num1 - Num2)) print(str(Num1) + "*" + str(Num2) + "=" + str(Num1 * Num2)) print(str(Num1) + "/" + str(Num2) + "=" + str(Num1 / Num2))
2a00ac4c9779ba9fb157713c025855961129fe94
hakepg/operations
/Basic/pattern_durga.py
146
3.671875
4
#pattern 55 n=5 for row in range(n,0,-1): print(' '*(n-row),end=' ') for column in range(1,n+1): print('*', end=' ') print()
a730eb4b33e4f45ea9b7b1ac8020d269f651474b
Klausop/python_practical-tscs
/21332_prac_5c.py
105
3.8125
4
dict={'data1':10,'data2':20,'data3':30} print("sum of dict values are :") print(sum(dict.values()))
64d928cb5450e0fc4728e0fa8562c73ed62b94b2
wilkice/Algorithms
/a3+b3=c3+d3.py
717
3.578125
4
''' find integer under 1000 to make a3+b3=c3+d3 ''' all_result = {} pairs_result = [] def add(num): for i in range(1,num+1): for j in range(i, num+1): result = i ** 3 + j ** 3 # 不在字典里就添加 if result not in all_result.keys(): all_result[result]=[(i,j)] else: # 添加新的数字队到字典的值, 且把这个值加到新列表,此表是有2个数字队的result组成的,后面直接从这里取值 all_result[result].append((i, j)) pairs_result.append(result) print('all been added') for result in pairs_result: print(result, all_result[result]) add(1000)
7b97716012a012dddd4e602a08f5bfe6ad2e892d
Moss89/Python_Semester_1
/p19/ass.py
4,518
3.71875
4
import emoji from random import choice import sys def run_slot_machine(): class Purse: def __init__(self): self.money = 10 def debit(self, amount): print(amount,"this") self.money -= amount def credit(self, amount): self.money += amount def get_balance(self): return self.money mypurse = Purse() class Column: def __init__(self): self.faces = [emoji.emojize(':red_apple:'), emoji.emojize(':pear:'), emoji.emojize(':tangerine:') ] def change_face(self): return choice(self.faces) class Slot: def __init__(self): self.column1 = Column() self.column2 = Column() self.column3 = Column() self.position1 = 0 self.position2 = 0 self.position3 = 0 self.bet = 0.0 def bet_amount(self, amount): self.bet = amount def get_bet(self): return self.bet # def take_bet(self): # self.bet = input("How much do you bet? ") # if self.bet == "N": # print("Thanks for playing!") # return False # if self.bet != "N": # self.bet = float(self.bet) # print(self.bet) # if self.bet<2: # print("Minimum bet is 2!") # return True # elif self.bet > mypurse.get_balance(): # print("You don't have enough money to make that bet! You only have:", mypurse.get_balance()) # return True # else: # return True def pull_handle(self): self.position1 = self.column1.change_face() self.position2 = self.column2.change_face() self.position3 = self.column3.change_face() def show_slot(self): print(self.position1, " ", self.position2, " ", self.position3) def score_slot(self, bet): if self.position1 == self.position2 and self.position2 == self.position3: mypurse.credit(bet*1.5) print("You score", bet*1.5, "You have:", mypurse.get_balance()) elif self.position1 == self.position2 or self.position1 == self.position3 or self.position2 == self.position3: mypurse.credit(bet) print("You score", bet, "You have:", mypurse.get_balance()) else: mypurse.debit(bet) print("You score", 0, "You have:", mypurse.get_balance()) if mypurse.get_balance() < 2: print("You don't have enough money for another bet! You have", mypurse.get_balance(), "Thanks for playing!") sys.exit() mySlot = Slot() def take_bet(): bet = input("How much do you bet? ") if bet == "N": print("Thanks for playing!") result = "Exit" if bet != "N": bet = float(bet) mySlot.bet_amount(bet) print("1") if bet < 2: print("2") print("Minimum bet is 2!") result = "Retry" elif bet > mypurse.get_balance(): print("3") print("You don't have enough money to make that bet! You only have:", mypurse.get_balance()) result = "Retry" else: result = "True" # # mySlot.take_bet() if result == "Retry": print("loop1") take_bet() if result == "True": print("loop2") # mySlot.take_bet() mySlot.pull_handle() mySlot.show_slot() mySlot.score_slot(mySlot.get_bet()) take_bet() if result == "Exit": print("Exit loop") sys.exit() take_bet() run_slot_machine()
e765792ab99db70cfaf7422eb17b9220222d1fc2
tallsam/shifting_hands
/sh_item.py
1,267
3.53125
4
# Shifting Hands # Item Classes # Sam Hassell class Item(object): def __init__(self, name, description, material, item_type, weight, base_value, actions): self.name = name self.description = description self.material = material #wood, gold, silver, food, steel self.item_type = item_type #weapon, armour, healing, food self.weight = weight self.base_value = base_value self.actions = actions def __str__(self): rep = "**You look at the " + self.name + "..\n" rep += self.description + "\n" rep += "It is made of " + self.material rep += " and weighs about " + self.weight + " grams.\n" return rep def save(self, datafile): item_data = {"material" : self.material, "description": self.description, "item_type" : self.item_type, "weight" : self.weight, "base_value" : self.base_value, "actions" : self.actions } key = str(self.loc[0]) + "," + str(self.loc[1]) gamedata = shelve.open(datafile, "c") gamedata[self.name] = item_data gamedata.sync() gamedata.close() if __name__ == "__main__": print "You ran this module directly (and did not 'import' it)." raw_input("\n\nPress the enter key to exit.")
e0f890117ec5ff0cb5fd9c721b2db24afee8ff83
akatzuka/ML-and-Neural-Nets-CST-463-
/HW and Exams/HW's/HW5.py
4,826
3.65625
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 3 14:12:23 2018 @author: Remilia """ import numpy as np import numpy.linalg as LA from sklearn.datasets import load_boston, load_iris from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import matplotlib.cm as cm def logistic(x): return 1/(1 + np.exp(-x)) # compute gradients at theta for logistic cost function # (refer to Equation 4-18 of the Geron textbook) # theta is an array of coefficients, X is an augmented # feature matrix, y is an array of numeric labels def logistic_gradient(theta, X, y): log_grad = 0 for i in range(len(X)): log_grad += (logistic(np.dot(theta, X[i])) - y[i]) * X[i] log_grad = 1/len(X) * log_grad return log_grad # test logistic_gradient m = 3 theta = np.array([0.5,1.0]) X = np.array([[0.27], [0.66], [0.87]]) X0 = np.ones((m,1)) X_aug = np.hstack((X0, X)) y = np.array([0,0,1]) # result should be about [0.41, 0.17] print(logistic_gradient(theta, X_aug, y)) # use gradient descent to find a vector that is the approximate # minimum of a function whose gradients can be computed with # function grads # grads - computes gradients of a function # n - length of vector expected by grads as input # alpha - learning rate # max_iterations and min_change are stopping conditions: # max_iterations - return if max_iterations performed # min_change - return if change to x is less than min_change def grad_descent(grads, n, alpha=0.01, max_iterations=10000, min_change=0.0001): x = np.zeros(n) # this is just one way to initialize num_iterations = 0 while num_iterations <= max_iterations: x_last = x x = x - grads(x)*alpha # update x resid = x - x_last change = np.sqrt(resid.dot(resid)) if change < min_change: print("stopped on min change") return(x) num_iterations += 1 print("stopped on max iterations") return(x) dat = load_boston() X = dat['data'][:,5:6] # avg. number of rooms y = dat['target'] # house price (thousands of dollars) dat['feature_names'] # remove data where the house price is exactly the max value # of 50.0; this is a result of censoring. not_max_rows = (y != 50.0) y = y[not_max_rows] X = X[not_max_rows] n,m = X.shape # convert target to 0/1, with 1 for house price > 25 y = np.where(y > 25.0, 1.0, 0.0) X0 = np.ones((n,1)) X_aug = np.hstack((X0, X)) plt.scatter(X, y) plt.xlabel('Number of rooms') plt.ylabel('House price > $25K') plt.title('House price by number of rooms'); # logistic regression loss function # (refer to Equation 4-17 of the Geron textbook) # X is an augmented feature matrix of two columns, y is an array of numeric labels def log_loss(theta, X, y): log_l = 0 for i in range(len(X)): log_l += ((y[i] * np.log(logistic(np.dot(theta, X[i])))) + ((1 - y[i]) * np.log(1 - logistic(np.dot(theta, X[i]))))) log_l = -1/len(X) * log_l return log_l # a version of the loss function where the training data is hidden def f_loss(theta): return log_loss(theta, X_aug, y) theta0 = np.linspace(-15, 5, 20) theta1 = np.linspace(-1.5, 2.5, 20) theta0, theta1 = np.meshgrid(theta0, theta1) # see stackoverflow.com/questions/9170838/surface-plots-in-matplotlib zs = np.array([f_loss(np.array([t0, t1])) for t0,t1 in zip(np.ravel(theta0), np.ravel(theta1))]) Z = zs.reshape(theta0.shape) cmap = cm.get_cmap('bwr') # red value is high, dark blue is low plt.contourf(theta0, theta1, Z, 30, cmap=cmap); # filled contour map # create version of log loss function with single vector input def f_grads(theta): return logistic_gradient(theta, X_aug, y) gd_coefs = grad_descent(f_grads, 2, alpha=0.01, max_iterations=30000, min_change=0.0001) print(gd_coefs) print(f_loss(gd_coefs)) lr_clf = LogisticRegression() lr_clf.fit(X, y) lr_clf.score(X, y) sk_coefs = np.array([lr_clf.intercept_[0], lr_clf.coef_[0,0]]) print(sk_coefs) print(f_loss(sk_coefs)) # compute accuracy using coefficients def accuracy(theta) : y_pred = logistic(X_aug.dot(theta)) y_pred = np.where(y_pred > 0.5, 1, 0) return accuracy_score(y, y_pred) print(accuracy(gd_coefs)) print(accuracy(sk_coefs)) X_new = np.linspace(0, 3, 1000).reshape(-1, 1) plt.figure(1, figsize=(4, 3)) plt.clf() plt.scatter(X.ravel(), y, color='black', zorder=20) plt.plot(X_new, gd_coefs[0] * X_new + gd_coefs[1], linewidth=1) plt.plot(X_new, sk_coefs[0] * X_new + sk_coefs[1], linewidth=1) plt.ylabel('y') plt.xlabel('X') plt.xticks(range(-5, 10)) plt.yticks([0, 0.5, 1]) plt.ylim(-.25, 1.25) plt.xlim(-4, 10) plt.legend(('Logistic Regression Model', 'Linear Regression Model'), loc="lower right", fontsize='small') plt.tight_layout() plt.show()
8cfa321aa6c665d02aa5014dc3e435a5b5e6c5c8
Konchannel/ABC_AtCoder_past-ques
/ABC159/C.py
327
3.53125
4
""" 問題文 正の整数Lが与えられます。 縦、横、高さの長さ (それぞれ、整数でなくてもかまいません) の合計が Lの直方体としてありうる体積の最大値を求めてください。 制約 1≤L≤1000 Lは整数 """ # === tried-01 === L = int(input()) s = L / 3 print(s ** 3)
f3d6d104d9a0eda528985bf9841e16d3d13979fd
DT-1236/leetcode-practice
/hard/freedom_trail.py
3,501
3.75
4
from collections import defaultdict class Solution: def findRotateSteps(self, ring: str, key: str) -> int: """Keeps track of all paths using a single array representing the ring As each letter is used, all costs for that letter are updated with the best cost at that time >>> test = Solution() None >>> test("edcba", "abcde") 10 >>> test("caotmcaataijjxi", "oatjiioicitatajtijciocjcaaxaaatmctxamacaamjjx") 137 ) """ indices = defaultdict(set) for idx in range(0, len(ring)): indices[ring[idx]].add(idx) # Assign cost of every index to the cost of moving and assigning costs = [ Solution.ring_cost(x, 0, len(ring)) for x in range(0, len(ring) + 0) ] print(costs) # Cycle through all subsequent characters in the key prev_char = key[0] for char in key[1:]: char_indices = indices[char] # Iterate all possible solutions # _i.e._ update costs for every position of the next character for c_idx in char_indices: # The update cost will be the best choice from the all previous positions costs[c_idx] = min( Solution.ring_cost(c_idx, prev_idx, len(costs)) + costs[prev_idx] for prev_idx in indices[prev_char]) prev_char = char return min(costs[x] for x in indices[key[-1]]) @staticmethod def ring_cost(c_idx: int, prev_idx: int, length: int) -> int: """Takes two indices and the length of the ring and returns the ring distance + 1""" if c_idx < prev_idx: lesser, greater = c_idx, prev_idx else: greater, lesser = c_idx, prev_idx return min(abs(c_idx - prev_idx), lesser + (length - greater)) + 1 def naive(self, ring: str, key: str) -> int: """This one actually times out. It needs a good implementation of Dynamic Programming/Backtracking""" counts = defaultdict(set) for idx in range(0, len(ring)): counts[ring[idx]].add(idx) def _recurse(key_index, count, current_index): # Stop when key_index == last index if key_index < len(key) - 1: next_letter = key[key_index + 1] if next_letter == ring[current_index]: _recurse(key_index + 1, count + 1, current_index) else: for next_index in counts[next_letter]: direct = abs(current_index - next_index) if current_index < next_index: lesser, greater = current_index, next_index else: greater, lesser = current_index, next_index loop = lesser + ((len(ring)) - greater) # The best way to get to the next_index steps = min(direct, loop) # Add travel time and cost to add the new character new_count = count + steps + 1 # Advance to the next key item at the location of the current letter _recurse(key_index + 1, new_count, next_index) else: self.best = min(count, self.best) self.best = float('inf') _recurse(-1, 0, 0) return self.best
86eae087c5fc1a8398c6d83cc7d9f0a5c1df3c09
liuhadong/7.21
/53.py
226
3.953125
4
def judge(string): print(string.islower()) if string.islower(): print('是由小写字母和数字组成') else: print('不是由小写字母和数字组成') word = input('请输入:') judge(word)
ff18b5eed66d9985cf4292eb96c47563ddea939e
inghgalvanIA/Master_Python
/python/17parametros.py
327
3.796875
4
nombre = input("Introduce tu nombre") edad = int(input("Ingresa tu edad")) def saludar(nombre,edad): mensaje = None if edad >= 18: mensaje = "Eres mayor de edad" else: mensaje = "Eres menor de edad" return "Hola " + nombre + " tienes " + str(edad) + " y " + mensaje print(saludar(nombre,edad))
5bdc07ac7fe5bc83c041000d7a655b6a078e0e7f
Abnernnetto/estudoParaTestesUnitarios-Python
/teste_aplicacao/test_comparador.py
2,031
3.53125
4
import unittest from aplicacao.comparador import compara_numeros_simples, compara_numeros_quadraplos class MyTestCase(unittest.TestCase): def test_comparacao_de_valores_a_maior(self): resultado = compara_numeros_simples(5, 2) self.assertTrue(resultado) def test_comparacao_de_valores_b_maior(self): resultado = compara_numeros_simples(1, 2) self.assertTrue(resultado) def test_comparacao_de_valores_iguais(self): resultado = compara_numeros_simples(5, 5) self.assertFalse(resultado) # =========================== # VV = V def test_comparacao_amaiorb_xmenory(self): resultado = compara_numeros_quadraplos(6, 5, 1, 2) self.assertTrue(resultado) # VF = F def test_comparacao_amaiorb_xmaiory(self): resultado = compara_numeros_quadraplos(6, 5, 3, 2) self.assertFalse(resultado) # FV = F def test_comparacao_amenorb_xmenory(self): resultado = compara_numeros_quadraplos(1, 5, 1, 2) self.assertFalse(resultado) # FF = F def test_comparacao_amenorb_xmaiory(self): resultado = compara_numeros_quadraplos(1, 5, 7, 2) self.assertFalse(resultado) def test_comparacao_aigualb_xigualy(self): resultado = compara_numeros_quadraplos(1, 1, 1, 1) self.assertFalse(resultado) def test_comparacao_aigualb_xmaiory(self): resultado = compara_numeros_quadraplos(1, 1, 2, 1) self.assertFalse(resultado) def test_comparacao_aigualb_xmenory(self): resultado = compara_numeros_quadraplos(1, 1, 1, 2) self.assertFalse(resultado) def test_comparacao_amenorb_xigualy(self): resultado = compara_numeros_quadraplos(1, 2, 3, 3) self.assertFalse(resultado) def test_comparacao_amaiorb_xigualy(self): resultado = compara_numeros_quadraplos(2, 1, 5, 5) self.assertFalse(resultado) if __name__ == '__main__': unittest.main()
dba2ec352e0c5c7d9d07d58a28de804ae71b89f1
MissSheyni/HackerRank
/Python/DateAndTime/calendar-module.py
300
3.765625
4
# https://www.hackerrank.com/challenges/calendar-module import calendar [month, day, year] = map(int, raw_input().split()) weekdayInt = calendar.weekday(year, month, day) weekdays = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"] print(weekdays[weekdayInt])
b700d05fc9080f218984db8cb0b78cacec758944
lenniecottrell/Python-Projects
/Mini projects/birthday_IF_statements.py
663
4.3125
4
import datetime today = datetime.date.today() checkDate = datetime.datetime(2020, 6, 30) allisonBday = datetime.datetime(2020, 5, 9) print(today) print(checkDate) print(allisonBday) if today.month == checkDate.month and today.day == checkDate.day: print("Happy birthday!") elif today.month == allisonBday.month and today.day == allisonBday.day: print("It's Allison's birthday!") else: print("It's not your or Allison's birthday") if today.month > 6: print("You have to wait until next year") elif today.month == 5 and today.day >= 10: print("Your birthday is next!!") else: print("Allison's birthday is next!!")
fb6808329e16b306a9bdf671d4e06e9d91c5c7ae
Aasthaengg/IBMdataset
/Python_codes/p02963/s465488423.py
462
3.671875
4
def divisor(n): ass = [] for i in range(1,int(n**0.5)+1): if n%i == 0: ass.append(i) if i**2 == n: continue ass.append(n//i) return ass #sortされていない def main(): S = int(input()) X1, Y1 = 0, 0 Y2 = 1 X2 = 10 ** 9 Y3 = S // X2 if S % X2 == 0 else S // X2 + 1 X3 = (10 ** 9) * Y3 - S print(X1,Y1,X2,Y2,X3,Y3) if __name__ == "__main__": main()
839e5569d99e906703c338501ec2b1e85c174f7d
karbekk/Python_Data_Structures
/Interview/TechieDelight/Array/sort_0_1_2.py
273
3.984375
4
def sort_three(nums): from collections import Counter my_list = [] for k , v in Counter(nums).items(): while v != 0: my_list.append(k) v -= 1 return my_list print sort_three( nums = [7, 1, 1, 2, 2, 1, 0, 0, 2, 0, 1, 1, 0])
4131dd87d173a164fe7d104a5061f55399e22d0f
raghubgowda/python
/beginer/converters.py
220
3.640625
4
def lbs_to_kg(weight: float): if weight > 0.0: return weight * 0.45 else: return 0.0 def kg_to_lbs(weight: float): if weight > 0.0: return weight / 0.45 else: return 0.0
5d16ef05e6a74d384a07ec837c8d6df55d2df293
LyriCeZ/py-core
/Python Data Structures/print.py
145
3.578125
4
text = raw_input("Enter a file name: ") texted = open(text) inside = texted.read() inside = inside.upper() inside = inside.rstrip() print inside
3b9180f6f3acaa3c93647037594b64726eb7e5da
PriscylaSantos/estudosPython
/TutorialPoint/05 - Numbers/2 - Random Number Functions/04 - seed()_method.py
411
3.703125
4
#!/usr/bin/python3 #The seed() method initializes the basic random number generator. Call this function before calling any other random module function. # seed ([x], [y]) import random random.seed() print ("random number with default seed", random.random()) random.seed(10) print ("random number with int seed", random.random()) random.seed("hello",2) print ("random number with string seed", random.random())
3254d5987a9537dbc7a69502431667628d6f10c2
KevinVargis/Breakout
/Paddle.py
576
3.703125
4
class paddle: def __init__(self): self.x = 25 self.y = 1 self.oldx = 25 self.oldy = 1 self.size = 5 self.oldsize = 5 self.speed = 2 def move(self, dir): # print(dir) self.oldx = self.x self.oldy = self.y if dir == 'a' or dir == 'A': if self.x-self.size-self.speed > 0: self.x = self.x - self.speed if dir == 'd' or dir == 'D': if self.x+self.size+self.speed+1 < 100: self.x = self.x + self.speed Paddle = paddle()
a7b55848abbb88a94997e6304eb564af957d682f
janakiraam/ML-ToyProbelm
/grdient_decent.py
511
3.609375
4
import numpy as np def gradient_decent(x,y): m_curr=0 b_curr=0 iteration=100 n = len(x) learning_rate=0.001 for i in range(iteration): y_predict=m_curr*x+b_curr md=-(2/n)*sum(x*(y-y_predict)) bd=-(2/n)*sum(y-y_predict) m_curr=m_curr - learning_rate*md b_curr=b_curr - learning_rate*bd print("m {}, b {} , iteration {}".format(m_curr,b_curr,i)) x=np.array([1,2,3,4,5]) y=np.array([5,7,11,25,13]) gradient_decent(x,y)
f34128088a213795dfa4a912f86cdfc5140eff13
vincent507cpu/Comprehensive-Algorithm-Solution
/LintCode/ladder 08 memorized search/必修/683. Word Break III/solution.py
1,021
3.90625
4
class Solution: """ @param: : A string @param: : A set of word @return: the number of possible sentences. """ def wordBreak3(self, s, dict): # Write your code here if not s or not dict: return 0 lower_dict = set() for piece in dict: lower_dict.add(piece.lower()) max_len = max([len(piece) for piece in dict]) return self.memo_search(s.lower(), lower_dict, 0, max_len, {}) def memo_search(self, s, dict, index, max_len, memo): if index == len(s): return 1 if index in memo: return memo[index] memo[index] = 0 for i in range(index, len(s)): if i + 1 - index > max_len: break word = s[index:i + 1] if word not in dict: continue memo[index] += self.memo_search(s, dict, i + 1, max_len, memo) return memo[index]
7331bd829344fdddafaf6fbcd77adab81e5ce098
patheticGeek/competitive-code
/strings/valid-palindrome.py
379
3.90625
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ string = "" for char in s: if(char.isalnum()): string += char.lower() res = string == string[::-1] return res sol = Solution() ans = sol.isPalindrome("A man, a plan, a canal: Panama") print(ans)
78089443a30ea5354b17a56823828240e9248a0d
weijiew/cs61a
/lab/lab08/lab08.py
16,394
4.1875
4
""" Lab 08: Midterm Review """ # Linked lists def insert(link, value, index): """Insert a value into a Link at the given index. >>> link = Link(1, Link(2, Link(3))) >>> print(link) <1 2 3> >>> insert(link, 9001, 0) >>> print(link) <9001 1 2 3> >>> insert(link, 100, 2) >>> print(link) <9001 1 100 2 3> >>> insert(link, 4, 5) IndexError """ if index == 0: link.rest = Link(link.first,link.rest) link.first = value elif link.rest is Link.empty: raise IndexError else: insert(link.rest, value, index - 1) # Recursion/Tree Recursion def insert_into_all(item, nested_list): """Assuming that nested_list is a list of lists, return a new list consisting of all the lists in nested_list, but with item added to the front of each. >>> nl = [[], [1, 2], [3]] >>> insert_into_all(0, nl) [[0], [0, 1, 2], [0, 3]] """ return [[item] + rest for rest in nested_list] def subseqs(s): """Assuming that S is a list, return a nested list of all subsequences of S (a list of lists). The subsequences can appear in any order. >>> seqs = subseqs([1, 2, 3]) >>> sorted(seqs) [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]] >>> subseqs([]) [[]] """ if not s: return [[]] else: with_in = insert_into_all(s[0],subseqs(s[1:])) with_out = subseqs(s[1:]) return with_in + with_out def inc_subseqs(s): """Assuming that S is a list, return a nested list of all subsequences of S (a list of lists) for which the elements of the subsequence are strictly nondecreasing. The subsequences can appear in any order. >>> seqs = inc_subseqs([1, 3, 2]) >>> sorted(seqs) [[], [1], [1, 2], [1, 3], [2], [3]] >>> inc_subseqs([]) [[]] >>> seqs2 = inc_subseqs([1, 1, 2]) >>> sorted(seqs2) [[], [1], [1], [1, 1], [1, 1, 2], [1, 2], [1, 2], [2]] """ def subseq_helper(s, prev): if not s: return [[]] elif s[0] < prev: return subseq_helper(s[1:], prev) else: a = subseq_helper(s[1:],s[0]) b = subseq_helper(s[1:],prev) return insert_into_all(s[0], a) + b return subseq_helper(s, 0) # Generators def permutations(seq): """Generates all permutations of the given sequence. Each permutation is a list of the elements in SEQ in a different order. The permutations may be yielded in any order. >>> perms = permutations([100]) >>> type(perms) <class 'generator'> >>> next(perms) [100] >>> try: ... next(perms) ... except StopIteration: ... print('No more permutations!') No more permutations! >>> sorted(permutations([1, 2, 3])) # Returns a sorted list containing elements of the generator [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] >>> sorted(permutations((10, 20, 30))) [[10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10]] >>> sorted(permutations("ab")) [['a', 'b'], ['b', 'a']] """ if not seq: yield [] else: for perm in permutations(seq[1:]): for i in range(len(seq)): yield perm[:i] + list(seq[0:1]) + perm[i:] # Tree class class Tree: """ >>> t = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) >>> t.label 3 >>> t.branches[0].label 2 >>> t.branches[1].is_leaf() True """ def __init__(self, label, branches=[]): for b in branches: assert isinstance(b, Tree) self.label = label self.branches = list(branches) def is_leaf(self): return not self.branches def map(self, fn): """ Apply a function `fn` to each node in the tree and mutate the tree. >>> t1 = Tree(1) >>> t1.map(lambda x: x + 2) >>> t1.map(lambda x : x * 4) >>> t1.label 12 >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) >>> t2.map(lambda x: x * x) >>> t2 Tree(9, [Tree(4, [Tree(25)]), Tree(16)]) """ self.label = fn(self.label) for b in self.branches: b.map(fn) def __contains__(self, e): """ Determine whether an element exists in the tree. >>> t1 = Tree(1) >>> 1 in t1 True >>> 8 in t1 False >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) >>> 6 in t2 False >>> 5 in t2 True """ if self.label == e: return True for b in self.branches: if e in b: return True return False def __repr__(self): if self.branches: branch_str = ', ' + repr(self.branches) else: branch_str = '' return 'Tree({0}{1})'.format(self.label, branch_str) def __str__(self): def print_tree(t, indent=0): tree_str = ' ' * indent + str(t.label) + "\n" for b in t.branches: tree_str += print_tree(b, indent + 1) return tree_str return print_tree(self).rstrip() # Link class class Link: """A linked list. >>> s = Link(1) >>> s.first 1 >>> s.rest is Link.empty True >>> s = Link(2, Link(3, Link(4))) >>> s.first = 5 >>> s.rest.first = 6 >>> s.rest.rest = Link.empty >>> s # Displays the contents of repr(s) Link(5, Link(6)) >>> s.rest = Link(7, Link(Link(8, Link(9)))) >>> s Link(5, Link(7, Link(Link(8, Link(9))))) >>> print(s) # Prints str(s) <5 7 <8 9>> """ empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest def __repr__(self): if self.rest is not Link.empty: rest_repr = ', ' + repr(self.rest) else: rest_repr = '' return 'Link(' + repr(self.first) + rest_repr + ')' def __str__(self): string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>' # OOP class Button: """ Represents a single button """ def __init__(self, pos, key): """ Creates a button """ self.pos = pos self.key = key self.times_pressed = 0 class Keyboard: """A Keyboard takes in an arbitrary amount of buttons, and has a dictionary of positions as keys, and values as Buttons. >>> b1 = Button(0, "H") >>> b2 = Button(1, "I") >>> k = Keyboard(b1, b2) >>> k.buttons[0].key 'H' >>> k.press(1) 'I' >>> k.press(2) #No button at this position '' >>> k.typing([0, 1]) 'HI' >>> k.typing([1, 0]) 'IH' >>> b1.times_pressed 2 >>> b2.times_pressed 3 """ def __init__(self, *args): ________________ for _________ in ________________: ________________ def press(self, info): """Takes in a position of the button pressed, and returns that button's output""" if ____________________: ________________ ________________ ________________ ________________ ________________ def typing(self, typing_input): """Takes in a list of positions of buttons pressed, and returns the total output""" ________________ for ________ in ____________________: ________________ ________________ # Nonlocal def make_advanced_counter_maker(): """Makes a function that makes counters that understands the messages "count", "global-count", "reset", and "global-reset". See the examples below: >>> make_counter = make_advanced_counter_maker() >>> tom_counter = make_counter() >>> tom_counter('count') 1 >>> tom_counter('count') 2 >>> tom_counter('global-count') 1 >>> jon_counter = make_counter() >>> jon_counter('global-count') 2 >>> jon_counter('count') 1 >>> jon_counter('reset') >>> jon_counter('count') 1 >>> tom_counter('count') 3 >>> jon_counter('global-count') 3 >>> jon_counter('global-reset') >>> tom_counter('global-count') 1 """ ________________ def ____________(__________): ________________ def ____________(__________): ________________ "*** YOUR CODE HERE ***" # as many lines as you want ________________ ________________ # Mutable Lists def trade(first, second): """Exchange the smallest prefixes of first and second that have equal sum. >>> a = [1, 1, 3, 2, 1, 1, 4] >>> b = [4, 3, 2, 7] >>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7 'Deal!' >>> a [4, 3, 1, 1, 4] >>> b [1, 1, 3, 2, 2, 7] >>> c = [3, 3, 2, 4, 1] >>> trade(b, c) 'No deal!' >>> b [1, 1, 3, 2, 2, 7] >>> c [3, 3, 2, 4, 1] >>> trade(a, c) 'Deal!' >>> a [3, 3, 2, 1, 4] >>> b [1, 1, 3, 2, 2, 7] >>> c [4, 3, 1, 4, 1] """ m, n = 1, 1 equal_prefix = lambda: ______________________ while _______________________________: if __________________: m += 1 else: n += 1 if equal_prefix(): first[:m], second[:n] = second[:n], first[:m] return 'Deal!' else: return 'No deal!' def card(n): """Return the playing card numeral as a string for a positive n <= 13.""" assert type(n) == int and n > 0 and n <= 13, "Bad card n" specials = {1: 'A', 11: 'J', 12: 'Q', 13: 'K'} return specials.get(n, str(n)) def shuffle(cards): """Return a shuffled list that interleaves the two halves of cards. >>> shuffle(range(6)) [0, 3, 1, 4, 2, 5] >>> suits = ['♡', '♢', '♤', '♧'] >>> cards = [card(n) + suit for n in range(1,14) for suit in suits] >>> cards[:12] ['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧'] >>> cards[26:30] ['7♤', '7♧', '8♡', '8♢'] >>> shuffle(cards)[:12] ['A♡', '7♤', 'A♢', '7♧', 'A♤', '8♡', 'A♧', '8♢', '2♡', '8♤', '2♢', '8♧'] >>> shuffle(shuffle(cards))[:12] ['A♡', '4♢', '7♤', '10♧', 'A♢', '4♤', '7♧', 'J♡', 'A♤', '4♧', '8♡', 'J♢'] >>> cards[:12] # Should not be changed ['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧'] """ assert len(cards) % 2 == 0, 'len(cards) must be even' half = _______________ shuffled = [] for i in _____________: _________________ _________________ return shuffled # Recursive Objects def deep_len(lnk): """ Returns the deep length of a possibly deep linked list. >>> deep_len(Link(1, Link(2, Link(3)))) 3 >>> deep_len(Link(Link(1, Link(2)), Link(3, Link(4)))) 4 >>> levels = Link(Link(Link(1, Link(2)), \ Link(3)), Link(Link(4), Link(5))) >>> print(levels) <<<1 2> 3> <4> 5> >>> deep_len(levels) 5 """ if ______________: return 0 elif ______________: return 1 else: return _________________________ def make_to_string(front, mid, back, empty_repr): """ Returns a function that turns linked lists to strings. >>> kevins_to_string = make_to_string("[", "|-]-->", "", "[]") >>> jerrys_to_string = make_to_string("(", " . ", ")", "()") >>> lst = Link(1, Link(2, Link(3, Link(4)))) >>> kevins_to_string(lst) '[1|-]-->[2|-]-->[3|-]-->[4|-]-->[]' >>> kevins_to_string(Link.empty) '[]' >>> jerrys_to_string(lst) '(1 . (2 . (3 . (4 . ()))))' >>> jerrys_to_string(Link.empty) '()' """ def printer(lnk): if ______________: return _________________________ else: return _________________________ return printer def prune_small(t, n): """Prune the tree mutatively, keeping only the n branches of each node with the smallest label. >>> t1 = Tree(6) >>> prune_small(t1, 2) >>> t1 Tree(6) >>> t2 = Tree(6, [Tree(3), Tree(4)]) >>> prune_small(t2, 1) >>> t2 Tree(6, [Tree(3)]) >>> t3 = Tree(6, [Tree(1), Tree(3, [Tree(1), Tree(2), Tree(3)]), Tree(5, [Tree(3), Tree(4)])]) >>> prune_small(t3, 2) >>> t3 Tree(6, [Tree(1), Tree(3, [Tree(1), Tree(2)])]) """ while ___________________________: largest = max(_______________, key=____________________) _________________________ for __ in _____________: ___________________ # Recursion / Tree Recursion def num_trees(n): """How many full binary trees have exactly n leaves? E.g., 1 2 3 3 ... * * * * / \ / \ / \ * * * * * * / \ / \ * * * * >>> num_trees(1) 1 >>> num_trees(2) 1 >>> num_trees(3) 2 >>> num_trees(8) 429 """ if ____________________: return _______________ return _______________ # Tree class class Tree: """ >>> t = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) >>> t.label 3 >>> t.branches[0].label 2 >>> t.branches[1].is_leaf() True """ def __init__(self, label, branches=[]): for b in branches: assert isinstance(b, Tree) self.label = label self.branches = list(branches) def is_leaf(self): return not self.branches def map(self, fn): """ Apply a function `fn` to each node in the tree and mutate the tree. >>> t1 = Tree(1) >>> t1.map(lambda x: x + 2) >>> t1.map(lambda x : x * 4) >>> t1.label 12 >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) >>> t2.map(lambda x: x * x) >>> t2 Tree(9, [Tree(4, [Tree(25)]), Tree(16)]) """ self.label = fn(self.label) for b in self.branches: b.map(fn) def __contains__(self, e): """ Determine whether an element exists in the tree. >>> t1 = Tree(1) >>> 1 in t1 True >>> 8 in t1 False >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) >>> 6 in t2 False >>> 5 in t2 True """ if self.label == e: return True for b in self.branches: if e in b: return True return False def __repr__(self): if self.branches: branch_str = ', ' + repr(self.branches) else: branch_str = '' return 'Tree({0}{1})'.format(self.label, branch_str) def __str__(self): def print_tree(t, indent=0): tree_str = ' ' * indent + str(t.label) + "\n" for b in t.branches: tree_str += print_tree(b, indent + 1) return tree_str return print_tree(self).rstrip() # Link class class Link: """A linked list. >>> s = Link(1) >>> s.first 1 >>> s.rest is Link.empty True >>> s = Link(2, Link(3, Link(4))) >>> s.first = 5 >>> s.rest.first = 6 >>> s.rest.rest = Link.empty >>> s # Displays the contents of repr(s) Link(5, Link(6)) >>> s.rest = Link(7, Link(Link(8, Link(9)))) >>> s Link(5, Link(7, Link(Link(8, Link(9))))) >>> print(s) # Prints str(s) <5 7 <8 9>> """ empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest def __repr__(self): if self.rest is not Link.empty: rest_repr = ', ' + repr(self.rest) else: rest_repr = '' return 'Link(' + repr(self.first) + rest_repr + ')' def __str__(self): string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>'
174437c1bf703c59eaffde53b5b9a8b93e292d21
lebull/AnotherAGC
/cpu.py
2,910
3.640625
4
class Registers(object): REG_A = "A" REG_P = "P" REG_Q = "Q" REG_LP = "LP" class AGC(object): def __init__(self): #The AGC had four 16-bit registers for general computational use, called the central registers: # A: The accumulator, for general computation # Z: The program counter - the address of the next instruction to be executed # Q: The remainder from the DV instruction, and the return address after TC instructions # LP: The lower product after MP instructions #Central registers self.registers = { Registers.REG_A: 0x00, Registers.REG_P: 0x00, Registers.REG_Q: 0x00, Registers.REG_LP: 0x00 } #There were also four locations in core memory, at addresses 20-23, #dubbed editing locations because whatever was stored there would #emerge shifted or rotated by one bit position, except for one that #shifted right seven bit positions, to extract one of the seven-bit #interpretive op. codes that were packed two to a word. #This was common to Block I and Block II AGCs. #The AGC had additional registers that were used internally in the course of operation: # S : 12-bit memory address register, the lower portion of the memory address # Bank/Fbank : 4-bit ROM bank register, to select the 1 kiloword ROM bank when addressing in the fixed-switchable mode # Ebank : 3-bit RAM bank register, to select the 256-word RAM bank when addressing in the erasable-switchable mode # Sbank (super-bank) : 1-bit extension to Fbank, required because the last 4 kilowords of the 36-kiloword ROM was not reachable using Fbank alone # SQ : 4-bit sequence register; the current instruction # G : 16-bit memory buffer register, to hold data words moving to and from memory # X : The 'x' input to the adder (the adder was used to perform all 1's complement arithmetic) or the increment to the program counter (Z register) # Y : The other ('y') input to the adder # U : Not really a register, but the output of the adder (the 1's complement sum of the contents of registers X and Y) # B : General-purpose buffer register, also used to pre-fetch the next instruction. At the start of the next instruction, the upper bits of B (containing the next op. code) were copied to SQ, and the lower bits (the address) were copied to S. # C : Not a separate register, but the 1's complement of the B register # IN : Four 16-bit input registers # OUT : Five 16-bit output registers self.otherRegisters = { } def setRegister(self, register, value): self.registers[register] = value def getRegister(self, register): return self.registers[register] #Timing #Memory #Instruction Set #Interrupts
292d677d9555c1b84da932863a1c897fcc1a4689
SergiBaucells/DAM_MP10_2017-18
/Tasca_3_Python/src/exercici_3_python.py
703
3.9375
4
def comptador(): while True: caracter = input("Introdueix una lletra: ") if(len(caracter)>1 or len(caracter)==0): print("Te que ser un caràcter i/o no pot estar buit!!!") caracter = "caracter" continue else: break while True: cadena = input("Introdueix una cadena: ") if (cadena == ""): print("La cadena no pot estar buida!!") else: comptador = 0 for lletra in cadena: if lletra == caracter: comptador = comptador + 1 print("La lletra",caracter,"està",comptador,"vegades") break print(comptador())
7f3d32aa201c0ab408cab474b6490a9179154c8c
Fouad-Karam/Python-DieRoll-Game
/main.py
1,028
4.1875
4
from art import logo from random import randint print(logo) print("") print("Welcome to Do-Not-Roll-1 game.\n") print("") print("Rules:\n1. Roll a single die, and as long as you don't roll 1, you keep adding the values you get.\n2. Feel lucky? keep rolling.\n3. The moment you roll a 1, you loose and the accumulated total will be shown.") print("") print("===================================") print("Rolling...") print("") def roll_the_die(): repeat = True total = 0 while repeat: roll = randint(1, 6) if roll == 1: print(f"You rolled a {roll}, you loose with a total of {total}!") break else: print(f"You rolled: {roll}") total = total + roll print(f"You total is: {total}") print("Do you want to roll again? Y/N") repeat = "y" in input().lower() else: print(f"You finished with a total of {total}. Thank you for playing. Good Bye!") roll_the_die()
6b01ee8e288c830414a7dbc7d0d3cc018f3ef480
Piratelhx/UrbanGen
/utils.py
6,276
3.640625
4
def crop(image, new_shape): ''' Function for cropping an image tensor: Given an image tensor and the new shape, crops to the center pixels (assumes that the input's size and the new size are even numbers). Parameters: image: image tensor of shape (batch size, channels, height, width) new_shape: a torch.Size object with the shape you want x to have ''' middle_height = image.shape[2] // 2 middle_width = image.shape[3] // 2 starting_height = middle_height - new_shape[2] // 2 final_height = starting_height + new_shape[2] starting_width = middle_width - new_shape[3] // 2 final_width = starting_width + new_shape[3] cropped_image = image[:, :, starting_height:final_height, starting_width:final_width] return cropped_image def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', use_sigmoid=False, init_type='normal', init_gain=0.02, gpu_id='cuda:0'): net = None norm_layer = get_norm_layer(norm_type=norm) if netD == 'basic': net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer, use_sigmoid=use_sigmoid) elif netD == 'n_layers': net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer, use_sigmoid=use_sigmoid) elif netD == 'pixel': net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer, use_sigmoid=use_sigmoid) elif netD == 'activation': net = ActivationDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer, use_sigmoid=use_sigmoid) elif netD == 'classification': net = Classifier(input_nc, len(buildings)) else: raise NotImplementedError( 'Discriminator model name [%s] is not recognized' % net) return init_net(net, init_type, init_gain, gpu_id) def define_G(input_nc, output_nc, ngf, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_id='cuda:0'): net = None norm_layer = get_norm_layer(norm_type=norm) net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9) return init_net(net, init_type, init_gain, gpu_id) def get_gen_class_loss(gen, disc, real, condition, adv_criterion, recon_criterion, lambda_recon): fake = gen(condition) ev = disc(fake, condition[:, :3, :, :]) adv_loss = adv_criterion(ev, torch.ones(ev.shape).to(device)) rec_loss = recon_criterion(fake, real) gen_loss = torch.sum(adv_loss) + (rec_loss * lambda_recon) return gen_loss def get_gen_loss(gen, disc, real, condition, adv_criterion, recon_criterion, lambda_recon): fake = gen(condition) ev = disc(fake, condition) adv_loss = adv_criterion(ev, torch.ones(ev.shape).to(device)) rec_loss = recon_criterion(fake, real) gen_loss = torch.sum(adv_loss) + (rec_loss * lambda_recon return gen_loss def get_norm_layer(norm_type='instance'): if norm_type == 'batch': norm_layer = functools.partial(nn.BatchNorm2d, affine=True) elif norm_type == 'instance': norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False) elif norm_type == 'switchable': norm_layer = SwitchNorm2d elif norm_type == 'none': norm_layer = None else: raise NotImplementedError( 'normalization layer [%s] is not found' % norm_type) return norm_layer def get_scheduler(optimizer): if lr_policy == 'lambda': def lambda_rule(epoch): lr_l = 1.0 - max(0, epoch + epoch_count - niter) / float( niter_decay + 1) print('New lr: {}'.format(lr_l)) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif lr_policy == 'step': scheduler = lr_scheduler.StepLR(optimizer, step_size=lr_decay_iters, gamma=0.1) elif lr_policy == 'plateau': scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5) elif lr_policy == 'cosine': scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=niter, eta_min=0) else: return NotImplementedError( 'learning rate policy [%s] is not implemented', lr_policy) return scheduler def init_net(net, init_type='normal', init_gain=0.02, gpu_id='cuda:0'): net.to(gpu_id) init_weights(net, init_type, gain=init_gain) return net def init_weights(net, init_type='normal', gain=0.02): def init_func(m): classname = m.__class__.__name__ if hasattr(m, 'weight') and ( classname.find('Conv') != -1 or classname.find('Linear') != -1): if init_type == 'normal': nn.init.normal_(m.weight.data, 0.0, gain) elif init_type == 'xavier': nn.init.xavier_normal_(m.weight.data, gain=gain) elif init_type == 'kaiming': nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') elif init_type == 'orthogonal': nn.init.orthogonal_(m.weight.data, gain=gain) else: raise NotImplementedError( 'initialization method [%s] is not implemented' % init_type) if hasattr(m, 'bias') and m.bias is not None: nn.init.constant_(m.bias.data, 0.0) elif classname.find('BatchNorm2d') != -1: nn.init.normal_(m.weight.data, 1.0, gain) nn.init.constant_(m.bias.data, 0.0) print('initialize network with %s' % init_type) net.apply(init_func) def show_image(tensor): _tensor = (tensor + 1) / 2 _tensor = _tensor.detach().cpu()[0] _tensor = _tensor.permute(1, 2, 0).squeeze() plt.imshow(_tensor.numpy()) def save_image(tensor, name): _tensor = (tensor + 1) / 2 _tensor = _tensor.detach().cpu()[0] _tensor = _tensor.permute(1, 2, 0).squeeze() plt.imsave(name + '.png', _tensor.numpy()) def update_learning_rate(scheduler, optimizer): scheduler.step() lr = optimizer.param_groups[0]['lr'] print('learning rate = %.7f' % lr) def weights_init(m): if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d): torch.nn.init.normal_(m.weight, 0.0, 0.02) if isinstance(m, nn.BatchNorm2d): torch.nn.init.normal_(m.weight, 0.0, 0.02) torch.nn.init.constant_(m.bias, 0)
cadeca818aff82697f119f9f4ce30cecbca9cf9c
Shmelnick/lyrics
/collect_data/merge_songs.py
875
3.609375
4
""" merge two songs.csv files in one """ import csv # set input1, input2 and output filenames here INPUT1 = "songs1.csv" INPUT2 = "songs2.csv" OUTPUT = "songs_merged.csv" if __name__=='__main__': csvfile = open(INPUT1, 'rb') reader = csv.reader(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) all_songs = {} for row in reader: if not all_songs.has_key(row[0]): all_songs[row[0]] = row csvfile = open(INPUT2, 'rb') reader = csv.reader(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) for row in reader: if not all_songs.has_key(row[0]): all_songs[row[0]] = row csvfile = open(OUTPUT, 'wb') writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) for song, song_row in all_songs.items(): writer.writerow(song_row)
880bdde2cbb91a1caf2ba6447b45a066d2a385e2
navnee22/Ineuron_MLDL
/python assignment 2.py
593
4.5
4
#!/usr/bin/env python # coding: utf-8 # 1. Create the below pattern using nested for loop in Python # # * # * * # * * * # * * * * # * * * * * # * * * * # * * * # * * # * # In[2]: n=5 for i in range(n): for j in range(i): print("*",end="") print("") for i in range(n,0,-1): for j in range(i): print("*",end="") print("") # 2. Write a Python program to reverse a word after accepting the input from the user. # Input word: ineuron # Output: norueni # In[3]: s= input("please enter the input :") output = s[::-1] print(output) # In[ ]:
8521c07ce8db1afcf06ee6f09888450474da4e2f
nischalshk/IWPython
/DataTypes/6.py
710
4.25
4
# Write a Python program to find the first appearance of the substring 'not' and # 'poor' from a given string, if 'not' follows the 'poor', replace the whole 'not'...'poor' # substring with 'good'. Return the resulting string. # Sample String : 'The lyrics is not that poor!' # 'The lyrics is poor!' # Expected Result : 'The lyrics is good!' # 'The lyrics is poor!' d = input("Enter a text: ") x = d.split(" ") pattern1 = "poor" pattern2 = "not" poor = d.find(pattern1) nott = d.find(pattern2) if poor > -1 and nott > -1: start = poor if poor < nott else nott end = poor + 4 if poor > nott else nott + 3 frontText = d[0:start] backText = d[end:] print(frontText + "good" + backText)
a34aa1edd835953dd7853763a6d185d0a5b5c75f
eddiequezada/Python-Projects
/Story.py
437
3.984375
4
def begin_story(): user_name = input("Please enter your name") print('You are a bandit and have just escaped prison and ran into an alley way that splits in three directions. Which way do you go?') print('Enter the number that corresponds to your decision') user_response = int(input('1. You decide to go right \n2. Your instincts tell you, you should go left \n3. You feel a strange vibe coming from the path straight ahead '))
d720e18755de710e9dbacca7252f58ce9f6e0ea6
bharat-kadchha/tutorials
/core-python/Core_Python/exception/ExceptionMethods.py
552
3.59375
4
''' e. and use all methods ''' ''' also try different exception like java file,array,string,numberformat ''' ''' user define exception ''' try: raise Exception('spam,','eggs') except Exception as inst: print("Type of instance : ",type(inst)) # the exception instance print("Arguments of instance : ",inst.args) # arguments stored in .args print("Instance print : ",inst) # __str__ allows args to be printed directly,but may be overridden in exception subclasses a,b = inst.args # unpack args print("a : ",a) print("b : ",b)
7af99d0d92ca6be5257f30b7629eb3f06c704f3c
MadhanArts/PythonInternshipBestEnlist
/day9_task1.py
177
4.1875
4
multiply = lambda x, y: x * y a = int(input("Enter 1st number : ")) b = int(input("Enter 2nd number : ")) print("Result after multiplying using lambda :", multiply(a, b))
f944441bffd12a80f5c7b8f47719c762b1ae1d24
tsafay/PycharmProjects
/book_learning/automation_py/ch5_字典/ticTacToe.py
788
4.125
4
# -*- coding: utf-8 -*- # @Author : leejufe # @Date : 2020/4/22 10:39 board = {'top_L':' ', 'top_M':' ', 'top_R':' ', 'mid_L':' ', 'mid_M':' ', 'mid_R':' ', 'low_L':' ', 'low_M':' ', 'low_R':' ' } def printBoard(board): print(board['top_L'] + '|' + board['top_M'] + '|' + board['top_R']) print('—+—+—') print(board['mid_L'] + '|' + board['mid_M'] + '|' + board['mid_R']) print('—+—+—') print(board['low_L'] + '|' + board['low_M'] + '|' + board['low_R']) turn = 'X' for i in range(9): printBoard(board) print('Turn for ' + '\'' + turn + '\'' + ' move on which space?') move = input('Enter space:') board[move] = turn if turn == 'X': turn = 'O' else: turn = 'X' printBoard(board)
963feb8fc4aaa22815d0988e12d038b4b60f7ee4
LorranSutter/URI-Online-Judge
/Beginner/1009.py
115
3.53125
4
NAME = input() SALARY = float(input()) MONTANTE = float(input()) print("TOTAL = R$ %.2f" % (SALARY+MONTANTE*0.15))
b521d3660841137b275eb19f4dee6ce4d17b472e
anjinsung/receipt_account
/receipt.py
3,300
3.6875
4
from operator import itemgetter, attrgetter class Receipt: def __init__(self,description,price): self.description = description self.price = price def print_data(self): print("Receipt Description : " + self.description + "\n" + "Receipt Price : " + str(self.price)) # def __lt__(self,other): # return self.price < other.price def main(): border_price = int(input("What is the minimum price? : ")) receipt_data = [] total_price = input_data(receipt_data) receipt_data = sorted(receipt_data, key=lambda receipt: receipt.price ,reverse=True) if(total_price > border_price): total_receipt = compute_receipt(total_price,border_price,receipt_data) def input_data(receipt_data): total_price = 0 while(True): description = input("Please write your receipt description. \n(If you do not have any receipts left, please enter quit) : ") if(description == "quit"): break price = int(input("Please write your receipt price. : ")) total_price += price receipt = Receipt(description,price) receipt_data.append(receipt) receipt_data[len(receipt_data) - 1].print_data() return total_price def compute_receipt(total_price,border_price,receipt_data): i = 0 # 리스트 참조 변수 use_price = 0 # 계산 후 돌려줄 일정 값 이상의 최솟값 use_list = [] # 계산 후 돌려줄 일정 값들의 리스트 모임 second_receipt_data = [] # 영수증 데이터에서 반드시 들어가야 될 값을 제한 나머지 리스트 while(True): if(total_price - receipt_data[i].price < border_price): # 제 1 경우 : 얘가 없으면 안됨 use_price += receipt_data[i].price use_list.append(receipt_data[i]) i += 1 elif(total_price - receipt_data[i].price == border_price): # 제 2 경우 : 얘만 없으면 딱 맞음 use_price = border_price use_list = receipt_data[:i] + receipt_data[i+1:] return [use_price,use_list] else: # 제 3 경우 : 얘는 있어도 되고 없어도 됨 second_receipt_data = receipt_data[i:] break second_border = border_price - use_price # 최소컷을 넘는 값 중에 필수값을 제한 나머지 값을 두번째 최소컷으로 잡음 second_lower_border_list = [] # 2차 최소컷을 못 넘는 값들을 과정마다 저장함 least_upper_second_border = total_price # 2차 최소컷 넘는 값 중에 최소값 least_upper_second_border_list = [] # 2차 최소컷 넘는 값 중에 최소값들 리스트 while(True): # 배열 중 2개를 더함 for x in range(len(second_receipt_data)): for y in range(x+1,len(second_receipt_data)): tmp = second_receipt_data[x] + second_receipt_data[y] if(tmp > second_border and least_upper_second_border > tmp): least_upper_second_border = tmp least_upper_second_border_list = [second_receipt_data[x],second_receipt_data[y]] else: pass return [use_price,use_list] if __name__ == "__main__": main()
a3d10c634fcf053dbac02eb5d911b8b930fc87fa
otomori-k/python
/Demo0926_A.py
1,198
4.03125
4
# 四則演算 1 + 2 1 - 2 4 * 5 7 / 5 # べき乗 3 ** 2 # データ型 type(10) type(2.718) type("hello") # 変数 x = 10 print(x) x = 100 print(x) y = 3.14 x * y type(x * y) # リスト a = [1, 2, 3, 4, 5] print(a) len(a) a[0] a[4] a[4] = 99 print(a) # スライシング # 0番目から2番目まで(2番目は含まない) a[0:2] # 1番目から最後まで a[1:] # 最初から3番目まで(3番目は含まない) a[:3] # 最初から最後の要素の1つ前まで a[:-1] # 最初から最後の要素の2つ前まで a[:-2] # ディクショナリ me = {'height':180} me['height'] me['weight'] = 70 print(me) # ブーリアン hungry = True sleepy = False type(hungry) not hungry hungry and sleepy hungry or sleepy # if文 hungry = True if hungry: print("I'm hungry") hungry = False if hungry: print("I'm hungry") else: print("I'm not hungry") print("I'm sleepy") # for文 for i in [1, 2, 3]: print(i) # 関数 def hello(): print("Hello World!") hello() def hello(object): print("Hello " + object + "!") hello("cat")
58ead9ce3f69b1fa997cbdfb9d3f111dc08c728a
scqsryws/DemoPractice
/blg/drawTree.py
653
3.984375
4
# 分支树 from turtle import Turtle def tree(plist, l, a, f): if l > 5: lst = [] for p in plist: p.forward(l) q = p.clone() p.left(a) q.right(a) lst.append(p) lst.append(q) tree(lst, l * f, a, f) def main(): p = Turtle() # 笔尺寸 p.pensize(5) # 笔颜色 p.color("green") # 隐藏箭头 p.hideturtle() # p.getscreen() # 画笔转向 p.left(90) # 提笔 p.penup() # 移动画笔到(x,y)处 p.goto(0, 0) # 落笔 p.pendown() tree([p], 200, 65, 0.6375) main()
9580a8dadb970abf8e60d917fe7af2f0f5e24ca3
drudolpho/Sorting
/src/iterative_sorting/iterative_sorting.py
1,265
4.09375
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for ii in range(cur_index + 1, len(arr)): if arr[ii] < arr[smallest_index]: smallest_index = ii # TO-DO: swap temp = arr[cur_index] arr[cur_index] = arr[smallest_index] arr[smallest_index] = temp return arr # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): swap_count = 1 while swap_count >= 1: swap_count = 0 for i in range(0, len(arr) - 1): if arr[i] > arr[i + 1]: temp = arr[i] arr[i] = arr[i + 1] arr[i + 1] = temp swap_count += 1 return arr array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] array2 = [76, 44, 3, 12, 60, 71, 100, 34, 22, 38, 99, 74, 45, 3, 67, 2] print(selection_sort(array)) print(bubble_sort(array)) print(selection_sort(array2)) print(bubble_sort(array2)) # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): return arr
9cd1b812b933b27bff4369a88f049283a914edd1
awuerf4505/caesar-crypt-decrypt
/caesar_cipher.py
971
3.9375
4
def shift(letter, n): unicode_value = ord(letter) + n if unicode_value > 126: value = unicode_value - 126 unicode_value == 32 + value return chr(unicode_value) if unicode_value < 32: n = 32 - unicode_value unicode_value = 126 - n return chr(unicode_value) def encrypt(message, shift_amount): result = "" for letter in message: result += shift(letter, shift_amount) return result def decrypt(message, shift_amount): result = "" for letter in message: result += shift(letter, shift_amount) return result secret_message = "encryption is fun" encrypted_message = encrypt(secret_message, 5) decrypted_message = decrypt(encrypted_message, -5) print(secret_message) print(encrypted_message) print(decrypted_message) with open('caesar_sample_run.txt', 'w') as f: f.write(encrypted_message + "\n") f.write(decrypted_message)
7cee8ab79039f50ab96616f2b1d13c4f1e6074b0
reinaaa05/python
/paiza_02/paiza_02_002_001.erb
313
3.71875
4
# coding: utf-8 # if文による条件分岐 import random number = random.randint(1, 5) print("あなたの順位は" + str(number) + "位です") # ここにif文を追加する if number == 1: print("おめでとう") elif number == 2: print("あと少し") else: print("よくがんばったね")
257f1bfd2a75bea5ed865d19570878995cff1ebe
jiwon-0129/likelion_jw
/파이썬과제1_jiwon.py
397
4.03125
4
the_answer = {"현숙": "이화여대 멋사 대표님", "세은": "파이썬 세션 튜터", "두희": "멋사 창립자", "마루": "야옹"} for i in the_answer: print("다음은 누구에 대한 설명일까요?") print(the_answer[i]) n=input() if the_answer[i]==the_answer.get(n): print("정답입니다.") else: print("오답입니다.") continue
56e9dd46ca8d3e2cba9186400404d4353914a0fc
chloeward00/CA117-Computer-Programming-2
/labs/swap_v2_042.py
377
3.703125
4
def swap_unique_keys_values(b): swapped_dictionary = {} for i in b: if b[i] in swapped_dictionary: del (swapped_dictionary[b[i]]) else: swapped_dictionary[b[i]] = i return swapped_dictionary def main(): x = {1: "a", 2: "b", 3: "c", 4: "c"} print (swap_unique_keys_values(x)) if __name__ == "__main__": main()
61501ecef813f8f4dec7680aecbc9da114f67ea5
sgozen/BootCamp2018
/ProbSets/Comp/ProbSet1/Calculator.py
229
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 25 19:47:41 2018 @author: suleymangozen """ import math def sum (a, b): return a + b def sqrt(a): return math.sqrt(a) def prod(a,b): return a*b
1058c5012d8cbd4777dba24f6f94e36525b888ee
yogeshoyadav08/sample_repo
/Day 3/city.py
256
4.03125
4
l1={"mumbai":"maharashtra","ranchi":"Jharkhand","ahemdabad":"gujarat"} #st=str(raw_input("Enter a city:")) print(l1[str(raw_input("Enter a city:"))]) #s=str(raw_input("Enter a state:")) print l1.keys()[l1.values().index(str(raw_input("Enter a state:")))]
4ff162f01df4ce1e7227f829379987f9f494303a
codeamt/udacity-dsa-nand
/3_004_Project_3_dsa/04_Problem_4.py
3,438
4.0625
4
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted Note: """ if input_list is None or len(input_list) <= 1: return input_list # positional indices low = 0 # store next position of smaller element from beginning mid = 0 # position of the element to be compared high = len(input_list) - 1 # store next position of greater element from end # iterate till all elements are sorted while mid <= high: if input_list[mid] == 0 and input_list[low] in [0, 1, 2]: # temp = input_list[low] # input_list[low] = input_list[mid] # input_list[mid] = temp : Swap optimized below Pythonic way :) if input_list[low] != 0: input_list[low], input_list[mid] = input_list[mid], input_list[low] low += 1 mid += 1 elif input_list[mid] == 1: mid += 1 elif input_list[mid] == 2 and input_list[high] in [0, 1, 2]: # temp = input_list[mid] # input_list[mid] = input_list[high] # input_list[high] = temp : Swap optimized below Pythonic way :) if input_list[high] != 2: input_list[mid], input_list[high] = input_list[high], input_list[mid] high -= 1 else: # element in the array out of the range [0, 1, 2] return input_list return input_list def test_function(test_case): sorted_array = sort_012(test_case[0]) solution = test_case[1] if sorted_array == solution: return "Pass" else: return "Fail" # Udacity supported test print("------- \t Udacity supported test \t -------") arr = [0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) arr = [2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # sorted arr = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # Arbitray input print("------- \t Arbitrary test \t -------") # all zeros arr = [0, 0, 0, 0, 0, 0] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # all ones arr = [1, 1, 1, 1, 1, 1] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # all twos arr = [2, 2, 2, 2, 2, 2] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # descending arr = [2, 2, 1, 1, 0, 0] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # single element arr = [0] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # two elements arr = [2,1] sol = sorted(arr) test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) print("------- \t Not valid input \t -------") # None arr = None sol = None test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # empty arr = [] sol = [] test = test_function([arr, sol]) print('{} \t {}'.format(sol, test)) # partially sorted arr = [2, 0, 1, 4, 0, 6, 2, 1, 2] sol = [0, 1, 1, 4, 0, 6, 2, 2, 2] test = test_function([arr, sol]) print('{} \t {}'.format(sol, test))
2960d2b03cdb474be1e51c4e1d1227adcefef5b2
JohannesBuchner/pystrict3
/tests/data23/recipe-302697.py
3,882
3.828125
4
'''\ An experiment with python properties using TVM equations as an example A TVM object works like a financial calculator. Given any four of (n, i, pmt, pv, fv) TVM object can calculate the fifth. This version assumes payments are at end of compounding period. Example: >>> loan=TVM() >>> loan.n=3*12 # set number of payments to 36 >>> loan.pv=6000 # set present value to 6000 >>> loan.i=6/12. # set interest rate to 6% annual >>> loan.fv=0 # set future value to zero >>> loan.pmt # ask for payment amount -182.5316247083343 # payment (note sign) Alternative style: >>> TVM(n=36, pv=6000, pmt=-200, fv=0).i*12 12.2489388032796 ''' from math import log class TVM (object): '''A Time Value of Money class using properties''' def __init__(self, n=None, i=None, pv=None, pmt=None, fv=None): self.__n=n self.__i=i self.__pv=pv self.__pmt=pmt self.__fv=fv def __repr__(self): return "TVM(n=%s, i=%s, pv=%s, pmt=%s, fv=%s)" % \ (self.__n, self.__i, self.__pv, self.__pmt, self.__fv) def __get_a(self): '''calculate 'a' intermediate value''' return (1+self.__i/100)**self.__n-1 def __get_b(self): '''calculate 'b' intermediate value''' return 100/self.__i def __get_c(self): '''calculate 'c' intermediate value''' return self.__get_b()*self.__pmt def get_n(self): c=self.__get_c() self.__n = log((c-self.__fv)/(c+self.__pv))/log(1+self.__i/100) return self.__n def set_n(self,value): self.__n=value n = property(get_n, set_n, None, 'number of payments') def get_i(self): # need to do an iterative solution - no closed form solution exists # trying Newton's method INTTOL=0.0000001 # tolerance ITERLIMIT=1000 # iteration limit # initial guess for interest if self.__i: i0=self.__i else: i0=1.0 # 10% higher interest rate - to get a slope calculation i1=1.1*i0 def f(tvm,i): '''function used in Newton's method; pmt(i)-pmt''' a = (1+i/100)**self.__n-1 b = 100/i out = -(tvm.__fv+tvm.__pv*(a+1))/(a*b)-tvm.__pmt return out fi0 = f(self,i0) if abs(fi0)<INTTOL: self.__i=i0 return i0 else: n=0 while 1: # Newton's method loop here fi1 = f(self,i1) if abs(fi1)<INTTOL: break if n>ITERLIMIT: print("Failed to converge; exceeded iteration limit") break slope=(fi1-fi0)/(i1-i0) i2=i0-fi0/slope # New 'i1' fi0 = fi1 i0=i1 i1=i2 n+=1 self.__i = i1 return self.__i def set_i(self,value): self.__i=value i = property(get_i, set_i, None, 'interest rate') def get_pv(self): a=self.__get_a() c=self.__get_c() self.__pv = -(self.__fv+a*c)/(a+1) return self.__pv def set_pv(self,value): self.__pv=value pv = property(get_pv, set_pv, None, 'present value') def get_pmt(self): a=self.__get_a() b=self.__get_b() self.__pmt = -(self.__fv+self.__pv*(a+1))/(a*b) return self.__pmt def set_pmt(self,value): self.__pmt=value pmt = property(get_pmt, set_pmt, None, 'payment') def get_fv(self): a=self.__get_a() c=self.__get_c() self.__fv = -(self.__pv+a*(self.__pv+c)) return self.__fv def set_fv(self,value): self.__fv=value fv = property(get_fv, set_fv, None, 'future value')
f86b71ecfff7440fc417ca0bd50ab03710be1ab3
creep1g/Datastructures-RU
/practice-tests/FinalExamSpring2020_solutions/P4/wait_list.py
4,099
3.703125
4
class Student: def __init__(self, id, name, phone, address): self.id = id self.name = name self.phone = phone self.address = address def __str__(self): return str(self.id) + " " + str(self.name) + " " + str(self.phone) + " " + str(self.address) def __lt__(self, other): return self.name < other.name class FunCourse: def __init__(self, max_participants): self.course_list = {} self.wait_list = [] self.max_participants = max_participants def add_student(self, student): if len(self.course_list) < self.max_participants: self.course_list[student.id] = student else: self.wait_list.append(student) def remove_student(self, id): try: del self.course_list[id] # THIS SHOULD ONLY HAPPEN IF SOMEONE WAS ACTUALLY REMOVED FROM THE COURSE if len(self.wait_list) > 0: student = self.wait_list.pop(0) self.course_list[student.id] = student except: for student in self.wait_list: if student.id == id: self.wait_list.remove(student) def get_participant_string(self): ordered_list = [] for id in self.course_list: ordered_list.append(self.course_list[id]) ordered_list.sort() ret_str = "" for student in ordered_list: ret_str += str(student) + "\n" return ret_str def get_wait_list_string(self): ret_str = "" for student in self.wait_list: ret_str += str(student) + "\n" return ret_str if __name__ == "__main__": course = FunCourse(3) course.add_student(Student(123, "Kári Halldórsson", "1234567", "Heimahagar 57")) course.add_student(Student(176, "Guðni Magnússon", "87685", "Heimahlíð 2")) course.add_student(Student(654, "Jón Jónsson", "54321", "Heimaholt 54")) course.add_student(Student(12, "Holgeir Friðgeirsson", "2354456567", "Heimateigur 65")) course.add_student(Student(32, "Geir Friðriksson", "99875", "Heimageisli 12")) print() print("COURSE PARTICIPANTS:") print(course.get_participant_string()) print("WAIT LIST:") print(course.get_wait_list_string()) print() course.remove_student(654) print("COURSE PARTICIPANTS:") print(course.get_participant_string()) print("WAIT LIST:") print(course.get_wait_list_string()) print() course.remove_student(176) print("COURSE PARTICIPANTS:") print(course.get_participant_string()) print("WAIT LIST:") print(course.get_wait_list_string()) print("\n\nSOME EXTRA TEST added after exam\n") course = FunCourse(3) course.add_student(Student(123, "Kári Halldórsson", "1234567", "Heimahagar 57")) course.add_student(Student(176, "Guðni Magnússon", "87685", "Heimahlíð 2")) course.add_student(Student(654, "Jón Jónsson", "54321", "Heimaholt 54")) course.add_student(Student(12, "Holgeir Friðgeirsson", "2354456567", "Heimateigur 65")) course.add_student(Student(32, "Geir Friðriksson", "99875", "Heimageisli 12")) print() print("COURSE PARTICIPANTS:") print(course.get_participant_string()) print("WAIT LIST:") print(course.get_wait_list_string()) print() course.remove_student(12) print("COURSE PARTICIPANTS:") print(course.get_participant_string()) print("WAIT LIST:") print(course.get_wait_list_string()) print() course.remove_student(000) print("COURSE PARTICIPANTS:") print(course.get_participant_string()) print("WAIT LIST:") print(course.get_wait_list_string()) print() course.remove_student(654) print("COURSE PARTICIPANTS:") print(course.get_participant_string()) print("WAIT LIST:") print(course.get_wait_list_string()) print() course.remove_student(176) print("COURSE PARTICIPANTS:") print(course.get_participant_string()) print("WAIT LIST:") print(course.get_wait_list_string())
efd1f9e5cdd1e5fee46f652f28e62cfd1ac09976
Mynuddin-dev/Practice-Python-01
/Function/factorial.py
847
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sun May 31 22:18:00 2020 @author: Mynuddin """ def factorial(n): fact=1 for i in range(1,n+1): fact=fact*i return fact x=int(input("Please enter your value:")) result=factorial(x) print("The factorial of", x," is :",result) #------------------------Recursion------------------------ import sys sys.setrecursionlimit() # You can set any value print(sys.getrecursionlimit()) def great(): print("Software Engineering,IIT") great() great() def factorial(n): if(n==0): return 1 elif(n==1): return 1 else: return n*factorial(n-1) x=int(input("Please enter your value:")) result=factorial(x) print("The factorial of", x," is :",result)
7e75f8025c0b58f8c1f1130d3f62d8a5a7eba82e
Nicola-Nardella/SomeCode
/BinarySerch.py
629
3.921875
4
# Serch algorithm in an ordered list def binary_search(list, n, x): '''Binary serch.''' i = 0 j = n - 1 while (i <= j): middle = int((i + j) / 2) if (x < list[middle]): j = middle - 1 elif (x > list[middle]): i = middle + 1 else: return middle return -1 # MAIN. l = [3, 4, 5, 13, 20, 21, 30, 33, 34, 35] # Example List i = binary_search(l, 10, int(input("Insert number to search in the list: "))) if (i >= 0): print("\nElement found in position %s\n" % i) else: print("Element not found!") input("Press Enter to continue...")
d7632bef393acee0420b68d6cd09c5188275e05a
yuyuOWO/source-code
/Python/拓扑排序.py
1,381
3.875
4
def topo_sort(graph): queue = [] for x in graph: if graph[x]["indegree"] == 0: queue.append(x)#首先将孤立的点都加入队列中 order_list = [] while len(order_list) != len(graph):#如果没有将所有顶点排完序 cur = queue.pop(0) order_list.append(cur) #每添加完一个新的顶点,将该顶点的所有邻接顶点入度都减1 for x in graph[cur]["adjacents"]: graph[x]["indegree"] -= 1 if graph[x]["indegree"] == 0:#如果减一后入度为0, 那么添加到队列中 queue.append(x) return order_list def init_graph(): graph = {} n = int(input())#输入顶点数目 for x in range(n): name = input()#输入顶点 adjs = list(map(str, input().strip().split()))#输入该顶点的邻接顶点 graph[name] = {"indegree" : 0, "adjacents" : adjs}#保存默认入度0, 和邻接点列表 for x in graph:#计算没个点的入度 for adj in graph[x]["adjacents"]: graph[adj]["indegree"] += 1 return graph#返回图 graph = init_graph() for x in graph: print(x, graph[x]["indegree"], graph[x]["adjacents"]) order_list = topo_sort(graph) print(order_list) ''' 9 undershorts pants shoes pants shoes belt belt jacket shirt tie belt tie jacket socks shoes watch jacket shoes '''
7f0f303a4a5578f1ef864e4f5f6decd65c5e4877
AdamZhouSE/pythonHomework
/Code/CodeRecords/2313/60787/312181.py
215
3.609375
4
n,root=[int(x) for x in input().split()] tree=dict() for i in range(n): p,l,r = [int(x) for x in input().split()] tree[p] = tuple([l,r]) print(n,root) #if n==3 and root==2: #print(true) #print(true)
07392e6c7de160cf7ad07723989c40407e306664
Combatd/learn_python
/timedeltas_start.py
900
4.03125
4
from datetime import date from datetime import time from datetime import datetime from datetime import timedelta def main(): print(timedelta(days=365, hours = 5, minutes = 1)) now = datetime.now() print("Today is: " + str(now)) print("One year from now it will be: " + str(now + timedelta(days = 365))) print("In 2 days and 3 weeks, it will be " + str(now + timedelta(days = 2, weeks = 3))) t = datetime.now() - timedelta(weeks=1) s = t.strftime("%A %B %d, %Y") print("One week ago it was " + s) today = date.today() afd = date(today.year, 4, 1) if afd < today: print("April fools day already went by %d days ago" % ((today-afd).days) ) afd = afd.replace(year = today.year + 1) time_to_afd = afd - today print("It's just", time_to_afd.days, "days until April Fool's Day") if __name__ == "__main__": main()
071816373de2e12d580f63af6a62e60a51fc18ae
vieiraguivieira/PhytonStart
/ifchallenge.py
474
4.1875
4
name = input("What's your name? ") age = int(input("How old are you? ")) if 18 < age <= 29: print("Welcome to the holidays {}!".format(name)) else: print("Go away {}!! You are {} years old!".format(name, age)) # tim solution # name = input("Please enter your name: ") # age = int(input("How old are you? ")) # if 18 <= age < 31: # print("Welcome to club 18-30 holidays, {0}".format(name)) # else: # print("I'm sorry, our holidays are only for cool people")
9d6cf0eb03f0fd8b98014601d597dd31b79ce84f
vitalii-vorobiov/lab_one
/task5.py
1,730
3.59375
4
def read_file(path): """ (str) -> (set) Return set of lines from file """ lst = set() f = open(path,'r') for one_line in f.readlines()[1:]: lst.add((one_line.split()[0], float(one_line.split()[1]), int(one_line.split()[2]))) f.close() return lst def votes_dict(lines_set,num_v): """ (set) -> (dict) Return dict from set of lines if number of votes > num_v """ dict_votes = {} for one_film in lines_set: if one_film[2] > num_v: if one_film[1] in dict_votes: dict_votes[one_film[1]].append(one_film[0]) else: dict_votes[one_film[1]] = [one_film[0]] return dict_votes def films_id(n,dict_votes): """ (int,dict) -> (set) Return set of n films id with highest rating """ chosen = 0 chosen_list = set() while chosen <= n: max_rating = max(dict_votes) if len(dict_votes[max_rating]) >= n - chosen: print(len(dict_votes[max_rating])) chosen_list.update(set(dict_votes[max_rating][0:n - chosen])) break else: chosen += len(dict_votes[max_rating]) chosen_list.update(set(dict_votes[max_rating])) dict_votes.pop(max_rating) return chosen_list def write_films_id(set_films_id): """ (set) -> None Write films_id to file """ f = open('result.txt','w') for one_film in set_films_id: f.write(one_film + '\n') f.close() def find_films_id(n,num_v): """ (int,int) -> None """ path = input("Enter path to file and its name ") write_films_id(films_id(n,votes_dict(read_file(path),num_v)))
4cb91c7683538505af257238da6c4885ec5daf06
algometrix/LeetCode
/Assessments/MathWorks/power_generator.py
441
3.5
4
import collections def segment(x, space): window = collections.deque() out = [] for i, n in enumerate(space): while window and space[window[-1]] > n: window.pop() window += i, if window[0] == i - x: window.popleft() if i >= x - 1: out += space[window[0]], return max(out) if __name__ == "__main__": nums = [7,1,3] k = 2 print(segment(k, nums))
c971bf5502e0f44f6c9242b3c45b973d0ffd0c90
nakhan98/CodeEval
/moderate/sum_to_zero.py
731
3.84375
4
#!/usr/bin/env python2 """ - CodeEval: Sum to Zero - https://www.codeeval.com/open_challenges/81/ """ from sys import argv from itertools import combinations N = 4 def find_sums_to_zero(numbers, n): """ Find and return combinations of n which sum to zero """ combs_to_zero = [] for comb in combinations(numbers, n): if sum(comb) == 0: combs_to_zero.append(comb) return combs_to_zero def main(): with open(argv[1]) as fh: for line in fh: numbers = line.rstrip().split(',') numbers = [int(i) for i in numbers] sums_to_zero = find_sums_to_zero(numbers, N) print(len(sums_to_zero)) if __name__ == "__main__": main()
754f50bb3f50a8eb94335149e30aee59aa13ef6d
cbass2404/bottega_classwork
/python/file_systems/file_systems.py
335
3.75
4
""" open takes two arguments (file_name, how_to_open_it) w+ tells it to write """ # file_builder = open("logger.txt", "w+") # file_builder.write("Hey, I'm in a file!") # file_builder.close() # file_builder = open("logger.txt", "w+") # # for i in range(1000): # file_builder.write(f"I'm on line {i+1}\n") # # file_builder.close()
07e77b6f044244e7a7f916cb4a1de2acb19ebc8c
rtminerva/hybrid-simulation
/Old Files (Unused)/For Testing Only/solve_lin_sys.py
816
4.09375
4
import numpy from numpy import matrix from numpy import linalg # A = numpy.zeros(shape=(3,3)) # A = numpy.eye(3, k = 1) # print A # A = numpy.zeros(shape=(3,3)) A = matrix( [[1,2,3],[11,12,13],[21,22,23]] ) # Creates a matrix. B = matrix( [[1,2,3],[11,12,13],[21,22,23]] ) # Creates a matrix. x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector). y = matrix( [[1,2,3]] ) # A[0,1] = 100 # print A # Creates a matrix (like a row vector). # print A.T # Transpose of A. # print A*x # Matrix multiplication of A and x. # print A.I # Inverse of A. print linalg.solve(A, x) # Solve the linear equation system. C = numpy.eye(9) print numpy.insert(C,A,axis = 1)