blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7be86cc9451180e7c306d5b4563c0e30036e0d0f
Sa4ras/amis_python71
/km71/Likhachov_Artemii/4/Task1.py
163
4
4
a = int(input('Input first number: ')) b = int(input('Input second number: ')) txt = 'Bigger number is: ' if a > b: print(txt, a) else: print(txt, b)
b932d89ec6ecc58b3a75a6abc030bac8c18c6068
YaohuiZeng/Leetcode
/334_increasing_triplet_subsequence.py
1,466
4.1875
4
# -*- coding: utf-8 -*- """ Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. Formally the function should: Return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. Your algorithm should run in O(n) time complexity and O(1) space complexity. Examples: Given [1, 2, 3, 4, 5], return true. Given [5, 4, 3, 2, 1], return false. """ # Time: O(n); Space: O(1) import bisect class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ left = mid = float("inf") for n in nums: if n <= left: left = n elif n <= mid: mid = n else: return True return False """ Generalize to k-uplet: use bisection algorithm """ def increasingKUplet(self, nums, k): inc = [float('inf')] * (k - 1) for num in nums: i = bisect.bisect_left(inc, num) if i == k - 1: return True inc[i] = num return k == 0 # consider case of k = 0 if __name__ == "__main__": nums = [9, 8, 1, 10, 3, 0, 1, -10, 2, 8] print Solution().increasingTriplet(nums) print Solution().increasingKUplet(nums, 3) print Solution().increasingKUplet(nums, 4) print Solution().increasingKUplet(nums, 5)
0a23b58e4522aea14882eaed7250ce532fec058a
NickSanft/PythonSQLiteFlaskDemo
/DatabaseUtils.py
3,762
3.75
4
from xlsxwriter.workbook import Workbook import sqlite3 as sql import Config con = sql.connect(Config.Database["databaseName"]) # This function creates all necessary tables needed in the SQLite database. def createTables(): cur = con.cursor() cur.executescript(Config.Database["createTablesQuery"]) print("Created all tables!") con.commit() # This function drops all non-system tables in the SQLite database. BE CAREFUL USING THIS FUNCTION!!! def dropAllTables(): cur = con.cursor() cur.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite%'") for row in cur.fetchall(): query = "DROP TABLE IF EXISTS " + row[0] print(query) cur.execute(query) con.commit() # USE AT YOUR OWN RISK, DELETES ALL ROWS FROM ALL TABLES def cleanTables(): cur = con.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table'") for row in cur: con.cursor().execute("DELETE FROM " + row[0]) con.commit() def tableExists(tableName): cur = con.cursor() cur.execute( "SELECT COUNT(1) FROM sqlite_master WHERE type='table' AND name=?;", (tableName,)) if(cur.fetchone()[0] < 1): return False return True def selectAllFromTable(tableName): cur = con.cursor() cur.execute("SELECT * FROM " + tableName) return cur def selectAllFromTableHTML(query): return queryToHTML(query, None) def queryToHTML(query, tupleValues): cur = executeQuery(query, tupleValues) resultHTML = Config.HTML["header"] resultHTML += Config.HTML["selectTable"] columnNames = [] for column in cur.description: resultHTML += "<th>" + column[0] + " </th> \n" resultHTML += "</tr></thead><tbody> \n" for row in cur: resultHTML += "<tr> \n" for column in row: resultHTML += "<td>" + str(column) + " </td> \n" resultHTML += "</tr> \n" resultHTML += "</tbody></table></div></body></html>" return resultHTML def executeQuery(query, tupleValues): cur = con.cursor() if tupleValues is None: cur.execute(query) else: cur.execute(query, tupleValues) con.commit() return cur def getHTMLForm(tableName, methodName): cur = con.cursor() query = """PRAGMA table_info('{0}')""".format(tableName,) cur.execute(query) formHTML = Config.HTML["header"] formHTML += Config.HTML["insertForm"].format( str(tableName) + "/" + str(methodName)) for row in cur: formHTML += """<label for="{0}">{0}({1}):</label><input type="text" class="form-control" id="{0}" name="{0}">""".format( str(row[1]), str(row[2])) formHTML += """<input type="submit" name="form" value="Submit"></form></div></body></html>""" return formHTML """ This function takes in a filepath and select SQL query and outputs the result (with columns) to the filepath specified. """ def generateExcelFile(path, selectQuery): cur = con.cursor() cur.execute(selectQuery) workbook = Workbook(path) sheet = workbook.add_worksheet() columnNames = [] for column in cur.description: columnNames.append(column[0]) listToWrite = cur.fetchall() listToWrite.insert(0, tuple(columnNames)) print(listToWrite) for r, row in enumerate(listToWrite): for c, col in enumerate(row): sheet.write(r, c, col) workbook.close() """ This is the main database script used to communicate with the SQLite database. This contains all necessary methods to create the schema for this database. """ def main(): createTables() # dropAllTables() #generateExcelFile("test.xlsx","SELECT * FROM accounts") if __name__ == "__main__": main()
71fca7003c8de0a7a2369bdeeca7155a7cfc564c
maysuircut007/python-basic
/56. Arbitrary Arguments (args).py
281
3.640625
4
# *args = tuple def add(*agrs): print(agrs) print(agrs[0] + agrs[1]) sum = 0 for item in agrs: sum += item print(sum) sum2 = 0 for i in range(len(agrs)): sum2 += agrs[i] print(sum2) add(10, 20, 30, 40)
666a0710ef2a66a1e827f9140b046b52e34e247c
vikvik98/Algoritmos_2017.1
/Atividade G/fabio_06_06.py
807
4
4
def main(): #48 a 57 frase = input("Digite uma frase: \n") nova_frase = "" for letra in frase: if is_number(letra): print(getAlgarismo(letra),end="") else: print(letra,end="") print("\n") def is_number(letra): return ord(letra) >= 48 and ord(letra) <= 57 def getAlgarismo(algarismo): algo = "" if(algarismo == "0"): algo = "Zero" elif(algarismo == "1"): algo = "Um" elif(algarismo == "2"): algo = "Dois" elif(algarismo == "3"): algo = "Três" elif(algarismo == "4"): algo = "Quatro" elif(algarismo == "5"): algo = "Cinco" elif(algarismo == "6"): algo = "Seis" elif(algarismo == "7"): algo = "Sete" elif(algarismo == "8"): algo = "Oito" elif(algarismo == "9"): algo = "Nove" return algo if __name__ == '__main__': main()
a9e63904be05f205a67c2e5ab57293d85f062616
labyrlnth/codeeval
/hard/String_List.py
875
3.703125
4
import sys def generate_strings(letters, number): if number == 0: return [] else: result = [] rest = generate_strings(letters, number - 1) for letter in letters: if rest == []: return letters else: for item in rest: new_string = ''.join([letter, item]) result.append(new_string) return result if __name__ == '__main__': f = open(sys.argv[1],'r') lines = f.readlines() for line in lines: if line: line = line.strip() number, letters = line.split(',') number = int(number) letters = list(set(letters)) letters.sort() result = generate_strings(letters, number) print ','.join(result)
ea8ff12752cd6f8fde54ef844e3d26afbe1c746c
muh-nasiruit/programming-fundamentals
/PF 05 Problems/pf5.py
885
4.125
4
''' 5. Write multiple functions for making the mark sheet program as you have done in the previous lab. ''' def m_sheet(): Name = input("Enter Name: ") FatherName = input("Enter Father Name: ") RollNumber = int(input("Enter Roll Number: ")) Subjects = [] Marks = [] for i in range(5): Subject = input("Enter Subject: ") Subjects.append(Subject) Mark = int(input("Enter Marks: ")) Marks.append(Mark) TotalPercentage = (sum(Marks)/500) * 100 print('Name: {}'.format(Name)) print('Father Name: {} '.format(FatherName)) print('Roll Number: {}'.format(RollNumber)) for i in range(3): print('Scored {} in {} out of 100'.format(Marks[i],Subjects[i])) print('Total Marks Obtained out of 500 are: {}'.format(sum(Marks))) print('Percentage Obtained: {}'.format(TotalPercentage)) m_sheet()
19e02d42cd503223639b84ae6fde51afb1498fc7
aultimus/project_euler
/17_number_letter_counts.py
904
3.671875
4
# http://projecteuler.net/problem=17 # If the numbers 1 to 5 are written out in words: one, two, three, four, five, # then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # # If all the numbers from 1 to 1000 (one thousand) inclusive were written out # in words, how many letters would be used? # # NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and # forty-two) contains 23 letters and 115 (one hundred and fifteen) contains # 20 letters. The use of "and" when writing out numbers is in compliance with # British usage. import num2word # https://pypi.python.org/pypi/num2words import re from collections import Counter def main(): l = [] for i in xrange(1, 1001): s = num2word.to_card(i) l.extend(re.findall(r"[\w']+", s)) count = 0 for word in l: count += len(word) return count if __name__ == "__main__": print main()
6365219b047903298c3d0460b1189f079eb84c0d
J-Keven/aps-design-patterns
/Iterator/problema/main.py
409
4.25
4
""" Um exemplo de problema simples onde temos uma lista de elementos e queremos percorre-la de formas diferentes. """ if __name__ == "__main__": # lista lista = [("a", "b"), ("c", "d"), 3] # mostrando na ordem de inserção for elemento in lista: print(elemento) # mostrando na ordem reversa for indice in range(len(lista) - 1, -1, -1): print(lista[indice])
be74995491f40299d16723e1ad7c4e2e0c2e3785
edutilos6666/CL_Uebung2
/Test/ComplicatedTest.py
1,599
3.640625
4
def test1(): assert 1== 1 class ComplexNumber: def __init__(self, real= 0, imag= 0): self.real = real self.imag = imag def add(self, other): ret = ComplexNumber() ret.real = self.real + other.real ret.imag = self.imag + other.imag return ret def subtract(self, other): ret = ComplexNumber ret.real = self.real - other.real ret.imag = self.imag - other.imag return ret def to_string(self): ret = str(self.real) + " + i*" + str(self.imag) if self.imag == 0: ret = self.real elif self.real == 0: ret = "i*" + str(self.imag) elif self.imag < 0: ret = str(self.real) + " + (i*" + str(self.imag) + ")" return ret def test_complex_number(): n1 = ComplexNumber(1,1) n2 = ComplexNumber(2, 2) assert n1.real == 1 assert n1.imag == 1 assert n2.real == 2 assert n2.imag == 2 _sum = n1.add(n2) _subtract = n1.subtract(n2) assert _sum.real == 3 assert _sum.imag == 3 assert _subtract.real == -1 assert _subtract.imag == -1 class Worker: def __init__(self, id , name, age, wage): self.id = id self.name = name self.age = age self.wage = wage def test_worker(): w1, w2 = Worker(1, "foo", 10, 100.0), Worker(2, "bar", 20, 200.0) assert w1.id == 1 assert w1.name == "foo" assert w1.age == 10 assert w1.wage == 100.0 assert w2.id == 2 assert w2.name == "bar" assert w2.age == 20 assert w2.wage == 200.0
b571aa429f2df67ba7e63e11cd5ea7bc4320031a
gsandova03/taller3_int_computacional
/punto3.py
421
3.765625
4
num_obreros = int( input('Numeros de obreros: ') ) salarios = [] for n in range( 1, num_obreros + 1 ): horas = int( input('Horas trabajadas: ') ) if( horas <= 40 ): pago = horas * 20 salarios.append( pago ) elif( horas > 40 ): pago = 40 * 20 horas_extra = horas - 40 pago_extra =int( horas_extra * 25 ) pago_total = pago + pago_extra salarios.append( pago_total ) print( salarios )
4376f52db4c2e04cc0884be14ce4e311bafeb048
LayaJose/Image-Cleaning
/Task1/Task1.py
2,181
3.65625
4
################ ## Task 1 - Tissue identification ## Byron Smith ## 9/10/2020 ## ## This code is written to identify tissue from a whole slide image. ## First, we can immediately see that slide background is white and can ## be identified as have red-green-blue values over 0.9 (or 240 on a 0-255 scale). ## In order to choose the tissue, we want to choose all pixel values that don't ## fit this criteria. import numpy as np import cv2 from matplotlib import pyplot as plt # Used to visualize the image intermittently if necessary. def fillHull(img): # Create a hull filling function equivalent to R. c2, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # RETR_EXTERNAL means only use external contours. for i in range(len(c2)): cv2.drawContours(img, c2, i, 255, -1) # Not all hulls got filled!! return img ###################### ## Read in the image ###################### pic1 = cv2.imread("~/AT2Scan.jpg") # The default read of a JPEG image using cv2 is in blue-green-red rather than red-green-blue. # I will convert this for consistency. pic1 = cv2.cvtColor(pic1, cv2.COLOR_BGR2RGB) pic1.shape # 2208, 2418, 3 ################### ## Identify tissue in the image ################### # Set up a mask and overlay it. mask = pic1.copy() mask[:,:,0] = 0 mask[:,:,2] = 0 mask[:,:,1] = 255 * (pic1[:,:,2] < 230) pic2 = pic1.copy() cv2.addWeighted(mask, 0.3, pic2, 0.7, 0, dst=pic2) plt.imshow(pic2) mask2 = cv2.cvtColor(pic1, cv2.COLOR_RGB2GRAY) mask2 = cv2.threshold(mask2, 200, 255, cv2.THRESH_BINARY_INV)[1] mask2 = cv2.morphologyEx(mask2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (101,101))) mask2 = fillHull(mask2) ########################## ## Output the image ########################## mask3 = np.zeros((pic1.shape), dtype='uint8') mask3[:,:,1] = mask2 pic3 = pic1.copy() cv2.addWeighted(mask3, 0.3, pic3, 0.7, 0, dst=pic3) out, figs = plt.subplots(1,3) figs[0].imshow(pic1) figs[1].imshow(pic2) figs[2].imshow(pic3) # How do I output this now? cv2.imwrite("Task1.jpg", figs)
ea51cefe67289ce2e61ca78fd58b775e6fa424a5
nidhinbose89/algorithm_study
/heaps.py
2,528
3.953125
4
#!/usr/bin/env python """Heap Implementation.""" from copy import copy class MaxHeap(object): """Max Heap Implementation.""" def __init__(self, items): """Initializer.""" for idx in range(len(items) - 1, -1, -1): self.heapify(the_input, idx) self.items = items def heapify(self, array, index): """Heapify.""" left_el = 2 * index + 1 right_el = 2 * index + 2 largest_idx = index if left_el < len(array): if array[left_el] > array[largest_idx]: largest_idx = left_el if right_el < len(array): if array[right_el] > array[largest_idx]: largest_idx = right_el if largest_idx != index: # swap and hepify array[largest_idx], array[index] = array[index], array[largest_idx] self.heapify(array, largest_idx) def insert(self, element): """Insert an element and heapify.""" self.items.append(element) new_elem_idx = len(self.items) - 1 parent = (new_elem_idx - 1) // 2 while parent >= 0: if element > self.items[parent]: # swap self.items[parent], self.items[new_elem_idx] = \ self.items[new_elem_idx], self.items[parent] new_elem_idx = parent parent = (parent - 1) // 2 return new_elem_idx def get_top_and_heapify(self): """Get Top Item and heapify.""" top_ele = None if self.items: # put last as first self.items[0], self.items[-1] = self.items[-1], self.items[0] top_ele = self.items.pop() # now that it is swapped, get the last self.heapify(self.items, 0) return top_ele def sorted(self): """Sort via heapify -- Heap Sort.""" initial_heap = copy(self.items) ret = [] for idx in range(len(self.items)): ret.append(self.get_top_and_heapify()) self.items = initial_heap return ret if __name__ == '__main__': the_input = [64, 89, 197, 151, 101, 43, 142, 25, 189, 59] heap_obj = MaxHeap(the_input) print heap_obj.items print "The largest: ", heap_obj.get_top_and_heapify() print heap_obj.items, "items..still hepified" print heap_obj.sorted(), "get sorted.." print heap_obj.insert(120), "inserted.. return the index" print heap_obj.items, 'items.. heap after an insert' print heap_obj.sorted(), 'sorted'
1a851669708e0f307e3f3239bd31afbc1d93e231
DerekHJH/LearnPython
/numpy/haha.py
6,713
3.59375
4
import numpy as np; import numpy.linalg as npl;#Linear algebra; import matplotlib.pyplot as plt; import time #from numpy import *; Use this to avoid adding the prefix np.; #The same as list(range(10)); ''' a = np.arange(10); print(a); ''' #ndarry is much faster than list and consume less memory ''' Sum = np.arange(1000000) Sum_list = list(range(1000000)) t1 = time.time() for i in range(10):Sum = Sum * 2 t2 = time.time() for i in range(10):Sum_list = [j * 2 for j in Sum_list] t3 = time.time() print(t2 - t1) print(t3 - t2) ''' #Print all the types and the corresponding letter; ''' for key, value in np.sctypeDict.items(): print(key, value); ''' #Types in np; ''' print(np.int8(34.5)); print(np.bool(34.5)); print(np.arange(10, dtype = np.uint8)); y = np.arange(7, dtype = "u2"); print(y.itemsize); print(y.dtype); ''' #Creating a struct ''' t = np.dtype([("name", np.str_, 40), ("age", "u8"), ("math", np.uint8)]); x = np.array([("liming", 35, 78), ("yangmi", 31, 58)], dtype = t); print(x); print(x[0]["name"]); print(x[1]["math"]); print(x["age"]); ''' #Indexing ''' a = np.arange(24); b = a.reshape(2 , 3 , 4);#Alter the dimension of this array without changing itself; #print(b); #print(b[0][0][1]); #print(b[0, 0, 1]); #print("*" * 20);#Print 20 "*"s; #print(b[1, 1:2, 1:]); #print(b.shape);#Check the dimesionality of b; c = np.copy(a); c.shape = (3, 8);#Alter the dimension with changing itself; #print(c); c.resize([2, 12]);#Alter the dimension with changing itself; #print(c); d = c.ravel() e = a.flatten() #print("*" * 20); print(a); print(c); print(d); print(e); #print("*" * 20); #print(c.transpose()); #print(c); ''' #Comnination of arrays ''' a = np.arange(9).reshape([3, 3]); #print(a); b = a * 2; #print(b); c = np.hstack((a, b, a)); #print(c); d = np.concatenate((a, b, a), axis = 1);#The same as hstack; #print(d); #print("*" * 20); e = np.vstack((a, b, a)); #print(e); f = np.concatenate((a, b, a), axis = 0);#The same as vstack; #print(f); #print("*" * 20); #print(a); #print(b); g = np.dstack((a, b, a));#Dimension expanded, g[][][0] == a; g[][][1] == b; g[][][2] == a; #print(g); #print("*" * 20); x = np.arange(9); y = x * 2; h = np.column_stack((x, y, x));#Combine as columns; i = np.column_stack((a, b, a));#View the n-1 D as one D; j = np.row_stack((x, y, x));#Combine as rows k = np.row_stack((a, b, a)); #print(h); #print(i); #print(j); #print(k); ''' #Split of arrays; ''' a = np.arange(24).reshape((4, 6)); print(a); b = np.hsplit(a, 3);#Split a[][] into a[][0-2] and a[][3-5]; for x in b: print("*" * 20); print(x); print(b); c = np.vsplit(a, 2);#Split a[][] into a[0-1][] and [2-3][]; for x in c: print("*" * 20); print(x); print(c); a = np.arange(24).reshape([2, 3, 4]); print(a); b = np.dsplit(a, 2);#Split a[][][] into a[][][0-1] and a[][][2-3]; for x in b: print("*" * 20); print(x); print(b); print("*" * 20); print(a); b = np.split(a, 4, axis = 2);#axis == 0 -> a[x][][]; axis == 1 -> a[][x][]; print(b); ''' #Read and save CSV file; ''' a = np.loadtxt("iris.data", dtype = np.float64, delimiter = ',', usecols = list(range(4)));#dtype default is float print(a); b = np.loadtxt("iris.data", dtype = "S", delimiter = ',', usecols = [4]); print(b); for x in range(len(b)): print(a[x], "is", b[x]); ''' #Another way ''' t = np.dtype([('sepal_length', 'f4'),('sepal_width', 'f4'),('petal_length', 'f4'),('petal_width', 'f'),('class', 'S20')]) a = np.loadtxt("iris.data", dtype = t, delimiter = ',') r = np.savetxt("iris.csv", a, fmt = "%03.3lf:%03.3lf:%03.3lf:%03.3lf:%s"); ''' #Math functions 1; ''' a, b = np.loadtxt("iris.data", delimiter = ',', usecols = [0, 1], unpack = True); #To use the a, b = np.loadtxt... form ,unpack needs to be True; print(a); print(b); print(np.sqrt(a)); print("*" * 20); y = np.random.normal(2, 0.1, 200);#Mean, standard deviation, how many; x = list(range(200)); plt.title("Normal Distribution", fontsize = 24); plt.plot(x, y, linewidth = 2); plt.savefig("NormalDistribution.png"); ''' #Math function 2; ''' a = np.arange(10); print(a); print(np.average(a)); print(np.mean(a)); print(np.max(a)); print(np.min(a)); print(np.ptp(a));#max - min; print(np.std(a));#Standard deviation; print(np.median(a)); print(np.rint(a));#round 4 5 ; print(np.gradient(a)); ''' #Math function 3 --- Linear algebra; ''' a = np.arange(9).reshape(3, 3); qq, rr =npl.qr(a); print(qq); print(rr); print(qq.dot(rr));#Multiply two matrix; b = [[1, 2], [2, 3]]; Inv = npl.inv(b); print(Inv); print(Inv.dot(b)); ''' ''' a = np.eye(5, dtype = int);#Create identity matrix; print(a); print(npl.matrix_rank(a)); b = np.arange(5).reshape(5, 1); x = npl.solve(a, b); y = np.dot(npl.inv(a), b); z = np.matmul(npl.inv(a), b); u = np.inner(npl.inv(a), np.transpose(b));#inner(a, b) == a*Transpose(b); #outer(a, b) == Transpose(a)*b; print(np.allclose(x, v));#Compare if two matrix are equal with tolerance; ''' #Broadcasting mechanism; ''' a = np.array([1, 2, 3]); print(a); print(a.shape); print(a.ndim); b = np.arange(0, 10).reshape(2, 5); print(b); print(b.shape);#[] x [] print(b.ndim);#Dimensionality ''' ''' a = np.arange(9).reshape(3, 3); b = np.arange(10, 19).reshape(3, 3); print(a / b);#Calculate in corresponding position; c = np.arange(3); print(a + c);#When doing the broadcasting mechanism, we make copis of c; #Two rules for broadcasting mechanism, please refer to the website; ''' #Norms; ''' x = np.array([1, 0, -2]); n0 = npl.norm(x, ord = 0);#0-norm, to calculate the number of 1s; n1 = npl.norm(x, ord = 1);#1-norm; n2 = npl.norm(x, ord = 2); nn = npl.norm(x, ord = np.inf);#to select the maximum(in absolute); y =np.array([[-1, 1, 0], [-4, 3, 0], [1, 0, 2]]); N1 = npl.norm(y, ord = 1);#For each column vector, we calculate its 1-norm, and select the maximum of them as the 1-norm of the matrix; NN = npl.norm(y, ord = np.inf);#For each row vector, we calculate its 1-norm, and select the maximum of them as the 1-norm of the matrix; N2 = npl.norm(y, ord = 2); yty = np.dot(y.T, y); print(npl.eigvals(yty), N2 * N2);#The same;2-norm; ''' #Matrix and array; ''' a = np.arange(12).reshape((3, 4)); b = np.arange(12).reshape((4, 3)); print(a); print(b); print(a * b.T, type(a));#position-wise multiply; print("*" * 20); print(np.matmul(a, b));#Matrix multiplization; print("*" * 20); x = np.matrix([[1, 3, 5], [2, 4, 6]]); y = np.matrix("7, 9, 11; 8, 10, 12");#Another way to create a matrix; print(x, x.shape, type(x)); print(x * y.T);#Matrix mul; print(np.matmul(x, y.T));#Matrix mul; print(np.multiply(x, y));#position-wise mul; ''' #Matrix rotation; ''' a = np.array([[1, 3, 5], [2, 4, 6], [7, 8, 9]]); print(np.rot90(a, 1));#Rotate for one time; print(np.rot90(a, -1)); print(np.rot90(a, 3)); '''
5b3439da727601373c182079675c0ed28e836a86
ClayPalmerOPHS/Y11-Python
/FOR LOOP challenges09.py
417
3.921875
4
#FOR LOOP challenges 09 #Clay Palmer invites = int(input("How many people do you want to invite to your party? ")) if invites < 10: for i in range(invites): print("") name = str(input("Enter the name of someone you want to invite: ")) print("") print(name,"has been invited") print("") print("We have invited as many people as you wanted") else: print("Too many people.")
3177ea41966870eea0b6a2171ffa68049f2df185
cmrdSurajYadav/adnotepad
/t.py
303
3.546875
4
from PIL import Image, ImageTk from tkinter import * a = Tk() img = Image.open("image/find.png") image_ = ImageTk.PhotoImage(img) scroll = Scrollbar(a, orient="vertical") text = Text(a, width=25, height=15, wrap="none", yscrollcommand=scroll.set) text.image_create("1.0", image=image_) a.mainloop()
8fdad2eb16fac5db921248135b91f66a46dbf524
eronekogin/leetcode
/2020/design_circular_deque.py
3,215
3.90625
4
""" https://leetcode.com/problems/design-circular-deque/ """ class ListNode: def __init__(self, val: int): self.val = val self.next = None self.prev = None class MyCircularDeque: def __init__(self, k: int): """ Initialize your data structure here. Set the size of the deque to be k. """ self.size = k self._tail = None self._cnt = 0 def insertFront(self, value: int) -> bool: """ Adds an item at the front of Deque. Return true if the operation is successful. """ if self.isFull(): return False if self.isEmpty(): self._tail = ListNode(value) self._tail.next = self._tail self._cnt = 1 else: preHead = self._tail.next self._tail.next = ListNode(value) self._tail.next.next = preHead preHead.prev = self._tail.next self._cnt += 1 return True def insertLast(self, value: int) -> bool: """ Adds an item at the rear of Deque. Return true if the operation is successful. """ if self.isFull(): return False if self.isEmpty(): self._tail = ListNode(value) self._tail.next = self._tail self._cnt = 1 else: preHead = self._tail.next self._tail.next = ListNode(value) self._tail.next.prev = self._tail self._tail = self._tail.next self._tail.next = preHead self._cnt += 1 return True def deleteFront(self) -> bool: """ Deletes an item from the front of Deque. Return true if the operation is successful. """ if self.isEmpty(): return False if self._cnt == 1: self._tail = None self._cnt = 0 else: self._tail.next = self._tail.next.next self._tail.next.prev = None self._cnt -= 1 return True def deleteLast(self) -> bool: """ Deletes an item from the rear of Deque. Return true if the operation is successful. """ if self.isEmpty(): return False if self._cnt == 1: self._tail = None self._cnt = 0 else: preTail = self._tail.prev preTail.next = self._tail.next self._tail = preTail self._cnt -= 1 return True def getFront(self) -> int: """ Get the front item from the deque. """ if self.isEmpty(): return -1 return self._tail.next.val def getRear(self) -> int: """ Get the last item from the deque. """ if self.isEmpty(): return -1 return self._tail.val def isEmpty(self) -> bool: """ Checks whether the circular deque is empty or not. """ return not self._cnt def isFull(self) -> bool: """ Checks whether the circular deque is full or not. """ return self._cnt == self.size
ce1ee6b8dceddbf85e92292c3bfc3564fbf69110
russellgao/algorithm
/dailyQuestion/2020/2020-06/06-12/python/solution.py
852
3.59375
4
def threeSum(nums: [int]) -> [[int]]: nums.sort() result = [] n = len(nums) if not nums or nums[0] > 0 or nums[-1] < 0 : return result for first in range(n) : if first > 0 and nums[first] == nums[first-1] : continue third = n-1 target = -nums[first] for second in range(first+1,n) : if second > first + 1 and nums[second] == nums[second-1] : continue while second < third and nums[second] + nums[third] > target: third -= 1 if second == third : break if nums[second] + nums[third] == target: result.append([nums[first],nums[second],nums[third]]) return result if __name__ == "__main__" : nums = [-1,0,1,2,-1,-4] result = threeSum(nums) print(result)
afa004c3e247baf2b226a05c594babd8eed9cd1b
moon-shrestha/python_assignment_dec8
/password.py
222
3.515625
4
#to check if the passords match or not password = 1234 def fun(pw): if (pw == password): print("Passwords match.") else: print("Wrong password.") pw = (input("Enter a password:")) fun(pw)
a75e8148c07657cff4cfc272316e0a56e269a468
brianjp93/desktopcodeeval
/fib/fib.py
264
3.65625
4
import sys def fib(n): if n == 0: return 0 else: total = 1 last = 1 temp = 0 for i in range(1, n): total += temp temp = last last = total return total with open(sys.argv[1], 'r') as f: for line in f: n = int(line.strip()) print(fib(n))
b14ec4e008d703d7d5f00ea9b3914b8761694575
shadowlugia567/Visualisation_Project
/W4_Conic.py
1,036
3.8125
4
import matplotlib.pyplot as plt import numpy as np G=6.673*(10**-11) M = float(input('Enter the mass of the bigger body: ')) m = float(input('Enter the mass of the smaller body: ')) rp = float(input('Enter the periapsis in m: ')) vp = float(input('Enter the v in m/s: ')) """ #Data for testing. Using the Sun and the Earth. m=5972000000000000000000000 M=1989000000000000000000000000000 rp=147100000000 vp=30290""" E = (0.5*m*vp**2) - ((G*M*m)/rp) L = m*rp*vp mu = G*(m+M) h = L/m p = (h**2)/mu e = (p/rp) - 1 print("The eccentricity is",e) print("Semilatus rectum is",p) print("The energy is",E) print("The angular momentum is",m) if(e > 1): print("The orbit's shape is hyperbolic") if(e == 1): print("The orbit's shape is parabolic") if(e > 0 and e < 1): print("The orbit's shape is elliptical") if(e == 0 ): print("The orbit's shape is circular") cos = np.cos pi = np.pi theta = np.linspace(0,2*pi, 360) r = p/(1+e*cos(theta)) plt.polar(theta, r) print(np.c_[r,theta]) plt.show()
eb2167c8adc1ccf0eef2856010e844c0f968f90c
Brunodev09/Java-OOP-samples
/Python/textGame.py
426
3.734375
4
from random import randint gameLoop = True rand_num1 = randint(1,101) rand_num2 = randint(0,2) print('Welcome to dragslay! Type play or quit!\n') while gameLoop: user = input() if (user == "quit"): print('\n----Made by Bruno Giannotti, thanks for playing----') break if (user == "play"): print('OK. Before entering the depths please choose a number from 1-50. Pick wisely for it could be your damnation.') user = input()
925ca46a38cddbfa49170e4c7544284a2fda3b7f
RIPtaDAcomp/hw4_help
/HarrisMHW4.py
3,505
4.15625
4
#=================================================================================================== # Program: ATM Program # Programmer: Matthew Harris # Date: 01/29/2018 # Abstract: This program is a simulation of an ATM. It will process deposits, # withdrawls, and invalid transaction codes, and provide a current # balance. #=================================================================================================== # The main function definition. def main(): # These statements ask for user inputs and will display and use in calculations. name = input("What is your name? ") account_id = input("What is your account ID? ") transaction_code = input("Press W or w for withdrawal, Press D or d for deposit. ") previous_balance = float(input("What is your previous balance? ")) transaction_amount = float(input("How much is the transaction amount? ")) # This if condition allows for a withdrawl and calls the process_withdrawal function. if transaction_code == "W" or transaction_code == "w": process_withdrawal(name, account_id, transaction_code, transaction_amount, previous_balance) # This elif condition allows for a deposit and it calls the process_deposit function. elif transaction_code == "D" or transaction_code == "d": process_deposit(name, account_id, previous_balance, transaction_code, transaction_amount) # This else condition is if they do not meet the previous if or elif condition and calls the # process_invalid_transaction function. else: process_invalid_transaction(name, account_id, previous_balance) # This definition function defines the withdrawl process def process_withdrawal(name, account_id, transaction_code, transaction_amount, previous_balance): # This if condition describes what happens when there are not enough funds for the transaction if transaction_amount > previous_balance: print("Withdrawal exceeds previous balance. ") new_balance = previous_balance print_balance(name, account_id, new_balance) # This else condition will allow a person to do a withdrawal since they did not meet the prior # if condition in this function. else: new_balance = previous_balance - transaction_amount print_balance(name, account_id, new_balance) # This function takes the user through the proces of procesing a deposit. def process_deposit(name, account_id, transaction_code, previous_balance, transaction_amount): new_balance = previous_balance + transaction_amount print_balance(name, account_id, new_balance) # This function takes the user to a error message if they type invalid input for doing a withdrawal # or a deposit. def process_invalid_transaction(name, account_id, previous_balance): print("Invalid transaction type") new_balance = previous_balance print_balance(name, account_id, new_balance) # This function will show the user their input of their name and account id. It also displays their new # balance after the transaction. def print_balance(name, account_id, new_balance): print("Hello", name) print("Your account ID is", account_id) print("Your new balance is $", format(new_balance, ',.2f'), \ sep='') # Call the main function. main () input('Press Enter to continue')
e32bb4cb955fdd108b0fe054391fad5b05534d7a
debuitc4/CA268
/week1/evenodd.py
213
4.0625
4
#!/usr/bin/env python3 import sys #even print second half of string #odd print first and last letter s = sys.argv[1] if len(s) % 2 == 0: print(s[len(s) // 2:]) else: print(s[0] + s[len(s) - 1])
94bb58c36c7aa59459797e314ca1603056c31874
gubarbosa/curso-python
/Mundo2/ex051.py
387
3.859375
4
"""Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão.""" def PA(): primeiro_termo = int(input('Primeiro termo da PA: ')) razao = int(input('Razão da PA: ')) decimo = primeiro_termo + (10 - 1) * razao for x in range(primeiro_termo, decimo + razao, razao): print(x, end= " -->") PA()
8d81facb0f0406354a06ce86232504cdec7e645d
wer153/leetcode
/0904-leaf-similar-trees/0904-leaf-similar-trees.py
671
3.90625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: return travalse(root1) == travalse(root2) def travalse(root): stack = [root] leafs = [] while stack: node = stack.pop() if node.right: stack.append(node.right) if node.left: stack.append(node.left) if node.right is None and node.left is None: leafs.append(node.val) return leafs
329690e647c98076045ee727a16e0b4fd5063add
Charlie-Say/CS-161
/assignments/assignment 5/distance.py
1,867
4.625
5
#! /usr/bin/env python3 # coding=utf-8 ''' write a function that calculates the distance in miles between two cities. Given the latitude and longitude coordinates of cities, calculate the distance in miles between them. Then, write a program that prompts for the coordinates of two cities, uses the function to calculate the distance, and outputs the result. Charlie Say Alex Nylund 10:00 AM Assignment 5 ---- PSUEDO ---- def calculation(): distance in miles between two cities given latitude and longitude def coordinates(): input: coordinates for city 1 input: coordinates for city 2 (call calculation function) output: result(distance in miles) ''' import math def distance(): """ Calculate the Haversine distance. Parameters ---------- city_coords_1 : tuple of float (lat, long) city_coords_2 : tuple of float (lat, long) Returns ------- distance_in_km : float Examples -------- >>> origin = (48.1372, 11.5756) # Munich >>> destination = (52.5186, 13.4083) # Berlin >>> round(distance(origin, destination), 1) 504.2 """ city1_lat = float(input("Enter the latitude for the first location: ")) city1_lon = float(input("Enter the longitude for the first location: ")) city2_lat = float(input("Enter the latitude of the second location: ")) city2_lon = float(input("Enter the longitude for the second location: ")) dlat = math.radians(city2_lat - city1_lat) dlon = math.radians(city2_lon - city1_lon) a = (math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(city1_lat)) * math.cos(math.radians(city2_lat)) * math.sin(dlon / 2) * math.sin(dlon / 2)) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) d = (6371 * c) * 0.621371 print(f"the distance is {round(d, 2)}") distance()
65154120a9ae2b960d1709761ab26e3b1af3c6c8
iverson52000/DataStructure_Algorithm
/LeetCode/0084. Largest Rectangle in Histogram.py
595
3.875
4
""" !84. Largest Rectangle in Histogram Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. """ class Solution: def largestRectangleArea(self, heights: List[int]) -> int: heights.append(0) s = [-1] res = 0 for i in range(len(heights)): while heights[i] < heights[s[-1]]: h = heights[s.pop()] w = i-s[-1]-1 res = max(res, h*w) s.append(i) #heights.pop() return res
d8d6e81e0fcefb77b679dfa9b3d9931d1f6c342f
wljSky/numpy-pandas-exercise
/Matplotlib画图基础/绘制x轴和y轴的刻度.py
750
3.5
4
import matplotlib.pyplot as plt import random x = range(2,26,2)#x轴的位置 y = [random.randint(15,30) for i in x] plt.figure(figsize=(20,8),dpi=80) #设置x轴的刻度 #plt.xticks(X) #plt.xticks(range(1,25)) #设置y轴的刻度 #plt.yticks(y) #plt.yticks(range(min(y)),max(y)+1) #构造x轴刻度标签,for循环读取x轴刻度并控制产生刻度标签的个数,并以相应的格式显示:{}中,放置format(i)括号中的i,也就是取得x x_ticks_label = ['{}:00'.format(i) for i in x] #rotation = 45 让字旋转45度 plt.xticks(x,x_ticks_label,rotation=45) #设置y轴的刻度标签 y_ticks_label = ['{}°C'.format(i) for i in range(min(y),max(y)+1)] plt.yticks(range(min(y),max(y)+1),y_ticks_label) #绘图 plt.plot(x,y) plt.show()
7ce391f5f7d8c192a834e94444bde5204251384e
agvaibhav/python-basics
/trip.py
498
3.671875
4
def hotel_cost(nights): return 140*nights def plane_ride_cost(city): if city=='Charlotte': return 183 elif city=='Tampa': return 220 elif city=='Pittsburgh': return 222 elif city=='Los Angeles': return 475 def rental_car_cost(days): rent=40*days if days>=7: return rent-50 elif 7>=days>=3: return rent-20 else : return rent def trip_cost(city,days,spending_money): return hotel_cost(days-1)+plane_ride_cost(city)+rental_car_cost(days)+spending_money
600160ce998cf98408d0bbe1b808ddabfefcfd61
Thejasvikha/Python-programs
/miles to km.py
205
4.25
4
#converting miles to kilometers def convert(): print("mile to km:") m=int(input("Enter the number of miles:")) t=m*1.609344 print("The number of kilometers for",m,"miles is",t)
1307d39e7e9accbeee0d5373b6ec1f0f953204ef
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_117/1158.py
1,911
3.609375
4
#!/usr/bin/python import sys def is_valley(rows, r, c, N, M): val = rows[r][c] up = down = right = left = False if r > 0: #CHECK UP up = rows[r-1][c] > val if r < N - 1: #CHECK DOWN down = rows[r+1][c] > val if c > 0: #CHECK LEFT left = rows[r][c-1] > val if c < M - 1: #CHECK RIGHT right = rows[r][c+1] > val return (up == True or down == True) and (left == True or right == True) def is_valley_2(rows, r, c, N, M): val = rows[r][c] vert = True horiz = True for i in range(0, N): if val < rows[i][c]: vert = False break for j in range(0, M): if val < rows[r][j]: horiz = False break return vert == False and horiz == False def can_do_pattern(rows, N, M): for r in rows: print r for r in range(0, len(rows)): for c in range(0, len(rows[r])): if is_valley_2(rows, r, c, N, M): print "No se puede:", r, c, "--", rows[r][c] return False return True def solve(in_file, out_file): cases = int(in_file.readline()) for case in range(0, cases): N, M = [int(x) for x in in_file.readline().split()] rows = [] for row in range(0, N): rows.append([int(x) for x in in_file.readline().split()]) result = can_do_pattern(rows, N, M) out_file.write("Case #%d: %s\n" % (case+1, "YES" if result else "NO")) if __name__ == "__main__": if len(sys.argv) != 2: print u"Error: Invalid number of arguments. Expected 1 and received %d." % (len(sys.argv) - 1) sys.exit(2) input_file_name = sys.argv[1] output_file_name = input_file_name.split('.')[0] + '.out' in_file = open(input_file_name, 'r') out_file = open(output_file_name, 'w') solve(in_file, out_file) in_file.close() out_file.close()
fe41cc99cfccbf15ee02ba924a9a089c436d484f
gabrielwry/InterviewPractice
/Algorithm/LeetCode/132Pattern.py
1,090
3.90625
4
""" Construct a min_list of the min value before this position Traverse the original array in reverse order, calculate the range from current position to the end of this array If the range falls into the range of the min_list and the current position, return True """ class Solution(object): def find132pattern(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums)<3: return False min_1 = float('inf') min_1_list = [] min_2 = nums[-1] min_2_list = [] found = False for each in nums: if each < min_1: min_1_list.append(each) min_1 = each else: min_1_list.append(min_1) print nums print min_1_list for i in range(0,len(nums)-1): print nums[len(nums)-1-i] if nums[i]> min_2 and nums[i] > min_1_list[i] and min_2 > min_1: return True if nums[i] < min_2: min_2 = nums[i] return False
10532a87a5d40bc524b412324f3b38129edd4850
ShuaiWang0410/LeetCode-2nd-Stage
/LeetCode-Stage2/Tricks/Problem_56.py
1,108
3.65625
4
''' 56. Merge Intervals ''' # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if [] == intervals: return [] intervals = sorted(intervals, key = lambda interval:interval.start) l_intervals = len(intervals) indexes = [0] if 1 == l_intervals: return intervals for i in range(1, l_intervals): if intervals[i].start <= intervals[i-1].end: intervals[i].start = intervals[i-1].start if intervals[i].end < intervals[i-1].end: intervals[i].end = intervals[i-1].end indexes[-1] = i else: indexes.append(i) return [intervals[i] for i in indexes] name = [[1,4],[4,6],[8,10],[15,18]] prob = [] for i in name: prob.append(Interval(i[0],i[1])) c = Solution() d = c.merge(prob) print(d)
9933b96174838ef93c2c03774f278e8bc3b8bf60
wkujo/RL
/explore_exploit/opt_init_value.py
1,399
3.59375
4
import numpy as np import matplotlib.pyplot as plt class Bandit: def __init__(self, chance, init_value): self.rel_win_chance = chance self.num_pulls = 0 self.mean = init_value def pull(self): return np.random.randn() * self.rel_win_chance def update(self, x): self.num_pulls += 1 self.mean = (1 - 1.0/self.num_pulls)*self.mean + 1.0/self.num_pulls*self.rel_win_chance def model(chance1, chance2, chance3, num_runs, init_value): bandits = [Bandit(chance1, init_value), Bandit(chance2, init_value), Bandit(chance3, init_value)] best_choice = [] act_choice = [] for i in range(num_runs): j = np.argmax([b.mean for b in bandits]) result = bandits[j].pull() bandits[j].update(result) best_choice.append(np.argmax([b.mean for b in bandits]) + 1) act_choice.append(j + 1) return best_choice, act_choice if __name__ == '__main__': num_runs = 10000 init_value = 100 best_choice, act_choice = model(3, 2, 1, num_runs, init_value) # what was considered "best" at each pull plt.plot(best_choice) plt.xscale('log') plt.show() # non-log plot of "best" at each pull plt.plot(best_choice) plt.show() # what was actually chosen plt.scatter(range(num_runs), act_choice, s=1, marker='.') plt.show()
722e203c2dca91a675b5b5e010715f6a04c722ec
jawillia18/problems
/submission_002-mastermind/mastermind.py
1,186
3.859375
4
import random def four_digit_code(): # TODO: Step 1: generate a random 4 digit code code = random.sample(range(1,8), 4) return code def usr_prompt(): usr_input = input("Input 4 digit code: ") return list(usr_input) def input_length(usr_input): # len_code = len(code) len_input = len(usr_input) # while True: if len_input == 4: # print("Please enter exactly 4 digits.") return True else: return False def checking_range(): index = 0 for i in range(0,len(usr_input)): if i != code[index]: return usr_input else: print(usr_input[i]) def run_game(): code = four_digit_code() print("4-digit Code has been set. Digits in range 1 to 8. You have 12 turns to break it.") usr_input = usr_prompt() input_length(usr_input) length = input_length(usr_input) while length == False: print("Please enter exactly 4 digits.") usr_input = usr_prompt() length = input_length(usr_input) else: pass """ TODO: implement Mastermind code here """ pass if __name__ == "__main__": run_game()
69c66a453e6a2226519481954dde76bf468a5abc
rohinarora/Algorithms
/Trees/Binary Search Trees/bst.py
4,617
4.21875
4
class BST(object): """ Simple BST Each tree contains some (maybe 0) BSTnode objects, representing nodes, and a pointer to the root. """ def __init__(self): self.root = None def insert(self,t): ''' Insert key in BST ''' new_node=BSTnode(t) y=None x=self.root while (x is not None): y=x if new_node.key<x.key: x=x.left else: x=x.right new_node.parent=y if y==None: self.root=new_node elif new_node.key<y.key: y.left=new_node else: y.right=new_node return new_node # this return helps only if you use further bstsize.py # helps update all the parent nodes in augmented bst def find(self, t): """Return the node for key t if is in the tree, or None otherwise.""" x=self.root while (x is not None): if x.key==t: return x elif t<x.key: x=x.left else: x=x.right return None def delete_min(self): # kinda like extract min from heap """Delete the minimum key (and return the old node containing it).""" if self.root is None: print ("Nothing to delete. No BSTnode in tree") return None, None # this return helps only if you use further bstsize.py else: x=self.root while (x.left is not None): x=x.left # x is the leftmost node if x.parent is not None: x.parent.left=x.right else: # The root was smallest. self.root=node.right if x.right is not None: x.right.parent = x.parent parent = x.parent x.disconnect() return x,parent # this return helps only if you use further bstsize.py def inorder_tree_walk(self,x): ''' print BST in sorted order ''' if (x is not None): self.inorder_tree_walk(x.left) print (x.key) self.inorder_tree_walk(x.right) def __str__(self): if self.root is None: return '<empty tree>' def recurse(node): if node is None: return [], 0, 0 label = str(node.key) left_lines, left_pos, left_width = recurse(node.left) right_lines, right_pos, right_width = recurse(node.right) middle = max(right_pos + left_width - left_pos + 1, len(label), 2) pos = left_pos + middle // 2 width = left_pos + middle + right_width - right_pos while len(left_lines) < len(right_lines): left_lines.append(' ' * left_width) while len(right_lines) < len(left_lines): right_lines.append(' ' * right_width) if (middle - len(label)) % 2 == 1 and node.parent is not None and \ node is node.parent.left and len(label) < middle: label += '.' label = label.center(middle, '.') if label[0] == '.': label = ' ' + label[1:] if label[-1] == '.': label = label[:-1] + ' ' lines = [' ' * left_pos + label + ' ' * (right_width - right_pos), ' ' * left_pos + '/' + ' ' * (middle-2) + '\\' + ' ' * (right_width - right_pos)] + \ [left_line + ' ' * (width - left_width - right_width) + right_line for left_line, right_line in zip(left_lines, right_lines)] return lines, pos, width return '\n'.join(recurse(self.root) [0]) class BSTnode(object): """ Node of a BST. It has left, right child, parent, and a key value """ def __init__(self, t): """Create a new leaf with key 'key'.""" self.key = t self.disconnect() def disconnect(self): self.right=None self.left=None self.parent=None def test(args=None, BSTtype=BST): import random, sys if not args: args = sys.argv[1:] if not args: print ('usage: {} <number-of-random-items | item item item ...>'.format(sys.argv[0])) sys.exit() elif len(args) == 1: items = (random.randrange(100) for i in range(int(args[0]))) else: items = [int(i) for i in args] tree = BSTtype() #print (tree) for item in items: tree.insert(item) #print (tree) print (tree) #tree.inorder_tree_walk(tree.root) if __name__ == '__main__': test()
7509d3d5ce84254abaeb0a2ee23659e944b3fc2b
ryandsowers/assembler
/SymbolTable.py
1,390
3.609375
4
# #SymbolTable.py # #Loren Peitso # # CS2001 Project 6 Assembler # 31 July 2013 # #complete # class SymbolTable(object): def __init__(self): self.table = { 'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'SCREEN': 16384, 'KBD': 24576, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14, 'R15': 15 } self.varIndex = 16 def addEntry(self, symbol, address): ''' adds a symbol:address pair to the table''' self.table[symbol] = address def contains(self, symbol): ''' is the requested symbol in the table? ''' if (self.table.get(symbol) == None): return False else: return True def getAddress(self, symbol): ''' returns the address of the requested symbol''' return self.table[symbol] def getNextVariableAddress(self): ''' gets what memory index the next variable should be assigned''' result = self.varIndex self.varIndex += 1 return result
2568b9decb0da5d27ec476e8a94c93ff433f3d17
Matizsta/Test
/12.7 Skillfactory.py
361
3.65625
4
per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0} money = int(input("Введите сумму: "))/100 float_deposit = [i * money for i in per_cent.values()] deposit = list(map(round, float_deposit)) print(deposit) print("Максимальная сумма, которую вы можете заработать — ", max(deposit))
37680376267cee764480d30d09a71b0834565c68
Haouach11/assignment
/code11.py
145
3.90625
4
a = range(int(input("enter a number")),int(input("enter a number"))+1) for j in a: for i in range(1, 11): print(j, "x", i, "=", i*j)
e881217d32517ed8e5a684d3c14b3cae966ded6a
evandroMSchmitz/learning
/livro-curso-intensivo-de-python/projeto-2-visualizacao-de-dados/Capitulo-15/geracao-visualizacao-matplotlib/mpl_squares.py
505
3.890625
4
import matplotlib.pyplot as plt input_values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] plt.plot(input_values, squares, "-o", linewidth=2) # Definir o título do Gráfico plt.title("Números Quadrados", fontsize=24) # Nomear os eixos plt.xlabel("Valor", fontsize=14) plt.ylabel("Quadrado do Valor", fontsize=14) # Definir o tamanho dos rótulos e das marcações plt.tick_params(axis="both", labelsize=14) # Apresentar um gird para ajudar na visualização plt.grid(True, linestyle=":") plt.show()
2f9244edf6cdf5d93eaf837209d725e64540dd8e
eawasthi/CodingDojo
/Python/Week1/Day1/practiceAtNight.py
927
3.53125
4
x="It's thanksgiving day. It's my birthday,too!" y=x.replace('day', 'month') print len(x) print y x = [2,54,-2,7,12,98] min1=x[0] max1=x[0] for i in x: if i > max1: max1=i if i<min1: min1=i print max1, min1 x = ["hello",2,54,-2,7,12,98,"world"] print x[0], x[len(x)-1], x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() print x y=x[:5] z=x[5:] print z for i in range(1,1000): if i%2!= 0: print i for i in range(5,1000000): i=i*5 print i a = [1, 2, 5, 10, 255, 3] sum=0; for i in a: sum=sum+i print sum a = [1, 2, 5, 10, 255, 3] sum=0 avg=0 for i in a: sum=sum+i avg=sum/len(a) print avg my_list=[1,"vipul",2,4,"ekta"] for i in my_list: if type(i)==int: print i if i>=100: print "Thats a big number" else: print "Thats a small number" if type(i)==str: print i if i>=50: print "Thats a long sentence" else: print "Short sentence" if len(my_list)>=10: print "Big list!"
a2c7cf5d70b93299e143b81eda99dd00fbea43f1
annalevijeva/Quadratic-equation
/test_equation.py
465
3.75
4
import unittest from equation import equation # class EquationTestCase(unittest.TestCase): # def test_equation(self): # result = equation(-2, 1, 1) # self.assertEqual(result, equation(-2, 1, 1)) class EquationTestCase(unittest.TestCase): def test_solves_equation(self): """Solve y=1*(x**2) + 0*x - 4""" solution = {2, -2} # {-2, 2} = {2, -2} result = equation(1, 0, -4) self.assertEqual(solution, result)
2df745eaae8bbe311bf75f151c8a852b5967dcbd
willpan/sample-csv
/samplecsv.py
1,958
3.59375
4
#! /usr/bin/env python """ samplecsv A utility to randomly sample data from a csv file """ import argparse import csv import random import sys def sniff(buffer): """Determine if csv has header and its dialect""" sample = buffer.read(4098) buffer.seek(0) sniffer = csv.Sniffer() has_header = sniffer.has_header(sample) dialect = sniffer.sniff(sample) return has_header, dialect def random_samples(n, seq, preserve_order=False): """Get n random samples from the sequence.""" samples = [] for idx, sample in enumerate(seq): if idx < n: samples.append((idx, sample)) else: i = random.randint(0, idx) if i < n: samples[i] = (idx, sample) if preserve_order: samples = sorted(samples, key=lambda x: x[0]) return [x[1] for x in samples] def main(filename, n, preserve_order): header = None with open(filename) as f: has_header, dialect = sniff(f) reader = csv.reader(f, dialect=dialect) if has_header: header = next(reader) samples = random_samples(n, reader, preserve_order) # TODO: Optionally preserve order writer = csv.writer(sys.stdout, dialect=dialect) if header is not None: writer.writerow(header) for line in samples: writer.writerow(line) if __name__ == '__main__': parser = argparse.ArgumentParser( description='A utility to randomly sample data from a csv file.') parser.add_argument('file', help='path to csv file to sample') parser.add_argument('-n', type=int, default=1000, help='number of lines to sample, default 1000') parser.add_argument('--preserve-order', default=False, action='store_true', help='keep samples in same order as in file') args = parser.parse_args() main(filename=args.file, n=args.n, preserve_order=args.preserve_order)
715f516aedcb41b9e8c1e049fdcd6005a5b03f0f
shubik22/Project-Euler
/prob_14.py
522
3.84375
4
def longest_collatz(max): longest_collatz = 1 collatz_dict = dict({1: 1}) for i in range(1, max + 1): temp_i = i collatz_len = 0 while temp_i not in collatz_dict: temp_i = next_collatz(temp_i) collatz_len += 1 collatz_dict[i] = collatz_dict[temp_i] + collatz_len if collatz_dict[i] > collatz_dict[longest_collatz]: longest_collatz = i return longest_collatz def next_collatz(n): if n % 2 == 0: return n/2 else: return 3 * n + 1 print longest_collatz(1000000)
0740e1a1287ad0337572db7157c523b38020e0cb
dgirija/SDE1
/dictionary_search.py
247
3.5625
4
import requests import json word = str(input("Word? <user inputs a word>(Ex – \“House\”)")) url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US' + '/' + word.lower() r = requests.get(url) data = json.dumps(r.json()) print(data)
a45245143c11c7ac18b699b7537bfd96b1585a52
MinSu-Kim/pandas_study
/8.data_preprocessing/2.duplicate_data/duplicated.py
505
3.53125
4
import pandas as pd # 중복 데이터를 갖는 데이터프레임 만들기 df = pd.DataFrame( { 'c1': ['a', 'a', 'b', 'a', 'b'], 'c2': [1, 1, 1, 2, 2], 'c3': [1, 1, 2, 2, 2] } ) print('df', df, sep='\n', end='\n\n') print("# 데이터프레임 전체 행 데이터 중에서 중복값 찾기") print(df.duplicated(), sep='\n', end='\n\n') print("# 데이터프레임의 특정 열 데이터에서 중복값 찾기") print(df['c2'].duplicated(), sep='\n', end='\n\n')
6a6a83fa40559bfba9c55452b393091459677288
statickidz/TemarioDAM
/ACTIVIDADES/eclipse-projects/Numeros/src/Actividad5-22/Actividad5-22.py
923
3.671875
4
# -*- coding: utf-8 -*- ''' Created on 27 de ene. de 2016 ''' # uso de and y or print" uso de and y or " print "ABC" and 0 print "ABC" and {} print "ABC" and [] print "ABC" and "" print "ABC" and False print "ABC" and None print "ABC" or 0 print "ABC" or {} print "ABC" or [] print "ABC" or "" print "ABC" or False print "ABC" or None print" and y or cortocircuito " def miFun(p): print p False and miFun("Valor AND") # La función no se ejecuta al ser falsa la expresión en el 1er operando False or miFun("Valor Or") # La función se ejecuta al ser verdadera la expresión en el 2º operando print" operador ?: " sOp1 = "a" sOp2 = "b" iVal = 5 print iVal == 5 and sOp1 or sOp2 print iVal != 5 and sOp1 or sOp2 print" funciones en linea (lambda) " print (lambda x: x * 3)(6) #función de un parámetro x, que se multiplica por tres (x*3). En este caso 18 (6)
cc5e35dc2bded6d98ace28f4d7e3aafec8eb7dfa
burov4j/ai
/python/lesson3/task4.py
240
3.875
4
def my_func(x, y): result = 1 for _ in range(abs(y)): result *= x return 1 / result num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) print(f"Result: {my_func(num1, num2)}")
28c8cf00b2a8ddfd6efd855f7e636a40bd1913a2
Hafisibnuhajar/print-formatting
/tugas 5.py
345
3.75
4
#!/usr/bin/env python # coding: utf-8 # In[8]: #strings print formating nama = "Hafis ibnu hajar" print(f'Nama Dosen pengampu mata kuliah animasi {nama}') # In[10]: nama = "Hafis ibnu hajar" f"Hallo {nama} selamat datang di Dehasen" # In[12]: user_nama = input ("siapa nama kamu? ") print(f'Hallo {user_nama} selamat datang di Dehasen') # In[ ]:
4cb21aba9db21dc3d546bb340f06be9f59165fde
arun246/PythonDataStructures
/python_194/powers.py
205
3.953125
4
def power(x,n): if n== 0: return 1 else: first=power(x,n//2) res= first*first if (n%2==1): return x*res return res print(power(2,3))
83acb8eb1e81719e4cca83daf299f2922e2a23b2
sakib-malik/problem_solving
/oops/LLD-Problems/vendingMachine.py
4,133
4.34375
4
""" Problem Statement: You need to write code to implement a Vending machine that has a bunch of products like chocolates, candy, cold-drink, and accept some coins like Nickle, Dime, Quarter, Cent, etc. Make sure you insert a coin, get a product back, and get your chance back. Also, write the Unit test to demonstrate that these common use cases work. Problem Source: https://medium.com/javarevisited/25-software-design-interview-questions-to-crack-any-programming-and-technical-interviews-4b8237942db0 To Do: 1. Write Unit tests 2. Accept different denomination of currency, and change them in vending machine Solution by: github.com/harshraj22 """ from enum import Enum from typing import Optional, Tuple, Type class Product: """Class representing products for sale """ def __init__( self, name, cost: Optional[int] = 0, count: Optional[int] = 0 ) -> None: self.name = name self.cost = cost self._count = count def __str__(self): return f"{self.name} : priced at {self.cost} each, \ total units = {self._count}" @property def count(self): """method to return the count of item of given product in the vending machine. Returns: int: returns the count of the product. """ return self._count @count.setter def count(self, new_count): """method to update the value of count of items of the given product in the vending machine. Setter allows it to be used as a property instead of method. Example: obj.count = 5 Args: new_count (int): The count of product. """ if new_count < 0: print("Count can not be negative") else: self._count = new_count class AvailableProducts(Enum): """Enum for representing the available objects in vending machine """ CHOCOLATES = 1 CANDY = 2 COLDDRINK = 3 class VendingMachine: """Vending Machine class depicting the usage of a typical vending machine""" def __init__(self, products=None): """Initializer for the class Args: products (dict(AvailableProducts, Products), optional): describes the products available in vending machine for sale. Defaults to None. """ if not products: products = { product: Product(product) for product in AvailableProducts } self._products = products def buy( self, product: Type[AvailableProducts], money: int ) -> Tuple[bool, int]: """Method for buying a product from the vending machine Args: product (AvailableProducts): Describes the type of product one wants to buy (one of the types represented by the enum AvailableProducts) money (int): The money customer gave to the vending machine Returns: Tuple(Bool, int): A tuple whose first parameter represents if the purchase was successful, and the second the money returned by vending machine (if any) after the purchase """ if product not in AvailableProducts: print(f"Product {product} is not sold here.") return (False, money) elif money < self._products[product].cost: print( f"Not Enough Money. One item costs \ {self._products[product].cost}" ) return (False, money) else: print(f"You bought {product}") self._products[product].count = self._products[product].count + 1 return (True, money - self._products[product].cost) def list_products(self): """Method for printing a list of available products for the vending machine """ print(self._products.keys()) if __name__ == "__main__": machine = VendingMachine() did_buy, money_left = machine.buy(AvailableProducts.CANDY, 3) machine.list_products()
bb2865d47bc32187f55f66755e0430a7ccf98279
MaldoCarre/PythonCursoIntermedioAvanzado
/combinando.py
451
4.15625
4
# de dos listas convinar los valores sin repetir # primera forma sin list list comprehensions list1 = [1,2,3] list2 = [3,4,5] result = [] for i in list1: for l in list2: if i != l: result.append((i,l)) result.append((l,i)) else: pass print(result) #usando list comprehensions lista = [1,2,3] listb = [3,4,5] resultado=[((i,l),(l,i))for i in lista for l in listb if i != l] print(resultado)
2fd24529cfdb7505043b25a858d4a0c5f64f8eec
dschonholtz/PsychEconSim
/Controller/SimpleController.py
1,932
3.734375
4
""" The simplest of controllers. Uses a base market and a TextView """ class SimpleController: def __init__(self, text_view, simple_market, rounds=30): self.view = text_view self.model = simple_market self.successful_sellers = 0 self.successful_buyers = 0 self.average_buyer_surplus = 0 self.average_seller_profit = 0 self.rounds = rounds def start(self): self.run_market() def run_market(self): for i in range(self.rounds): self.reset_market_except_seller_prices() print("On round {0} of {1}".format(i + 1, self.rounds)) sellers = self.model.sellers total_buyer_surplus = 0 total_seller_profit = 0 for buyer in self.model.buyers: chosen_seller = buyer.choose_seller(sellers) if chosen_seller is not None: total_buyer_surplus += buyer.price - chosen_seller.estimated_price total_seller_profit += chosen_seller.estimated_price - chosen_seller.price self.successful_sellers += 1 self.successful_buyers += 1 self.average_buyer_surplus = total_buyer_surplus / self.successful_buyers self.average_seller_profit = total_seller_profit / self.successful_sellers self.view.show_stats(self.successful_sellers, self.successful_buyers, self.average_seller_profit, self.average_buyer_surplus) new_sellers = [] for seller in self.model.sellers: seller.adjust_estimated_price() new_sellers.append(seller) self.model.sellers = new_sellers def reset_market_except_seller_prices(self): self.successful_buyers = 0 self.successful_sellers = 0 self.average_buyer_surplus = 0 self.average_seller_profit = 0
4a6e5573431ca4ee3b042655e95c899c22ba8def
cad75/GBLessons
/Lesson_7_HW_2.py
767
3.84375
4
from abc import ABC, abstractmethod class AClothes(ABC): @abstractmethod def get_cloth_count(self): pass class Coat(AClothes): def __init__(self, v): self.v = v def get_cloth_count(self): return self.v / 6.5 + 0.5 class Costume(AClothes): def __init__(self, h): self.h = h def get_cloth_count(self): return 2 * self.h + 0.3 @property def cloth_count(self): return self.get_cloth_count() coat = Coat(55) print(f"Кол-во ткани на пальто: {coat.get_cloth_count()}") costume = Costume(180) print("Кол-во ткани на костюм:") print("As property: " + str(costume.cloth_count)) print("As method: " + str(costume.get_cloth_count())) print('*' * 20)
40164bb65828d27c7e50380d6f047c41f3594498
endredaroczy/hackerrank-python
/iterables-and-iterators.py
528
3.546875
4
import itertools as it def read_from_std(): _ = int(input()) letter_list = input().rstrip().rsplit() K = int(input()) return {'letter_list':letter_list, 'K':K} def read_from_file(): f = open('C:\\Users\\dkendre\\source\\repos\\scripts-python\\hackerrank\\input_file.txt', 'r') _ = int(f.readline()) letter_list = f.readline().rstrip().rsplit() K = int(f.readline()) f.close() return {'letter_list':letter_list, 'K':K} def solution(l, K): pass if __name__ == "__main__": pass
1c66531294e380ca4054de21d208fd05e70f76ea
TheAlgorithms/Python
/bit_manipulation/index_of_rightmost_set_bit.py
1,483
4.28125
4
# Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/ def get_index_of_rightmost_set_bit(number: int) -> int: """ Take in a positive integer 'number'. Returns the zero-based index of first set bit in that 'number' from right. Returns -1, If no set bit found. >>> get_index_of_rightmost_set_bit(0) -1 >>> get_index_of_rightmost_set_bit(5) 0 >>> get_index_of_rightmost_set_bit(36) 2 >>> get_index_of_rightmost_set_bit(8) 3 >>> get_index_of_rightmost_set_bit(-18) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_index_of_rightmost_set_bit('test') Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_index_of_rightmost_set_bit(1.25) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer """ if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") intermediate = number & ~(number - 1) index = 0 while intermediate: intermediate >>= 1 index += 1 return index - 1 if __name__ == "__main__": """ Finding the index of rightmost set bit has some very peculiar use-cases, especially in finding missing or/and repeating numbers in a list of positive integers. """ import doctest doctest.testmod(verbose=True)
e809af9e059c43de168f6d2877fa5686ec1bc998
DegardinJonathan/Python
/Exercice de base/1.py
147
3.8125
4
a = int(input('Donnez la valeur de a : ')) b = int(input('Donnez la valeur de b : ')) temp=b b=a a=temp print ('a = ',a ) print ('b = ',b )
6ce7a4ce21a8f60e2e858f9f66fbfde1da955c3e
aleexnl/aws-python
/UF2/Practica 22/ejercicio2.py
780
3.765625
4
# definim la funcio posicio lletra. def pos_letra(): paraula = input('Introdueix una paraula:') # Pedimos al usuario una palabra. lletra = input('Introdueix una lletra per saber la seba posicio:') # Pedimos una letra. if lletra not in paraula: # Si la lletra introduida no es en la paraula. print('Error la lletra no es en la paraula.') # Imprimira aquest missatge. for i in range(len(paraula)): # Si pasa per cada posicdio de la paraula. if lletra == paraula[i]: # si la lletra es a la paraula. posicio = paraula.index(lletra) # guardem la posicio de la lletra en la variable posicio. print(posicio + 1) # imprimim la variable i li sumem 1, ja que comença des de 0. # cridem a la funcio pos_letra. pos_letra()
4debf4217d22ed297272041d814b8313c42d2bac
juansalvatore/algoritmos-1
/tps/tp0/vectores.py
520
3.84375
4
def diferencia(x1, y1, z1, x2, y2, z2): """Recibe las coordenadas de dos vectores en R3 y devuelve su diferencia""" dif_x = x1 - x2 dif_y = y1 - y2 dif_z = z1 - z2 return dif_x, dif_y, dif_z def norma(x, y, z): """Recibe un vector en R3 y devuelve su norma""" return (x**2 + y**2 + z**2) ** 0.5 def producto_vectorial(x1, y1, z1, x2, y2, z2): """Recibe las coordenadas de dos vectores en R3 y devuelve el producto vectorial""" return y1*z2 - z1*y2, z1*x2 - x1*z2, x1*y2 - y1*x2
85728b6135540121b326be556fa348ca22344c3f
angelmary77/test-repo
/GetPowerValuesUsingLambdaFunction.py
350
3.703125
4
import logging """z = lambda x,y:x+y print z(1,2)""" logging.basicConfig(filename='myapp.log', level=logging.INFO) logging.info('Started') logging.info('doing calculation') squares1=list(map(lambda x: x ** 2, [10,20,30,40])) print squares1 numbers=[1,2,3,4] squares2=list(map(lambda x:pow(x,2), numbers)) print squares2 logging.warning('finished')
56d9052fd76cc67d535d7fba4d06f1d5fdb30b74
yogisen/python
/basedeA-Z_-datascience/textVSdict.py
849
3.875
4
f = open("texte.txt", "r", encoding="utf-8") texte = f.read() g = open("dictionnaire.txt", "r", encoding="utf-8") vocabulary = g.read() tokenized_vocabulary = vocabulary.split(" ") def clean_text(text_string, special_caracters, replacement_string): cleaned_string = text_string for string in special_caracters: cleaned_string = cleaned_string.replace(string, replacement_string) cleaned_string = cleaned_string.lower() cleaned_string = cleaned_string.split(" ") return (cleaned_string) clean_characters = [".", "'", ",", "\n"] replacement = "" cleaned_text = clean_text(texte, clean_characters, replacement) print(cleaned_text) print(tokenized_vocabulary) misspelled_words = [] for missed in cleaned_text: if missed not in tokenized_vocabulary: misspelled_words.append(missed) print(misspelled_words)
d2bab1c0b17217f7d8924f58310d69f9fe68ebc7
Vineet2000-dotcom/python
/algorithms/graphs/Bron-Kerbosch.py
941
3.609375
4
# dealing with a graph as list of lists graph = [[0,1,0,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,1,0,1,1],[1,1,0,1,0,0],[0,0,0,1,0,0]] #function determines the neighbors of a given vertex def N(vertex): c = 0 l = [] for i in graph[vertex]: if i is 1 : l.append(c) c+=1 return l #the Bron-Kerbosch recursive algorithm def bronk(r,p,x): if len(p) == 0 and len(x) == 0: # when no more possible neighbors are found, the max clique is printed print(r) return for vertex in p[:]: # iterates through all possible neigbors r_new = r[::] r_new.append(vertex) p_new = [val for val in p if val in N(vertex)] # p intersects N(vertex) x_new = [val for val in x if val in N(vertex)] # x intersects N(vertex) bronk(r_new,p_new,x_new) # recursiv call with new r, p and x p.remove(vertex) x.append(vertex) bronk([], [0,1,2,3,4,5], [])
3454e8b6e5c4970a2bed998e42c4b6c61d8b20b8
gcross/dmrg101_tutorial
/solutions/two_qbit_system.py
3,453
3.53125
4
#!/usr/bin/env python """ Calculates the entanglement entropy of a two qbit system Calculates the von Neumann entanglement entropu of a system of two spin one-half spins restricted to the subspace of total spin equal to zero. Usage: two_qbit_system.py [--dir=DIR -o=FILE] two_qbit_system.py -h | --help Options: -h --help Shows this screen. -o --output=FILE Ouput file [default: two_qbit_entropies.dat] --dir=DIR Ouput directory [default: ./] """ from docopt import docopt import os from math import cos, sin, pi from dmrg101.core.entropies import calculate_entropy from dmrg101.core.reduced_DM import diagonalize from dmrg101.core.wavefunction import Wavefunction def create_two_qbit_system_in_singlet(psi): """ Returns the wf of the system as a function of `psi`. The (normalized) wavefunction of the two-qbit system can be parametrized as a function an angle `psi`. Parameters ---------- psi : a double Parametrizes the wavefunction. Returns ------- result : a Wavefunction The wavefunction of the two-qbit system for the given `psi`. """ result = Wavefunction(2, 2) # set the different components. result.as_matrix[0, 0] = 0. result.as_matrix[0, 1] = cos(psi) result.as_matrix[1, 0] = sin(psi) result.as_matrix[1, 1] = 0. return result def trace_out_left_qbit_and_calculate_entropy(wf): """Calculates the entropy after tracing out the left qbit. To calculate the entanglement entropy you need to first build the reduced density matrix tracing out the degrees of freedom of one of the two qbits (it does not matter which, we pick up left here.) Parameters ---------- wf : a Wavefunction The wavefunction you build up the reduced density matrix with. Returns ------- result : a double The value of the von Neumann entanglement entropy after tracing out the left qbit. """ reduced_DM_for_right_qbit = wf.build_reduced_density_matrix('left') evals, evecs = diagonalize(reduced_DM_for_right_qbit) result = calculate_entropy(evals) return result def main(args): """Calculates the entanglement entropy for a system of two qbits in a singlet state. """ # # get a bunch of values (number_of_psi) for psi # number_of_psi = 1000 step = 2*pi/number_of_psi psi_values = [x*step for x in range(number_of_psi)] # # python function map applies a function to a sequence # wfs = map(create_two_qbit_system_in_singlet, psi_values) entropies = map(trace_out_left_qbit_and_calculate_entropy, wfs) # # find to which value of psi corresponds the max entropy # zipped = zip(psi_values, entropies) max_value = max(zipped, key=lambda item: (item[1])) # # print the results # print "The maximum value for entropy is %8.6f." %max_value[1] print "The wavefunction with max entropy is: " print create_two_qbit_system_in_singlet(max_value[0]).as_matrix # # save for plotting # filename = args['--output'] f = open(filename, 'w') f.write('\n'.join('%s %s' % x for x in zipped)) f.close() if __name__ == '__main__': args = docopt(__doc__, version = 0.1) main(args) output_file = os.path.join(os.path.abspath(args['--dir']), args['--output']) print "The whole list of psi vs entropies is saved in", print output_file+'.'
61e3306c1ffdd8423421e017c8d118d363df661f
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH15/EX15.21.py
631
4.25
4
# 15.21 (Binary to decimal) Write a recursive function that parses a binary number as a # string into a decimal integer. The function header is as follows: # def binaryToDecimal(binaryString): # Write a test program that prompts the user to enter a binary string and displays its # decimal equivalent. def binaryToDecimal(binaryString): return binaryToDecimalHelper(binaryString, 0, 0) def binaryToDecimalHelper(str, dec, i): if str != '': dec += int(str[-1]) * 2 ** i return binaryToDecimalHelper(str[:len(str) - 1], dec, i + 1) return dec print(binaryToDecimal(input("Enter binary string: ")))
52a800be400e1dbab18c89c0c3c46d2246d80ba5
rotemgb/LeetCode
/Two Sum.py
538
3.546875
4
class Solution(object): def twoSum(self, nums, target): # Create Hash Table d = {} # looping through pairs of indecies and numbers for i, num in enumerate(nums): # create a new target to search in dictionary new_target = target - num # if not in dictionary, add to dictionary if new_target not in d: d.update( { num : i } ) # if it is, we found pair of numbers else: return [d[new_target], i]
49e882f90eb31359dc279364fa73d3b44fc8906e
eprj453/algorithm
/PYTHON/BAEKJOON/10870_피보나치수5.py
175
3.59375
4
fibo = [0, 1] + [None] * 19 def get_fibo(n): if fibo[n] is not None: return fibo[n] return get_fibo(n-1) + get_fibo(n-2) n = int(input()) print(get_fibo(n))
550f55b4f8a332a41f81b9621f6fadd3c65b2db6
ChristopheTeixeira/swinnen
/chapitre-3/part3.py
113
3.671875
4
a = 7 if a > 0 : print("a est positif") elif a < 0 : print("a est négatif") else: print("a est nul")
47bc2d0f4202671907fe80c4a004eb03388ff2ad
mgmarino/RunDB
/utilities/signal_handler.py
890
3.5
4
import threading """ SignalHandler handles signals being sent to and from a process. """ class SignalHandler: msg_semaphore = threading.Event() msg_die = threading.Event() @classmethod def msg_handler(cls, signum, frame): # We've received a msg from the user, # check the msg semaphore. print "Recieved signal to wake" cls.msg_semaphore.set() @classmethod def exit_handler(cls, signum, frame): # We've received a kill msg print "Recieved signal to shutdown" cls.msg_die.set() @classmethod def wait_on_msg(cls): # We need to release the block every so often to allow the signal # handler to be called while (not cls.msg_semaphore.wait(1) and not cls.msg_die.wait(0)): pass if (cls.msg_die.wait(0)): return False cls.msg_semaphore.clear() return True
8f713812f1c2be59cc144a0589b946172ad6d44b
dineshpabbi10/Python
/randint.py
383
3.65625
4
import random # x = random.randint(5,10) # print(x) data = [1,2,3,4,5,10] def shuffle(data): data2 = list() un = list() length = len(data) while(len(data2) != length): x = random.randint(0,length-1) check = (x in un) if(not check): un.append(x) data2.append(data[x]) print(data2) shuffle(data)
0f9c7e283384bd7bad98a50931ad27f01ba83c50
swcide/algorithm
/hanghae/05_4344(평균은넘겠지).py
1,677
3.5625
4
""" 대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다. 당신은 그들에게 슬픈 진실을 알려줘야 한다. 첫째 줄에는 테스트 케이스의 개수 C가 주어진다. 둘째 줄부터 각 테스트 케이스마다 학생의 수 N(1 ≤ N ≤ 1000, N은 정수)이 첫 수로 주어지고, 이어서 N명의 점수가 주어진다. 점수는 0보다 크거나 같고, 100보다 작거나 같은 정수이다. 테스트케이스 = n list [0] = 학생 수 """ n = int(input()) for i in range(n): score = list(map(int, input().split())) avg = sum(score[1:]) / score[0] count = 0 for j in range(1, len(score)): if score[j] > avg: count += 1 per_1 = round((count / (score[0])) * 100, 3) print(f'{per_1:.3f}%') """ for j in range(1, len(score)): if score[j] > avg: count += 1 이부분에서 range(len(score)) 로만 넘기려고 했는데 파이참에선 통과하는데 백준에선 안됐다.. 이유가 뭘까 하고 생각해봤는데 0번째 인덱스인 학생 수를 입력하는 경우에 평균이 학생수를 넘지 못할 경우를 생각을 못했다.. 즉 1의자리 숫자의 점수를 생각 못한것이다. *** 추가 소수점 3자리숫자까지 뽑아야 하는데 3자리 수 이상인 경우에는 라운드 함수를 사용해도 표현이 되지만 3자리수 이하일 경우엔 소숫점 첫재까지 출력이되더라! 그래서 f 스트링으로 .3f 를 활용해 0퍼센트일 경우에도 3자리까지 강제로 출력하게 구현! 그러니까 됩니다 ! 돼요 여러분! 대한독립만세 """
7b9af265e7fd8157d973923f733dbb72cbb1d5b0
yWolfBR/Python-CursoEmVideo
/Mundo 1/Exercicios/Desafio013.py
136
3.53125
4
n = float(input('Digite seu salário atual: R$')) print('Com o aumento, seu novo salário será R${:.2f}'.format(n + (n * (15 / 100))))
01b3f83516359dc8d3b10cda5eec101c064d5343
rishabh-in/DataStructure-Python
/Pattern/RecPattern.py
385
3.8125
4
## Solid rectangle star pattern r = 3 c = 5 for i in range(r): for j in range(c): print("*", end=" ") print() print("\n") ## Hollow rectangle star pattern row = 4 col = 7 for i in range(row): for j in range(col): if i == 0 or i == row-1 or j == 0 or j == col - 1: print("*", end=" ") else: print(" ", end=" ") print()
4d912cce98e72ee7c8f7b2a4193746fe7343d8cd
shikhasingh1797/List
/sum_of_less_than_50_marks.py
358
3.671875
4
students_marks=[23,45,67,89,90,54,34,21,34,23,19,28,10,45,86,9] length=len(students_marks) index=0 sum=0 sum1=0 while index<len(students_marks): if students_marks<50: sum=sum+students_marks[index] else: sum=sum+students_marks[index] index=index+1 print("total marks less than 50 = ",sum) print("totalmarks more than 50 = ",sum1)
d5b132b392a91b3cc1c11e2eb70ff527e1d1ae5c
sanjeevseera/Python-Practice
/Data-Structures/String/part2/P036.py
286
4.125
4
""" Write a Python program to format a number with a percentage """ x = 0.25 y = -0.25 print("\nOriginal Number: ", x) print("Formatted Number with percentage: "+"{:.2%}".format(x)); print("Original Number: ", y) print("Formatted Number with percentage: "+"{:.2%}".format(y));
8428e8242e64d80456db49800909587b8fa1b747
NishanthMHegde/NumpyPractice
/Reshaping.py
690
4.84375
5
import numpy as np #Reshaping can be used to change the shape of an array #A shape of an array is given by (m,n) where m is the number of rows and n is the number of columns #Let us take a 1D array and reshape it into a 2D array with (3,3) shape x = np.arange(9) print(x) #After reshaping x = x.reshape(3,3) print(x) #Alternate way x = np.arange(9).reshape(3,3) print(x) #if any one of the row value or column value is negative, then numpy automatically corrects the wrong index value by making #use of the index value which is proper x = np.arange(9).reshape(3,-1) print(x) x = np.arange(9).reshape(-1,3) print(x) #LEt us create a 3D array y = np.arange(18).reshape(2,3,3) print(y)
a0889882249bd3880ea9797fdd47a77f12088dfb
barinova-iv/geek-python-09-20
/homework03/task05.py
1,297
3.890625
4
# Программа запрашивает у пользователя строку чисел, разделенных пробелом. # При нажатии Enter должна выводиться сумма чисел.Пользователь может продолжить # ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных # чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится # специальный символ, выполнение программы завершается. Если специальный символ # введен после нескольких чисел, то вначале нужно добавить сумму этих чисел к # полученной ранее сумме и после этого завершить программу. def my_func(): num = 0 try: while True: for x in input("Введите числа через пробел (для выхода введите любую букву): ").split(): num += int(x) print(num) pass except ValueError: print(num) my_func()
f65116c972d75671552da880725ca24b95acc486
natnew/Python-Projects-Sort-Numbers
/sort numbers.py
1,298
4.15625
4
digits = [2, 3, 4, 5,0, 1, 9, 8, 10, 6] print('Printing original list:') print(digits) digits.sort() print('Sorting the list:') print(digits) digits.reverse() print('Reversing the list:') print(digits) digits.sort(reverse=True) print('Reversing the list:') print(digits) more_digits = [1, 0, 2, 3, 5, 4, -5, -3, -2, -1, -4] print('Printing original list:') print(more_digits) more_digits.sort() print('Sorting the list:') print(more_digits) more_digits.sort(reverse=True) print('Reversing the list:') print(more_digits) def absvalue(more_digits): return abs(more_digits) more_digits.sort(key = absvalue) print('Sorting based on absolute value:') print(more_digits) more_digits.sort(key = lambda more_digits: abs(more_digits)) print('Using lambada:') print(more_digits) digit_sorted = [3, 6, 4, 7, 5, 2] print('Printing original list:') print(digit_sorted) print('Sorting the list:') new_list = sorted(digit_sorted) print(new_list) print('A tuple:') tupleDigits = (3, 5, 7, 1, 2, 4, 6, 8, 9) print(tupleDigits) print('Reverse tuple:') new_tuple = sorted(tupleDigits, reverse=True) print(new_tuple) print('A dictionary:') dict_dig = {5, 5, 10, 1, 0} print(dict_dig) dict_dig_sorted = sorted(dict_dig) print(dict_dig_sorted)
59448c4ca19215cb4400b4c26b7cfae62ea0a973
gabriellaec/desoft-analise-exercicios
/backup/user_026/ch45_2020_04_12_13_39_28_520923.py
299
3.921875
4
numeros=int(input("digite um número inteiro positivo: ")) lista=[] while numeros>0: lista.append(numeros) numeros=int(input("digite um número inteiro positivo: ")) i=0 invertida=[0]*len(lista) while i<len(invertida): invertida[i]=lista[len(lista)-i] i+=1 print(invertida)
743c932141bb70752e5d0437dbf866966d6d0b30
obliviateandsurrender/Course-Portal
/app/students/models.py
614
3.515625
4
from flask_sqlalchemy import SQLAlchemy from app import db class Student(db.Model): __tablename__ = 'student' # Define the fields here roll = db.Column(db.String(8), primary_key = True) name = db.Column(db.String(200)) year = db.Column(db.String(3)) #courses = db.Column(db.String(1000)) def __init__(self, roll, name, year): # fill this up self.roll = roll self.name = name self.year = year def __repr__(self): return '<Student\'s Roll Number is: %r, Student\'s Name is: %r, Student\'s Year is: %r>>' %(self.roll, self.name, self.year)
9d299caef0eb2d51dc614c15c249dd4f95d5ecd4
jamtot/CodingBatPython
/Warmup-2/string_splosion.py
686
3.703125
4
# Given a non-empty string like "Code" return a string like "CCoCodCode". from test import Tester def string_splosion(str): result = '' for i in range(len(str)): result += str[:i+1] return result Tester(string_splosion('Code'), 'CCoCodCode') Tester(string_splosion('abc'), 'aababc') Tester(string_splosion('ab'), 'aab') Tester(string_splosion('x'), 'x') Tester(string_splosion('fade'), 'ffafadfade') Tester(string_splosion('There'), 'TThTheTherThere') Tester(string_splosion('Kitten'), 'KKiKitKittKitteKitten') Tester(string_splosion('Bye'), 'BByBye') Tester(string_splosion('Good'), 'GGoGooGood') Tester(string_splosion('Bad'), 'BBaBad')
9748b25ae387900619ea3fee3407ea7ff2de8909
smahmud5949/All-code
/24.py
124
4.1875
4
num=int(input("Enter a number: ")) n=1 while num>0: n=n*num num=num-1 print ("Factorial of the given number is ",n)
5cc699392432d3c3539c860ed6c499f31b0a068b
alexeynico/les
/program.py
160
3.65625
4
phones = ["iPhone Xs", "Samsung Galaxy S10", "Xiaomi Mi8"] phones.append("iPhone Xs") print(phones) ln = len(phones) print(ln) print(phones.count("iPhone Xs"))
5a4388ee81d7dd3c43bca2717699c5d161575847
ejmoyer/python-projects
/ex17.py
591
3.640625
4
# ex 17 def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses.") print(f"You have {boxes_of_crackers} boxes of crackers.") print("That's enough for a party!") #we can give it numbers directly cheese_and_crackers(20, 30) # or we can use variables amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) # or we can do math within the function call cheese_and_crackers(10 + 20, 5 + 6) # or we can combine the two cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
c082f303bcc3c5e6c1f131182fc162cb1503711f
patiregina89/Exercicios-Logistica_Algoritimos
/Exercicio2_Ordemdesc.py
1,016
4.3125
4
print("*"*12,"FACULDADE CESUSC","*"*12) print("CURSO: ANÁLISE E DESENV. DE SISTEMAS") print("Discipl.: Lógica Computacional e Algorítimos") print("Turma: ADS11") print("Nome: Patricia Regina Rodrigues") print("Exercício 2 - Números inteiros decrescente") print(("*"*42)) #2. Faça um Programa que leia um vetor de 10 números reais e mostre-os na ordem inversa. num = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] num[0] = int(input("Informe um número: ")) num[1] = int(input("Informe um número: ")) num[2] = int(input("Informe um número: ")) num[3] = int(input("Informe um número: ")) num[4] = int(input("Informe um número: ")) num[5] = int(input("Informe um número: ")) num[6] = int(input("Informe um número: ")) num[7] = int(input("Informe um número: ")) num[8] = int(input("Informe um número: ")) num[9] = int(input("Informe um número: ")) lista = [num] print("Os números digiados foram: ", num[9],",", num[8],",", num[7],",", num[6],",", num[5],",", num[4],",", num[3],",", num[2],",", num[1],",", num[0])
65c6feb79bbeecc0c5f1444506982280123a7c1d
jlmasson/Ayudant-asFundamentos2017-I
/Funciones-Arreglos/TicTac.py
2,495
3.578125
4
def dibujar_linea(width, edge, filling): print(filling.join([edge] * (width + 1))) def mostrar_ganador(player): if player == 0: print("Tie") else: print("Player " + str(player) + " wins!") def revisar_ganador_fila(row): """ Return the player number that wins for that row. If there is no winner, return 0. """ if row[0] == row[1] and row[1] == row[2]: return row[0] return 0 def get_columna(game, col_number): return [game[x][col_number] for x in range(3)] def get_fila(game, row_number): return game[row_number] def revisar_ganador(game): game_slices = [] for index in range(3): game_slices.append(get_fila(game, index)) game_slices.append(get_columna(game, index)) # check diagonals down_diagonal = [game[x][x] for x in range(3)] up_diagonal = [game[0][2], game[1][1], game[2][0]] game_slices.append(down_diagonal) game_slices.append(up_diagonal) for game_slice in game_slices: winner = revisar_ganador_fila(game_slice) if winner != 0: return winner return winner def iniciar_juego(): return [[0, 0, 0] for x in range(3)] def mostrar_juego(game): d = {2: "O", 1: "X", 0: "_"} dibujar_linea(3, " ", "_") for row_num in range(3): new_row = [] for col_num in range(3): new_row.append(d[game[row_num][col_num]]) print("|" + "|".join(new_row) + "|") def add_pieza(game, player, row, column): """ game: game state player: player number row: 0-index row column: 0-index column """ game[row][column] = player return game def revisar_vacio(game, row, column): return game[row][column] == 0 def transformar_coordenada(user_input): return user_input - 1 def cambiar_jugador(player): if player == 1: return 2 else: return 1 def verificar_movimiento(game): for row_num in range(3): for col_num in range(3): if game[row_num][col_num] == 0: return True return False if __name__ == '__main__': game = iniciar_juego() mostrar_juego(game) player = 1 winner = 0 # the winner is not yet defined # go on forever while winner == 0 and verificar_movimiento(game): print("Currently player: " + str(player)) available = False while not available: row = transformar_coordenada(int(input("Which row? (start with 1) "))) column = transformar_coordenada(int(input("Which column? (start with 1) "))) available = revisar_vacio(game, row, column) game = add_pieza(game, player, row, column) mostrar_juego(game) player = cambiar_jugador(player) winner = revisar_ganador(game) mostrar_ganador(winner)
62e96c00c8872087cf20eec1e93bfbbb1559c555
TolentinoDev/Computer-science-130
/Computer Science 130 copy/RyanTolentinoxassignment0.py
2,261
4.3125
4
#Ryan Tolentino #8-18-2016 #Assignment 0 print('assignment: Assignment 0') print('programmer: Ryan Tolentino') print('date: 8/16/2016') print('Correct Answers') print('Problem 1') print('Check if the first character of my first name "Denny" is the same as') print('the first character of your name "Ryan"') firstName1 ='Denny' firstName2 ='Ryan' print ('Initial Value: ' , firstName1) print ('Initial Value: ' , firstName2) isItTrue=(firstName1[0]==firstName2[0]) print ('Result: ' , isItTrue) print('Problem 2') print('Display my first name "Ryan" with my last name "Tolentino" i.e. as "Ryan Tolentino" ') firstName='Ryan' lastName='Tolentino' print ('Initial Value: ' , firstName) print ('Initial Value: ' , lastName) name=(firstName+' '+lastName) print ('Result: ' , name) print('Problem 3') print('Display the first character of my first name "Ryan" with my last name "Tolentino" i.e. as "D. Czejdo" initial and the last name') firstName='Ryan' lastName='Tolentino' print ('Initial Value: ' , firstName) print ('Initial Value: ' , lastName) name=(firstName[0]+'. '+lastName) print ('Result: ' , name ) print('Problem 4') print('Check if the length of my first name ‘Denny’ is the same as the length of your name ‘Ryan’ ') firstName='Denny' lastName='Ryan' print ('Initial Value: ' , firstName) print ('Initial Value: ' , lastName) isItTrue=(len(firstName1)==len(firstName2)) print ('Result: ' ,isItTrue ) print('Problem 5') print('Display your age next year assuming that you are now twenty years old ') currentAge=20 print ('Initial Value: ' , currentAge) futureAge=currentAge+1 print ('Result: ' , futureAge) print('Problem 6') print('Create a list of John’s scores that are 99, 77, 19, 80, and 100. John took a next test and got 98. ') print('Update the list.') scores=[99,77,19,80,100] score1=98 print ('Initial Value: ' , scores ) print ('Initial Value: ' , score1) scores.append(score1) print ('Result: ' , scores) print('Problem 7') print('Create a list of John’s scores that are 99, 77, 19, 80, 100 and 98.') print('John took a makeup for third quiz and got 90. Update the list.') scores=[99,77,19,80,100,98] score2=80 print ('Initial Value: ' , scores) print ('Initial Value: ' , score2) scores[2]=score2 print ('Result: ' , scores)
fb64f1f221b017bfd2dd95b6425a7d89330ac21f
Fischerlopes/EstudosPython
/cursoEmVideoMundo2/ex045.py
1,494
3.96875
4
import time import random print(' === JOGO JOKENPO === ') print(''' ESCOLHA SUA OPCÃO [ 1 ] - PEDRA [ 2 ] - PAPEL [ 3 ] - TESOURA''') jogador = int(input('Qual é a sua jogada ? ')) print('Vamos ao jogo!!') time.sleep(1) print('Jo') time.sleep(1) print('Ken') time.sleep(1) print('Po') list = ['Pedra','Papel','Tesoura'] computador = random.choice(list) if jogador == 1 and computador == 'Papel': print('O Computador jogou: {}'.format(computador)) print('Você jogou: Pedra') print('O computador venceu') elif jogador == 2 and computador == 'Tesoura': print('O Computador jogou: {}'.format(computador)) print('Você jogou: Papel') print('O computador venceu') elif jogador == 3 and computador == 'Pedra': print('O Computador jogou: {}'.format(computador)) print('Você jogou: Tesoura') print('O computador venceu') elif jogador == 1 and computador == 'Tesoura': print('O Computador jogou: {}'.format(computador)) print('Você jogou: Pedra') print('O jogador venceu') elif jogador == 3 and computador == 'Papel': print('O Computador jogou: {}'.format(computador)) print('Você jogou: Tesoura') print('O jogado venceu') elif jogador == 2 and computador == 'Pedra': print('O Computador jogou: {}'.format(computador)) print('Você jogou: Papel') print('O jogador venceu') else: print('O Computador jogou: {}'.format(computador)) print('Você jogou: {}'.format(computador)) print('Empate - Joque novamente')
fd0401194f81aa364d99b1631c4399fef7760700
monkeyking/getIOU
/get_iou.py
1,942
3.59375
4
def xywh(bboxA, bboxB): """ This function computes the intersection over union between two 2-d boxes (usually bounding boxes in an image. Attributes: bboxA (list): defined by 4 values: [xmin, ymin, width, height]. bboxB (list): defined by 4 values: [xmin, ymin, width, height]. (Order is irrelevant). Returns: IOU (float): a value between 0-1 representing how much these boxes overlap. """ xA, yA, wA, hA = bboxA areaA = wA * hA xB, yB, wB, hB = bboxB areaB = wB * hB overlap_xmin = max(xA, xB) overlap_ymin = max(yA, yB) overlap_xmax = min(xA + wA, xB + wB) overlap_ymax = min(yA + hA, yB + hB) W = overlap_xmax - overlap_xmin H = overlap_ymax - overlap_ymin if min(W, H) < 0: return 0 intersect = W * H union = areaA + areaB - intersect return intersect / union def xyXY(bboxA, bboxB): """ Similar to the above function, this one computes the intersection over union between two 2-d boxes. The difference with this function is that it accepts bounding boxes in the form [xmin, ymin, XMAX, YMAX]. Attributes: bboxA (list): defined by 4 values: [xmin, ymin, XMAX, YMAX]. bboxB (list): defined by 4 values: [xmin, ymin, XMAX, YMAX]. Returns: IOU (float): a value between 0-1 representing how much these boxes overlap. """ xminA, yminA, xmaxA, ymaxA = bboxA widthA = xmaxA - xminA heightA = ymaxA - yminA areaA = widthA * heightA xminB, yminB, xmaxB, ymaxB = bboxB widthB = xmaxB - xminB heightB = ymaxB - yminB areaB = widthB * heightB xA = max(xminA, xminB) yA = max(yminA, yminB) xB = min(xmaxA, xmaxB) yB = min(ymaxA, ymaxB) W = xB - xA H = yB - yA if min(W, H) < 0: return 0 intersect = W * H union = areaA + areaB - intersect iou = intersect / union return iou
f5a5a8c755529ff9a01512da1ae50cfab187184e
thor4/Computational-Neuroscience
/models/supervised/mlp.py
4,412
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 10 09:31:24 2018 @author: bryan """ import numpy # sigmoid function from scipy.special import scipy.special # define a neural network class that can be initialized, trained and queried class neuralNetwork: # initialize the network def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # set the number of nodes in each layer: input, hidden and output self.inodes = input_nodes self.hnodes = hidden_nodes self.onodes = output_nodes # set the learning rate for the network self.lrate = learning_rate # set the weights for edges connecting each node from each layer # weights inside the array are of the form w_ij where origination node # is found in layer i, target node is found in layer j # numpy.random.rand selects a number at random [0,1]. subtracting 0.5 # ensures there are negative numbers to allow for weights to go from # [-0.5,0.5]. convention will be matrices of (j,i). ie: (hidden,input) self.w_input_hidden = (numpy.random.rand(self.hnodes,self.inodes) - 0.5) self.w_hidden_output = (numpy.random.rand(self.onodes,self.hnodes) - 0.5) # define the activation function to use (sigmoid) # assign anonymous function lambda as activation_function. have it # take in x and return expit(x) self.activation_function = lambda x:scipy.special.expit(x) pass # train the network with a list of inputs and list of targets def train(self, inputs_list, targets_list): # ensure inputs and targets list is a 2d array (inputs x 1) inputs = numpy.array(inputs_list,ndmin=2).T targets = numpy.array(targets_list,ndmin=2).T # feed-forward inputs through to output layer hidden_inputs = numpy.dot(self.w_input_hidden,inputs) hidden_outputs = self.activation_function(hidden_inputs) final_inputs = numpy.dot(self.w_hidden_output,hidden_outputs) final_outputs = self.activation_function(final_inputs) # calculate the error (target - prediction) output_errors = targets - final_outputs # use output errors to determine error at the hidden layer: multiply # each hidden weight by output errors hidden_errors = numpy.dot(self.w_hidden_output.T,output_errors) # update weights on edges connecting hidden and output layers # formula is lrate * error * sig(output) * (1-sig(output)) * hidden self.w_hidden_output += self.lrate * numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)), numpy.transpose(hidden_outputs)) # update weights on edges connecting input and hidden layers self.w_input_hidden += self.lrate * numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)), numpy.transpose(inputs)) pass # query the network with list of inputs def query(self, inputs_list): # ensure inputs list is a 2d array (inputs x 1) inputs = numpy.array(inputs_list,ndmin=2).T # pass the inputs to the hidden layer by multiplying with each edge's # weight and summing together hidden_inputs = numpy.dot(self.w_input_hidden,inputs) # add bias? # pass hidden inputs through activation function to determine hidden # layer output hidden_outputs = self.activation_function(hidden_inputs) # pass hidden layer outputs to final output layer by multiplying with # each edge's weight and summing together final_inputs = numpy.dot(self.w_hidden_output,hidden_outputs) # pass through activation function to determine final output layer final_outputs = self.activation_function(final_inputs) return final_outputs # iniitalize neural network object architecture: input,hidden and output layer # nodes and learning rate input_nodes = 2 hidden_nodes = 2 output_nodes = 1 learning_rate = 0.3 # create instance of neural network class n = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate) # query neural network instance with some random inputs n.query([1.0, 0.5, -1.5]) n.train([1.0, 0.5, -1.5], [2.0, 0.0, 1.0]) n.train([1, 1], [0]) n.train([1, 0], [1]) n.train([0, 1], [1]) n.train([0, 0], [0]) n.query([0, 0]) numpy.random.rand(3,4) - 0.5 inputs_list = [1.0, 0.5, -1.5] expit()
35e570f2627249951580740343ed7fe5b6acfa8f
Jfprado11/holbertonschool-higher_level_programming
/0x0A-python-inheritance/11-square.py
718
4.1875
4
#!/usr/bin/python3 """A method that holds a class witch it inherates from the class rectangle """ Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """a class witch holds an inheratence of rectangle """ def __init__(self, size): """ initiation of the class containing the super class to bring up the methods from the paretn class """ self.__size = size self.integer_validator("size", self.__size) super().__init__(size, size) def area(self): """gives the area of a square""" return self.__size * self.__size def __str__(self): return "[Square] {}/{}".format(self.__size, self.__size)
c872635443a38a5e30a464cd28237f06cc02b126
vikramraghav90/Python
/van/van_fizzuzz_2.py
761
4.40625
4
""" 2. Write a function called fizz_buzz that takes a number. - If the number is divisible by 3, it should return “Fizz”. - If it is divisible by 5, it should return “Buzz”. - If it is divisible by both 3 and 5, it should return “FizzBuzz”. - Otherwise, it should return the same number. """ def fizz_buzz (a): if a == 0 or type(a) != int: return 0 else: if a % 3 == 0: if a % 5 == 0: return 'FizzBuzz' else: return 'Fizz' elif a % 5 == 0: return 'Buzz' else: return 'Null' print(fizz_buzz(24)) print(fizz_buzz(13)) print(fizz_buzz(15)) print(fizz_buzz(9)) print(fizz_buzz(20)) print(fizz_buzz(0)) print(fizz_buzz('string'))
93a6775e32a1a12637a2102ab3fa3e958871eeb7
Adam-Petersen/secret-santa
/graph.py
4,381
3.5625
4
import random from random import randint from random import shuffle class Graph: def __init__(self, people): self.people = people self.targeted = {} # Specifies whether a person is currently being targeted self.old_edges_collection = {} # Used in assigning algorithm for restoring destroyed edges self.visited = {} # Used in DFS for p in people: self.visited[p] = False self.targeted[p] = False self.old_edges_collection[p] = {} self.init_edges() # Set edges between every person and remove ones that violate people's cant_get list def init_edges(self): self.edges = {} for p1 in self.people: self.edges[p1] = {} for p2 in self.people: self.edges[p1][p2] = True self.edges[p1][p1] = False for p2 in p1.cant_get: self.edges[p1][p2] = False # Returns true if every person has a target def complete(self): for p in self.people: if not p.has_target(): return False return True # Returns true if person has no potential targets or if person can't be targeted, false otherwise def bad_state(self): for p1 in self.people: if not p1.has_target(): no_targets = True for p2 in self.people: if self.edges[p1][p2]: no_targets = False if no_targets: return True if not self.targeted[p1]: cant_be_targeted = True for p2 in self.people: if self.edges[p2][p1]: cant_be_targeted = False if cant_be_targeted: return True return False # Returns possible targets for given person def get_targets(self, person): targets = [] for p2 in self.people: if self.edges[person][p2]: targets.append(p2) return targets # Returns possible targets for given person in random order def get_targets_random(self, person): targets = self.get_targets(person) shuffle(targets) return targets # Gets blank data structure representing old edges that could need to be restored def get_blank_old_edge_dict(self): d = {} for p in self.people: d[p] = [] return d # Assigns target to person, removes other edges pointing out from person, and removes other edges pointing to target def set_target(self, person, target): person.target = target self.targeted[target] = True old_edges = self.get_blank_old_edge_dict() for p2 in self.people: if p2 != target and self.edges[person][p2]: old_edges[person].append(p2) self.edges[person][p2] = False if p2 != person and self.edges[p2][target]: old_edges[p2].append(target) self.edges[p2][target] = False self.old_edges_collection[person] = old_edges # Reverts target assignment and restores all edges destroyed when assignemnt happened def revert_target(self, person): self.targeted[person.target] = False person.target = None old_edges = self.old_edges_collection[person] for p1 in self.people: for p2 in old_edges[p1]: self.edges[p1][p2] = True self.old_edges_collection[person] = {} # Main algorithm that randomly assigns people using recursion def assign_targets(self, person): if self.complete(): return True elif self.bad_state(): return False targets = self.get_targets_random(person) valid_target_found = False for target in targets: if not self.targeted[target]: self.set_target(person, target) valid_target_found = self.assign_targets(target) if valid_target_found: return True else: self.revert_target(person) return False # Determines possible number of assignment combinations given a root node def get_num_combos(self, person, tally): if self.complete(): return tally + 1 elif self.bad_state(): return tally targets = self.get_targets(person) valid_target_found = False for target in targets: if not self.targeted[target]: self.set_target(person, target) new_tally = self.get_num_combos(target, tally) if new_tally > tally: self.revert_target(person) tally = new_tally else: self.revert_target(person) return tally # Overload for initial call def get_num_combos(self): return get_num_combos(self.people[0], 0)
bff4eba7d2e064c44b32d162be96a09087c141ae
codicevitae/learningtocode
/1_Assignment_Statements/problem_1.py
510
4.375
4
# We have to convert the input to a number. Here we use an int, but we could use a float() # so the user could enter things like 21.4 fahrenheit = int(input("Enter your Fahrenheit temperature: ")) # Notice that because there is division in this formula, that even if every other number in it # is an integer, the answer will be a decimal (floating value). celcius = ((fahrenheit) - 32) * 5 / 9 # We have to convert the answer to string, since you can't concatenate numbers! print("Celcius: " + str(celcius))
811e92443e4ac330a149e84649bc0e1328470b49
dummy3k/Project-Euler
/problem039/solve.py
1,009
3.515625
4
import doctest import math from euler_tools.misc import StopWatch max_perimeter = 1001 def cnt_solutions(perimeter): """ >>> cnt_solutions(120) 3 """ retval = 0 for a in range(1, perimeter / 2): for b in range(a + 1, perimeter / 2): c = perimeter - a -b if a ** 2 + b ** 2 == c ** 2: #~ print "%s^2 * %s^2 = %s^2" % (a, b, c) retval += 1 #for c in range(b + 1, perimeter): #if a ** 2 + b ** 2 == c ** 2 and a + b + c == perimeter: ##~ print "%s^2 * %s^2 = %s^2" % (a, b, c) #retval += 1 return retval def main(): watch = StopWatch() max_length = 0 for d in range(1, 1001): length = cnt_solutions(d) if length > max_length: print "%s -> %s" % (d, length) max_length = length watch.print_time() # 840 -> 8 if __name__ == '__main__': doctest.testmod() main()
7c5ff79a909e7cb1ea13aada45c1ace861aa2872
AaronAS2016/Sudoku_Solver_EDD
/reader.py
1,971
4.21875
4
# TODO: # [] Leer archivo # [X] Leer csv # [X] Excepciones # [] Completar docs import os import csv class Reader(): """ A class to read Files Attributes ---------- filepath : str the path of the file that want to read Methods ---------- setFile(filepath) change the Path of the class readFile return the content of the file readFileAsCSV return the content of the file of a csv """ def __init__(self, filepath="", delimiter=","): self._filepath = filepath self._delimiter = delimiter def setDelimiter(self, delimiter): self._delimiter = delimiter def setFile(self, filepath): """ Change the Path of the class Parameter -------- filepath: str the new path of the file that want to read """ self._filepath = filepath def checkIfExistFile(self): return os.path.exists(self._filepath) def readFileAsCSV(self, delimiter=None): # Use the default delimiter if delimiter is None: delimiter = self._delimiter if(self.checkIfExistFile()): try: with open(self._filepath, 'r') as readerCsv: reader = csv.reader(readerCsv, delimiter=delimiter) data = [] for row in reader: row = [int(i) for i in row] data.append(row) except ValueError: print("Error trying to read the file: " + ValueError) return data else: raise ValueError("Ups!, The filepath looks wrong, try to change the filepath") # Test caseros # Caso bueno """ lector = Reader() lector.setFile('resources/boards.csv') print(lector.readFileAsCSV(',')) """ # Caso Malo """ lector2 = Reader() lector2.setFile('rutaquenoexisteniagancho') print(lector2.readFileAsCSV()) """
4f2be28714a913de52b5ca9abda25912b0e04096
yask123/PracticeHR
/selectionsort.py
412
3.578125
4
def select_sort(alist): for i in range(len(alist)): max_num = alist[0] for j in range(len(alist) - i): if alist[j] >= max_num: max_num = alist[j] max_num_index = j alist[max_num_index], alist[len(alist) - i - 1] = alist[len(alist) - i - 1], alist[max_num_index] return alist print select_sort([32, 21, 345, 123, 435231, 324123, 213])
931d483c759128ad29b634224705673f9f1f2a53
DebojyotiRoy15/LeetCode
/75. Sort Colors.py
619
3.546875
4
#https://leetcode.com/problems/sort-colors/ if len(nums) == 1: return nums elif len(nums) == 2: if nums[0] > nums[1]: nums[0], nums[1] = nums[1], nums[0] return nums else: hash = {0: 0, 1: 0, 2: 0} for num in nums: hash[num] = hash[num] + 1 k = 0 for i in range(0, 3): while (hash[i] != 0): nums[k] = i hash[i] = hash[i] - 1 k = k + 1 return nums
5d3629827da18118869f958892a5f836b9615d45
amouhk/redfish_utils
/utils.py
480
3.625
4
# Foncutions utile sur les string # Extraction d'une chaine de caractere entre 2 chaines def find_between(s, first, last): try: start = s.index(first) + len(first) end = s.index(last, start) return s[start:end] except ValueError: return "" def find_between_r(s, first, last): try: start = s.rindex(first) + len(first) end = s.rindex(last, start) return s[start:end] except ValueError: return ""
82ffc32e1c8d100450b4b9c75501b578804651be
NunationFL/FPRO
/raise_exception.py
192
3.640625
4
def raise_exception(alist, value): out=[] for elem in alist: if elem <= value: out.append(ValueError("{} is not greater than {}".format(elem,value))) return out