blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
ec766ca884efc1dd2fa42853eb1c3445fb81635a
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Nilo_3ed/cap06/Exercicio_06-07.py
651
3.96875
4
expressao = input("Insira a expressão apenas com parẽnteses") contador = 0 pilha =[] while contador < len(expressao): #Cria um laço para percorrer a expressão if expressao[contador] == "(": pilha.append('(') # Adiciona ( a pilha if expressao[contador] == ")": if len(pilha) > 0: # Verifica se a pilha está vazia pilha.pop(-1) # pilha não está vazia, sendo assim retira-se o elemento do topo else: pilha.append(")") # pilha vazia, então occorrreu um erro pois o elemento ) veio sem um ( break contador+=1 if len(pilha) == 0: print('OK') else: print('Erro')
337039a59e6ca3b1194b10d3bb19d0b4a5a6303e
koiic/python_mastery
/advance/processing.py
531
3.53125
4
import time from multiprocessing import Pool, Process import random def f(x): return x + x class Processor(Process): def __init__(self, number): Process.__init__(self) self._number = number def run(self): sleep = random.randrange(1, 10) time.sleep(sleep) print(f'Worker {self._number}, slept for {sleep} seconds') if __name__ == '__main__': for i in range(1, 6): t = Processor(i) t.start() # with Pool(5) as p: # print(p.map(f, [1, 2, 3]))
4e34e55f043f2b883beacdcee6f9791e548b0db1
goginenigvk/PythonSep_2019
/Python_OOPS/sumofdiffrentnumbers.py
258
3.59375
4
class MultipleAddition: def sum(self,*numbers): total='' for num in numbers: total=total+num print('Result is ',total) add=MultipleAddition() add.sum(1,'two') add.sum('two','three','four')
cf17b540412fd0d01628418dab909ab23235f607
fatihcihant/ProjectEuler
/projectEuler06.py
180
3.53125
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 14 20:48:40 2020 @author: fatih cihan """ sum1 = 0 sum2 = 0 for i in range(1,101): sum1 += i**2 sum2 += i print(sum2**2 - sum1)
e196140898d4d3a4136964bc60ab081845aacb81
Woetha/ThomasMore-Python
/Pycharm20-21/C3 Iteration/Ex3_FathersAge.py
679
4.0625
4
# Program tells when your father is twice your age my_age = int(input("How old are you: ")) fathers_age = int(input("How old is your father: ")) years = 0 answer = True # Keep testing until my father is twice my age while fathers_age != my_age * 2: if fathers_age <= my_age or fathers_age > 110: # If it is not possible print("This is not possible") fathers_age = my_age * 2 answer = False # Stops the other answer else: fathers_age += 1 my_age += 1 years += 1 if answer: print("Within", years, " Your father will be twice your age.") print("Your father will be", fathers_age, "and you will be", my_age, "years.")
783275989d61b14c87e721bfbed8097d15d78744
MartenSkogh/QiskitVQEWrapper
/vqe_wrapper/index_mapping.py
4,594
4.0625
4
def total_parity(n): """ Checks the binary parity of the value `n`. 01001 is even parity, 011001 is odd parity. :param n: any positive integer :returns: 1 for odd parity, 0 for even parity. """ if n == 0: return 0 N = int(np.ceil(np.log2(n))) if 2 ** N == n: N += 1 set_bits = 0 for i in range(N): if n & 2**i: set_bits += 1 return set_bits % 2 def parity_representation(n, N): """ Converts from the Fock representation to the parity representation. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :returns: the integer representing the parity mapped value """ if n == 0: return 0 mask = 2 ** (N) - 1 parity_value = 0 for i in range(N): parity_value = parity_value << 1 if total_parity(n & mask): parity_value += 1 #print(f'{n} = {n:b}: {mask:04b} {n & mask:04b} {parity_value:04b}') mask = (mask - 1) >> 1 return parity_value def fock_representation(n, N): """ Converts from the parity representation to the Fock representation. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :returns: the integer representing the Fock mapped value """ mask = 2 ** (N) - 1 fock_rep = n ^ (n << 1) #print(f'{n} = {n:b}: {fock_rep:04b} {mask:04b}') return fock_rep & mask def z2_reduction(n, N): """ Performs so-called Z2-symmetry reduction on a parity representation. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :returns: the integer representing the Z2 reduced parity value """ lower_mask = 2 ** (N//2 - 1) - 1 upper_mask = lower_mask << N//2 z2_reduced = (n & lower_mask) + ((n & upper_mask) >> 1) #print(f'{n} = {n:0{N}b} : {z2_reduced:0{N-2}b} {lower_mask:0{N}b} {upper_mask:0{N}b}') return z2_reduced def z2_expansion(n, N, n_a, n_b): """ Performs so-called Z2-symmetry expansion on a parity representation. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :param n_a: the number of alpha electrons :param n_b: the number of beta spin electrons :returns: the integer representing the parity value after expansion """ lower_mask = 2 ** (N//2) - 1 upper_mask = lower_mask << N//2 z2_expanded = (n & lower_mask) + (((n_a) % 2) << N//2) + ((n & upper_mask) << 1) + (((n_a + n_b) % 2) << (N + 1)) #print(f'{n} = {n:0{N}b} : {z2_expanded:0{N+2}b} {lower_mask:0{N+2}b} {upper_mask:0{N+2}b}') return z2_expanded # For Fock representations def num_alpha(n, N): """ Counts the number of alpha electrons in a Fock representation. Assumes that the orbitals are sorted by spin first. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :returns: an integer giving the number of alpha electrons """ lower_mask = (2 ** (N//2) - 1) masked = (n & lower_mask) counter = 0 indexer = 1 for i in range(N//2): counter += bool(masked & indexer) indexer = indexer << 1 return counter # For Fock representations def num_beta(n, N): """ Counts the number of beta electrons in a Fock representation. Assumes that the orbitals are sorted by spin first. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :returns: an integer giving the number of alpha electrons """ upper_mask = (2 ** (N//2) - 1) << N//2 masked = (n & upper_mask) counter = 0 indexer = 2 ** (N//2) for i in range(N//2): counter += bool(masked & indexer) # a bool is automatically cast to 1 or 0 indexer = indexer << 1 return counter def z2_parity_to_fock(n, N, n_a, n_b): """ Performs so-called Z2-symmetry expansion on a Z2 reduced parity representation and returns a Fock representation. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :param n_a: the number of alpha electrons :param n_b: the number of beta spin electrons :returns: the integer representing the Fock value after expansion and mapping """ parity_rep = z2_expansion(n, N, n_a, n_b) fock_rep = fock_representation(parity_rep, N+2) return fock_rep
6f491931df419f7a2fcb78d8e50e03f6b924bdce
824zzy/SocialNetwork_spectral_cluster_algrithrom
/Social_Network_Graph/lib/laplacian.py
572
4.03125
4
# encoding=utf-8 # 求图的拉普拉斯矩阵 laplacian matrix of a graph import numpy as np def laplacian(A): #get size of A size_of_A = A.shape n = size_of_A[0] m = size_of_A[1] if( n != m): print "Matrix must be a square" return #transposed_A = np.transpose(A) #or_A = A|transposed_A d=(n,m) L = np.zeros(d) for i in range(0,n): for j in range(0,m): if(A[i][j] == A[j][i] and A[i][j] != 0): L[i][j] = -1 L[j][i] = -1 L = L - np.diag(sum(L)) return L
1e80d23c7b4ce4d0e78b17f59f5fadf0030d8c9f
dark4igi/atom-python-test
/coursera/Chapter_7.py
479
4.03125
4
### Data type ##file # example open file xfile = open (file.txt) for line in xfile: print (line ) ## work with strings # line.rstrip() # strip whitespaces and newline from the right-hand of the string line.startswith('some text') # became true if line starts with 'some text' line.upper() # upper case for line line.lower() # lower case for line line[20:] # string after 20 chapter line[:20] # string before 20 chapter line [3:8] # string from 3rd to 8th, not include 8th
c70f3002f1e4824c8fcb8599ba4cd6a67c564d04
VakhoGeoLab/J_davalebebi
/Davaleba_5.py
314
3.828125
4
def acronym(string): word_list = string.split() #print(word_list) char_list = [] for item in word_list: char_list.append(item[0]) acro = "".join(char_list) print(acro) def main(): #print("hello world") sentence = "trakshi pari draki" acronym(sentence) main()
705a3e13381e8f2c8cc2387f9955ad50895be75d
seanho00/twu
/python/.old/sumsquares.py
558
4.25
4
"""Calculate the sum of squares up to an integer. Sean Ho CMPT14x Fall 2008 """ def sum_squares(n): """Return the sum of squares from 1**2 up to n**2. n must be a positive integer.""" sum = 0 for counter in range(n+1): sum += counter*counter return sum # Main program num = 1 while True: num = input("Enter a positive integer [0 to quit]: ") if type(num) != type(0) or num <= 0: break print " Sum from 1**2 up to %d**2 = %d." % (num, sum_squares(num)) print "Goodbye! Press <Enter> to close." raw_input()
1bc2f6d169739c7f7925f28af9142918757017ac
Tankino/rosemary.py
/pancakes.py
821
3.734375
4
from kitchen import Rosemary from kitchen.utensils import Pan, Plate, Bowl from kitchen.ingredients import Egg, Flour, Milk, Salt, Butter #Putting 2 eggs in a bowl and mixing bowl=Bowl.use(name='Pancake') for i in range(2): egg = Egg.take() egg.crack() bowl.add(egg) bowl.mix() bowl.add(Salt.take('Dash')) #Mixing in the flour in batches for i in range(5): bowl.add (Flour.take(grams=50)) bowl.mix() #mixing in the milk in batches for i in range (2): bowl.add (Milk.take(ml=250)) bowl.mix() #making the actual pancakes pan = Pan.use(name='pancake') plate = Plate.use() for i in range(8): pan.add(Butter.take('slice')) pan.add(bowl.take('1/8')) pan.cook(minutes=1) pan.flip() pan.cook(minutes=1) pancake = pan.take() plate.add(pancake) Rosemary.serve(plate)
839058b03d3265d490bc230a3872fa9e6e0a3155
cyber7nights/Python-learningtest
/learningtest_def_fact.py
266
3.6875
4
# -*- coding=utf-8 -*- def fact(n): if n == 1 : return 1 return n*fact(n-1) print(fact(10)) def fact(n): return dev_fact(n,1) def dev_fact(num,product): if num==1: return product return dev_fact(num-1,product*num) print(fact(10))
98f4c270d81d3b088ed6986a25bc73277cc88197
chrisqinxz/LeetCode-5
/0017.py
1,236
3.984375
4
''' 17. Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. 1:N/A, 2:abc, 3:def, 4:ghi, 5:jkl, 6:mno, 7:pqrs, 8:tuv, 9:wxyz, 0:N/A Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want. wklchris Note: 0 or 1 will NOT be present in the input. In case they do, use 1="*" and 0=" ". ''' from functools import reduce class Solution: def letterCombinations(self, digits): if '' == digits: return [] d = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} return reduce(lambda x, y: [i + j for i in x for j in d[y]], digits, ['']) # TEST ONLY import unittest class TestConvert(unittest.TestCase): def test_equal(self): func = Solution().letterCombinations self.assertEqual(func("23"), ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']) if __name__ == "__main__": unittest.main()
b17885dbcd2848753a0df8f05cc47109f9e7e91b
gyom/miscCodeExercisesAndSingleUsage
/programmingPearls_interviewPreparation/salariesTaxRatesSimplification.py
1,194
3.53125
4
import random def method1(income): if income <= 2200: tax = 0 elif income <= 2700: tax = 0.14 * (income-2200) elif income <= 3200: tax = 70 + 0.15 * (income-2700) elif income <= 3700: tax = 145 + 0.16 * (income-3200) elif income <= 4200: tax = 225 + 0.17 * (income-3700) else: # not the point here, but let's say that the super-rich pay no taxes tax = 0 return tax def method2(income): categoryBase = [0, 2200, 2700, 3200, 3700, 4200, 1000000] categoryTaxRate = [0, 0.14, 0.15, 0.16, 0.17, 0, 0] categoryOffset = [0, 0, 70, 145, 225, 0, 0] i = 0 while( categoryBase[i+1] <= income): i+=1 # terminates when categoryBase[i] <= income < categoryBase[i+1] return (income - categoryBase[i])*categoryTaxRate[i] + categoryOffset[i] if __name__ == "__main__": nreps = 100 (minval, maxval) = (0, 5000) (okCount, errorCount) = (0, 0) results = {} for r in range(0, nreps): income = random.randint(minval, maxval) t1 = method1(income) t2 = method2(income) if (t1 == t2): okCount += 1 else: errorCount += 1 results[(r,income, t1, t2)] = (t1==t2) print "okCount = %d, errorCount = %d" % (okCount, errorCount)
6aa323b4d69f7323764c318fd101165532453f5e
PhiBoy788/CodeJamQualifier
/qualifier/qualifier.py
5,174
3.96875
4
from typing import Any, List, Optional import math def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str: """ :param rows: 2D list containing objects that have a single-line representation (via `str`). All rows must be of the same length. :param labels: List containing the column labels. If present, the length must equal to that of each row. :param centered: If the items should be aligned to the center, else they are left aligned. :return: A table representing the rows passed in. """ ... #sets up the final table as a blank array that will be filled later final_table = [] #Creates an Array of the longest string in both the columns of the given rows list and labels(if given) longest_object,new_rows_list = longest_item(rows,labels) #Creates a boolean to handle table appending with or without labels. if labels: labels_bool = True else: labels_bool = False #Appends the top line of the table, spacing characters according #to the length of the longest string in the column final_table.append("┌") for i in range(len(longest_object)): final_table.append("─" * (longest_object[i] + 2)) if i < len(longest_object) - 1: final_table.append("┬") final_table.append("┐\n") #Appends the middle portion of the table and formats it with or without labels for i in range(len(new_rows_list)): for j in range(len(new_rows_list[i])): #Calculates the item length and spacing needed #for centering, then appends them accordingly item = str(new_rows_list[i][j]) item_length = len(item) item_left = item_length / 2 item_right = item_length / 2 spacing_left = longest_object[j] / 2 spacing_right = longest_object[j] / 2 if type(item_left) is float: item_left = math.ceil(item_left) item_right = math.floor(item_right) if type(spacing_left) is float: spacing_left = math.ceil(spacing_left) spacing_right = math.floor(spacing_right) if centered == False: final_table.append('│' + " " + item + (" " * (longest_object[j] + 1 - item_length))) else: final_table.append('│' + (" " * (spacing_left + 1 - item_left)) + item + (" " * (spacing_right + 1 - item_right))) final_table.append('│\n') #Gives the labels an extra line underneath them if they are present. if labels_bool: final_table.append("├",) for i in range(len(longest_object)): final_table.append("─" * (longest_object[i] + 2)) if i < len(longest_object) - 1: final_table.append("┼") labels_bool = False final_table.append("┤\n") #Appends bottom line of table using similar logic as the top line final_table.append("└") for i in range(len(longest_object)): final_table.append("─" * (longest_object[i] + 2)) if i < len(longest_object) - 1: final_table.append("┴") final_table.append("┘") final_table = "".join(final_table) return final_table #Returns an array with the value of the longest string in each column of a given 2D array def longest_item(row_list, labels = None): longest_array = [] new_list = [] if labels: for i in range (len(row_list)): new_list.insert(i,row_list[i]) new_list.insert(0,labels) else: new_list = row_list new_list = stringifier(new_list) for i in range(len(new_list[0])): longest = 0 for j in range(len(new_list)): item_string = str(new_list[j][i]) current = len(item_string) if current > longest: longest = current longest_array.append(longest) return longest_array, new_list #Goes through each item and changes it into a string to handle edge cases #of ints, floats, and strings being mixed. #returns a 2D stringified array def stringifier(labels_and_rows): stringified_list = [] for i in range(len(labels_and_rows)): inside_list = [] for j in range(len(labels_and_rows[i])): stringified_item = str(labels_and_rows[i][j]) inside_list.append(stringified_item) stringified_list.append(inside_list) return stringified_list #DEBUG CODE rows=[["Lemon", 18_3285, "Owner"],["Sebastiaan", 18_3285.1, "Owner"],["KutieKatj", 15_000, "Admin"],["Jake", "MoreThanU", "Helper"],["Joe", -12, "Idk Tbh"]] labels=["User", "Messages", "Role"] #Centered #rows=[["Apple", 5, 70]] #labels=["Name", "Duckiness"] #centered=True #rows=[["Apple", 5, 70, "Red"],["Banana", 3, 5, "Yellow"],["Cherry", 7, 31, "Red"],["Pear", 6, 50, "Green"]] #labels=["Fruit", "Tastiness", "Sweetness", "Colour"] #rows=[[None, 1, 2.5, None, 32j, '123']] #labels=[3, None, 12, "A", 12.6, 12j] centered=True table = make_table(rows,labels, True) print (table)
fcf87bcddfb9865ceebff67714770b8767da42e9
horacn/test_python
/test/except/test21.py
785
4.0625
4
# 调试、日志 # 断言 # 启动Python解释器时可以用-O参数来关闭assert def foo(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main(): foo('0') # main() # logging import logging logging.basicConfig(level=logging.DEBUG) s = '0' n = int(s) logging.debug('n = %d' % n) print(10 / n) # pdb # $ python -m pdb err.py # 以参数-m pdb启动后,pdb定位到下一步要执行的代码-> s = '0'。输入命令l来查看代码 # 输入命令n可以单步执行代码 # 任何时候都可以输入命令p 变量名来查看变量 # 输入命令q结束调试,退出程序 # pdb.set_trace() # 运行代码,程序会自动在pdb.set_trace()暂停并进入pdb调试环境,可以用命令p查看变量,或者用命令c继续运行
5052b82d2beeb95adff1737db5a5476632cdb4c4
shayhan-ameen/Beecrowd-URI
/Beginner/URI 1098.py
446
3.578125
4
i = 0.0 while i<1.9: j = 1.0 while j<=3.0: if i==int(i) and (i+j)==int(i+j): print(f'I={int(i)} J={int(i+j)}') elif i==int(i): print(f'I={int(i)} J={(i+j):.1f}') elif (i+j)==int(i+j): print(f'I={i:.1f} J={int(i+j)}') else: print(f'I={i:.1f} J={(i+j):.1f}') j += 1.0 i += 0.2 print(f'I=2 J=3') print(f'I=2 J=4') print(f'I=2 J=5')
dc1e4f0bb9b637954efe66653e2716b1ec1f4272
jskescola/exercicios_python_2
/ex17.py
268
3.59375
4
import random def main(): alunos = [] for i in range(1,5): aluno = input('Digite o nome do aluno: ') alunos.append(aluno) print(f'{alunos[random.randint(0,3)]} irá escrever no quadro!') if __name__ == '__main__': main()
7f11fda3e665ef52383037c85f018a030835246d
aligonultas/Deneme
/Untitled.py
236
3.59375
4
#Kullanıcıdan yaşını ve ismini alıp, 100 yaşına geldiği zamanki seneyi veren kod. isim=str(input("İsminiz:")) yas=int(input("Yaşınız:")) kalan=100-yas yıl=2020+kalan print("100.yaşınıza geldiğiniz yıl-->",yıl)
a0a69277db45fdf2c38611a1a9275cdc384fcb00
gorilazz/BP
/Utility/Python/reverseList.py
141
3.8125
4
def reverseList(l): if len(l)<=1: return l else: return l[len(l)-1:]+reverseList(l[0:len(l)-1]) l = [1,2,3,4,5] print(reverseList(l))
a1ce40e535580d9d68f81ad54112dccbe6342f46
SkyYonG/git-branch-practice-1
/main.py
154
3.71875
4
for a in range(1,100+1): if a%15==0: print("fizzbuzz") elif a%3==0 : print("fizz") elif a%5==0 : print("buzz") else: print(a)
afa38abc7419f8999c757a08f65682c427a3de85
Nemo1122/python_note
/Python笔记/python基础/随机排按班级.py
1,721
3.59375
4
import xlrd, xlwt import random # 需要按班级列出学生,一个班一列 excel = xlrd.open_workbook('E:\工作\海德\晚间特训\晚自习前特训分组表.xlsx') sheet = excel.sheet_by_index(0) # 从excel中获取数据并组成一个list s = [] for n_row in range(sheet.nrows): # 去掉其中的空字符 s.append([i for i in sheet.row_values(n_row) if i]) # print(s) ls = [] for sx in s: ls.append(len(sx)) # 按照人数最少的班级,从每个班级中随机获取一个组成一个组 s_end = [] for i in range(min(ls)): s_t = [] for sx in s: si = random.sample(sx, 1) sx.remove(si[0]) s_t.append(si[0]) # 将每组的人打乱 random.shuffle(s_t) s_end.append(s_t) # 处理剩余的人 s = [ii for i in s for ii in i if s] # print(s) # 如果人数是3的倍数,直接按3人分组 if len(s) % 3 == 0: for i in range(len(s)//3): si = random.sample(s, 3) for i in si: s.remove(i) s_end.append(si) # 如果人数不是3的倍数, else: while len(s) >= 3: for i in range(len(s) // 3): si = random.sample(s, 3) for i in si: s.remove(i) s_end.append(si) else: for i in range(len(s)): s_end[i].append(s[i]) # 最后再将组打乱 random.shuffle(s_end) for i in s_end: print(i) print(len(s_end)) # 写入文件 # 新建一个excel对象 wb = xlwt.Workbook() # 新建一个名为text的sheet页 sh = wb.add_sheet("test") # 前两个参数为单元格位置 for i in range(len(s_end)): for j in range(len(s_end[i])): sh.write(j, i, s_end[i][j]) # 目前只能保存成xls后缀 wb.save("data.xls")
e3d19da9ccf59df1c02c7ebe86892ce8b2adc097
nandansn/pythonlab
/durgasoft/chapter8/bytes.py
373
3.609375
4
''' bytes data type , it is like an array, this is immutable. to use mutable array use bytearray.''' x = [10,20,30,40] b = bytes(x) for i in b: print(i) # b[0]=50 immutable: Error: TypeError: 'bytes' object does not support item assignment b = bytearray(x) b[0]=50 for i in b: print(i) b[0]=500 # ValueError: byte must be in range(0, 256)
5496fe671ea4fa5abeeec381eee309f2ca5300ce
AaronNolan/College-Lab-Sheets
/tt-time-slot.py
438
3.578125
4
#!/usr/bin/env python #Create a list of all the strings s = raw_input() l = [] while s != "end": l.append(s) s = raw_input() # go through each string and print if true i = 0 a = [] while i < len(l): s = l[i] start_n = s[2:4] # Staring Hour if start_n == "09": start_n = "9" end_n = int(start_n) + int(s[5]) - 1 # Ending Hour print(s[0:2] + start_n + ":00 " + str(end_n) + ":50" + s[6:]) i += 1
81d34813ea5fc38f5cd7f2bb52597225d049fd5a
5anthosh/tictactoe-python3
/tictactoe.py
6,873
3.5625
4
import random def inputsymbol(board,p,s): board[p-1]=s def checkingwin(board,p): if (board[0] == p and board[1] == p and board[2] == p) or (board[3] == p and board[4] == p and board[5]==p) or (board[6]==p and board[7]==p and board[8]==p): return(True) if (board[0]==p and board[3]==p and board[6]==p) or (board[1]==p and board[4]==p and board[7]==p) or (board[2]==p and board[5]==p and board[8]==p): return(True) if (board[0]==p and board[4]==p and board[8] == p) or (board[2]== p and board[4] == p and board[6]==p): return(True) else: return(False) def checkingtie(board): if board.count(' ')==0: return True else: return False def getcopy(board): boardcopy=[] for i in board: boardcopy.append(i) return(boardcopy) def possiblemove(bo): plist=[] for i in range(0,9): if bo[i]==' ': plist.append(int(i)) return(plist) def machine_move(b,s,p): if b.count(p)== 1: ini=b.index(p) if ini==0: if b[8]==' ': b[8]=s return(False) elif ini ==2: if b[6]==' ': b[6]=s return(False) elif ini == 6: if b[2]==' ': b[2]=s return(False) elif ini == 8: if b[0]==' ': b[0] =s return(False) for i in range(0,9): copy=getcopy(b) if copy[i]==' ': copy[i]=s if checkingwin(copy,s): b[i]=s return(True) for j in range(0,9): copy=getcopy(b) if copy[j]==' ': copy[j]=p if checkingwin(copy,p): b[j]=s return(False) possible_moves=possiblemove(b) corner=[] side=[] for i in possible_moves: if i%2==0 and i!=4: corner.append(i) if i%2!=0: side.append(i) if len(corner)!=0: move1=random.choice(corner) b[move1]=s return(False) elif b[4] == ' ': b[4]=s return(False) else: move1=random.choice(side) b[move1]=s return(False) def printboard(board): print(' ','+---'*3,'+',sep='') print(' | ',board[0],' | ',board[1],' | ',board[2],' | ',sep='') print(' ','+---'*3,'+',sep='') print(' | ',board[3],' | ',board[4],' | ',board[5],' | ',sep='') print(' ','+---'*3,'+',sep='') print(' | ',board[6],' | ',board[7],' | ',board[8],' | ',sep='') print(' ','+---'*3,'+',sep='') def sampleboard(): print("< sample board >".center(60,'$')) print(' ','+---'*3,'+',sep='') print(' | ','1',' | ','2',' | ','3',' | ',sep='') print(' ','+---'*3,'+',sep='') print(' | ','4',' | ','5',' | ','6',' | ',sep='') print(' ','+---'*3,'+',sep='') print(' | ','7',' | ','8',' | ','9',' | ',sep='') print(' ','+---'*3,'+',sep='') def getplayersymbol(): while True: try: symbol=input("enter the your symbol ('O' or 'X')\n your symbol:") symbol=symbol.upper() except: print("enter correct symbol".center(60,'-')) else: if symbol!='O' and symbol!='X': print("enter correct symbol".center(60,'-')) print('try again....') continue elif symbol=='X': return('X','O') else: return('O','X') if symbol=='X' or symbol == 'O': break def toss(): turn=random.randint(0,10) if turn%2==0: turn='O' else: turn='X' return(turn) def playagain(): print("do you want to play again(y/n)") while True: try: try1=input("enter: ") except: print("enter the proper choice") continue else: if try1!='y' and try1!='n': print(" enter correct option-(y/n) ".center(60,'*')) continue else: if try1=='y': tictactoe() else: print(" exited ".center(60,'-')) exit() break def tictactoe(): board=[' ']*9 sampleboard() print("game starts".center(60,'-')) player_symbol,machine_symbol=getplayersymbol() print('\n','toss begins.....') turn=toss() if turn==player_symbol: print('\n',' player goes first '.center(60,'*')) else: print('\n',' machine goes first '.center(60,'*')) while True: if turn==player_symbol: print('\n',"your turn.....") while True: try: position=int(input('enter :')) except: print(" integer only ".center(60,'-')) continue else: if position < 1 or position > 9: print(" enter correct position(1-9) ".center(60,'-')) sampleboard() print(" try again....") continue elif board[position-1]!=' ': print(' position is already filled ') print(" try again....") continue else: inputsymbol(board,position,player_symbol) printboard(board) check1=checkingwin(board,player_symbol) if check1: print(" wow! you are won ".center(60,'*')) playagain() else: tie_status=checkingtie(board) if tie_status: print(' match is tie '.center(60,'-')) playagain() else: turn=machine_move break else: print("machine move") status=machine_move(board,machine_symbol,player_symbol) if status: printboard(board) print(" sorry baby machine won ".center(60,'*')) playagain() else: printboard(board) tie_status=checkingtie(board) if tie_status: print(' match is tie '.center(60,'-')) playagain() else: turn=player_symbol print(" game is started ".center(60,'*')) tictactoe()
14405bf137b031a445d396da429f13b90ea166fd
nilpath/ud120-projects
/datasets_questions/explore_enron_data.py
2,616
3.546875
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 """ import pickle enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r")) print "number of persons: {}".format(len(enron_data)) print "number of features per person: {}".format(len(enron_data['METTS MARK'])) print enron_data['METTS MARK']['poi'] persons_of_interest = [person for person in enron_data.values() if person['poi'] is True] print "number of poi: {}".format(len(persons_of_interest)) print "total value of stock belonging to James Prentice: {}".format(enron_data['PRENTICE JAMES']['total_stock_value']) print "number of emails from Wesley Colwell to poi: {}".format(enron_data['COLWELL WESLEY']['from_this_person_to_poi']) print "value of exercised stocks belonging to Jeffrey Skilling: {}".format(enron_data['SKILLING JEFFREY K']['exercised_stock_options']) print "total payments of Jeffery Skilling: {}".format(enron_data['SKILLING JEFFREY K']['total_payments']) print "total payments of Kenneth Lay: {}".format(enron_data['LAY KENNETH L']['total_payments']) print "total payments of Andrew Fastow: {}".format(enron_data['FASTOW ANDREW S']['total_payments']) persons_with_salary = [person for person in enron_data.values() if person['salary'] != 'NaN'] print "persons in dataset with a quantified salary: {}".format(len(persons_with_salary)) persons_with_email = [person for person in enron_data.values() if person['email_address'] != 'NaN'] print "persons in dataset with an email address: {}".format(len(persons_with_email)) persons_without_total_payments = [person for person in enron_data.values() if person['total_payments'] == 'NaN'] print "persons without total payments: {}".format(len(persons_without_total_payments)) print "percentage of people without total payments: {0:.2f}".format(float( len(persons_without_total_payments) ) / len(enron_data.values())) poi_without_total_payments = [poi for poi in persons_of_interest if poi['total_payments'] == 'NaN'] print "poi without total payments: {}".format(len(poi_without_total_payments)) print "percentage of poi without total payments: {0:.2f}".format(float( len(poi_without_total_payments) ) / len(persons_of_interest))
8f8be8cc9fc3d7bcbbc80aec4030e03fd1e5b445
andrejeller/Learning_Python_FromStart
/Exercicios/Fase_10_Condicoes/Exercicio_028.py
550
4.15625
4
""" Desafio 028 - Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu. """ import random from time import sleep rand = random.randint(0, 5) n = int(input('Tente descobrir o número que eu escolhi: ')) print('PROCESSANDO.....') sleep(3) print('Se eu escolhi {}, você '.format(rand), end='') if rand == n: print('Acertou!') else: print('Errou!')
f4a89fb98190deabab7d1c7a6dc5a063fb6196a1
1339475125/algorithms
/min_stack.py
649
4.0625
4
""" 包含min函数的栈 """ class stack(object): def __init__(self): self.data_stack = [] self.min_stack = [] def push(self, data): self.data_stack.append(data) self.min_stack.append( data if not self.min_stack else min(self.min(), data)) def pop(self): self.data_stack.pop() self.min_stack.pop() def min(self): return self.min_stack[-1] def top(self): return self.data_stack[-1] if __name__ == "__main__": s = stack() s.push(10) s.push(11) s.push(8) s.push(7) print(s.top, s.min) print(s.data_stack, s.min_stack)
51add7b10abd05387d0e08465a9aa2f5d177cf0f
Vells/ctci
/chapter1/1.1_unique_chars.py
804
4.15625
4
""" Problem 1.1: Implement an algorithm to determine if a string has all unique characters """ def unique_characters(a_string): """ Space complexity: O(1) TIme complexity: O(n) """ if a_string is None: return False if len(a_string) > 256: return False unique_chars = [False] * 256 for letter in a_string: if unique_chars[ord(letter)]: return False unique_chars[ord(letter)] = True return True def unique_characters_2(a_string): return len(set(a_string)) == len(set(a_string)) print unique_characters('a') is True print unique_characters('aa') is False print unique_characters(' ') is False print unique_characters_2('a') is True print unique_characters_2('aa') is False print unique_characters_2('') is True
3159d6f4f14138845d3b8a306377612d4e89e384
tmayphillips/DigitalCrafts-Assignments
/day07_grocery_app_withhelp.py
1,657
4.3125
4
user_input = "" shopping_lists = [] from day07_grocery_app_modules import * def show_menu(): print("Enter 1 to add shopping list: ") print("Enter 2 to add grocery item: ") print("Enter 3 to view shopping lists: ") print("Enter q to quit: ") def add_shopping_list(): name = input("Enter the name of shopping list: ") address = input("Enter address of shopping list: ") shopping_list = ShoppingList(name,address) shopping_lists.append(shopping_list) def view_all_shopping_lists(): for index in range(0,len(shopping_lists)): shopping_list = shopping_lists[index] print(f"{shopping_list.name} - {shopping_list.address}") for grocery_item in shopping_list.grocery_item: print(f"{grocery_item.name}") def add_grocery_item(): for index in range(0,len(shopping_lists)): shopping_list = shopping_lists[index] print(f"{index + 1} - {shopping_list.name} - {shopping_list.address}") shopping_list_number = int(input("Enter the shopping list number: ")) shopping_list = shopping_lists[shopping_list_number -1] name = input("Enter name of the grocery item: ") price = float(input("Enter the price of the item: ")) quantity = int(input("Enter the quantity: ")) grocery_item = GroceryItem(name,price,quantity) shopping_list.grocery_item.append(grocery_item) while user_input != "q": show_menu() user_input = input("Enter your choice: ") if user_input == "1": add_shopping_list() if user_input == "2": add_grocery_item() if user_input == "3": view_all_shopping_lists() if user_input == "4":
e642ae58e935da036302d9c10184334b346a2a49
stephenchenxj/myLeetCode
/973_K_Closest_Points_to_Origin.py
1,798
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 27 21:30:52 2020 @author: stephenchen 973. K Closest Points to Origin Medium 1222 101 Add to List Share We have a list of points on the plane. Find the K closest points to the origin (0, 0). (Here, the distance between two points on a plane is the Euclidean distance.) You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) Example 1: Input: points = [[1,3],[-2,2]], K = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. Example 2: Input: points = [[3,3],[5,-1],[-2,4]], K = 2 Output: [[3,3],[-2,4]] (The answer [[-2,4],[3,3]] would also be accepted.) Note: 1 <= K <= points.length <= 10000 -10000 < points[i][0] < 10000 -10000 < points[i][1] < 10000 Accepted 199,688 Submissions 322,691 """ class Solution(object): def kClosest(self, points, K): """ :type points: List[List[int]] :type K: int :rtype: List[List[int]] """ counter=0 my_dict=dict() for i in range(len(points)): my_dict[i]=self.distance(points[i]) res=sorted(my_dict.items(), key=lambda x:x[1]) output=[] for i in res: if counter<K: output.append(points[i[0]]) counter+=1 return output def distance(self,x): origin=[0,0] return (x[0]-origin[0])**2+(x[1]-origin[1])**2 points = [[1,3],[-2,2],[2,-2]] K = 2 print(Solution().kClosest(points, K))
be0225a38cc506eb0a292f0b7f3b8368a4b6ff90
Mbaoma/workedExamples
/examples/triangle-calculator/soln.py
1,865
4.71875
5
import math def main(): # Introductory explanation print("Welcome to the Triangle Calculator!") print("What information do you have about your triangle so far?") print("(1) Length of all three sides") print("(2) Length of two sides and the angle between them") choice = int(input("Please choose 1 or 2: ")) # Both options 1 and 2 ask for two side lengths side_a = float(input("Length of side 1: ")) side_b = float(input("Length of side 2: ")) # If we know all three sides if choice == 1: side_c = float(input("Length of side 3: ")) # Add up all the sides to get the perimeter, divide by 2 for semiperimeter! perimeter = side_a + side_b + side_c semiperimeter = perimeter / 2 # This is Heron's Formula for finding the area of a triangle using three sides area = math.sqrt(semiperimeter * (semiperimeter - side_a) * (semiperimeter - side_b) * (semiperimeter - side_c)) # If we know the angle between the two sides else: angle_opposite_c = float(input("Angle between them in degrees: ")) # Convert into radians angle_opposite_c = angle_opposite_c * math.pi / 180 # The area of a triangle is 1/2 * a * b * sin(C) area = 1/2 * side_a * side_b * math.sin(angle_opposite_c) # Law of Cosines side_c = math.sqrt((side_a * side_a) + (side_b * side_b) - (2 * side_a * side_b * math.cos(angle_opposite_c))) # Now that we have all the sides, we can find the perimeter perimeter = side_a + side_b + side_c print("---") print("Information about your triangle...") print("Side 1: ", side_a) print("Side 2: ", side_b) print("Side 3: ", side_c) print("Perimeter: ", perimeter) print("Area: ", area) print("---") if __name__ == "__main__": main()
c54b3bf8a2cbbfccfdb026e153df9ea053bb085a
LucasMaiale/Libro1-python
/Cap1/Ejemplo 1_1.py
741
4.0625
4
# -*- coding: utf-8 -*- """ @author: guardati Ejemplo 1_1 Impresiones en Python. """ edad = 83 print("Hola otoño") print('Edad del abuelo: ', edad) # Por omisión separa con espacio en blanco. print("verde", "rojo", "azul") # Se establece como separador el - print("verde", "rojo", "azul", sep = "-") # Se establece como separador el --> print("verde", "rojo, amarillo o café", "se cae", sep = " --> ") # Por omisión termina con un salto de línea. print("dulce", "amargo", "ácido") # Se establece que, al terminar, no baje de renglón. print("Hola", end = "") # Se establece que, al terminar, no baje de renglón y escriba :) print('otoño, estación de los colores opacos', end = ":)")
326f97eacfae3f00c18f85468bcae9ec6b877a6b
YoungdanNoh/Machine_learning_basic
/선형회귀 가설함수 구현/main.py
483
3.546875
4
import numpy as np def prediction(theta_0, theta_1, x): """주어진 학습 데이터 벡터 x에 대해서 예측 값을 리턴하는 함수""" # 코드를 쓰세요 return theta_0 + theta_1*x # 테스트 코드 # 입력 변수(집 크기) 초기화 (모든 집 평수 데이터를 1/10 크기로 줄임) house_size = np.array([0.9, 1.4, 2, 2.1, 2.6, 3.3, 3.35, 3.9, 4.4, 4.7, 5.2, 5.75, 6.7, 6.9]) theta_0 = -3 theta_1 = 2 prediction(theta_0, theta_1, house_size)
e646ab7d875d95ede3472a21fc7bb60096376bb7
StevanCakic/ORS-UDG
/Nedelja 5/files.py
1,238
3.671875
4
# Files f = open("test.txt") ''' print(f.read()) print(f.read()) f.seek(0) print(f.read()) ''' f.seek(0) for line in f: print(line) f.seek(0) lines = f.readlines() for line in lines: print(line) f.seek(0) lines_without_newline = f.read().split("\n") for line in lines_without_newline: print(line) f.close() with open("test.txt") as f: print(f.read()) with open("novi_fajl.txt", mode="w") as file: file.write("Upis u fajl iz Pythona") # Zadatak 1 # Iz fajlova brojevi.txt izdvojiti sve dvocifrene i trocifrene brojeve # i upisati ih u novi fajl odabrani_brojevi.txt nova_lista = [] with open("brojevi.txt") as file: brojevi = file.read().split("\n") for broj in brojevi: if 1 < len(broj) < 4: nova_lista.append(broj) print(nova_lista) with open("odabrani_brojevi.txt", mode="w") as file: for broj in nova_lista: file.write(broj + "\n") # Zadatak 2 # U fajlu studenti nalazi se lista studenata sa ocjenama za zadati predmet. # (A - 10, B - 9, C - 8, D - 7, E - 6, F - 5) # Napisati funkciju koja vraca prosjecnu ocjenu ostvarenu na ispitu. # E [6 - 6.5), D [6.5, 7.5), C [7.5, 8.5), B [8.5, 9.5), A [9.5, 10] # Studente koji su dobili ocjenu F ne ukljucivati u prosjek
e88fe5677ed6562ea2fe62c39b1eb1d2e5ae3ca7
developerdiniz/Python
/00.Introdução a Linguagem Python/09.Resposta_exercicio_fixacao.py
531
3.84375
4
lista = [2,59,635,48,1.5,7,8.75,0.75] #Criado duas funções diferentes para mostrar formas diferentes de logicas. #Usando um lado de repetição para percorrer a lista e comparar um por um para ver qual é o maior. def imprime_maior(lista): x = 0 for y in lista: if y > x : x = y return x #Ordenando a lista em ordem crescente e pegando o primeiro numero que por logica vai ser o menor #Para pegar o maior, poderiamos usar lista[-1] def imprime_menor(lista): lista.sort() return lista[0]
03560358cdf25c46e3a74a3306557a4505398e97
lindenwxl/Machine-Learning
/Grokking_Algorithms/binary_search.py
901
4
4
from __future__ import print_function,division def binary_search(lists, item): low = 0 high = len(lists) - 1 # low and high keep track of which part of the list you’ll search in. while low <= high : # While you haven’t narrowed it down to one element … mid = (low + high) // 2 # check the middle element. guess = lists[mid] if guess == item: # Found the item. return mid if guess > item: # The guess was too high. high = mid - 1 else: # The guess was too low low = mid + 1 return None # The item doesn’t exist if __name__ == "__main__": my_list = [1, 3, 5, 6, 7, 9, 11] print(binary_search(my_list, 3)) print(binary_search(my_list, 5)) print(binary_search(my_list, -1))
7d82a9ad57cc73a6babfcb129280bd4cc195acd0
jessestoler/SchoolSystem
/schedules/model.py
1,491
3.546875
4
'''Defines the model for schedule''' import json from SchoolSystem.data.logger import get_logger _log = get_logger(__name__) class Schedule: '''A ClassScheduleSchedule that defines how schedules should behave''' def __init__(self, db_id=-1, username='', schedule={'period_1': '', 'period_2': '', 'period_3': '', 'period_4': '', 'period_5': ''}): self._id = db_id self.username = username self.schedule = schedule def get_id(self): '''Returns the id of the Schedule''' return self._id def set_id(self, _id): '''Sets the id of the Schedule''' self._id = _id def __str__(self): '''String representation of the Schedule''' string = "_id: " + str(self._id) + " name: " + self.username string += " Instance of: " + type(self).__name__ return string def __repr__(self): '''Returns string representation of self''' return self.__str__() def to_dict(self): '''Returns the dictionary representation of itself''' return self.__dict__ @classmethod def from_dict(cls, input_schedule): '''Creates an instance of the Schedule from a dictionary''' schedule = Schedule() schedule.__dict__.update(input_schedule) return schedule class ScheduleEncoder(json.JSONEncoder): ''' Allows us to serialize our objects as JSON ''' def default(self, o): return o.to_dict()
149703529a517ac74b60400353ddfbac3ace3c27
AlissonRaphael/python_exercises
/exercise060.py
284
4.09375
4
numero = int(input('Insira o número para calcular o fatorial: ')) print('Calculando {}! = '.format(numero), end='') fatorial = 1 while numero > 0: print('{} = '.format(numero) if numero == 1 else '{} x '.format(numero), end='') fatorial *= numero numero -= 1 print(fatorial)
1fa7c7f44113fe5b1b17a763e3970e10b33a9973
qtccz/data-python
/algorithm/selectSort.py
1,118
4.40625
4
#!/usr/bin/python # -*- coding:utf-8 -*- """ 5、直接选择排序 基本思想: 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置, 然后再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。 以此类推,直到所有元素均排序完毕。 """ def select_sort(lists): count = len(lists) for i in range(0, count): # 假设找到的最小元素下标为i min_index = i # 寻找最小元素的过程 for j in range(i + 1, count): # 假设最小下标的值,大于循环中一个元素,那么就改变最小值的下标 if lists[min_index] > lists[j]: min_index = j # 在不停的循环中,不停的交换两个不一样大小的值 lists[min_index], lists[i] = lists[i], lists[min_index] return lists def main(): import numpy as np lists = list(np.random.randint(0, 100, size=10)) print("排序前", lists) print("排序后", select_sort(lists)) if __name__ == '__main__': main()
bb95fcfdc3b69362590edcd49a4dd126bbc00c9f
Donzellini/pythonCampinasTech
/Exercises/ex1.py
1,257
4.28125
4
#1. Algoritmo para ligar um carro (Imprimir a sequência para ligar um carro) print(" ") print(" LIGAR UM CARRO") print("_______________________") print(" ") opcao = input("Seu carro é manual ou automático? (M/A): ") print("01. Encontrar as chaves") print("02. Ir até o carro") print("03. Abrir a porta") print("04. Sentar no banco") #opção manual if opcao == "M": print("05. Verificar se o câmbio está em ponto morto") print("06. Verificar espelhos") print("07. Pisar no freio") print("08. Abaixar o freio de mão") print("09. Conectar a chave") print("10. Girar a chave") print("11. Torcer para que o carro ligue") print("12. Pisar na embreagem e engatar a primeira marcha no câmbio") print("13. Soltar a embregem e acelerar") #opção automático else: print("05. Verificar se o câmbio está em ponto D") print("06. Verificar espelhos") print("07. Pisar no freio") print("08. Abaixar o freio de mão") print("09. Conectar a chave") print("10. Girar a chave") print("11. Torcer para que o carro ligue") print("12. Tirar o pé do freio e acelerar") print("_______________________") print(" FIM")
e8dbb715e0a6c141db72cd7320f75e815d7d070e
AnkitMishra19007/DS-Algo
/Searching/Linear Search/LinearSearch.py
301
3.921875
4
n= int(input("Enter the length of array- ")) print("Enter the values of array separated by space") arr= list(map(int,input().split())) find= int(input("Enter the value to search- ")) for i in range(n): if(arr[i]==find): print("%d was found at index %d"%(find,i)) print("Value not found")
05610e5e69a3ed336df3f3723fc31db023c40447
clamslam12/PyCharm-Projects
/hw2_part3/worstCaseRandomCaseAlgo.py
4,093
3.90625
4
import random from random import choice #exclude100 = [0,1,2,3,4,5,6,7,8] #compGuess100 = random.choice([i for i in range(0,10) if i not in exclude100]) #print(compGuess100) def dWorstCase(): highestGInTry = 0 numTries = 0 totalG = 0 correctTries = 0 # correct guess for all 3 numbers lowestTries = 0 for x in range(1, 10001): numTries += 1 # generate 3 random numbers rand1 = random.randint(0, 9) rand2 = random.randint(0, 9) rand3 = random.randint(0, 9) # store in a tuple randT = (rand1, rand2, rand3) # guess the 3 numbers # For this try numGuess = 0 # list of tuples that contains numbers that are already guessed exclude = [] while numGuess <= 1000: # max guess # computer guess compG1 = random.randint(0, 9) compG2 = random.randint(0, 9) compG3 = random.randint(0, 9) compT = (compG1, compG2, compG3) if compT == randT and compT not in exclude: # correct guess totalG += 1 # increment total number of guess for all tries correctTries += 1 # increment number of correct tries lowestTries += 1 numGuess += 1 #highestGInTry = numGuess break elif compT != randT and compT not in exclude: # wrong guess totalG += 1 # increment total number of guess for all tries numGuess += 1 # increment number of guess for a try exclude.append(compT) else: continue if numGuess >= highestGInTry: highestGInTry = numGuess if numGuess >= highestGInTry and numGuess == 1001: highestGInTry = numGuess - 1 if correctTries >= 1: lowestTries = 1 else: lowestTries = 0 print("Deterministic worst case algorithm\n") print("Number of tries:", numTries) print("Highest number of guess in a try:", highestGInTry) print("Lowest Tries:", lowestTries) print("Number of Correct Tries:", correctTries) print("Average number of Tries:", totalG, "/", numTries, ": ",totalG/numTries ) def cRandAlgo(): highestGInTry = 0 numTries = 0 totalG = 0 correctTries = 0 # correct guess for all 3 numbers lowestTries = 0 for x in range(1, 10001): numTries += 1 # generate 3 random numbers rand1 = random.randint(0, 9) rand2 = random.randint(0, 9) rand3 = random.randint(0, 9) # store in a tuple randT = (rand1, rand2, rand3) # guess the 3 numbers # For this try numGuess = 0 while numGuess <= 10000: # max guess # computer guess compG1 = random.randint(0, 9) compG2 = random.randint(0, 9) compG3 = random.randint(0, 9) compT = (compG1, compG2, compG3) if compT == randT: # correct guess totalG += 1 # increment total number of guess for all tries correctTries += 1 # increment number of correct tries lowestTries += 1 numGuess += 1 break else: # wrong guess totalG += 1 # increment total number of guess for all tries numGuess += 1 # increment number of guess for a try if numGuess >= highestGInTry: highestGInTry = numGuess if numGuess >= highestGInTry and numGuess == 10001: highestGInTry = numGuess - 1 if correctTries >= 1: lowestTries = 1 else: lowestTries = 0 print("Complete random algorithm\n") print("Number of tries:", numTries) print("Highest number of guess in a try:", highestGInTry) print("Lowest Tries:", lowestTries) print("Number of Correct Tries:", correctTries) print("Average number of Tries:", totalG, "/", numTries, ": ", totalG / numTries) dWorstCase() print() cRandAlgo()
d553e4df93e7fd93fe879b3a923d42b88dfcdaff
jkreinik/si364-hw1
/SI364F18_HW1.py
6,991
3.859375
4
## HW 1 ## SI 364 F18 ## 1000 points ################################# ## List below here, in a comment/comments, the people you worked with on this assignment AND any resources you used to find code (50 point deduction for not doing so). If none, write "None". ## Worked with Kevin Rothstien ## [PROBLEM 1] - 150 points ## Below is code for one of the simplest possible Flask applications. Edit the code so that once you run this application locally and go to the URL 'http://localhost:5000/class', you see a page that says "Welcome to SI 364!" import requests import json from flask import Flask, request app = Flask(__name__) app.debug = True @app.route('/class') def hello_to_you(): return 'Welcome to SI 364' @app.route('/movie/<name>') def hello_name(name): response = requests.get('https://itunes.apple.com/search?term=' + name + '&limit=25' + '&entity=movie').text return response @app.route('/question') def formView(): html_form = ''' <html> <body> <form action = "/result" method = "POST"> <label for = "number"> Enter your favorite number:</label><br> <br> <input type = "text" name = "number"></input> <input type = "submit" name = "Submit"></input> </form> </body> </html> ''' return html_form @app.route('/result', methods = ['GET', 'POST']) def resultView(): if request.method == "POST": number = request.form.get("number", "Did not recieve a value for favorite number") print (type(number)) number_int = int(number) double_number = str(number_int*2) return "Double your favorite number is " + double_number #double_number = int(number)*2 #print (double_number) @app.route('/problem4form',methods=["GET","POST"]) def see_form(): formstring = """<br><br> <form action="" method='POST'> <input type="text" name="author"> Enter a your favorite author <br><br> <legend> pick how many results you want to search for</legend> <input type="checkbox" name="num_results" value="1"> 1<br> <input type="checkbox" name="num_results" value="5"> 5<br> <input type="checkbox" name="num_results" value="10"> 10<br> <input type="submit" value="Submit"> </form> """ ## HINT: In there ^ is where you need to add a little bit to the code... if request.method == "POST": author = request.values.get('author') num_results = request.values.get('num_results') humes = requests.get('https://itunes.apple.com/search?', params={'term':author, 'limit':num_results,'entity':'ebook'}).text res = json.loads(humes) text = '<h1> Here are ' + num_results + ' based on your search of ' + author +'</h1><br><br>' #number_results = res['resultCount'] for x in res['results']: title = x['trackName'] description = x['description'] string = 'Title: {} <br><br> Description: {}'.format(title, description) text += string return formstring + text # # Add more code here so that when someone enters a phrase, you see their data (somehow) AND the form! else: return formstring # @app.route('/problem4form',methods=["GET","POST"]) # def see_form(): # formstring = """<br><br> # <form action="" method='POST'> # <input type="text" name="phrase"> Enter a phrase: <br> # <input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br> # <input type="checkbox" name="vehicle2" value="Car"> I have a car<br> # <input type="checkbox" name="vehicle3" value="Trolley"> I have a trolley # <input type="submit" value="Submit"> # </form> # """ # return formstring if __name__ == '__main__': app.run() ## [PROBLEM 2] - 250 points ## Edit the code chunk above again so that if you go to the URL 'http://localhost:5000/movie/<name-of-movie-here-one-word>' you see a big dictionary of data on the page. For example, if you go to the URL 'http://localhost:5000/movie/ratatouille', you should see something like the data shown in the included file sample_ratatouille_data.txt, which contains data about the animated movie Ratatouille. However, if you go to the url http://localhost:5000/movie/titanic, you should get different data, and if you go to the url 'http://localhost:5000/movie/dsagdsgskfsl' for example, you should see data on the page that looks like this: # { # "resultCount":0, # "results": [] # } ## You should use the iTunes Search API to get that data. ## Docs for that API are here: https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/ ## Of course, you'll also need the requests library and knowledge of how to make a request to a REST API for data. ## Run the app locally (repeatedly) and try these URLs out! ## [PROBLEM 3] - 250 points ## Edit the above Flask application code so that if you run the application locally and got to the URL http://localhost:5000/question, you see a form that asks you to enter your favorite number. ## Once you enter a number and submit it to the form, you should then see a web page that says "Double your favorite number is <number>". For example, if you enter 2 into the form, you should then see a page that says "Double your favorite number is 4". Careful about types in your Python code! ## You can assume a user will always enter a number only. ## [PROBLEM 4] - 350 points ## Come up with your own interactive data exchange that you want to see happen dynamically in the Flask application, and build it into the above code for a Flask application, following a few requirements. ## You should create a form that appears at the route: http://localhost:5000/problem4form ## Submitting the form should result in your seeing the results of the form on the same page. ## What you do for this problem should: # - not be an exact repeat of something you did in class # - must include an HTML form with checkboxes and text entry # - should, on submission of data to the HTML form, show new data that depends upon the data entered into the submission form and is readable by humans (more readable than e.g. the data you got in Problem 2 of this HW). The new data should be gathered via API request or BeautifulSoup. # You should feel free to be creative and do something fun for you -- # And use this opportunity to make sure you understand these steps: if you think going slowly and carefully writing out steps for a simpler data transaction, like Problem 1, will help build your understanding, you should definitely try that! # You can assume that a user will give you the type of input/response you expect in your form; you do not need to handle errors or user confusion. (e.g. if your form asks for a name, you can assume a user will type a reasonable name; if your form asks for a number, you can assume a user will type a reasonable number; if your form asks the user to select a checkbox, you can assume they will do that.) # Points will be assigned for each specification in the problem.
f3d28bf30ad7857d9921c1cd39a2e2d78739f025
ryanblahnik/Automate-the-Boring-Stuff
/0161.py
347
3.53125
4
import pprint message = 'There ain\'t nothin you would ask I could answer you that I won\'t.. but I was gonna change and I\'m not if you keep doin things I don\'t' count = {} for character in message.upper(): count.setdefault(character, 0) count[character] = count[character] + 1 print(message) pprint.pprint(count)
1c068daa9bc712bd4ce6d49ed728da8666c080a9
rajeshsvv/Lenovo_Back
/1 PYTHON/3 TELUSKO/42_Filter_Map_Reduce.py
1,155
4.34375
4
# program to find even numbers in the list with basic function # def is_even(a): # return a%2==0 # # nums=[2,3,4,5,6,8,9] # # evens=list(filter(is_even,nums)) # print(evens) # program to find even numbers in the list with lambda function # nums=[2,3,4,5,6,8,9] # # evens=list(filter(lambda n:n%2==0,nums)) # print(evens) # # program to double the numbers in the list with normal function # # def update(a): # return a*2 # nums=[2,3,4,5,6,8,9] # evens=list(filter(lambda n:n%2==0,nums)) # doubles=list(map(update,evens)) # print(evens) # print(doubles) # program to double the numbers in the list with lambda function # nums=[2,3,4,5,6,8,9] # evens=list(filter(lambda n:n%2==0,nums)) # doubles=list(map(lambda n:n*2,evens)) # print(evens) # print(doubles) # program to add two numbers in the list in the list with reduce function from functools import reduce # def Add_All(a,b): # return a+b nums=[2,3,4,5,6,8,9] evens=list(filter(lambda n:n%2==0,nums)) doubles=list(map(lambda n:n*2,evens)) # sum=reduce(Add_All,doubles) sum=reduce(lambda a,b:a+b,doubles) # with lambda function print(evens) print(doubles) print(sum)
551d6fcd123d55103d018be229bab01bdc8dd8da
jjc521/E-book-Collection
/Python/Python编程实践gwpy2-code/code/searchsort/sort1.py
322
4.125
4
def find_largest(n, L): """ (int, list) -> list Return the n largest values in L in order from smallest to largest. >>> L = [3, 4, 7, -1, 2, 5] >>> find_largest(3, L) [4, 5, 7] """ copy = sorted(L) return copy[-n:] if __name__ == '__main__': import doctest doctest.testmod()
b3f9bb0c3e39786b957dad14b45d6cfb287c3586
mmasniy/Maraphon-Python
/sprint00/t08_what_is_the_address/address.py
370
3.703125
4
first_var = 1000 second_var = 1000 third_var = 999 print(f'first_var = {first_var}, address is {id(first_var)}') print(f'second_var = {second_var}, address is {id(second_var)}') print(f'third_var = {third_var}, address is {id(third_var)}') print(f'{first_var} is {second_var} = {first_var is second_var}') print(f'{first_var} is {third_var} = {first_var is third_var}')
b12904ceabc3bb03f5f65d4b8306f4fbcea73d3e
AWangHe/Python-basis
/12.面向对象提升与收发邮件/3.对象属性与类属性/对象属性与类属性.py
858
3.890625
4
# -*- coding: utf-8 -*- class Person(object): #这里的属性实际上属于类属性(用类名来调用) name = "sunck" def __init__(self, name): #pass #对象属性 self.name = name print(Person.name) per = Person("tom") #对象属性的优先级高于类属性 print(per.name) print(Person.name) #动态的给对象添加对象属性 per.age = 18 #只针对当前对象生效,对于类创建的其它对象没有作用 print(per.age) per2 = Person("lilei") #print(per2.age) #没有age属性 #删除对象中的name属性,在调用会使用到同名的类属性 del per.name print(per.name) #注意:以后千万不要将对象属性与类属性重名,因为对象属性会屏蔽掉类属性。 #但是当删除对象属性后,在使用又能使用类属性了
26c6ef8d972530814c6b7c4f19e10dc06f405a7c
RicardoBaniski/Python
/Opet/4_Periodo/Scripts_CEV/Mundo_01/Desafio010.py
125
3.625
4
us = 3.27 rs = float(input('Quanto tem na carteira: ')) dolar = rs / us print('Você pode comprar {} dolars'.format(dolar))
0c06ace88c1d06f0d44ced3624a8ca06361d9db6
countone/exercism-python
/wordy.py
914
3.78125
4
def calculate(question): question= question[:len(question)-1] question=question.split(' ') arguments= question[2:] if len(arguments)>4: if arguments[1] in ['multiplied','divided']: first_result= calculate('What is '+' '.join(arguments[:4])+'?') return calculate('What is '+' '.join([str(first_result)]+arguments[4:])+'?') elif arguments[1] in ['plus','minus']: first_result= calculate('What is '+' '.join(arguments[:3])+'?') return calculate('What is '+' '.join([str(first_result)]+arguments[3:])+'?') else: raise ValueError('ValueError') operator=arguments[1] if operator=='plus': return int(arguments[0])+int(arguments[2]) elif operator=='minus': return int(arguments[0])-int(arguments[2]) elif operator=='multiplied': return int(arguments[0])*int(arguments[3]) elif operator=='divided': return int(arguments[0])/int(arguments[3]) else: raise ValueError('ValueError')
f36ef34769cb0f3cf7328401e68f8b546a8df0c8
BarbBoyaji/neural-nets
/hw2/nndl/softmax.py
10,715
3.984375
4
import numpy as np class Softmax(object): def __init__(self, dims=[10, 3073]): self.init_weights(dims=dims) def init_weights(self, dims): """ Initializes the weight matrix of the Softmax classifier. Note that it has shape (C, D) where C is the number of classes and D is the feature size. """ self.W = np.random.normal(size=dims) * 0.0001 def loss(self, X, y): """ Calculates the softmax loss. Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - X: A numpy array of shape (N, D) containing a minibatch of data. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label c, where 0 <= c < C. Returns a tuple of: - loss as single float """ # Initialize the loss to zero. loss = 0.0 # ================================================================ # # YOUR CODE HERE: # Calculate the normalized softmax loss. Store it as the variable loss. # (That is, calculate the sum of the losses of all the training # set margins, and then normalize the loss by the number of # training examples.) # ================================================================ # m = X.shape[0] for i in range(m): loss += np.log(np.sum(np.exp(self.W.dot(X[i].T)))) - self.W[y[i]].dot(X[i]) loss = loss/len(y) pass # ================================================================ # # END YOUR CODE HERE # ================================================================ # return loss def loss_and_grad(self, X, y): """ Same as self.loss(X, y), except that it also returns the gradient. Output: grad -- a matrix of the same dimensions as W containing the gradient of the loss with respect to W. """ # Initialize the loss and gradient to zero. loss = 0.0 grad = np.zeros_like(self.W) # ================================================================ # # YOUR CODE HERE: # Calculate the softmax loss and the gradient. Store the gradient # as the variable grad. # ================================================================ # loss = self.loss(X,y) m = X.shape[0] for i in range(m): scores=np.dot(self.W,X[i,:].T) #calculate a for all k log_k = max(scores) scores = scores - log_k #normalize the score sumE=np.sum(np.exp(scores), axis=0) softmax = np.exp(scores)/sumE for k in range(self.W.shape[0]): if k == y[i]: grad[k,:] += X[i,:]*(softmax[k] - 1) else: grad[k,:] += X[i,:]*softmax[k] grad /= X.shape[0] #print(f"sumE: {sumE}") #print(f"size of yi: {y[1]}") #print(f"size of Xi: {X[1,:].shape}") print(f"size of gradient is: {grad.shape}") # ================================================================ # # END YOUR CODE HERE # ================================================================ # return loss, grad def grad_check_sparse(self, X, y, your_grad, num_checks=10, h=1e-5): """ sample a few random elements and only return numerical in these dimensions. """ for i in np.arange(num_checks): ix = tuple([np.random.randint(m) for m in self.W.shape]) oldval = self.W[ix] self.W[ix] = oldval + h # increment by h fxph = self.loss(X, y) self.W[ix] = oldval - h # decrement by h fxmh = self.loss(X,y) # evaluate f(x - h) self.W[ix] = oldval # reset grad_numerical = (fxph - fxmh) / (2 * h) grad_analytic = your_grad[ix] rel_error = abs(grad_numerical - grad_analytic) / (abs(grad_numerical) + abs(grad_analytic)) print('numerical: %f analytic: %f, relative error: %e' % (grad_numerical, grad_analytic, rel_error)) def fast_loss_and_grad(self, X, y): """ A vectorized implementation of loss_and_grad. It shares the same inputs and ouptuts as loss_and_grad. """ loss = 0.0 grad = np.zeros(self.W.shape) # initialize the gradient as zero # ================================================================ # # YOUR CODE HERE: # Calculate the softmax loss and gradient WITHOUT any for loops. # ================================================================ # #sanity check shapes #print(f"W: {self.W.shape}") #print(f"X: {X.shape}") #print(f"y: {y.shape}") scores = np.dot(self.W, X.T) # scores for all training samples summed_E = np.sum(np.exp(scores), axis = 0) #more sanity #print(f"summed_E dim: {summed_E.shape}") #print(f"np.choose(y,scores) dim: {np.choose(y,scores).shape}") #print(f"scores dim: {scores.shape}") #loss calculation loss = np.sum((np.log(summed_E) - np.choose(y,scores)))/X.shape[0] #normalizing magic log_k = np.max(scores, axis = 0) #print(f"log_k size: {log_k.shape}") #normalize the score scores = scores - log_k summed_E=np.sum(np.exp(scores), axis=0) softmax = np.exp(scores)/summed_E #print(f"softmax size: {softmax.shape}") #create indicator classes = np.tile(np.arange(self.W.shape[0]), (softmax.shape[1],1)) indicator = (y.T == classes.T) #print(f"classes dim: {classes.T.shape}") #print(f"classes: {classes.T}") #print(f"indicator: {indicator}") #gradient calculation grad = np.dot((softmax - 1*indicator), X)/X.shape[0] # ================================================================ # # END YOUR CODE HERE # ================================================================ # return loss, grad def train(self, X, y, learning_rate=1e-3, num_iters=100, batch_size=200, verbose=False): """ Train this linear classifier using stochastic gradient descent. Inputs: - X: A numpy array of shape (N, D) containing training data; there are N training samples each of dimension D. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label 0 <= c < C for C classes. - learning_rate: (float) learning rate for optimization. - num_iters: (integer) number of steps to take when optimizing - batch_size: (integer) number of training examples to use at each step. - verbose: (boolean) If true, print progress during optimization. Outputs: A list containing the value of the loss function at each training iteration. """ num_train, dim = X.shape num_classes = np.max(y) + 1 # assume y takes values 0...K-1 where K is number of classes self.init_weights(dims=[np.max(y) + 1, X.shape[1]]) # initializes the weights of self.W # Run stochastic gradient descent to optimize W loss_history = [] for it in np.arange(num_iters): X_batch = None y_batch = None # ================================================================ # # YOUR CODE HERE: # Sample batch_size elements from the training data for use in # gradient descent. After sampling, # - X_batch should have shape: (batch_size, dim) # - y_batch should have shape: (batch_size,) # The indices should be randomly generated to reduce correlations # in the dataset. Use np.random.choice. It's okay to sample with # replacement. # ================================================================ # idx_row = np.random.choice(num_train, batch_size) #sanity check #print(f"idx_row size: {idx_row}") X_batch = X[idx_row] y_batch = y[idx_row] #sanity check #print(f"X_batch size: {X_batch.shape}") #print(f"y_batch size: {y_batch.shape}") pass # ================================================================ # # END YOUR CODE HERE # ================================================================ # # evaluate loss and gradient loss, grad = self.fast_loss_and_grad(X_batch, y_batch) loss_history.append(loss) # ================================================================ # # YOUR CODE HERE: # Update the parameters, self.W, with a gradient step # ================================================================ # W_compare = self.W self.W = self.W - learning_rate*grad if np.linalg.norm(W_compare - self.W) < 1e-6: break # ================================================================ # # END YOUR CODE HERE # ================================================================ # if verbose and it % 100 == 0: print('iteration {} / {}: loss {}'.format(it, num_iters, loss)) return loss_history def predict(self, X): """ Inputs: - X: N x D array of training data. Each row is a D-dimensional point. Returns: - y_pred: Predicted labels for the data in X. y_pred is a 1-dimensional array of length N, and each element is an integer giving the predicted class. """ y_pred = np.zeros(X.shape[1]) # ================================================================ # # YOUR CODE HERE: # Predict the labels given the training data. # ================================================================ # prob_ = np.dot(self.W, X.T) y_pred = np.argmax(prob_, axis = 0) #pass # ================================================================ # # END YOUR CODE HERE # ================================================================ # return y_pred
8f07a45afc32541c302395ff2c2efd7f22a30041
jordanwatson1/Kattis_Problems
/calculating_dart_scores/calculating_dart_scores.py
1,091
4.09375
4
#!/usr/bin/env python3 """ Kattis: Calculating Dart Scores July 19, 2019 """ import sys def main(): target_score = int(sys.stdin.readline().strip()) multiple = ("single", "double", "triple") # The first 3 for loops represent the three numbers where the player hit # The last three for loops represent the section where the dart was thrown # (single, double or triple points). It will exhaust every combo possible # and if the target score cannot be found, impossible is printed at the end. # num1 for a in range(20, 0, -1): # num2 for b in range(20, 0, -1): # num3 for c in range(20, 0, -1): # single, double, or triple for x in range(3, -1, -1): for y in range(3, -1, -1): for z in range(3, -1, -1): num = ((a * x) + (b * y) + (c * z)) if (num == target_score): if (x > 0): print (multiple[x-1] + " " + str(a)) if (y > 0): print (multiple[y-1] + " " + str(b)) if (z > 0): print (multiple[z-1] + " " + str(c)) return print("impossible") if __name__ == '__main__': main()
aa6a5b7987038ef0c17bc7a6af0d4c2c3bbe8fa5
JerinPaulS/Python-Programs
/ValidPallindrome.py
1,124
4.21875
4
''' Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Example 2: Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome. Constraints: 1 <= s.length <= 2 * 105 s consists only of printable ASCII characters. ''' class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ str_inp = "" for index in range(len(s)): if s[index].isalnum(): str_inp = str_inp + s[index].lower() if len(str_inp) == 0: return True start = 0 end = len(str_inp) - 1 while start <= end: if str_inp[start] != str_inp[end]: return False start = start + 1 end = end - 1 print "Hello" return True obj = Solution() #print(obj.isPalindrome("A man, a plan, a canal: Panama")) #print(obj.isPalindrome("race a car")) print(obj.isPalindrome("0P"))
278ae8cb34912a85c9757efb98606faf22802a6f
greenfox-zerda-lasers/gygabor
/week-04/day-3/diagrect.py
224
3.84375
4
from tkinter import * root = Tk() canvas = Canvas(root, width = 300, height = 300) canvas.pack() for i in range(1, 19): i *= 10 square = canvas.create_rectangle(i, i, i+10, i+10, fill = 'purple') root.mainloop()
3cc4f8608ce225db4e64f3def20f98578f5b50da
lmacionis/Exercises
/13. Files/Exercise_2.py
393
3.9375
4
""" Write a program that reads a file and prints only those lines that contain the substring snake. """ my_file = open("exercise_2_snake.txt") # opens the file for line in my_file: # takes every line if "snake" in line: # checks if line has a word snake print(line) # prints the line which contains word snake my_file.close() # closes the file
89e1491a5bbfedebff9f528e7c72a0e7941d0911
FishingOnATree/LeetCodeChallenge
/algorithms/11_container_with_most_water.py
934
3.71875
4
# https://leetcode.com/problems/container-with-most-water/ import random class Solution(object): def maxArea(self, height): left, right = 0, len(height) - 1 max_area = 0 while right > left: max_area = max((right - left) * min(height[left], height[right]), max_area) if height[left] < height[right]: left += 1 else: right -= 1 return max_area def correct_answer(heights): return max([min(heights[i], heights[j]) * (j-i) for i in range(len(heights) - 1) for j in range(i+1, len(heights))]) def generate_test(max_size, max_value): n = int(random.random() * (max_size - 5)) + 5 return [int(random.random() * max_value) for _ in range(n)] a = Solution() for _ in range(10000): the_list = generate_test(100, 100) if (a.maxArea(the_list) != correct_answer(the_list)): print(the_list) print("Finished")
735fea1916c9eca2bd10de9df68e8d4336302e66
adityabads/cracking-coding-interview
/chapter4/3_list_of_depths.py
1,470
4.09375
4
# List of Depths # Given a binary tree, design an algorithm which creates a list of all the # nodes at each depth (e.g., if you have a tree with depth D, you'll have D lists). from collections import deque from mybinarytree import TreeNode, make_binary_tree from typing import List import unittest def list_of_depths(root: TreeNode) -> List[TreeNode]: """Return list of nodes at each depth of tree""" # modified level-order traversal nodes = [] q = deque([root]) while q: num_nodes_in_level = len(q) nodes_in_level = [] while num_nodes_in_level > 0: n = q.popleft() nodes_in_level.append(n) if n.left: q.append(n.left) if n.right: q.append(n.right) num_nodes_in_level -= 1 nodes.append(nodes_in_level) return nodes class TestListOfDepths(unittest.TestCase): def test_list_of_depths(self): arrs = [[i for i in range(1, 7)], [i for i in range(1, 8)], [i for i in range(1, 9)], [i for i in range(1, 10)], [1, 2, 3, 4, 5, 6, None, 7]] for arr in arrs: tree = make_binary_tree(arr) depths = list_of_depths(tree) for depth in depths: for node in depth: print(node, end=" ") print() print() if __name__ == "__main__": unittest.main()
f58fb7630c1fe69118448c395aeddf7f535a40a2
Mugdass/performmathcalculation
/mathcalculation.py
1,626
4.21875
4
"Program 1" hoursworked = int(input("Enter hours worked: ")) hourlyrate = int(input("Enter your hourlyrate: ")) print('{} * {} = '.format(hoursworked, hourlyrate)) print("The total is",hoursworked * hourlyrate) print("Is that what you expected?") answer = input ("Answer yes or no please: ") if answer == "yes": print("That is a fair amount!") elif answer == "no": print("You still did better than the average!") else: input("Something went wrong.Would you like to try another calculation? Answer yes or no please: ") if answer=="no": print("Thank you for your time!") print("Goodbye!") answer1=input("Would you like to try another calculation? Answer yes or no please: ") if answer =="yes": print("Okay,Let us try it!") elif answer== "no": print("Thank you for your time!") print("Goodbye!") "Program 2" milesdriven=int(input("Enter number of miles driven: ")) gasused=int(input("Enter gas used: ")) print('{} / {} = '.format(milesdriven, gasused)) print("The total is",hoursworked / hourlyrate) print("On average, you drove this number of miles per galon?") answer=input("Answer yes or no: ") if answer == "yes": print("That is a good number of miles per one galon!") elif answer =="no": print("Revise your numbers!") else: input("An error occurred. Would you like to try another calculation? Answer yes or no please: ") answer2=input("Answer yes or no: ") if answer == "yes": print("Good work! That's impressive.") print("Thank you!") print("Goodbye!") elif answer=="no": print("Thank you for your help!") print("Goodbye!")
0a9c224f066adb85eb7fd9458415cd28892ed99e
pndwrzk/Python-fundamental
/list_method.py
611
4.0625
4
angka = [1, 2, 3, 4, 5] print(angka) # append = menambahkan elemen ke dalam array angka.append(6) print(angka) print("=======") # insert = menambahkan elemen ke dalam array dengan mengatur index arraynya # parameter 1 =index yang ingin di isi # parameter 2 = objek yg ingin dimasukkan angka.insert(2, 11) print(angka) print("=======") # pop = mengapus elemen # parameter = index yang akan di apus angka.pop(0) print(angka) print("=======") # remove = mengapus elemen # parameter = objek yang akan di apus angka.remove(4) print(angka) print("=======") angka.sort() print(angka)
68da4f7f9003cc013a229ad141839bfcb801a75f
sendurr/spring-grading
/submission - lab5/set2/KAITLYN CALLAHAN SHEREYK_9399_assignsubmission_file_Lab5/lab5/Q2.py
289
3.703125
4
def printstar(n): print '*'*n def printstarx(n, row=1): default=1 for i in range(row): printstar(n) # call printstar function row number of times printstarx(10)# print star of lenth n and in 4 row printstarx(10,5)# print stars of length 18 and in one row (default value of row = 1)
5ebe293ca44096c38f6bbfff3fba7d836586e0a1
muh-nasiruit/object-oriented-programming
/OOP 12/Lab 12 Assignment.py
1,077
4.34375
4
''' 1. Create a class People and Birthday and perform the composition Create class People and Birthday which contains instance variables and also implement following methods printDetails()to print the information ''' class Birthday: def __init__(self, day, month, year): self.day = day self.month = month self.year = year def birthDate(self): return f"{self.day}th of {self.month},{self.year}" class Person: def __init__(self, name, age, birthdate): #birthdate FORMAT: "DD/MM/YYYY" self.x = birthdate y = self.x.split('/') self.name = name self.age = age self.day = y[0] self.month = y[1] self.year = y[2] self.hbd = Birthday(self.day, self.month, self.year) def info(self): return f"Name: {self.name}\nAge: {self.age}" def printDetails(self): return f"{self.name} is {self.age}yrs old.\nHe was born on {self.hbd.birthDate()}." p1 = Person("Ahmed", 17, '20/July/2020') print(p1.printDetails())
6fbbf33fce42c2dd091d83073402ab4d99970e38
ebirdvt/hello-world
/Uganda_Project.py
24,632
3.625
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 25 17:40:07 2018 @author: Beth """ from tkinter import * import datetime # Medication tk = Tk () f1 = Frame(tk, bg='blue') f1.grid (sticky = "nsew") Grid.columnconfigure (tk, 0, weight = 1) Grid.rowconfigure (tk, 0, weight = 1) tk.title("Uganda Project") def medication(): """This will run the Medication Reminder Program""" root = Tk () root.bind ("<Return>", lambda event: answer1 ()) f = Frame(root, bg='lightgray') f.grid (sticky = "nsew") Grid.columnconfigure (root, 0, weight = 1) Grid.rowconfigure (root, 0, weight = 1) root.title("Uganda Project") #This is the first Question Bar = Scrollbar (f) T = Listbox (f, fg='white', bg='blue', yscrollcommand = Bar.set, width = 50, height = 50) Bar.config (command = T.yview) T.grid (row = 0, column = 0, columnspan = 2, sticky = "nsew") Bar.grid (row = 0, column = 2, sticky = "ns") Grid.columnconfigure (f, 0, weight = 1) Grid.rowconfigure (f, 0, weight = 1) T.insert (END, "Support:") T.insert (END, " Did you take your medicine?") T.insert (END, " 1= Yes") T.insert (END, " 2= No") #Make an entry box to answer the question in e = Entry(f, fg='black', bg='lightgray') e.focus_force () e.grid (row = 1, column = 0, sticky = "ew") def answer1(): """ What to do with the answer in the entry box""" answer1 = e.get() T.insert (END, "Patient: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " Good Job! Have a good day!") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) elif answer1=="2": T.insert (END, "Support:") T.insert (END, " 1= Did you forget?") T.insert (END, " 2= Did you run out of medicine?") T.insert (END, " 3= Did it have bad side effects?") send.config (command = answer2) root.bind ("<Return>", lambda event: answer2 ()) else: T.insert (END, "Support:") T.insert (END, " I did not understand your response.") T.insert (END, " Please try again.") T.insert (END, "Support:") T.insert (END, " Did you take your medicine?") T.insert (END, " 1= Yes") T.insert (END, " 2= No") answer1 = e.get() T.insert (END, "Patient: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " Good Job! Have a good day!") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) elif answer1=="2": T.insert (END, "Support:") T.insert (END, " 1= Did you forget?") T.insert (END, " 2= Did you run out of medicine?") T.insert (END, " 3= Did it have bad side effects?") send.config (command = answer2) root.bind ("<Return>", lambda event: answer2 ()) return answer1 #Make a Send button to send the answer from the entry box to the definition of answer1 send = Button(f, text="Send", command=answer1) send.grid(row = 1, column = 1, columnspan = 2) #This is the second question def save (): with open ("Medication Log - %s.txt" % str (datetime.datetime.now ()).replace (":", "."), "w") as f: f.write ("\n".join (T.get (0, END))) def answer2(): """ What to do with the answer in the entry box""" answer2 = e.get() T.insert (END, "Patient: " + answer2) e.delete (0, END) #This is the response to the second entry box if answer2=="1": T.insert (END, "Support:") T.insert (END, " Take it as your earliest convience.") T.insert (END, " Do Not Take two doses at once!") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () elif answer2=="2": T.insert (END, "Support:") T.insert (END, " Please contact your doctor or") T.insert (END, " pharmacy for refills.\n") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () elif answer2=="3": T.insert (END, "Support:") T.insert (END, " Please contact your doctor about") T.insert (END, " changing your medications or") T.insert (END, " dealing with your symptoms.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () else: T.insert (END, "Support:") T.insert (END, " I did not understand your response.") T.insert (END, " Please try again.") T.insert (END, "Support:") T.insert (END, " 1= Did you forget?") T.insert (END, " 2= Did you run out of medicine?") T.insert (END, " 3= Did it have bad side effects?") answer2 = e.get() T.insert (END, "Patient: " + answer2) e.delete (0, END) #This is the response to the second entry box if answer2=="1": T.insert (END, "Support:") T.insert (END, " Take it as your earliest convience.") T.insert (END, " Do Not Take two doses at once!") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () elif answer2=="2": T.insert (END, "Support:") T.insert (END, " Please contact your doctor or") T.insert (END, " pharmacy for refills.\n") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () elif answer2=="3": T.insert (END, "Support:") T.insert (END, " Please contact your doctor about") T.insert (END, " changing your medications or") T.insert (END, " dealing with your symptoms.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () return answer2 root.mainloop() return medication button1 = Button(f1, text="Medication", command=medication) button1.grid(row = 1, column = 1, columnspan = 2) # Appoinment def appointment(): """This will run the Appointment Reminder Program""" root = Tk () root.bind ("<Return>", lambda event: answer1 ()) f = Frame(root, bg='lightgray') f.grid (sticky = "nsew") Grid.columnconfigure (root, 0, weight = 1) Grid.rowconfigure (root, 0, weight = 1) root.title("Uganda Project") #This is the first Question Bar = Scrollbar (f) T = Listbox (f, fg='white', bg='blue', yscrollcommand = Bar.set, width = 50, height = 50) Bar.config (command = T.yview) T.grid (row = 0, column = 0, columnspan = 2, sticky = "nsew") Bar.grid (row = 0, column = 2, sticky = "ns") Grid.columnconfigure (f, 0, weight = 1) Grid.rowconfigure (f, 0, weight = 1) T.insert (END, "Support:") T.insert (END, " Remember your appointment is on") T.insert (END, " 6/5/18 at 10:30am at location A.") T.insert (END, " 1= Confirm appointment") T.insert (END, " 2= Reschedule") #Make an entry box to answer the question in e = Entry(f, fg='black', bg='lightgray') e.focus_force () e.grid (row = 1, column = 0, sticky = "ew") def save (): with open ("Appointmnet Log - %s.txt" % str (datetime.datetime.now ()).replace (":", "."), "w") as f: f.write ("\n".join (T.get (0, END))) def answer1(): """ What to do with the answer in the entry box""" answer1 = e.get() T.insert (END, "Patient: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " Thank you. See you then.") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) save () e.pack_forget () elif answer1=="2": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you to reschedule.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () else: T.insert (END, "Support:") T.insert (END, " I did not understand your response.") T.insert (END, " Please try again.") T.insert (END, "Support:") T.insert (END, " Remember your appointment is on") T.insert (END, " 6/5/18 at 10:30am at location A.") T.insert (END, " 1= Confirm appointment") T.insert (END, " 2= Reschedule") answer1 = e.get() T.insert (END, "Patient: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " Thank you. See you then.") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) save () e.pack_forget () elif answer1=="2": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you to reschedule.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () return answer1 #Make a Send button to send the answer from the entry box to the definition of answer1 send = Button(f, text="Send", command=answer1) send.grid(row = 1, column = 1, columnspan = 2) root.mainloop() return appointment button2 = Button(f1, text="Appointment", command=appointment) button2.grid(row = 2, column = 1, columnspan = 2) # Prescription def prescription(): """This will run the Prescription is Ready for Pick-Up Remider Program""" root = Tk () root.bind ("<Return>", lambda event: answer1 ()) f = Frame(root, bg='lightgray') f.grid (sticky = "nsew") Grid.columnconfigure (root, 0, weight = 1) Grid.rowconfigure (root, 0, weight = 1) root.title("Uganda Project") #This is the first Question Bar = Scrollbar (f) T = Listbox (f, fg='white', bg='blue', yscrollcommand = Bar.set, width = 50, height = 50) Bar.config (command = T.yview) T.grid (row = 0, column = 0, columnspan = 2, sticky = "nsew") Bar.grid (row = 0, column = 2, sticky = "ns") Grid.columnconfigure (f, 0, weight = 1) Grid.rowconfigure (f, 0, weight = 1) T.insert (END, "Support:") T.insert (END, " Your prescription is ready for pick-up.") T.insert (END, " Please get it at your earliest convience.") T.insert (END, " 1= Confirm read message.") T.insert (END, " 2= Didn't need a refill.") #Make an entry box to answer the question in e = Entry(f, fg='black', bg='lightgray') e.focus_force () e.grid (row = 1, column = 0, sticky = "ew") def save (): with open ("Prescription Log - %s.txt" % str (datetime.datetime.now ()).replace (":", "."), "w") as f: f.write ("\n".join (T.get (0, END))) def answer1(): """ What to do with the answer in the entry box""" answer1 = e.get() T.insert (END, "Patient: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " Thank you. Have a good day.") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) save () e.pack_forget () elif answer1=="2": T.insert (END, "Support:") T.insert (END, " Sorry for the error.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () else: T.insert (END, "Support:") T.insert (END, " I did not understand your response.") T.insert (END, " Please try again.") T.insert (END, "Support:") T.insert (END, " Your prescription is ready for pick-up.") T.insert (END, " Please get it at your earliest convience.") T.insert (END, " 1= Confirm read message.") T.insert (END, " 2= Didn't need a refill.") answer1 = e.get() T.insert (END, "Patient: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " Thank you. Have a good day.") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) save () e.pack_forget () elif answer1=="2": T.insert (END, "Support:") T.insert (END, " Sorry for the error.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () return answer1 #Make a Send button to send the answer from the entry box to the definition of answer1 send = Button(f, text="Send", command=answer1) send.grid(row = 1, column = 1, columnspan = 2) root.mainloop() return prescription button3 = Button(f1, text="Prescription", command=prescription) button3.grid(row = 3, column = 1, columnspan = 2) # Side Effects def side_effects(): """This will run the Side Effects Program""" root = Tk () root.bind ("<Return>", lambda event: answer1 ()) f = Frame(root, bg='lightgray') f.grid (sticky = "nsew") Grid.columnconfigure (root, 0, weight = 1) Grid.rowconfigure (root, 0, weight = 1) root.title("Uganda Project") #This is the first Question Bar = Scrollbar (f) T = Listbox (f, fg='white', bg='blue', yscrollcommand = Bar.set, width = 50, height = 50) Bar.config (command = T.yview) T.grid (row = 0, column = 0, columnspan = 2, sticky = "nsew") Bar.grid (row = 0, column = 2, sticky = "ns") Grid.columnconfigure (f, 0, weight = 1) Grid.rowconfigure (f, 0, weight = 1) T.insert (END, "Support:") T.insert (END, " Are you having bad side effects from your medicine?") T.insert (END, " 1= Yes") T.insert (END, " 2= No") #Make an entry box to answer the question in e = Entry(f, fg='black', bg='lightgray') e.focus_force () e.grid (row = 1, column = 0, sticky = "ew") def save (): with open ("Side Effect Log - %s.txt" % str (datetime.datetime.now ()).replace (":", "."), "w") as f: f.write ("\n".join (T.get (0, END))) def answer1(): """ What to do with the answer in the entry box""" answer1 = e.get() T.insert (END, "Patient: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you.") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) save () e.pack_forget () elif answer1=="2": T.insert (END, "Support:") T.insert (END, " I'm glad to hear you aren't having bad side effects.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save() e.pack_forget () else: T.insert (END, "Support:") T.insert (END, " I did not understand your response.") T.insert (END, " Please try again.") T.insert (END, "Support:") T.insert (END, " Are you having bad side effects from your medicine?") T.insert (END, " 1= Yes") T.insert (END, " 2= No") answer1 = e.get() T.insert (END, "Patient: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you.") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) save () e.pack_forget () elif answer1=="2": T.insert (END, "Support:") T.insert (END, " I'm glad to hear you aren't having bad side effects.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save() e.pack_forget () return answer1 #Make a Send button to send the answer from the entry box to the definition of answer1 send = Button(f, text="Send", command=answer1) send.grid(row = 1, column = 1, columnspan = 2) root.mainloop() return side_effects button4 = Button(f1, text="Side Effects", command=side_effects) button4.grid(row = 4, column = 1, columnspan = 2) # Patient Initiated def patient_initiated(): """This will run the Patient Initiated Conversation Program""" root = Tk () root.bind ("<Return>", lambda event: start_convo ()) f = Frame(root, bg='lightgray') f.grid (sticky = "nsew") Grid.columnconfigure (root, 0, weight = 1) Grid.rowconfigure (root, 0, weight = 1) root.title("Uganda Project") #This is the beginning of the conversation Bar = Scrollbar (f) T = Listbox (f, fg='white', bg='blue', yscrollcommand = Bar.set, width = 50, height = 50) Bar.config (command = T.yview) T.grid (row = 0, column = 0, columnspan = 2, sticky = "nsew") Bar.grid (row = 0, column = 2, sticky = "ns") Grid.columnconfigure (f, 0, weight = 1) Grid.rowconfigure (f, 0, weight = 1) #Make an entry box to answer the question in e = Entry(f, fg='black', bg='lightgray') e.focus_force () e.grid (row = 1, column = 0, sticky = "ew") def start_convo(): """ What to do with the answer in the entry box""" start_convo = e.get() T.insert (END, "Patient: " + start_convo) e.delete (0, END) if start_convo=="77": T.insert (END, "Support:") T.insert (END, " 1= Need to talk to the Nurse.") T.insert (END, " 2= Need to reschedule an appoinment.") T.insert (END, " 3= Need a medication refill.") send.config (command = answer2) root.bind ("<Return>", lambda event: answer2 ()) else: T.insert (END, "Support:") T.insert (END, " I did not understand your response.") T.insert (END, " Were you trying to contact us for help?") T.insert (END, " Please text 77.") start_convo = e.get() T.insert (END, "Patient: " + start_convo) e.delete (0, END) if start_convo=="77": T.insert (END, "Support:") T.insert (END, " 1= Need to talk to the Nurse.") T.insert (END, " 2= Need to reschedule an appoinment.") T.insert (END, " 3= Need a medication refill.") send.config (command = answer2) root.bind ("<Return>", lambda event: answer2 ()) return start_convo #Make a Send button to send the answer from the entry box to the definition of answer1 send = Button(f, text="Send", command=start_convo) send.grid(row = 1, column = 1, columnspan = 2) #This is the second question def save (): with open ("Patient Log - %s.txt" % str (datetime.datetime.now ()).replace (":", "."), "w") as f: f.write ("\n".join (T.get (0, END))) def answer2(): """ What to do with the answer in the entry box""" answer2 = e.get() T.insert (END, "Patient: " + answer2) e.delete (0, END) #This is the response to the second entry box if answer2=="1": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you.") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) save () e.pack_forget () elif answer2=="2": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () elif answer2=="3": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () else: T.insert (END, "Support:") T.insert (END, " I did not understand your response.") T.insert (END, " Please try again.") T.insert (END, "Support:") T.insert (END, " 1= Need to talk to the Nurse.") T.insert (END, " 2= Need to reschedule an appoinment.") T.insert (END, " 3= Need a medication refill.") answer2 = e.get() T.insert (END, "Patient: " + answer2) e.delete (0, END) #This is the response to the second entry box if answer2=="1": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you.") send.config (text = "OK", command = root.destroy) root.bind ("<Return>", lambda event: root.destroy ()) save () e.pack_forget () elif answer2=="2": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () elif answer2=="3": T.insert (END, "Support:") T.insert (END, " The Nurse will contact you.") root.bind ("<Return>", lambda event: root.destroy ()) send.config (text = "OK", command = root.destroy) save () e.pack_forget () return answer2 root.mainloop() return patient_initiated button5 = Button(f1, text="Patient Initiated", command=patient_initiated) button5.grid(row = 5, column = 1, columnspan = 2) tk.mainloop()
5aa178a981fc160728d44e91e7f5f2d991114505
anirbaSP/myWork
/dualColor/myutilities.py
895
3.625
4
import json import numpy as np class NumpyEncoder(json.JSONEncoder): """ Because numpy.ndarray is not a type that json knows how to handle, this approach "jsonify" numpy.ndarrays to list that can be saved to .json. Example: a = np.array([123]) print(json.dumps({'aa':[2, (2, 3, 4), a], 'bb': [2]}, cls=NumpyEncoder Copyright kalB (Dec 2017) from stackoverflow """ def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj) def find(search_list, elem): """ Search multiple elements in a list. :param search_list: a nested list. :param elem: a list. :return: a nested list, each with 0 or 1 for a searched element. """ return [[i for i, x in enumerate(search_list) if e in x] for e in elem]
3043a9ecf26c8fee1269e76e59d2443fc6d8f6e7
amakhlin/Udacity-CS373-Artificial-Intelligence-for-Robotics
/final_dp.py
2,591
3.71875
4
# ---------- # User Instructions: # # Create a function compute_value() which returns # a grid of values. Value is defined as the minimum # number of moves required to get from a cell to the # goal. # # If it is impossible to reach the goal from a cell # you should assign that cell a value of 99. # ---------- grid = [[0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0]] init = [0, 5] goal = [len(grid)-1, len(grid[0])-1] delta_name = ['^', '<', 'v', '>'] cost_step_adj = 1 # the cost associated with moving from a cell to an adjacent one. cost_step_diag = 1.5 # ---------------------------------------- # insert code below # ---------------------------------------- def compute_cost_to_goal(grid, init, goal, cost_step_adj, cost_step_diag): delta = [[-1, 0 ], # 0 go up [ 0, -1], # 1 go left [ 1, 0 ], # 2 go down [ 0, 1 ], # 3 go right [-1, -1], # 4 diag up-left [-1, 1], # 5 diag up-right [1, -1], # 6 diag down-left [1, 1],] # 7 diag down-right value = [[999 for row in range(len(grid[0]))] for col in range(len(grid))] value[goal[0]][goal[1]] = 0 open = [] open.append([ 0, goal[0], goal[1]]) visited = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] visited[goal[0]][goal[1]] = 1 while(1): if len(open) == 0: break; else: open.sort() open.reverse() next = open.pop() x = next[1] y = next[2] for i in range(len(delta)): x2 = x + delta[i][0] y2 = y + delta[i][1] if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]): if visited[x2][y2] == 0 and grid[x2][y2] == 0: if i < 4: cost = cost_step_adj else: cost = cost_step_diag value[x2][y2] = value[x][y] + cost open.append([value[x2][y2], x2, y2]) visited[x2][y2] = 1 #for i in range(len(value)): # print value[i] return value[init[0]][init[1]] # return cost to the goal from the init state print compute_cost_to_goal(grid, init, goal, cost_step_adj, cost_step_diag)
14dfccd59f9ba0f6d82751e826cb64183c30d21a
priyankaauti123/Algo
/kmp_search.py
1,048
3.75
4
text="abxabcabcaby" pattern1="abcaby" pattern2="aabaabaaa" pattern3="cabc" def prefix(pattern): prefix_arr=[0 for i in range(len(pattern))] prefix_arr[0]=0 i=0 j=1 while(j>=i and j<len(pattern)): if pattern[i]==pattern[j]: prefix_arr[j]=i+1 j+=1 i+=1 else: if i==0: i=0 j+=1 else: i=prefix_arr[i-1] return prefix_arr def kmp_search(text,pattern,prefix_arr): i=0 j=0 while(j<=i): if pattern[j]==text[i]: if j==len(pattern)-1: print "found" return 0 else: i+=1 j+=1 else: if len(pattern[j:])>len(text[i:]): print "not found" return 1 if j==0: j=0 i+=1 else: j=prefix_arr[j-1] prefix_arr=prefix(pattern3) print prefix_arr val=kmp_search(text,pattern3,prefix_arr)
3fe1c11abd9c6bcc3593e95bf46bade86a3228dd
LeviShepherd/Coupon_Calculations
/store/coupon_calculations.py
2,342
4.09375
4
""" Program: coupon_calculations.py Author: Levi Shepherd Last date modified: 9/21/2020 The purpose of this program is to take input for amount of purchase, cash coupon amount, and percent coupon, then calculate and display the total order amount. """ # Calculate the total amount due based on user input for price, cash coupon and percent coupons def calculate_price(price, cash_coupon, percent_coupon): TAX_RATE = 1.06 SHIP_10 = 5.95 SHIP_30 = 7.95 SHIP_50 = 11.95 CASH_5 = 5 CASH_10 = 10 PERCENT_10 = .90 PERCENT_15 = .85 PERCENT_20 = .80 subtotal = 0 # Factoring in coupons, cash discounts and tax # Determine subtotal with all instances of no cash discount if cash_coupon == 0: if percent_coupon == 0: subtotal = (price * TAX_RATE) elif percent_coupon == 10: subtotal = (price * PERCENT_10) * TAX_RATE elif percent_coupon == 15: subtotal = (price * PERCENT_15) * TAX_RATE else: subtotal = (price * PERCENT_20) * TAX_RATE # Determine subtotal with all instances of a 5 dollar cash discount elif cash_coupon == 5: if percent_coupon == 0: subtotal = (price - CASH_5) * TAX_RATE elif percent_coupon == 10: subtotal = ((price - CASH_5) * PERCENT_10) * TAX_RATE elif percent_coupon == 15: subtotal = ((price - CASH_5) * PERCENT_15) * TAX_RATE else: subtotal = ((price - CASH_5) * PERCENT_20) * TAX_RATE # Determine subtotal with all instances of a 10 dollar cash discount else: if percent_coupon == 0: subtotal = (price - CASH_10) * TAX_RATE elif percent_coupon == 10: subtotal = ((price - CASH_10) * PERCENT_10) * TAX_RATE elif percent_coupon == 15: subtotal = ((price - CASH_10) * PERCENT_15) * TAX_RATE else: subtotal = ((price - CASH_10) * PERCENT_20) * TAX_RATE # Determine total if subtotal >= 50: total = subtotal elif 30 <= subtotal < 50: total = subtotal + SHIP_50 elif 10 <= subtotal < 30: total = subtotal + SHIP_30 elif subtotal < 10: total = subtotal + SHIP_10 else: print("Looks like we owe you one!") return total if __name__ == '__main__': pass
0ae3c7d322f21ce7176e68d8721c7ab7a176d9bf
osbilln/shell
/maxWidthsCsv.py
640
3.546875
4
#!/usr/bin/env python """ Prints the max widths of the columns of the given CSV_FILE padded by 10. Usage: maxWidthsCsv.py CSV_FILE Bugs: Calculates the widths in bytes, not characters. """ import csv import sys if len(sys.argv) < 2: print __doc__ sys.exit(1) reader = csv.reader(open(sys.argv[1])) lengths = {} first = True for row in reader: if first: headers = row i=0 for col in row: lengths[i] = 0 i = i+1 first = False else: i=0 for col in row: leng = len(col) if leng > lengths[i]: lengths[i] = leng i = i+1 i=0 for col in headers: print '%-50s = %d' % (headers[i], lengths[i]+10) i = i+1
3b74ebe0cac395156d0c238b20acfdcdcd815fd0
Agchai52/Leetcode1
/0897.py
1,428
3.9375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def increasingBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ ''' 1. in-order Traversal 2. generate new tree at the same time 3. Time O(N) Space O(N) ''' ''' # Method 1: Stack if not root or not root.left and not root.right: return root stack = [] head = pointer = TreeNode(0) while True: while root: stack.append(root) root = root.left if not stack: return head.right root = stack.pop() pointer.right = TreeNode(root.val) pointer = pointer.right root = root.right return head.right ''' # Method 2: Recursion if not root or not root.right and not root.left: return root head = TreeNode(0) self.point = head self.dfs(root) return head.right def dfs(self, root): if not root: return None self.dfs(root.left) self.point.right = TreeNode(root.val) self.point = self.point.right self.dfs(root.right)
309149e161f3c53595db7adc30e5063e55f97c52
sigamateusz/decoder
/riddle1.py
937
3.640625
4
ALPHABET = (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'), ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')) def content_to_str(data_file_name): """Creates string with content from file""" content = [] with open(data_file_name, 'r') as f: content = f.read() return content def print_decoded(i, n): poz = ALPHABET[n].index(i) + 1 print(ALPHABET[n][-poz], end='') def main(): word = content_to_str('text.txt') for i in word: if i == '\n': print('') elif i == " ": print(' ', end='') elif i in ALPHABET[0]: print_decoded(i, 0) elif i in ALPHABET[1]: print_decoded(i, 1) if __name__ == '__main__': main()
2b16380940f1841b5013ad7649de25f819aace7a
ThereIsOnlyZuul/paper_towersOfHanoi
/code/lib/towers.py
755
4.03125
4
##### This module provides a model for playing the Towers of Hanoi ### Tower - a tower for the disks to stand on class Tower: def __init__(self,disks): self._disks = disks ### The disks that must be moved from tower to tower class Disk: ## the size of the disk is returned (Object Oriented Design) def size(self): return self._size ## disks should be moved one at a time def move(self,owner,target): self._moveCount += 1; owner._disks.remove(self); target._disks.append(self); ## each disk keeps track of the number of moves it has made def moveCount(self): return self._moveCount; def __init__(self,size): self._size = size self._moveCount = 0;
34f9716964252a211b7f70d31f93ef72a12404b1
YevhenMix/courses
/Python Pro/Лекция 7. Генераторы/Lection_7_tsk_2.py
1,437
3.828125
4
from random import randint def my_range(*args): if len(args) == 1: stop = args[0] i = 0 while i != stop: yield i i += 1 elif len(args) == 2: start = args[0] stop = args[1] if start > stop: return [] else: while start != stop: yield start start += 1 elif len(args) == 3: start = args[0] stop = args[1] step = args[2] if start > stop: return [] else: while start < stop: yield start start += step else: raise TypeError for col in range(5): stop1 = randint(1, 30) print(f'{stop1}') a = range(stop1) b = my_range(stop1) print(f'Classic range: {list(a)}') print(f'My range: {list(b)}') print('*' * 100) for col in range(5): start1 = randint(1, 30) stop1 = randint(1, 30) print(f'{start1}, {stop1}') a = range(start1, stop1) b = my_range(start1, stop1) print(f'Classic range: {list(a)}') print(f'My range: {list(b)}') print('*' * 100) for col in range(5): start1 = randint(1, 30) stop1 = randint(1, 30) step1 = randint(1, 5) print(f'{start1}, {stop1}, {step1}') a = range(start1, stop1, step1) b = my_range(start1, stop1, step1) print(f'Classic range: {list(a)}') print(f'My range: {list(b)}')
0c2ca73f66821f9bce5b0d6a8583ee3e0bcd9ef4
otaithleigh/libtalley-py
/src/libtalley/latex.py
2,677
3.515625
4
"""Functions that format strings into the appropriate LaTeX format.""" def diff(f, x, n=1, partial=False): """Derivative representation. Parameters ---------- f: function to be differentiated. x: variable to diff w.r.t. n: number of times to diff. (default: 1) partial Whether this is a partial derivative or not. """ if partial: differ = R'\partial' else: differ = Rf"\mathrm{{d}}" if n > 1: level = f"^{n}" else: level = '' diff = '\\frac{%(differ)s%(level)s{%(f)s}}{%(differ)s{%(x)s}%(level)s}' % { 'differ': differ, 'level': level, 'f': f, 'x': x, } return diff def steel_shape_name(shape, frac='nicefrac'): R"""Return LaTeX code for nicely typesetting a steel section name. Assumes the "by" part of the section is represented by an 'X', and that compound fractions are separated by '-' (hyphen, not endash). Only tested on W and HSS names so far. Parameters ---------- shape : str Name of a steel section. frac : {'frac', 'tfrac', 'sfrac', 'nicefrac'}, optional The fraction macro to use. (default: 'nicefrac') Example ------- >>> name = 'HSS3-1/2X3-1/2X3/16' >>> steel_shape_name(name) 'HSS3\\nicefrac{1}{2}\\(\\times\\)3\\nicefrac{1}{2}\\(\\times\\)\\nicefrac{3}{16}' """ # Whether or not we need to be in math mode to use the specified macro. try: math_mode = { 'frac': True, 'tfrac': True, 'sfrac': False, 'nicefrac': False, }[frac] except KeyError as exc: raise ValueError(f'Unrecognized fraction macro {frac!r}') from exc def frac_to_nicefrac(f): """Return LaTeX code for a nicefrac from a fraction like '3/16'. Does not support compound fractions.""" (numer, denom) = f.split('/') frac_code = R'\%s{%s}{%s}' % (frac, numer, denom) if math_mode: frac_code = R'\(' + frac_code + R'\)' return frac_code # Split the name into pieces, and deal with any fractions. shape_parts = shape.split('X') for [index, part] in enumerate(shape_parts): if '/' in part and '-' in part: # Got a compound fraction (integer, fraction) = part.split('-') newfraction = frac_to_nicefrac(fraction) shape_parts[index] = integer + newfraction elif '/' in part: # Got a plain fraction shape_parts[index] = frac_to_nicefrac(part) latex_code = R'\(\times\)'.join(shape_parts) return latex_code
788f648094e9b6baf67e75b404063dce224703bd
nikhilcusc/HRP-1
/ProbSol/pairs.py
989
3.96875
4
''' You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value. ''' def pairs(k, arr): countPairs = 0 for i in range(len(arr)): for j in range(i+1,len(arr) ): if abs(arr[i]-arr[j])==k: countPairs+=1 return countPairs def pairsDic(k, cost): #using dictionary ind = {} countPairs = 0 for i in (cost): ind[i]=1 print(ind) for i in cost: if i-k in ind.keys(): countPairs+=1 return countPairs def pairsDic2(k, cost): #using dictionary and exception handling ind = {} countPairs = 0 for i in (cost): ind[i]=1 print(ind) for i in cost: try: print(ind[i-k]) countPairs+=1 except KeyError: continue return countPairs target = 2 arr = '1 5 3 4 2' arr = list(map(int, arr.split())) print(pairsDic2(target, arr))
fb06409033fcf74a923908d99f0e53190529d552
alexadusei/PythonScripts
/Grid/Grid.py
503
3.84375
4
""" Name: Alex Adusei Date: Friday September 13 2013 Program: Grid Details: Program has a function that draws a grid """ def grid(x, y): numRows = x numCols = y def printGrid(): print numRows * ('+ - - - - ') + str('+') print 4 * (numRows * ('| ') + str('|\n')), def loop(cols): counter = 1; while counter <= cols: printGrid() counter += 1 print numRows * ('+ - - - - ') + str('+') loop(numCols)
974c6d477ef0f54cdd175c151654d6cfee106e01
bhagesh-codebeast/mscbioinfo
/MATHEMATICS/MATRIX_CALCULATION/matrix_py/test_files/test_loop.py
388
3.890625
4
n_lines = int(input('How many lines do you want to input?')) lines = [] for i in range(n_lines): x = input() lines.append(x) if int(x) >= 5: break print(lines) n_lines = int(input('How many lines do you want to inputvvvv?')) lines = [input() for i in range(5 if n_lines>5 else n_lines)] lines = "" for i in range(no_of_lines): lines+=input()+"\n" print(lines)
d24d2ae8343b330335f0b489ab555e1e065006f5
KimGreenbush/CodingDojo
/Python/Fundamentals/OOP/user_with_bank_account.py
1,160
3.734375
4
class User: def __init__(self, name, email): self.name = name self.email = email self.account_one = BankAccount(int_rate=0.01, balance=0) self.account_two = BankAccount(int_rate=0.02, balance=0) class BankAccount: def __init__(self, int_rate=0.01, balance=0): self.int_rate = int_rate self.account_balance = balance def deposit(self, amount): self.account_balance += amount return self def withdraw(self, amount): self.account_balance -= amount return self def display_user_info(self): print("Account Balance: $" + str(self.account_balance) + ", Interest Rate: " + str(self.int_rate)) return self def transfer_money(self, other_user, amount): self.account_balance -= amount other_user.account_balance += amount return self def yield_interest(self): self.account_balance += (self.account_balance * self.int_rate) return self kim = User("Kimberley", "kk@gg.com") kim.account_one.deposit(85) kim.account_one.display_user_info() kim.account_two.deposit(100) kim.account_two.display_user_info()
ea839d0a817ec67f7e6b0641161d6592838aa6d9
Anh1223/-ng-Quang-Anh-C4T6
/Session 8/inventory.py
1,767
3.5625
4
# def show(age): # print("My age", age) # huy_age = 17 # quang_anh_age = 29 # show(huy_age) # show(quang_anh_age) player = { "NAME": "Quang Anh", "HP": 60, "STR": 20, "DEF": 5, "LUCK": 10, "CRT": 6, "EXP": 1, "LVL": 1, } MiniZombie = { "NAME": "MiniZombie", "HP": 40, "STR": 17, "DEF": 7, "LUCK": 2, "EXP": 1, "LVL": 1, } # steal_gauntlet = { # "NAME": "Steal gauntlet", # "DEF": 5, # "STR": 5, # "AGI": 3, # } # # bronze_shield = { # "NAME": "Bronze shield", # "DEF": 12, # "STR": 4, # "AGI": -5, # } # # golden_stick = { # "NAME": "Golden stick", # "AGI": 15, # "HP": 20, # "STR": 100 # } inventory = [player, MiniZombie] def combat(attacker, defender): print(attacker["NAME"], "is beating", defender["NAME"]) damage = attacker["STR"] - defender["DEF"] if damage > 0: defender["HP"] -= damage print(defender["NAME"], "lost", damage, "HP") else: attacker["HP"] -= abs(damage) print(attacker["NAME"], "lost", abs(damage), "HP") def show_index(name): print("*"*15) for key, value in name.items(): print("*", key, value) print("*"*15) while True: combat(player, MiniZombie) show_index(player) show_index(MiniZombie) if MiniZombie["HP"] <= 0: print("You win") break elif player["HP"] <= 0: print("Game over") break combat(MiniZombie, player) show_index(player) show_index(MiniZombie) if MiniZombie["HP"] <= 0: print("You win") break elif player["HP"] <= 0: print("Game over") break
2ddf6cf834a440913468ea3682934af85ac0ffdd
woorud/Algorithm
/practice/구현/하노이의 탑.py
316
3.96875
4
def solution(n): def hanoi(n, start, to, end): if n == 1: answer.append([start, to]) else: hanoi(n-1, start, end, to) answer.append([start, to]) hanoi(n-1, end, to, start) answer = [] hanoi(n, 1, 3, 2) return answer print(solution(2))
634ed7619b433c365b3fc3d9cf64f7870a737347
alokojjwal/snakes_and_ladder
/snakes_and_ladder.py
3,381
3.953125
4
import random def check_ladder(pnt): if pnt==2: print("ladder and the points is now 23") return 23 elif pnt==6: print("ladder and the points is now 45") return 45 elif pnt==20: print("ladder and the points is now 59") return 59 elif pnt==57: print("ladder and the points is now 96") return 96 elif pnt==22: print("ladder and the points is now 72") return 72 elif pnt==77: print("ladder and the points is now 92") return 92 else: return pnt def check_snakes(pnt): if pnt==98: print("snake and the points is now 40") return 40 elif pnt==87: print("snake and the points is now 49") return 49 elif pnt==84: print("snake and the points is now 58") return 58 elif pnt==73: print("snake and the points is now 15") return 15 elif pnt==56: print("snake and the points is now 8") return 8 elif pnt==50: print("snake and the points is now 5") return 5 elif pnt==43: print("snake and the points is now 17") return 17 else: return pnt def won(pnt): if pnt==100: return True else: return False def snakes(): player1=input("Enter the name of player 1: ") player2=input("Enter the name of player 2: ") pp1=0 pp2=0 turn=0 while(1): if turn%2==0: print(" ") print("Hey",player1,"it's your turn") x=int(input("Roll the dice: (Enter 1 to roll): ")) while(1): if x!=1: print("Invalid input, try again") x=int(input("Roll the dice: (Enter 1 to roll): ")) else: break dice=random.randint(1,6) print("Hey",player1,"your dice shows:",dice) pp1=pp1+dice print(" ") print("Hey",player1,"your score is: ",pp1) if pp1>100: pp1=pp1-dice print("Your points returns to ",pp1) else: pp1=check_ladder(pp1) pp1=check_snakes(pp1) if won(pp1): print("Hey",player1,"you won") break else: print(" ") print("Hey",player2,"it's your turn") x=int(input("Roll the dice: (Enter 1 to roll): ")) while(1): if x!=1: print("Invalid input, try again") x=int(input("Roll the dice: (Enter 1 to roll): ")) else: break dice=random.randint(1,6) print("Hey",player2,"your dice shows:",dice) pp2=pp2+dice print(" ") print("Hey",player2,"your score is: ",pp2) if pp2>100: pp2=pp2-dice print("Your points returns to ",pp2) else: pp2=check_ladder(pp2) pp2=check_snakes(pp2) if won(pp2): print("Hey",player2,"you won") break turn+=1 snakes()
4716c59c902d55f8f0e842c50cc22e5e184922ab
MDOBreno/PythonExercicios
/ex065.py
533
3.921875
4
''' Exercicio 065 ''' from sys import float_info media = 0.0 qtdNumeros = 0 maior = float_info.min menor = float_info.max n = 1 continuar = True while continuar: n = int(input('Digite um número: ')) media += n qtdNumeros += 1 if n > maior: maior = n if n < menor: menor = n continuar = str(input('Deseja continuar: [S/N] ')).upper() == 'S' media = media / qtdNumeros print(f'\nDeu uma media de {media}, dos {qtdNumeros} números digitados. ') print(f'O menor={menor}, e o maior={maior}')
5974545b571caf6abe503665d04aaba4f4b9950d
zjuzpz/Algorithms
/others/Monty Hall Problem.py
635
3.78125
4
""" Monty Hall problem """ from random import randint def win(change): target = randint(1, 3) choose = randint(1, 3) if target != choose: for i in range(1, 4): if i != choose and i != target: if change: return True return False elif change: return False return True if __name__ == "__main__": countChange, countNotChange, total = 0, 0, 10000 for i in range(total): if win(True): countChange += 1 if win(False): countNotChange += 1 print(countChange / total, countNotChange / total)
ec6895ce86cb293f917acf42156f1c40299b5150
SatyaChipp/PythonImpls
/HackerRank/Challenges/AscendIO/Q4_Origin_destinationCities.py
573
3.5
4
Given a list of oring cities and a list of destination cities find if there is a route from origin to destination if origin cities and destination cities have common divisors, then there is a route from origin to destination sample origin [1, 2,3] dest [4, 5, 6] Origin divisors dest divisors 1 1 4 1,2 4 2 1, 2 5 1, 5 3 1, 3 6 1, 2, 3, 6 if we have a threshold of 2 then eliminate cities <2 now city 3 and dest city 6 have common divisors ..hence there is a route from 3 to 6!! Now get cracking!
26088678c442ad73cd9c14b5b78fdd5a5c19fa3a
SherryShall/LeetCode
/Sort_BubbleSort.py
1,007
4.125
4
# 时间 O(n^2) 最坏O(n^2) 最好O(n) # 空间 O(1) # 稳定 def bubble_sort(array): def swap(a, b): a = a ^ b b = a ^ b a = a ^ b return a, b swap_flag = False for i in range(len(array)-1): for j in range(len(array)-i-1): if array[j+1] < array[j]: swap_flag = True # print(array[j], array[j+1]) # array[j+1], array[j] = array[j], array[j+1] array[j], array[j+1] = swap(array[j], array[j+1]) # print(array[j], array[j+1]) if not swap_flag: break return array """ 冒泡排序改进算法,时间复杂度O(n^2) 设置flag,当一轮比较中未发生交换动作,则说明后面的元素其实已经有序排列了。 对于比较规整的元素集合,可提高一定的排序效率。 """ if __name__ == "__main__": print(bubble_sort([3, 6, 1, 2, 8, 4, 9, 9, 10, 8])) print(bubble_sort([]))
42536ee31aab19c4f1a139723e8fa2026cb42a52
PullBack993/Python-OOP
/6.Polymorphism - Exercise/3.Account.py
4,113
3.5625
4
class Account: def __init__(self, owner: str, amount=0): self.owner = owner self.amount = amount self._transactions = [] def add_transaction(self, amount): if not isinstance(amount, int): raise ValueError("please use int for amount") # self.amount += amount self._transactions.append(amount) @property def balance(self): return sum(self._transactions) + self.amount @staticmethod def validate_transaction(account: 'Account', amount_to_add): if account.balance + amount_to_add < 0: raise ValueError("sorry cannot go in debt!") account.add_transaction(amount_to_add) return f'New balance: {account.balance}' def __str__(self): return f"Account of {self.owner} with starting amount: {self.amount}" def __repr__(self): return f'Account({self.owner}, {self.amount})' def __len__(self): return len(self._transactions) def __getitem__(self, index): return self._transactions[index] def __eq__(self, other): return self.balance == other.balance def __ne__(self, other): return self.balance != other.balance def __lt__(self, other): return self.balance < other.balance def __le__(self, other): return self.balance <= other.balance def __gt__(self, other): return self.balance > other.balance def __ge__(self, other): return self.balance >= other.balance def __add__(self, other): new_acc = Account(self.owner + "&" + other.owner, self.amount + other.amount) new_acc._transactions = self._transactions + other._transactions return new_acc # def main(): # def test_add_transaction(): # acc = Account('john die ', amount=20) # acc.add_transaction(20) # acc.add_transaction(10) # # print(acc._transactions, 'Should be [20, 10]') # # def test_balance(): # acc = Account('john die ', amount=20) # acc.add_transaction(20) # acc.add_transaction(10) # print(acc.balance, 'should be 50') # # def test_safe_transaction(): # acc = Account('john die ', amount=0) # acc.add_transaction(-10) # print(acc.balance, 'Shout be -10') # try: # acc.validate_transaction(acc, -10) # except ValueError: # print('transaction failed') # # def test_account_to_string(): # acc = Account('bob', amount=20) # print(str(acc), 'should be "Account of bob with starting amount: 20"') # # def test_account_to_repr(): # acc = Account('bob', amount=20) # print(repr(acc), f'Account(bob, 20)') # # def test_len_account(): # acc = Account('mery', amount=20) # acc.add_transaction(20) # acc.add_transaction(10) # print(len(acc), 'should be 2') # # def test_iteration_account(): # acc = Account('mery', amount=20) # acc.add_transaction(10) # acc.add_transaction(15) # acc.add_transaction(20) # print(list(acc), 'Should be [10, 15, 20]') # # def test_index_account(): # acc = Account('mery', amount=20) # acc.add_transaction(10) # acc.add_transaction(15) # acc.add_transaction(20) # print(acc[1], 'Should be 15') # # test_add_transaction() # test_balance() # test_safe_transaction() # test_account_to_string() # test_account_to_repr() # test_len_account() # test_iteration_account() # test_index_account() # # if __name__ == "__main__": # main() acc = Account('bob', 10) acc2 = Account('john') print(acc) print(repr(acc)) acc.add_transaction(20) acc.add_transaction(-20) acc.add_transaction(30) print(acc.balance) print(len(acc)) for transaction in acc: print(transaction) print(acc[1]) print(list(reversed(acc))) acc2.add_transaction(10) acc2.add_transaction(60) print(acc > acc2) print(acc >= acc2) print(acc < acc2) print(acc <= acc2) print(acc == acc2) print(acc != acc2) acc3 = acc + acc2 print(acc3) print(acc3._transactions)
86b3b1476ff9727158e09b3d0d677c3749e9c064
nileshbhoyar/LargeScaleML
/HW2/Total_sort/mapper.py
227
3.71875
4
#!/usr/bin/env python # START STUDENT CODE HW212MAPPER import sys import re for line in sys.stdin: line = line.strip() for word in re.findall(r'[a-z]+', line.lower()): print word,"\t",1 # END STUDENT CODE HW212MAPPER
5f66f56a558fdeafa2295eb59a7268e31f4e320a
higoress/HackerRank
/python/cycle_detection.py
259
3.703125
4
#identify cycles in a linked list def has_cycle(head): taboo_list = list() temp = head while temp: if temp not in taboo_list: taboo_list.append(temp) temp = temp.next else: return 1 return 0
81550b5a1901263ccb135ad3adba44be5184d631
AidenLong/ai
/test/test/Solution.py
1,058
4.1875
4
# -*- coding:utf-8 -*- """ 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def level_order(root): """ :type root: TreeNode :rtype: List[List[int]] """ queue = [root] res = [] if not root: return [] while queue: templist = [] templen = len(queue) for i in range(templen): temp = queue.pop(0) templist.append(temp.val) if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) res.append(templist) return res if __name__ == '__main__': root_node = TreeNode(1) root_node.left = TreeNode(2) right = TreeNode(3) right.left = TreeNode(4) right.right = TreeNode(5) root_node.right = right print(level_order(root_node))
b24cfbb7bd5711bc83fc3213f418387fac2d65c2
JyotiSathe/Python
/Assignments/Class Assignments/temp.py
131
4
4
number=eval(input("Enter Number: ")) if number<10: print ("Number is lt 10") else: print ("Number is = or gt 10")
179c06542f574333fa63456c4300495b797b435f
VictoryWekwa/SCAMP-C2-Assignment-and-Projects
/Projects/HangMan_Game.py
454
3.609375
4
""" A program that selects a random word then allows the user to guess it in a game of hangman. Like the real game there should be blank spots for each letter in the word, and a part of the body should be each time the user guesses a letter that is not in the answer. You may choose how many wrong turns the user can make until the game ends. sub-goals: if the user losses, print out the word at the end of the game. Create a give up option."""
9e68c7dc769f5f1b66eb6b58f862fb048f3510a3
Ankan-Mukherjee/stp
/Final/Cs 224 Assgn/bridge.py
11,204
4.03125
4
class Bridge: ''' Each of the bridges present in the network is made an object of this class. Their properties are given below. Member Variables: name - Stores the name of the bridge as a string (B1, B2, ...) lans - Set storing the names of lans (A,B,...) connected to the bridge root - Stores the bridge object which is the root of the tree (note that this is NOT the immediate root of the current bridge object, but rather the root of the entire tree) printTrace - Flag for printing the trace changed - Stores True if the message received by a bridge has changed its root, or distance, else False rp - Stores the root port lan of the bridge dp - Stores the lans whose ports with the bridge are designated ports distance - Stores the distance of the bridge from the root trace - Stores the trace to be printed transmits - Stores True if and only if the bridge sends a message top - Stores the immediate root of the bridge under consideration (i.e., the bridge object whose leaf is the current tree) (note that this is NOT the root of the entire tree) Member Functions: newConnection - Adds a new lan as a connection to the bridge sendMessage - Sends a message to its connected lans receiveMessage - Receives a message from its adjascent lans and updates its information accrodingly display - Prints the bridge name along with its connected lans (for debugging puposes only, actual printing is done in the STP class) ''' def __init__(self,name,printTrace): self.name=name self.lans=set() self.root=self self.printTrace=printTrace self.changed=False self.rp=None self.dp=set() self.distance=0 self.trace=list() self.transmits=False self.top=None def newConnection(self,lan): self.lans.add(lan) #Append a new lan object to the set of Lans of the bridge for every new Lan detected self.dp.add(lan) #Initially, we set all ports to all lans as designated (DP) def sendMessage(self, time): #We will send a message from the bridge if and only if it is a root (whereby it generates its own message) or if transmission is enabledS if self.root is self or self.transmits: # If printing trace is enabled, we append the trace to the trace of bridge if self.printTrace: for _ in self.lans: self.trace.append(f'{time} s {self.name} ({self.root.name} {self.distance} {self.name})') # We send the message of the bridge to all its lans for lan in self.lans: lan.sendMessage((self.root, self.distance, self), time) # Since we have just sent messages and not received them yet, changes are not done for the current round. Thus, we set changed and transmit to False after transmitting once self.changed = False self.transmits = False def receiveMessage(self, message, lan, time): # Here, the bridge will receive the messages from the lan, which have in turn been transmitted to it by the previous bridge # Extracting the releveant data from the message root, distance, bridge = message # If printing trace is enabled, we append the trace to the trace of bridge if self.printTrace: self.trace.append(f'{time+1} r {self.name} ({root.name} {distance} {bridge.name})') #This is the condition for updating the information about the lans stored in the bridge. Later in this method, we shall modify the other information of the bridge if distance < self.distance or (distance == self.distance and bridge.name < self.name): # Since we have found a message from a "better bridge", the lan under consideration is no longer a designated port of the self bridge # Since we have updated bridge information, we set changed to True if lan in self.dp: self.dp.remove(lan) self.changed = True # Distance is incremented by 1 since the message measured the distance of the sender from the root, so we add sender to receiver distance, which is assumed to be 1 distance += 1 # If the current bridge is "better" than the bridge sending the message, we do nothing and return if root.name > self.root.name or (root.name == self.root.name and distance > self.distance): return # If the current bridge is not the root of the tree and it is neither "better" nor "worse" than "its" root, we assign the bridge with smaller id (here, name) as the the root of the other if self.top: if root.name == self.root.name and distance == self.distance and bridge.name > self.top.name: return # If bridge information were not to be modified, we would have returned by now. Since bridge information is modified, it means the lan sending it is a root port (could be np if and only if the bridge is hanging) and the root, distance and sender of the message become the root, distance+1 and the local root of the self bridge self.changed = True self.transmits = True self.root = root self.distance = distance self.rp = lan self.top = bridge def display(self): print('{}: {}'.format(self.name, self.lans)) class Lan: ''' Each of the LANs present in the network is made an object of this class. Their properties are given below. Member Variables: name - Stores the name of the Lan as a string (A, B, ...) bridges - Set storing the names of bridges (B1, B2,...) connected to the lan Member Functions: newConnection - Adds a new bridge as a connection to the lan sendMessage - Sends a message to its connected bridges display - Prints the lan name along with its connected bridges (for debugging puposes only, actual printing is done in the STP class) ''' def __init__(self, name): self.name = name self.bridges = set() def newConnection(self, bridge): # This is rather straightforward, we are simply appending the bridges connected to the lan to a set self.bridges.add(bridge) def sendMessage(self, message, t): # We send the message a lan receives from all the bridges connected to it to all the bridges connected to it except the sender sender = message[2] for bridge in self.bridges: if bridge is not sender: bridge.receiveMessage(message, self, t) def display(self): print('{}: {}'.format(self.name, self.bridges)) class STP: ''' This class conatins the tree Member Variables: BRIDGES - Stores the bridge objects of the tree LANS - Stores the bridge objects of the tree flag - Stores flag for printing trace (True or 1 for printing) output - Stores the lines Member Functions: parseInput - Separates the input into the bridge and its lans initialize - Initializes the bridge and lan objects and the member variables generateSpanningTree - Generates the sapnning tree printOutput - Prints output to stdout writeOutput - Writes output to the output filename ''' def __init__(self): self.BRIDGES={} self.LANS={} self.flag=True self.output=list() def parseInput(self,inp): inputs = inp.split() return inputs[0][:-1], inputs[1:] def initialize(self): # Reading the input from the file self.flag=int(input()) n = int(input()) # Storing the bridges and lans for i in range(n): bridge, lans = self.parseInput(input()) self.BRIDGES[i] = Bridge(bridge, self.flag) for lan in lans: if lan not in self.LANS: self.LANS[lan] = Lan(lan) self.BRIDGES[i].newConnection(self.LANS[lan]) self.LANS[lan].newConnection(self.BRIDGES[i]) def generateSpanningTree(self): #Loop is set to True to start the program. It is set to false inside while and set to True again if any bridge has its changed value as True loop = True time = 1 while loop: # Sending messages from each bridge as long as the loop is running for i in self.BRIDGES: self.BRIDGES[i].sendMessage(time) time += 1 # Checking if any bridge had their values changed loop = False for i in self.BRIDGES: if self.BRIDGES[i].changed: # If any bridge had a change in its parameters, it means the tree is not yet fully setup and loop must continue loop = True break # After loop is completed, the tree is fully set-up and each bridge has the final information about the root, distance and the nature of ports # Now, we are setting up and printing the trace if the flag variable (for trace) was set to True if self.flag: trace = [] for i in self.BRIDGES: trace.extend(self.BRIDGES[i].trace) self.BRIDGES[i].trace.clear() self.output.append('\n'.join(sorted(trace))) # This is the output for the type of each port for i in range(len(self.BRIDGES)): bridge = self.BRIDGES[i] output = [] for lan in bridge.lans: # A port cannot be both root port and designated port. If it is a root port, it must be removed from the designated ports list if lan in bridge.dp and bridge.rp is lan: bridge.dp.remove(lan) for lan in bridge.lans: # If the bridge is a hanging bridge, all its ports are Non-active if len(bridge.dp)==0: output.append(f'{lan.name}-NP') # If the port is a root port, we print the same elif bridge.rp is lan: output.append(f'{lan.name}-RP') # If the port is a desiganted port, we print the same elif lan in bridge.dp: output.append(f'{lan.name}-DP') # If the port is neither a root port nor a designated port, it must be non-active else: output.append(f'{lan.name}-NP') # Appending this output to the trace self.output.append(f'{bridge.name}: ' + ' '.join(sorted(output))) def printOutput(self): for i in self.output: print(i)
082482fa78f6de049b03599a88b13a895788b765
doddthomas/tools
/dog_name_list_ex.py
662
4.0625
4
#----------------------------------------------------------------------- # # dog_name_list_ex.py - a python script showing examples of dynamically # adding items to an array/list # #--------------------- module history ----------------------------- # # 12-OCT-18 : PTR XXXX, Created, Dodd M. Thomas # #----------------------------------------------------------------------- dogNames = [] while True: print('Enter dog name #' + str(len(dogNames)+1) + ' or [ENTER/RETURN] to exit=>',end=' ') name = input() if name =='': break dogNames = dogNames + [name] print('Dog names:') for name in dogNames: print(name)
a9e97d9ba94237596b7d5c2ed938ac5c9c1b05ba
AliZet-to/Homework1
/Task_3.py
211
3.78125
4
#Data input x = int(input("Please input 3-digit number \n")) #Reverse workflow number1 = x // 100 number3 = x % 10 number2 = (x % 100) // 10 #Output the result print(str(number3) + str(number2) + str(number1))
7bf85a76f746bc4fe9962a57e3000e3a5c301f12
westondlugos/Dlugos_Weston
/ProgrammingLesson_07/@.py
261
3.796875
4
sentence = input("Write a sentence:") top = 0 while top < sentence.count("a")>0: sentence = sentence[0 : sentence.index("a")]+"@"+ sentence[sentence.index("a")+1 :len(sentence)] print("You sentence with @'s for a's ......",sentence)
fdae1068c7e66cdbe9c16c3e4d58aaaa41f67539
jakehawk34/MIT-Algorithms
/quicksort.py
1,558
3.859375
4
def quicksort(A, p, r=None): if r == None: r = len(A) if p < r: q = partition(A, p, r) quicksort(A, p, q) quicksort(A, q + 1, r) return A # Linear-time partitioning subroutine: def partition(A, p, q): pivot = A[p] # Set pivot at first element of subarray i = p for j in range(p + 1, q): # If a value in the subarray is greater than the pivot if A[j] <= pivot: # increase i by 1 and swap the values at i and j i += 1 A[j], A[i] = A[i], A[j] A[p], A[i] = A[i], A[p] # swap the pivot to the value of the array where i ended at return i A = [6, 10, 13, 5, 8, 3, 2, 11] B = [1, 2, 4, 5, 6, 7, 8, 9, 10] print(quicksort(A, 0)) print(quicksort(B, 0)) ''' Visualization for partition subroutine: 6 10 13 5 8 3 2 11 -> 6 is the pivot; A[i] = 6, A[j] = 10 A[j] > pivot 6 10 13 5 8 3 2 11 -> A[i] = 6, A[j] = 13 A[j] > pivot 6 10 13 5 8 3 2 11 -> A[i] = 6, A[j] = 5 A[j] <= pivot 6 10 13 5 8 3 2 11 -> i = i + 1, A[i] = 10, A[j] = 5 Swap A[j] and A[i] 6 5 13 10 8 3 2 11 -> A[i] = 5, A[j] = 8 A[j] > pivot 6 5 13 10 8 3 2 11 -> A[i] = 5, A[j] = 3 A[j] <= pivot 6 5 13 10 8 3 2 11 -> i = i + 1, A[i] = 13, A[j] = 3 Swap A[j] and A[i] 6 5 3 10 8 13 2 11 -> A[i] = 3, A[j] = 2 A[j] <= pivot 6 5 3 10 8 13 2 11 -> i = i + 1, A[i] = 10, A[j] = 2 Swap A[j] and A[i] 6 5 3 2 8 13 10 11 -> A[i] = 2, A[j] = 11 A[j] > pivot 6 5 3 2 8 13 10 11 -> Loop of j from start + 1 to end complete, A[i] = 2, pivot = 6 Swap pivot and A[i] 2 5 3 6 8 13 10 11 Return index of pivot -> 3 '''
50e25e926d18e95b437e342d28a20602640029a9
qnkhuat/algo_training
/longest_palindromic_substring/solution.py
1,262
3.703125
4
# https://leetcode.com/problems/longest-palindromic-substring/ class Solution(object): def longestPalindrome(self, s: str) -> str: longest = "" for i, c in enumerate(s): i_f = i i_b = i temp = "" while True: if i_f < 0 or i_b >= len(s): break if s[i_f] == s[i_b]: temp = s[i_f:i_b+1] if i_f > 1 and s[i_f - 1] == s[i_b] and len(temp)%2 == 1: i_f -= 1 elif i_b < len(s) - 1 and s[i_f] == s[i_b+1] and len(temp) % 2 == 1: i_b += 1 elif i_b > 1 and i_b < len(s) - 2 and len(temp) % 2 == 0: i_f -= 1 i_b += 1 else: break else: break if len(temp) > len(longest): longest = temp return longest def test(case, expect): output = Solution().longestPalindrome(case) print(f"{'Passed' if output == expect else 'Failed'} | case: {case}, output: {output}, expect: {expect} ") test("babad", "aba") test("cbbd", "bb") test("a", "a") test("ac", "a") test("aacabdkacaa", "aca") test("bb", "bb")
a8966a349567d6ca583610d32be38b0f9c4efca6
Quantum-Cheese/my_AIProjects
/DeepLearning/NNmodel_expriment/NN (MLP).py
1,446
3.71875
4
''''' 预测模型:简单神经网络— 多层感知机(MLP) ''''' import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Dense,Dropout from keras import optimizers from keras.utils import to_categorical dataSets = pd.read_csv("processed_data") # 分割训练集和测试集,80%的数据用来训练,其余测试 sample_index=np.random.choice(dataSets.index, size=int(len(dataSets)*0.8), replace=False) trainSets,testSets = dataSets.iloc[sample_index],dataSets.drop(sample_index) # 区分特征数据和标签数据(输入和输出),把y转换成binary格式:两类(0或1) X_train=trainSets.drop(['income'],axis=1) X_test=testSets.drop(['income'], axis=1) y_train=to_categorical(trainSets['income']) y_test=to_categorical(testSets['income']) # 训练数据 X:(9045,87)y:(9045,2),测试数据 X:(36177,87)y:(36177,2) # 构建神经网络模型 NN_1 = Sequential() NN_1.add(Dense(45, input_dim=87, activation='relu')) NN_1.add(Dropout(0.5)) NN_1.add(Dense(130,activation='relu')) NN_1.add(Dropout(0.5)) NN_1.add(Dense(2,activation='sigmoid')) sgd=optimizers.SGD(lr=0.01,decay=1e-6,momentum=0.9) NN_1.compile(optimizer=sgd, metrics=['accuracy'], loss='categorical_crossentropy') NN_1.fit(x=X_train,y=y_train,batch_size=1000,epochs=20) NN_1_score=NN_1.evaluate(X_test,y_test,batch_size=500) print("Accuracy of NN_1 : ",NN_1_score)
4ccdf376228f0b75a7bc1fb3627781f3bf027089
MaxKim-J/Algo
/problems/202103/boj-14499-주사위굴리기.py
2,486
3.671875
4
''' 주사위 하나를 고정된 배열로 놓고, 숫자를 바꾸는게 훨씬 용이한 접근이었다 내 방법은 디버깅이 너무 힘들었음ㅜㅜ 문제에 충실하게, 자연스럽게, 문제의 힌트를 죄다 이용하며 푸는 방법이 뭔지 생각해봐야한다 ''' # 맨위는 arr[1], 맨 아래는 arr[6] => 그림으로 나온 눈금을 위치값으로 사용하면 되었다 def move(n, arr): if n == 1: # 동 return [0, arr[3], arr[2], arr[6], arr[1], arr[5], arr[4]] elif n == 2: # 서 return [0, arr[4], arr[2], arr[1], arr[6], arr[5], arr[3]] elif n == 3: # 북 return [0, arr[2], arr[6], arr[3], arr[4], arr[1], arr[5]] elif n == 4: # 남 return [0, arr[5], arr[1], arr[3], arr[4], arr[6], arr[2]] if __name__ == "__main__": # input N, M, y, x, K = map(int, input().split()) arr = [list(map(int, input().split())) for _ in range(N)] order = list(map(int, input().split())) dice = [0] * 7 # 주사위 dy = [0, 0, 0, -1, 1] dx = [0, 1, -1, 0, 0] # 명령 수행 for i in range(len(order)): if y + dy[order[i]] < 0 or y + dy[order[i]] >= N or x + dx[order[i]] < 0 or x + dx[order[i]] >= M: continue else: x, y = x + dx[order[i]], y + dy[order[i]] # 좌표 이동 dice = move(order[i], dice) # 주사위 이동 if arr[y][x] == 0: arr[y][x] = dice[6] # 주사위 -> 칸 else: dice[6] = arr[y][x] # 칸 -> 주사위 arr[y][x] = 0 # 칸에 있는 수 0으로 수정 print(dice[1]) ''' N, M, X, Y, K = map(int, input().split()) board = [] for _ in range(N): board.append(list(map(int, input().split()))) orders = list(map(lambda x:x-1, map(int, input().split()))) dice = [0,0,0,0,0,0] way = [[2,5,1,4], [2,5,3,0], [4,1,3,0], [2,5,4,1], [2,5,0,3], [1,4,3,0]] dr = [0, 0, -1, 1] dc = [1, -1, 0, 0] def get_apposite(top): if top < 3: return top + 3 elif top >= 3: return top - 3 current = (X, Y) top = 1 for order in orders: r, c = current bottom = get_apposite(top) if board[r][c] == 0: board[r][c] = dice[bottom] else: dice[bottom] = board[r][c] board[r][c] = 0 print(board, dice) nr = r + dr[order] nc = c + dc[order] if (-1 < nr < N) and (-1 < nc < M): current = (nr, nc) bottom = way[top][order] print(dice[get_apposite(bottom)]) '''
7da6885dd827a0d4e604f55e1ac98c3714456cdf
Hourout/tensordata
/tensordata/gfile/_gfile.py
4,433
3.546875
4
import os import shutil __all__ = ['copy', 'exists', 'isdir', 'isfile', 'listdir', 'makedirs', 'remove', 'stat', 'walk', 'path_join', 'rename'] def exists(path): """Determines whether a path exists or not. Args: path: string, a path, filepath or dirpath. Returns: True if the path exists, whether it's a file or a directory. False if the path does not exist and there are no filesystem errors. """ return os.path.exists(path) def isdir(path): """Returns whether the path is a directory or not. Args: path: string, path to a potential directory. Returns: True, if the path is a directory; False otherwise. """ return os.path.isdir(path) def isfile(path): """Returns whether the path is a regular file or not. Args: path: string, path to a potential file. Returns: True, if the path is a regular file; False otherwise. """ return os.path.isfile(path) def listdir(path): """Returns a list of entries contained within a directory. Args: path: string, path to a directory. Returns: [filename1, filename2, ... filenameN] as strings. Raises: errors. NotFoundError if directory doesn't exist. """ return os.listdir(path) def copy(src, dst, overwrite=False): """Copies data from src to dst. 1.copy file to file. 2.copy file to directory. 3.copy directory to directory. Args: src: string, name of the file whose contents need to be copied dst: string, name of the file to which to copy to overwrite: boolean, Whether to overwrite the file if existing file. """ assert exists(src), "src not exists." if isfile(src): if overwrite or not exists(dst): shutil.copy(src, dst) else: makedirs(dst) path = path_join(dst, path_join(src).split('/')[-1]) if overwrite or not exists(path): remove(path) shutil.copytree(src, path) def makedirs(path): """Creates a directory and all parent/intermediate directories. Args: path: string, name of the directory to be created. """ if not exists(path): os.makedirs(path) def remove(path): """Deletes a directory or file. Args: path: string, a path, filepath or dirpath. Raises: errors. NotFoundError if directory or file doesn't exist. """ if exists(path): if isfile(path): os.remove(path) else: shutil.rmtree(path) def rename(src, dst, overwrite=False): """Rename or move a file / directory. Args: src: string, pathname for a file. dst: string, pathname to which the file needs to be moved. overwrite: boolean, Whether to overwrite the file if existing file. """ assert exists(src), "src not exists." if exists(dst): assert isdir(src)==isdir(dst), "src and dst should same type." assert isfile(src)==isfile(dst), "src and dst should same type." if overwrite: shutil.rmtree(dst) os.rename(src, dst) else: os.rename(src, dst) def stat(path): """Returns file or directory statistics for a given path. Args: path: string, a path, filepath or dirpath. Returns: FileStatistics struct that contains information about the path. """ return os.stat(path) def walk(top, topdown=True, onerror=None): """Recursive directory tree generator for directories. Args: top: string, a Directory name topdown: bool, Traverse pre order if True, post order if False. onerror: optional handler for errors. Should be a function, it will be called with the error as argument. Rethrowing the error aborts the walk. Errors that happen while listing directories are ignored. Returns: Yields, Each yield is a 3-tuple: the pathname of a directory, followed by lists of all its subdirectories and leaf files. That is, each yield looks like: (dirname, [subdirname, subdirname, ...], [filename, filename, ...]). Each item is a string. """ return os.walk(top, topdown, onerror) def path_join(path, *paths): return eval(repr(os.path.join(path, *paths)).replace("\\", '/').replace("//", '/'))
e2194cf7bc229649de2f123464df7a0026894a5b
icot/euler
/p156.py
459
3.5
4
#!/usr/bin/python2.7 from utils import isprime def p(n, c): return n*n + c if __name__ == "__main__": limit = 1000000 cs = (3, 7, 9, 13, 27) print "Generating groups" groups = [[n, p(n, 1)] for n in xrange(limit) if isprime(p(n,1))] for c in cs: groups = [item + [p(item[0], c)] for item in groups] groups = filter(lambda x: isprime(x[-1]), groups) print "Filter: ", len(groups) print "Suma: ", sum(cs)