blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
da275f6e143f10058c1e65bece861203cd76e043
vaishvikmaisuria/Sorting-Python-Time
/sort-time.py
2,941
4.125
4
############### Bubble Sort ############### def bubble_sort(L): '''(list) -> NoneType Sort the items in L in non-descending order. >>> L = [1, 4, 2, 5, 3, 6] >>> bubble_sort(L) >>> L [1, 2, 3, 4, 5, 6] ''' uns_index = len(L) - 1 while uns_index > 0: for curr_index in range(uns_index): if L[curr_index] > L[curr_index + 1]: L[curr_index], L[curr_index + 1] = L[curr_index + 1], L[curr_index] uns_index -= 1 ############### Selection Sort ############### def find_minimum(L, start_index): '''() -> int Return the index of the smallest value in the list that occurs at or after start_index. Note: start_index must be legal, so L cannot be empty. >>> find_minimum([5, 3, 7, 4], 0) 1 >>> find_minimum([3, 5, 7, 4], 1) 3 ''' index_min = start_index index = start_index + 1 while index < len(L): if L[index] < L[index_min]: index_min = index index += 1 return index_min def selection_sort(L): '''(list) -> NoneType Sort the items in L in non-descending order. >>> L = [5, 3, 7, 4] >>> selection_sort(L) >>> L [3, 4, 5, 7] >>> L = [1, 4, 2, 5, 3, 6] >>> selection_sort(L) >>> L [1, 2, 3, 4, 5, 6] ''' uns_index = 0 while uns_index < len(L): min_index = find_minimum(L, uns_index) L[min_index], L[uns_index] = L[uns_index], L[min_index] uns_index += 1 ############### Insertion Sort ############### def insert(L, index): '''(list, int) -> NoneType Insert the item at position index in list L into the range [0..index] so that [0..index] is sorted. [0..index-1] is already sorted. >>> L = [1, 0] >>> insert(L, 1) >>> L [0, 1] ''' while index > 0 and L[index - 1] > L[index]: L[index], L[index - 1] = L[index - 1], L[index] index -= 1 def insertion_sort(L): '''(list) -> NoneType Sort the items in L in non-descending order. >>> L = [5, 3, 7, 4] >>> insertion_sort(L) >>> L [3, 4, 5, 7] >>> L = [1, 4, 2, 5, 3, 6] >>> insertion_sort(L) >>> L [1, 2, 3, 4, 5, 6] ''' uns_index = 1 while uns_index < len(L): insert(L, uns_index) uns_index += 1 ############### Insertion Sort ############### def system_sort(L): '''A wrapper for the system's sort function, so we can time it. ''' L.sort() if __name__ == '__main__': import doctest doctest.testmod() from timing import time_listfunc print("bubble 4000", time_listfunc(bubble_sort, 4000, 3)) print("selection 4000", time_listfunc(selection_sort, 4000, 3)) print("insertion 4000", time_listfunc(insertion_sort, 4000, 3)) print("system sort 4000", time_listfunc(system_sort, 4000, 3))
d0297fd7ba9dbd5a5df3da0d294fe5a940c32ed7
laowantong/paroxython
/examples/idioms/programs/099.2693-format-date-yyyy-mm-dd.py
360
3.5625
4
"""Format date YYYY-MM-DD. Assign to string _x the value of fields (year, month, day) of date _d, in format _YYYY-_MM-_DD. Source: programming-idioms.org """ # Implementation author: jessedhillon # Created on 2019-09-26T13:46:18.91621Z # Last modified on 2019-09-26T13:46:18.91621Z # Version 1 from datetime import date d = date.today() x = d.isoformat()
8673ebbea8a9610e58382e5b91db2aabfedf0c83
dataAlgorithms/dataStructure
/linkedList/sortedCircularLinkedList.py
4,431
3.734375
4
class CircularSortedLinkedList: # Init def __init__(self): self._listRef = None self._size = 0 # Length def __len__(self): return self._size # Check whether the list is empty def isEmpty(self): return self._size == 0 # Check whether the item in the list def __contains__(self, item): curNode = self._listRef done = self._listRef is None while not done: curNode = curNode.next if curNode.value == item: return True else: done = curNode is self._listRef or curNode.value > item return False # Add operation def add(self, item): newnode = _DLinkListNode(item) if self._listRef is None: self._listRef = newnode newnode.next = newnode elif item < self._listRef.next.value: newnode.next = self._listRef.next self._listRef.next = newnode elif item > self._listRef.value: newnode.next = self._listRef.next self._listRef.next = newnode self._listRef = newnode else: preNode = None curNode = self._listRef done = self._listRef is None while not done: preNode = curNode curNode = curNode.next done = curNode is self._listRef or curNode.value > item newnode.next = curNode preNode.next = newnode self._size += 1 # Remove operation def remove(self, item): assert item in self, "item is not in" if self._listRef is None: return False elif item == self._listRef.next.value: self._listRef.next = self._listRef.next.next elif item == self._listRef.value: preNode = None curNode = self._listRef done = self._listRef is None while not done: preNode = curNode curNode = curNode.next done = curNode is self._listRef preNode.next = self._listRef.next self._listRef = preNode else: preNode = None curNode = self._listRef.next done = self._listRef is None while not done: preNode = curNode curNode = curNode.next done = curNode is self._listRef or curNode.value == item preNode.next = curNode.next self._listRef = preNode self._size -= 1 # Iter def __iter__(self): return _CircularSortedLinkedListIter(self._listRef, self._size) # Iter class _CircularSortedLinkedListIter: # Init def __init__(self, listRef, size): self._curNode = listRef.next self._size = size self._cIndex = 0 def __iter__(self): return self def next(self): if self._cIndex < self._size: value = self._curNode.value self._curNode = self._curNode.next self._cIndex += 1 return value else: raise StopIteration # Node class _DLinkListNode: # Init def __init__(self, item): self.value = item self.next = None def test_sortedcircularlinkedlist(): # init a linkedlist named smith smith = CircularSortedLinkedList() smith.add('CSCI-112') smith.add('MATH-121') smith.add('HIST-340') smith.add('ECON-101') # print smith print 'primary smith' for item in smith: print item # remove one item smith.remove('MATH-121') smith.remove('HIST-340') # print smith print '\ndeleted smith' for item in smith: print item # pring length print '\nlenght of smith' print len(smith) # check whether not in print '\ncheck whether not in' print 'abc' in smith # check whether in print '\ncheck whether in' print 'ECON-101' in smith # delete all smith.remove('CSCI-112') smith.remove('ECON-101') for item in smith: print item ''' primary smith CSCI-112 ECON-101 HIST-340 MATH-121 deleted smith CSCI-112 ECON-101 lenght of smith 2 check whether not in False check whether in True ''' if __name__ == "__main__": test_sortedcircularlinkedlist()
f20728989d03b52b2dcdaf33c846db166b9e7604
Fattore/2-Semestre_Fattore
/16_09_19/Ex5.py
234
3.875
4
#coding: utf-8# ''' Faça um programa que leia um número natural e calcule o seu fatorial ''' n1 = int(input("Digite um número natural: ")) fat = 1 for i in range(2,n1+1): fat = fat * i print("%d! = %d" %(n1, fat))
d6a506ee13bb1ebc854e124ad25aa93e343dc4a4
SummerBigData/SurenRepo
/Coursera.EX4/neuTrainerMNISTfast.py
10,193
3.90625
4
# Written by: Suren Gourapura # Written on: May 25, 2018 # Purpose: To solve exercise 4 on Multi-class Classification and Neural Networks in Coursera # Goal: Use backpropagation to find the best theta values # Import the modules import numpy as np from math import exp, log from scipy.optimize import minimize import scipy.io import time import struct as st import gzip #import matplotlib.pyplot as plt #from scipy.optimize import check_grad # For imgNorm from numpy.polynomial import polynomial as P from scipy.ndimage import rotate from math import pi, atan # This will be fun import argparse #---------GLOBAL VARIABLES----------GLOBAL VARIABLES----------GLOBAL VARIABLES----------GLOBAL VARIABLES parser = argparse.ArgumentParser() parser.add_argument("n", help="Number of Datapoints", type=int) #parser.add_argument("f1", help="Number of Features (pixels) in images", type=int) parser.add_argument("f2", help="Number of Features in hidden layer", type=int) parser.add_argument("lamb", help="Lambda, the overfitting knob", type=float) #parser.add_argument("eps", help="Bounds for theta matrix randomization, [-eps, eps]", type=float) parser.add_argument("tolexp", help="Exponent of tolerance of minimize function, good value 10e-4, so -4", type=int) parser.add_argument("normimg", help="Choose whether or not to straighten the images", type=str) g = parser.parse_args() g.lamb /= 1000.0 saveStr = 'thetaArrs/theta' + str(g.n)+ 'MNIST'+str(g.tolexp)+'Lamb'+str(g.lamb)+'Nor'+g.normimg+'.out' gStep = 0 g.f1 = 784 g.eps = 0.12 print 'You have chosen:', g print 'Will be saved in: ', saveStr print ' ' #----------DEFINITIONS HERE----------DEFINITIONS HERE----------DEFINITIONS HERE----------DEFINITIONS HERE # Save an instance of theta values def saveTheta(theta): np.savetxt(saveStr, theta, delimiter=',') # Read the MNIST dataset def read_idx(filename, n=None): with gzip.open(filename) as f: zero, dtype, dims = st.unpack('>HBB', f.read(4)) shape = tuple(st.unpack('>I', f.read(4))[0] for d in range(dims)) arr = np.fromstring(f.read(), dtype=np.uint8).reshape(shape) if not n is None: arr = arr[:n] return arr # Calculate the Hypothesis (for layer l to l+1) def hypothesis(thetaArr, xArr): oldhypo = np.matmul(thetaArr, np.transpose(xArr) ) oldhypo = np.array(oldhypo, dtype=np.float128) newhypo = 1.0/(1.0+np.exp(-oldhypo)) return np.array(newhypo, dtype=np.float64) # Generate random theta matrices with a range [-eps, eps] def randTheta(x, y): theta = np.random.rand(x,y) # Makes a (x) x (y) random matrix of [0,1] return theta*2*g.eps - g.eps # Make it range [-eps, eps] # Calculate the Hypothesis (layer 3) using just layer 1. xArr.shape -> 5000 x 401 def FullHypo(theta1, theta2, xArr): # Calculate a2 using theta1 and the x data (xArr == a1) a2 = hypothesis(theta1, xArr) # Add a row of 1's on top of the a1 matrix a2Arr = np.vstack(( np.asarray([1 for i in range(g.n)]) , a2)) # Calculate and return the output from a2 and theta2. This is a3 (a3.shape -> 10 x 5000) return hypothesis(theta2, a2Arr.T) # Calculate the regularized Cost J(theta) using ALL thetas. yArr.shape = 5000 x 10 def RegJCost(thetaAll, xArr, yArr): # Seperate and reshape the Theta values theta1, theta2 = UnLin(thetaAll, g.f2, g.f1+1, 10, g.f2+1) hypo = FullHypo(theta1, theta2, xArr) J = (1.0/g.n)*np.sum( -1*np.multiply(yArr, np.log(hypo.T)) - np.multiply(1-yArr, np.log(1 - hypo.T)) ) J = J + (0.5 * g.lamb/g.n)*( np.sum(theta1**2) - np.sum(column(theta1, 0)**2) + np.sum(theta2**2) - np.sum(column(theta2, 0)**2) ) return J # Create the y matrix that is 5000 x 10, with a 1 in the index(number) and 0 elsewhere # Also fixes 10 -> 0. Since this function is rarely called, I use loops def GenYMat(yvals): yvals = np.ravel(yvals) yArr = np.zeros((g.n, 10)) for i in range(len(yvals)): for j in range(10): if yvals[i] == j or (yvals[i] == 10 and j == 0): yArr[i][j] = 1 return yArr def BackProp(thetaAll, xArr, yArr): # To keep track of how many times this code is called global gStep gStep += 1 if gStep % 50 == 0: print 'Global Step: ', gStep if gStep % 200 == 0: print 'Saving Global Step : ', gStep saveTheta(thetaAll) # Seperate and reshape the Theta values theta1, theta2 = UnLin(thetaAll, g.f2, g.f1+1, 10, g.f2+1) # Forward propagating to get a2, a3 a2 = hypothesis(theta1, xArr) # 36 x g.n a2 = np.vstack(( np.asarray([1 for i in range(g.n)]) , a2)) # Reshape to 37 x g.n (Add bias row) a3 = FullHypo(theta1, theta2, xArr) # 10 x g.n # Creating (Capital) Delta matrices Delta2 = np.zeros((10, g.f2+1)) # 10 x 37 Delta1 = np.zeros((g.f2, g.f1+1)) # 36 x 785 # Calculate (Lowercase) deltas for each element in the dataset and add it's contributions to the Deltas delta3 = a3.T - yArr # g.n x 10 gPrime = np.multiply(a2.T, 1 - a2.T) # g.n x 37 delta2 = np.multiply(np.matmul(delta3, theta2), gPrime) # g.n x 37 Delta2 = Delta2 + np.matmul(a2, delta3).T # Note: we use the bias row to calculate Delta2 but not Delta1, so it is removed below Delta1 = Delta1 + np.delete( np.matmul(xArr.T, delta2).T , 0, 0) # Since the calculation calls for [if j=0, D = Delta/m], we make Theta matrices so [Theta(j=0)=1 for all i]. Theta2 = np.delete(theta2, 0, 1) # Remove the bias layers Theta1 = np.delete(theta1, 0, 1) # Now, these are 10 x 25, 25 x 400 respectively Theta2 = np.hstack(( np.asarray([[0] for i in range(10)]) , Theta2)) # Add the bias layer as 0's Theta1 = np.hstack(( np.asarray([[0] for i in range(g.f2)]) , Theta1)) # Now, these are 10 x 26, 25 x 401 respectively # Now we calculate D normally and the j = 0 case is taken care of D2 = (Delta2 + g.lamb * Theta2) / (g.n+0.0) # 10 x 26 D1 = (Delta1 + g.lamb * Theta1) / (g.n+0.0) # 25 x 401 DAll = Lin(D1, D2) return DAll # Take out one column (column i) from a matrix def column(matrix, i): return np.asarray([row[i] for row in matrix]) # Linearize: Take 2 matrices, unroll them, and stitch them together into a vector def Lin(a, b): return np.concatenate((np.ravel(a), np.ravel(b))) # Unlinearize: Take a vector, break it into two vectors, and roll it back up def UnLin(vec, a1, a2, b1, b2): if a1*a2+b1*b2 != len(vec): return 'Incorrect Dimensions! ', a1*a2+b1*b2, ' does not equal ', len(vec) else: a = vec[0:a1*a2] b = vec[a1*a2:len(vec)] return np.reshape(a, (a1, a2)) , np.reshape(b, (b1, b2)) # Reorder the data randomly def randData(xvals, yvals): # Reshape the y values into a column, so hstack can work yvals = np.column_stack(yvals).T # Combine the x and y values so that the shuffling doesn't seperate them XandY = np.hstack((xvals, yvals)) # Shuffle the matrix. We are shuffling the rows here np.random.shuffle(XandY) # Reseperate the matrices xVals = XandY[0:g.n,0:g.f1] yVals = XandY[0:g.n,g.f1:g.f1+1] # Convert the y values back as integers and as vectors, not matrices yVals = np.ravel(yVals.astype(int)) return xVals, yVals def normImg(datx): print "Normalizing data" # Get the size of the picture matrices s = int(np.sqrt(g.f1)) # Create an array of numbers [1,2,3,4,...] to use for average position computation index = np.zeros((s)) for i in range(s): index[i] = i + 1 # Calculate the rotated matrix for all data points. First, initialize it rotmat = np.zeros((g.n, g.f1)) for i in range(g.n): # Convert it back to a matrix mat = np.reshape(datx[i], (s,s)) hcenter = np.zeros((s)) # We need the horizontal centers for each row for j in range(s): # Handle the zero case seperately, due to divide by zero. The value here doesn't matter, since the weight will kill it if sum(mat[j]) == 0: hcenter[j] = -1 # Calculate and store the center of each column else: hcenter[j] = sum(mat[j]*index)/ (sum(mat[j])+0.0) # We don't want to include the zero cases, so form a weights matrix to record them weights = np.zeros((s)) for j in range(s): if hcenter[j] < 0: weights[j] = 0 else: weights[j] = 1 # print hcenter # Calculate the line of best fit for all of the horizontal centers c = P.polyfit(index,hcenter,1,full=False, w=weights) # Here's some tools to visualize the process # print c[0], c[1], atan(c[1])*180.0/pi # bestfit = c[0] + c[1]*index # plt.plot(hcenter,'green', bestfit, 'red') # plt.show() # Rotate, unravel, and record the matrix rotmat[i] = np.ravel(rotate(mat, -1*atan(c[1])*180.0/pi, reshape=False)).reshape(1, g.f1) return rotmat #----------STARTS HERE----------STARTS HERE----------STARTS HERE----------STARTS HERE # To see how long the code runs for, we start a timestamp totStart = time.time() # PREPARING DATA # Obtain the data values and convert them from arrays to lists datx = read_idx('data/train-images-idx3-ubyte.gz', g.n) daty = read_idx('data/train-labels-idx1-ubyte.gz', g.n) datx = np.ravel(datx).reshape((g.n, g.f1)) # Straighten the images if desired: if g.normimg == 'true': datx = normImg(datx) # Reorder the data randomly #datx, daty = randData(datx, daty) # Form the correct x and y arrays, with a column of 1's in the xArr xArr = np.hstack(( np.asarray([[1] for i in range(g.n)]) , datx)) # g('n') x g('f1')+1 yArr = GenYMat(daty) # g('n') x 10 # Randomize theta1 and theta2. Comment this out to use their theta values (weights) theta1 = randTheta(g.f2, g.f1+1) theta2 = randTheta(10, g.f2+1) # Reshape and splice theta1, theta2 thetaAll = Lin(theta1, theta2) # MINIMIZING THETAS # Check the cost of the initial theta matrices print 'Initial Theta JCost: ', RegJCost(thetaAll, xArr, yArr) # Outputting around 12.332 # Check the gradient function. ~1.43362624525e-05 for randomized thetas #print check_grad(RegJCost, BackProp, thetaAll, xArr, yArr) # Calculate the best theta values for a given j and store them. Usually tol=10e-4 res = minimize(fun=RegJCost, x0= thetaAll, method='CG', tol=10**g.tolexp, jac=BackProp, args=(xArr, yArr)) bestThetas = res.x print 'Final Theta JCost', RegJCost(bestThetas, xArr, yArr) saveTheta(bestThetas) # Stop the timestamp and print out the total time totend = time.time() print'neuTrainerMNIST.py took ', totend - totStart, 'seconds to run'
20aaf3f2d92a6c68635b31c55aaa48368fd05c89
alblaszczyk/python
/codecademy/pmp10.py
212
3.53125
4
def censor(text, word): lst = text.split() new = [] for item in lst: if item != word: new.append(item) else: censored = "*" * len(item) new.append(censored) return " ".join(new)
3753f6c95c24cdef207706259943b633a513a895
mrzhouyu/Automated_Test
/PishOTA/testone.py
724
3.65625
4
# -*- coding: utf-8 -*- # @Time : 2018/12/8 16:39 # @Author : YuChou # @Site : # @File : testone.py # @Software: PyCharm import multiprocessing import time import threading class Demo: def __init__(self, thread_num=5): self.thread_num = thread_num def productor(self, i): print("thread-%d start" % i) def start(self,num): global y y =100 threads = [] for x in range(num): t = threading.Thread(target=self.productor, args=(x,)) threads.append(t) for t in threads: t.start() for t in threads: t.join() print('all thread end') d if __name__ == "__mian__": demo = Demo()
cbfbce823f2ebbce9a622fbed4f2e73e0a01e211
ProjectBWeb/Cosmosium
/js/MPO_data/csv2json.py
537
3.59375
4
import csv import json def csv2json(csvFile, headers=True): # converts csv in fname csv to json @ json fname # if headers==True, read them from file, else assume header is list of header strings. csvfile = open(csvFile, 'r') jsonfile = open(csvFile.split('.')[0]+'.json', 'w') if headers!=True: fieldnames = headers reader = csv.DictReader( csvfile, fieldnames) else: reader = csv.DictReader( csvfile ) for row in reader: json.dump(row, jsonfile) jsonfile.write('\n')
5f583abd4b34305719072e2096ed693d2fe3f385
esrefaltug/kutuphaneuyg
/ktphane uygulama.py
1,739
3.9375
4
import os kitapListe=list() menu=""" [1]Kitap Ekle [2]Kitap Al [3]Tümünü Listele [Q]Çıkış """ def kitapEkle(kitap:tuple,liste:list): liste.append(kitap) print("Ekleme işlemi tamamlandı") print("Ana menüye dönmek için enter'e basın.") input() def kontrol(kitap:tuple,liste:list): if kitap in liste: return True else: return False def kitapCıkar(kitap:tuple,liste:list): if kontrol(kitap,liste): #kitap çıkartılıyor liste.remove(kitap) print("kitap çıkartma işlemi tamamlandı") print("Ana menüye dönmek için enter'e basın.") input() else: print("Arattığınz kitap mevcut değildir.") print("Ana menüye dönmek için enter'e basınız.") input() def Listele(liste:list): for i in liste: print("Kitap Adı: {}-----> Yazar:{}".format(i[0],i[1])) print("Ana menüye dönmek için enter'e basın.") input() while True: os.system("cls")#terminal ekranını temizler. print(menu) secim=input("işleminizi seçiniz.") if secim=="1": kitap_isim=input("Kitabın adı: ") kitap_yazar=input("yazarın adı: ") kitap=(kitap_isim,kitap_yazar) kitapEkle(kitap,kitapListe) elif secim=="2": kitap_isim=input("Kitabın adı: ") kitap_yazar=input("Yazarın adı: ") kitap(kitap_isim,kitap_yazar) kitapCıkar(kitap,kitapListe) elif secim=="3": pass elif secim=="Q" or secim=="q": quit() else: print("Hatalı giriş yaptınız...")
9c1d558865fc26efd9bef5401d1e5e476bb670a6
AlexMarquez-coder/Beroepsopdracht-week-1-10
/Tekstbased applicatie in Python.py
2,906
3.59375
4
import time # hier worden de functions def verhaalstukje1(): print("Hallo mijn naam Naya ik ben 11 jaar en woon in Syrië") print ("A. Naar buiten gaan") print ("B. Binnen blijven") antwoord= input("Maak een keuze, A of B? ") if antwoord=="A": verhaalstukje2() # naar buiten elif antwoord=="B": verhaalstukje3() # binnen blijven else: print("Je kunt alleen antwoorden met A of B.") verhaalstukje1() def verhaalstukje2(): print("") print("Naar buiten gaan") print ("A. Kijken waar de schoten van daan komen") print ("B. Vluchten") antwoord= input("Maak een keuze, A of B? ") if antwoord=="A": verhaalstukje4() # buiten is een oorlog gaande elif antwoord=="B": verhaalstukje5() # binnen blijven else: print("Je kunt alleen antwoorden met A of B.") def verhaalstukje4(): print("") print("Je bent gespot") print("") time.sleep(1) Verhaal4 = input("Game over") def verhaalstukje5(): print("") print ("Vluchten") print ("A. Middag") print ("B. Avond") antwoord= input("Maak een keuze, A of B? ") if antwoord=="A": verhaalstukje8() # naar buiten elif antwoord=="B": verhaalstukje11() # binnen blijven else: print("Je kunt alleen antwoorden met A of B.") def verhaalstukje8(): print("") print("Je bent gespot") print("") time.sleep(1) Verhaal8 = input("Game over") def verhaalstukje3(): print("") print("Binnenen blijeven") print("") print("Bellen voor hulp") time.sleep(1) verhaalstukje16() def verhaalstukje11(): print("") print ("Avond, hoe ga je?") print ("A. Auto") print ("B. Lopen") antwoord= input("Maak een keuze, A of B? ") if antwoord=="A": verhaalstukje13() # naar buiten elif antwoord=="B": verhaalstukje15() # binnen blijven else: print("Je kunt alleen antwoorden met A of B.") def verhaalstukje13(): print("") print("Je gaat autorijden") print("Je bent gespot ") print("") time.sleep(1) Verhaal8 = input("Game over") def verhaalstukje15(): print("") print("Lopen ") print("") print("Je bent op de grens van de Turkije") time.sleep(1) print("") print("Je zit in het vleigtuig naar Amsterdam") time.sleep(1) print("") Verhaal4 = input("Je bent in veilig Nederland") time.sleep(1) def verhaalstukje16(): print("") print("Je hebt geen electriciteit wil je poberen te vluchten of het optegeven") print ("A. vluchten") print ("B. opgeven") verhaal10 = input("Maak een keuze, A of B? ") if verhaal10 == "A": print("") verhaalstukje5() elif verhaal10 == "B": print("Opgeven en niks doen") # hier start de main verhaalstukje1()
58e4ad602784651764a408058f0acb6cf90e501c
sandrahdezledesma/TIC2-SandraHernandez
/Concatenador.py
290
3.640625
4
def Concatenador(): nombre= raw_input ("Dime tu nombre") apellido1= raw_input ("Dime tu primer apellido") apellido2= raw_input ("Dime tu segundo apellido") NombreCompleto= nombre+" "+apellido1+" "+apellido2 print "Te llamas" + NombreCompleto Concatenador()
139c17056de0c7e08953b97658e1a603bc10ee6c
Pandalism/Advent_of_code
/day2/solution_day2.py
2,716
4.09375
4
# Advent of Code - Day 2 # # Part 1: find number of passwords within text file that are valid # format is: # 1-3 a: abcde # 1-3 b: cdefg # 2-9 c: ccccccccc # Where the password is after the colon and the password requirements are before. # The letter before the colon is required to be in the password a set amount of times, defined by the first # digit as a minimum and the second digit as a maximum. # On the first example, a must be present in the password (abcde) a minimum of 1 times and maximum of 3, # in this case it is valid. # Load data as simple array print('#############################################') array = [] text_input = open("input.txt", "r") for i in text_input: array.append(i) text_input.close() print('Loaded array') def check_req(req, letter, pswrd): count = 0 for i in pswrd: if i == letter: count = count + 1 return ((int(req[0]) <= count) & (count <= int(req[1]))) def find_correct_pass(in_array): count = 0 for line in in_array: req = line.split()[0].split('-') letter = line.split()[1][0] pswrd = line.split()[2] # print(f'Line: {line.strip()}, req: {req}, letter = {letter}, pswrd: {pswrd}') if check_req(req, letter, pswrd): # print(f'line: {line}') count = count + 1 return (count) print(f'Count of valid passwords (part 1 requirements): {find_correct_pass(array)}') # Part 2: The password requirements are now # format is: # 1-3 a: abcde # 1-3 b: cdefg # 2-9 c: ccccccccc # Where the password is after the colon and the password requirements are before. # The letter before the colon is required to be in the password in one of the two set positions, but not both, # as defined by the first digit and the second digit, using index of 1. # On the first example, a must be present in the password (abcde) in either the 1st or 3rd character, # in this case it is valid. # tweak check_req def check_req_part2(req, letter, pswrd): return (pswrd[int(req[0])-1] == letter) ^ (pswrd[int(req[1])-1] == letter) # tweak find_correct_pass def find_correct_pass_part2(in_array): count = 0 for line in in_array: req = line.split()[0].split('-') letter = line.split()[1][0] pswrd = line.split()[2] # print(f'Line: {line.strip()}, req: {req}, letter = {letter}, pswrd_at_req: {pswrd[int(req[0])-1]}, pswrd_at_req2: {pswrd[int(req[1])-1]}') if check_req_part2(req, letter, pswrd): # print(f'line: {line}') count = count + 1 return (count) print(f'Count of valid passwords (part 2 requirements): {find_correct_pass_part2(array)}')
f401b3272d8cdf6c0e70cc8b34fb2170a6423354
tsjamm/LPyTHW
/ex04.py
622
3.71875
4
bikes = 50 space_in_a_bike = 3.0 drivers = 30 passengers = 50 bikes_not_driven = bikes - drivers bikes_driven = drivers transport_capacity = bikes_driven * space_in_a_bike average_passengers_per_bike = passengers / bikes_driven print "There are", bikes, "bikes available." print "There are only", drivers, "drivers available." print "There will be", bikes_not_driven, "empty bikes today." print "We can transport", transport_capacity, "people today." print "We have", passengers, "to transport today." print "We need to put about", average_passengers_per_bike, print "or", average_passengers_per_bike+1, "on each bike."
6def46475623fbd84687fa150530df67d48581f4
haidfs/LeetCode
/Hot100/最长连续序列128.py
1,774
3.515625
4
# 给定一个未排序的整数数组,找出最长连续序列的长度。 # # 要求算法的时间复杂度为 O(n)。 # # 示例: # # 输入: [100, 4, 200, 1, 3, 2] # 输出: 4 # 解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4 from collections import defaultdict class Solution(object): def longestConsecutive(self, nums): if not nums: return 0 nums = list(sorted(set(nums))) length = len(nums) max_sub = 1 temp_sub = 1 for i in range(length - 1): if nums[i + 1] == nums[i] + 1: temp_sub += 1 max_sub = max(max_sub, temp_sub) else: temp_sub = 1 return max_sub # 其实在要求时间复杂度的前提下,直接定义好集合就可以了,确实没有必要对数组进行排序了 def longestConsecutive2(self, nums): nums = set(nums) res = 0 for num in nums: if num - 1 not in nums: tmp = 1 while num + 1 in nums: num += 1 tmp += 1 res = max(res, tmp) return res # 法三,用字典或者hash记录目前与该值可以组成的最长连续序列 def longestConsecutive3(self, nums): # 记录首尾值的最长长度 lookup = defaultdict(lambda: 0) res = 0 for num in nums: left, right = lookup[num - 1], lookup[num + 1] # 记录长度 lookup[num] = lookup[num - left] = lookup[num + right] = left + right + 1 res = max(res, left + right + 1) return res if __name__ == '__main__': nums = [1,2,0,1] s = Solution() print(s.longestConsecutive3(nums))
7c40a657bc5411f26a150cafc16063e8d0a38f36
IvanWoo/coding-interview-questions
/puzzles/couples_holding_hands.py
1,813
3.75
4
# https://leetcode.com/problems/couples-holding-hands/ """ N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1). The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th seat. Example 1: Input: row = [0, 2, 1, 3] Output: 1 Explanation: We only need to swap the second (row[1]) and third (row[2]) person. Example 2: Input: row = [3, 2, 0, 1] Output: 0 Explanation: All couples are already seated side by side. Note: len(row) is even and in the range of [4, 60]. row is guaranteed to be a permutation of 0...len(row)-1. """ from typing import List def min_swaps_couples(row: List[int]) -> int: class UF: def __init__(self, n): self.count = n self.parent = list(range(n)) def find(self, x): while self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x def union(self, u, v): root_u, root_v = self.find(u), self.find(v) if root_u == root_v: return self.parent[root_u] = root_v self.count -= 1 n = len(row) // 2 uf = UF(n) for i in range(n): a = row[2 * i] b = row[2 * i + 1] uf.union(a // 2, b // 2) return n - uf.count if __name__ == "__main__": min_swaps_couples([5, 4, 2, 6, 3, 1, 0, 7])
07c7aedebff35f9dfe43c1321862209a7cbe80c6
Niptlox/Phis
/Billiard.py
10,619
3.578125
4
import pygame SX, SY = 1000, 1000 FPS = 30 def circle(screen, x, y, r, color=(255, 0, 0)): cof = 10 x = x * cof + SX // 2 y = y * cof + SY // 2 r *= cof pygame.draw.circle(screen, color, (int(x), int(y)), int(r), 1) pygame.draw.circle(screen, (255, 255, 0), (int(x), int(y)), 1) from math import sqrt from typing import Type class Vector2: def __init__(self, x, y): self.x, self.y = x, y @property def xy(self): return self.x, self.y @xy.setter def xy(self, value): self.x, self.y = value @classmethod def Zero(cls): return cls(0, 0) def len_2(self): return self.x ** 2 + self.y ** 2 def len(self): return sqrt(self.len_2()) def Left(self): return Vector2(self.y, self.x) def Right(self): return Vector2(self.y, self.x) def __add__(self, other): return Vector2(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector2(self.x - other.x, self.y - other.y) @staticmethod def dot(self, vec1, vec2): return vec1.x * vec2.x + vec1.y * vec2.y def __str__(self): return f"<{self.__class__.__name__}>{self.xy}" def copy(self): return self.__class__(self.x, self.y) class Collider: def __init__(self, gameObject): self.gameObject = gameObject @property def position(self): return self.gameObject.position @position.setter def position(self, value): self.gameObject.position = value # check colliding for list GameObjects def collisions(self, objs): return [] class CircleCollider(Collider): def __init__(self, gameObject, radius=1): super().__init__(gameObject) self.radius = radius # check colliding for list GameObjects def collisions(self, objs): # my position mx, my = self.position.xy # столкновения Collider collisions = [] for obj in objs: coll = obj.collider if coll is self: continue if type(coll) is CircleCollider: px, py = coll.position.xy # проверяем соприклсновение кругов summ_r_2 = (self.radius + coll.radius) ** 2 dist_2 = abs(px - mx) ** 2 + abs(py - my) ** 2 if dist_2 <= summ_r_2: collisions.append(coll) return collisions class Physbody: def __init__(self, gameObject, speed=Vector2.Zero()): self.gameObject = gameObject self.speed = speed # в текущий такт происходила ли проверка физики объекта self.is_update_collisions = False @property def position(self): return self.gameObject.position @position.setter def position(self, value): self.gameObject.position = value @property def collider(self): return self.gameObject.collider # обновление координаты от скорости def update(self): self.is_update_collisions = False mx, my = self.position.xy self.position.xy = mx + self.speed.x, my + self.speed.y return self.position.xy # вычисление столкновений def collisions(self, collisions): my_pos = self.position sx, sy = self.speed.xy if type(self.collider) is CircleCollider: for coll in collisions: if type(coll) is CircleCollider: coll_physbody = coll.gameObject.physbody coll_pos = coll.position # вектор между кругами H = (coll_pos - my_pos) if H.len_2() == 0: continue if coll_physbody: sx2, sy2 = coll_physbody.speed.xy else: sx2, sy2 = 0, 0 hx, hy = H.xy a = sx*hx + sy*hy - sx2*hx - sy2*hy a /= H.len_2() my_speed = Vector2(sx - a * hx, sy - a * hy) if coll_physbody: other_speed = Vector2(sx2 + a * hx, sy2 + a * hy) coll_physbody.speed = other_speed coll_physbody.is_update_collisions = True sx, sy = my_speed.xy self.speed.xy = sx, sy class GameObject: def __init__(self, position: Vector2, Collider=None, Physbody=None, speed=Vector2.Zero(), name="GameObject"): self.position = position self.collider = Collider(self) self.physbody = Physbody(self, speed=speed) self.name = name @property def xy(self): return self.position.xy @xy.setter def xy(self, value): self.position.xy = value def __str__(self): return f"<{self.name}>{self.position}" class Circle(GameObject): def __init__(self, position: Vector2, Collider=None, Physbody=None, radius=1, speed=Vector2.Zero(), name="GameObject"): super().__init__(position, Collider, Physbody, speed, name) self.collider.radius = radius class Player(GameObject): def __init__(self, position: Vector2, speed=Vector2.Zero(), name="Player"): super().__init__(position, Collider=CircleCollider, Physbody=Physbody, speed=speed, name=name) self.collider.radius = 1 self.max_speed = 1 # ускорение self.acceleration = 0.2 def handle_event(self, event): speed = self.physbody.speed.copy() if event.type == pygame.KEYDOWN: if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: speed.x = min(-self.max_speed, speed.x - self.acceleration) if event.key == pygame.K_RIGHT: speed.x = max(self.max_speed, speed.x + self.acceleration) if event.key == pygame.K_UP: speed.y = min(-self.max_speed, speed.y - self.acceleration) if event.key == pygame.K_DOWN: speed.y = max(self.max_speed, speed.y + self.acceleration) mod = speed.len() if mod > 0: speed.x = speed.x / mod * abs(speed.x) speed.y = speed.y / mod * abs(speed.y) class Space: def __init__(self, size, objs: dict={}): self.width, self.height = size self.objs = objs if objs: self.max_obj_id = max(objs.keys()) else: self.max_obj_id = 0 def append(self, obj): new_id = self.max_obj_id + 1 self.objs[new_id] = obj self.max_obj_id = new_id return new_id def pop(self, obj_id): return self.objs.pop(obj_id) def update(self): lst_objs = self.objs.values() for obj in lst_objs: if obj.physbody: obj.physbody.update() for obj_id, obj in self.objs.items(): if obj.physbody: if not obj.physbody.is_update_collisions: collisions = obj.collider.collisions(lst_objs) obj.physbody.collisions(collisions) print(obj_id, obj.position, obj.physbody.speed) # input("Letter...") def main(self): while True: self.update() class Camera: def __init__(self, space, screen, player): self.space= space self.screen = screen self.player = player def main(self): clock = pygame.time.Clock() running = True fps = FPS while running: self.screen.fill("black") for event in pygame.event.get(): if event.type == pygame.QUIT: running = False self.player.handle_event(event) self.space.update() for obj in self.space.objs.values(): if obj.name == "Player": circle(self.screen, obj.position.x, obj.position.y, obj.collider.radius, color=(0, 0, 255)) else: circle(self.screen, obj.position.x, obj.position.y, obj.collider.radius) clock.tick(fps) pygame.display.flip() pygame.quit() if __name__ == "__main__": objs = { 1: GameObject(Vector2(-5, 0), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(1, 0)), 2: GameObject(Vector2(6, 5), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(-1, 0)), 3: GameObject(Vector2(4, 3), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(-1, -1)), 4: GameObject(Vector2(4, 4), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(-1, -1)), 5: GameObject(Vector2(5, 5), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(-1, -1)), 6: GameObject(Vector2(4, 6), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(-1, -1)), 7: GameObject(Vector2(4, 6), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(-1, -1)), 8: GameObject(Vector2(4, 6), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(-1, -1)), 9: GameObject(Vector2(4, 6), Collider=CircleCollider, Physbody=Physbody, speed=Vector2(-1, -1)), } space = Space((100, 100), objs) player = Player(Vector2(-5, 15)) space.append(player) # for x in range(-20, 20, 2): # for y in range(-4, 4, 2): # obj = GameObject(Vector2(x, y), Collider=CircleCollider, # Physbody=Physbody, speed=Vector2(y / 5, x / 25)) # space.append(obj) pygame.init() pygame.display.set_caption('Board') size = SX, SY screen = pygame.display.set_mode(size) camera = Camera(space, screen, player) camera.main()
33ce45941c0a1c347d258f5ef0e7a66e70268ae7
caihj/jbyte
/src/main/resources/class.py
309
3.546875
4
#coding:utf-8 class foo(): def __init__(self,a): self.a=a self.b=2 def show(self): print self.a class Too(foo): def __init__(self,a): foo.__init__(self,a) f=foo(2) d=foo(3) f.show() d.show() q=Too(6) q.show() if q < f: print "sss"
3a2714e1fe3f8a7845ddb76e1ef5f93ff5f29e48
Hasthon/python-beginner-programming-exercises
/exercises/22-Bottles-Of-Milk/app.py
1,374
3.9375
4
def number_of_bottles(): for i in range(99,-1,-1): if i == 1: print('1 bottle of milk on the wall, 1 bottle of milk.') print('Take one down and pass it around, no more bottles of milk on the wall.') elif i == 0: print('No more bottles of milk on the wall, no more bottles of milk.') print('Go to the store and buy some more, 99 bottles of milk on the wall.') else: print(str(i)+ ' bottles of milk on the wall, '+str(i)+' bottles of milk.') print('Take one down and pass it around, '+str(i-1)+' bottles of milk on the wall.') number_of_bottles() """ def number_of_bottles(): bottles = 99 while bottles > 1: print(str(bottles)+ ' bottles of milk on the wall, '+ str(bottles)+' bottles of milk.') bottles -=1 print('Take one down and pass it around, '+ str(bottles)+' bottles of milk on the wall') if bottles == 1: print(str(bottles)+' bottle of milk on the wall, '+str(bottles)+' bottle of milk.') print('Take one down and pass it around, no more bottles of milk on the wall.') elif bottles == 0: print('no more bottles of milk on the wall, no more bottles of milk.') print('Go to the store and buy some more, 99 bottles of milk on the wall.') number_of_bottles() """
e3237e0a3466ea238d3698db75d81f9304349f9d
JingzOoi/pygame_sudoku_solver
/main.py
7,564
3.765625
4
import pygame import sudoku class Grid(sudoku.Grid): """A space on a Sudoku board. Holds a value unique to row, column, and box.""" SIZE = 50 COLOR_BACKGROUND = (255, 255, 255) COLOR_TEXT = (0, 0, 0) def __init__(self, pos: tuple, value: int = None): super().__init__(pos, value) self.SURFACE = pygame.Surface((self.SIZE, self.SIZE)) self.coordinates = ((self.col-1)*self.SIZE, (self.row-1)*self.SIZE) def draw(self, surface: pygame.Surface): """Blits value onto self, then is blitted to surface (Board)""" font = pygame.font.SysFont('Consolas', Grid.SIZE // 2) text = font.render(f"{self.value if self.value else ' '}", True, self.COLOR_TEXT) text_rect = text.get_rect() text_rect.centerx = self.SURFACE.get_rect().centerx text_rect.centery = self.SURFACE.get_rect().centery self.SURFACE.fill(self.COLOR_BACKGROUND) self.SURFACE.blit(text, text_rect) surface.blit(self.SURFACE, self.coordinates) class Board(sudoku.Board): """A collection of arranged Grids.""" WIDTH, HEIGHT = Grid.SIZE * 9, Grid.SIZE * 9 SIZE = (WIDTH, HEIGHT) COORDINATES = (Grid.SIZE, Grid.SIZE) TOP = Grid.SIZE LEFT = Grid.SIZE BOTTOM = TOP + HEIGHT RIGHT = LEFT + WIDTH WIDTH_LINE = 2 COLOR_LINE = (0, 0, 0) def __init__(self): super().__init__([Grid((i, j)) for j in range(1, 10) for i in range(1, 10)]) self.SURFACE = pygame.Surface((self.WIDTH + self.WIDTH_LINE, self.HEIGHT + self.WIDTH_LINE)) self.vertical_lines = [((i * Grid.SIZE, 0), (i * Grid.SIZE, self.HEIGHT)) for i in range(10)] self.horizontal_lines = [((0, i * Grid.SIZE), (self.WIDTH, i * Grid.SIZE)) for i in range(10)] def collide(self, pos: tuple) -> bool: """Checks if coordinates (from window) given is within the board.""" x, y = pos return self.LEFT <= x <= self.RIGHT and self.TOP <= y <= self.BOTTOM def collide_grid(self, pos: tuple) -> Grid: """Returns the grid placed in the coordinates given.""" x, y = pos board_pos = (x // Grid.SIZE, y // Grid.SIZE) for grid in self.grids: if grid.position == board_pos: return grid else: raise GridNotFoundError("No grid found in specified mouse position!") def draw(self, surface: pygame.Surface): """Blits grids onto self, then is blitted to surface (Window)""" for grid in self.grids: grid.draw(self.SURFACE) # basic lines between grids for vertical_line, horizontal_line in zip(self.vertical_lines, self.horizontal_lines): pygame.draw.line(self.SURFACE, self.COLOR_LINE, vertical_line[0], vertical_line[1], self.WIDTH_LINE) pygame.draw.line(self.SURFACE, self.COLOR_LINE, horizontal_line[0], horizontal_line[1], self.WIDTH_LINE) # thicker lines between boxes for vertical_line in self.vertical_lines[::3]: pygame.draw.line(self.SURFACE, self.COLOR_LINE, vertical_line[0], vertical_line[1], 2 * self.WIDTH_LINE) for horizontal_line in self.horizontal_lines[::3]: pygame.draw.line(self.SURFACE, self.COLOR_LINE, horizontal_line[0], horizontal_line[1], 2 * self.WIDTH_LINE) surface.blit(self.SURFACE, self.COORDINATES) class Game(sudoku.Game): """An instance of a Sudoku game. Holds the logic to solving the game.""" def __init__(self): super().__init__(Board()) self.current_value = 1 @property def candidates(self): candidate_dict = {} for i in range(1, 10): candidate_dict[i] = Grid((0, 0), i) candidate_dict[i].coordinates = (candidate_dict[i].value * Grid.SIZE, self.board.BOTTOM + Grid.SIZE // 2) return candidate_dict def change_current_value(self, num: int): """Changes the current value held by the mouse button.""" self.current_value = num if 0 < num < 10 else 1 def clear_grid(self): """Clears all grids on the board.""" for grid in self.board: grid.value = None def draw(self, surface: pygame.Surface): """Draws game elements and board.""" self.board.draw(surface) for g_index in list(self.candidates): g = self.candidates[g_index] g.draw(surface) c_value_grid = self.candidates[self.current_value] rect = pygame.Rect(c_value_grid.coordinates[0], c_value_grid.coordinates[1], Grid.SIZE, Grid.SIZE) pygame.draw.rect(surface, Board.COLOR_LINE, rect, 3) class Window: """An instance of a running application. Handles events.""" FPS = 30 FPSCLOCK = pygame.time.Clock() WIDTH, HEIGHT = Board.WIDTH + 2 * Grid.SIZE, Board.HEIGHT + 3 * Grid.SIZE def __init__(self): pygame.init() self.SIZE = (self.WIDTH, self.HEIGHT) self.RENDERER = Renderer(self.SIZE) self.game = Game() def handle_events(self) -> bool: keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == pygame.QUIT or keys[pygame.K_ESCAPE]: return False if event.type == pygame.MOUSEBUTTONUP: mouse_pos = pygame.mouse.get_pos() # checks if mouse clicked in board area if self.game.board.collide(mouse_pos): grid = self.game.board.collide_grid(mouse_pos) if event.button == 1: grid.value = self.game.current_value elif event.button == 3: grid.value = None if keys[pygame.K_SPACE]: self.game.clear_grid() if keys[pygame.K_RETURN]: self.game.solve() if keys[pygame.K_0]: self.game.current_value = None elif keys[pygame.K_1]: self.game.current_value = 1 elif keys[pygame.K_2]: self.game.current_value = 2 elif keys[pygame.K_3]: self.game.current_value = 3 elif keys[pygame.K_4]: self.game.current_value = 4 elif keys[pygame.K_5]: self.game.current_value = 5 elif keys[pygame.K_6]: self.game.current_value = 6 elif keys[pygame.K_7]: self.game.current_value = 7 elif keys[pygame.K_8]: self.game.current_value = 8 elif keys[pygame.K_9]: self.game.current_value = 9 return True def update(self) -> bool: with self.RENDERER: self.RENDERER.draw_game(self.game) return self.handle_events() class Renderer: """An instance of a renderer. Draws everything on the Window.""" COLOR_BACKGROUND = (180, 180, 180) def __init__(self, size: tuple): self.SIZE = size self.WIDTH, self.HEIGHT = self.SIZE self.DISPLAY = pygame.display.set_mode(self.SIZE) pygame.display.set_caption("Sudoku w/Pygame by JZ") def __enter__(self): self.DISPLAY.fill(self.COLOR_BACKGROUND) def __exit__(self, exc_type, exc_value, exc_trace): pygame.display.update() def draw_game(self, game): game.draw(self.DISPLAY) if __name__ == "__main__": win = Window() while win.update(): win.FPSCLOCK.tick(win.FPS) class GridNotFoundError(Exception): """Called when grid is not found in the board."""
09b3f5135c37cfdbbf3aa08bf393712c1b8469d0
sunho-park/study1
/numpy/indexing.py
367
3.578125
4
import numpy as np array1d = np.arange(start=1, stop=10) print(array1d) print(array1d>5) array3d=array1d[array1d>5] print(array3d) boolean_indexes = np.array([False, False, False, False, False, True, True, True, True]) # True 에 해당하는 인덱스의 값을 저장 array3 = array1d[boolean_indexes] print('불린 인덱스로 필터링 결과 : ', array3)
f6be3854a04c09b4199d2776a2a7d9272b899136
jamesthekee/password-manager
/Client/lib/clientconfig.py
673
3.796875
4
import configparser """ This module is just for extracting the variables from the config file, converting them to their correct data type and returning them to the main program. """ config = configparser.ConfigParser() config.read("clientconfig.ini") def is_int_string(s): try: int(s) return True except ValueError: return False def handle_config_value(value): if value in ("true", "false"): return value == "true" elif is_int_string(value): return int(value) else: return value connection = dict((x[0], handle_config_value(x[1])) for x in config.items("CONNECTION"))
e4964b57defd22d44d4866fe7e1d9281d11c4b92
annusabu/Task
/P1.py
271
3.625
4
def star(words): size = max(len(word) for word in words) print('*' * (size + 4)) for word in words: print('* {:<{}} *'.format(word, size)) print('*' * (size + 4)) f = open(r"E:\file1.txt") for line in f: s=line.split() star(s)
b50cdba4fec9c0faf4813c0651e22ea4ec0f1e1e
ArnoutAllaert/Informatica5
/08-Functies/Ave Caesar.py
944
3.640625
4
def is_letter(n): if n in 'abcdefghijklmnopqrstuvwxyz' or n in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': waarheid = True else: waarheid = False return waarheid def roteer_letter(n, k): if is_letter(n) == True: if n in 'abcdefghijklmnopqrstuvwxyz': if ord(n) + k > 122: return chr((ord(n) + k) - 26) else: return chr(ord(n) + k) elif n in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': if ord(n) + k > 90: return chr((ord(n) + k) - 26) else: return chr(ord(n)+k) else: return n def versleutel(z, k): zin = '' for letter in z: zin += roteer_letter(letter, k) return zin print(versleutel('H', 20)) print(versleutel('Het leven bestaat voor 10% uit dingen die gebeuren en voor 90% uit hoe jij daarop reageert.', 20)) print(versleutel('Vertrouw op je kracht en vier het leven!',8))
1e3f2491b3d011451f1c8b031c9e1943ab63e849
wllmwng1/CMPUT366_Assignment3
/A_3_Code/mc_agent.py
2,946
3.625
4
#!/usr/bin/env python """ Author: Adam White, Matthew Schlegel, Mohammad M. Ajallooeian, Sina Ghiassian Purpose: Skeleton code for Monte Carlo Exploring Starts Control Agent for use on A3 of Reinforcement learning course University of Alberta Fall 2017 """ from utils import rand_in_range, rand_un import numpy as np import pickle num_total_states = 99 last_action = 1 last_state = 1 episode = [] def agent_init(): """ Hint: Initialize the variables that need to be reset before each run begins Returns: nothing """ #initialize the policy array in a smart way global pi global Q global R pi = [] Q = [[0.0 for x in range(num_total_states/2+1)]for y in range(num_total_states)] R = dict() for s in range(1,num_total_states+1): pi.append(np.random.randint(1,min(s+1,num_total_states-s+2))) #Q.append(np.zeros(min(s+1,num_total_states-s+2))) for i in range(min(s+1,num_total_states-s+2)): R[(s,i)] = [0,0] def agent_start(state): """ Hint: Initialize the variavbles that you want to reset before starting a new episode Arguments: state: numpy array Returns: action: integer """ # pick the first action, don't forget about exploring starts action = np.random.randint(1,min(state+1,num_total_states-state+2)) last_action = action last_state = state return action def agent_step(reward, state): # returns NumPy array, reward: floating point, this_observation: NumPy array """ Arguments: reward: floting point, state: integer Returns: action: integer """ # select an action, based on Q episode.append((last_state,last_action,reward)) action = pi[state[0]-1] return action def agent_end(reward): """ Arguments: reward: floating point Returns: Nothing """ # do learning and update pi episode.append((last_state,last_action,reward)) end = reward for e in range(len(episode)): (state,action,reward) = episode[e] R[(state,action)] = [int(R[(state,action)][0])+end,int(R[(state,action)][1])+1] Q[state][action-1] = sum(R[(state,action)])/len(R[(state,action)]) for i in range(len(pi)): pi[i] = Q[i].index(max(Q[i])) + 1 return def agent_cleanup(): """ This function is not used """ # clean up return def agent_message(in_message): # returns string, in_message: string global Q """ Arguments: in_message: string returns: The value function as a string. This function is complete. You do not need to add code here. """ # should not need to modify this function. Modify at your own risk if (in_message == 'ValueFunction'): return pickle.dumps(np.max(Q, axis=1), protocol=0) else: return "I don't know what to return!!" # agent_init() # episode = [(1,1,0),(2,2,0),(4,4,0),(8,8,0),(16,8,0),(8,8,0),(16,16,0),(32,32,0)] # last_state = 64 # last_action = 36 # agent_end(1.0)
7d2f253eee14961a59163144a71465cba144c126
Gemisheresy/DungeonCrawl
/grid2.py
2,078
3.703125
4
import curses from curses import wrapper from grid import * stdscr = curses.initscr() stdscr.keypad(True) def start(): # starts game by creating to loops done = False while True: try: wide = int(input("How wide do you want the room? ")) break except ValueError: print('Thate wasnt a number try again') while True: try: height = int(input("How high do you want the room? ")) break except ValueError: print('That wasnt a number try again') if wide >= 25: wide = 25 if height >= 25: height = 25 size_grid(wide,height) row[hero['point'][0]][hero['point'][1]] = '1 ' monster['point'][0] = random_spot(wide-1) monster['point'][1] = random_spot(height-1) if monster['point'] == hero['point']: monster['point'][0] = random_spot(wide-1) monster['point'][1] = random_spot(height-1) sword['point'][0] = random_spot(wide-1) sword['point'][1] = random_spot(height-1) if sword['point'] == monster['point'] or hero['point']: sword['point'][0] = random_spot(wide-1) sword['point'][1] = random_spot(height-1) row[monster['point'][0]][monster['point'][1]] = 'X ' row[sword['point'][0]][sword['point'][0]] = '+ ' draw_grid() while done == False: stdscr.echo() stdscr.cbreak() print("where do you want to go") way = curses.getkey() if way == 'e': done = True cls() elif way == 'x': attack() else: move(way) if monster['health'] <= 0: row[monster['point'][0]][monster['point'][1]] = '0 ' if hero['point'] == monster['point']: row[monster['point'][0]][monster['point'][1]] = '1 ' change_phrase('defeated') draw_grid() print(phrase['last']) print(hero['attack']) print(monster['health']) def main(stdscr): stdscr.clear() start() if __name__ == '__main__': wrapper(main)
e48f523d3b1bed4d82dc11760a7803782b3b7ace
nikkisora/cses_problemset
/10 Advanced Techniques/10 Necessary Cities.py
993
3.828125
4
''' CSES - Necessary Cities Time limit: 1.00 s Memory limit: 512 MB There are n cities and m roads between them. There is a route between any two cities. A city is called necessary if there is no route between some other two cities after removing that city (and adjacent roads). Your task is to find all necessary cities. Input The first input line has two integers n and m: the number of cities and roads. The cities are numbered 1,2,...,n. After this, there are m lines that describe the roads. Each line has two integers a and b: there is a road between cities a and b. There is at most one road between two cities, and every road connects two distinct cities. Output First print an integer k: the number of necessary cities. After that, print a list of k cities. You may print the cities in any order. Constraints 2 <= n <= 10^5 1 <= m <= 2 * 10^5 1 <= a,b <= n Example Input: 5 5 1 2 1 4 2 4 3 5 4 5 Output: 2 4 5 '''
2ec409f18f8144ef3b575933497fe389451a118b
iamthedkr/AIVN-Course-2019
/Week1/2. Bài tập lý thuyết/bai1.py
317
4.09375
4
#Chuyen goc tu do sang radian import math degree = float(input("Input Degree: ")) #tinh goc theo radian radian = degree * math.pi / 180 print("Radian: ", radian) #Chuyen goc tu radian -> do radian_change = float(input("Input Radian: ")) degree_change = radian * 180 / math.pi print("Degree: ", degree_change)
9e59992966b164875b6da721b0f1554a4f34d13d
sejun09/sejun
/E-oN 4주차 과제.py
646
3.890625
4
a = list(map(int, input("오름차순으로 정렬할 숫자를 입력하세요: ").split())) def bubble_sort(bubble): for i in range(1, len(bubble), 1): # list에 입력된 숫자의 갯수만큼 반복 for j in range(1, len(bubble), 1 ): # list의 첫번 째 자리부터 list의 마지막 자리까지 1씩 더해가며 정렬 if bubble[j-1] > bubble[j]: bubble[j-1], bubble[j] = bubble[j], bubble[j-1] return bubble # 함수 값 반환 print("정렬 전 숫자",a) print("정렬 후 정렬", bubble_sort(a)) # 정렬 후 값 출력
f7a9aeb77884dc1e0650201dc938afd6b6354134
ParkinWu/leetcode
/python/leetcode/209.py
1,488
3.5625
4
# 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。 # # 示例:  # # 输入: s = 7, nums = [2,3,1,2,4,3] # 输出: 2 # 解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。 # 进阶: # # 如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 from typing import List class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: if not nums: return 0 left = 0 right = 0 ans = float('inf') sum_of_nums = nums[0] while left <= right < len(nums): if sum_of_nums < s: right += 1 if right < len(nums): sum_of_nums += nums[right] else: ans = min(ans, right - left + 1) sum_of_nums -= nums[left] left += 1 return 0 if ans == float('inf') else ans if __name__ == '__main__': s = Solution() assert s.minSubArrayLen(7, [2, 3, 1, 2, 4, 3]) == 2 assert s.minSubArrayLen(4, [1, 4, 4]) == 1 assert s.minSubArrayLen(11, [1, 2, 3, 4, 5]) == 3
4a4ebe06465a7dc45c746e15f0aeb23f4abd55b9
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/difference-of-squares/64253a2e99094e2f9e5e03adb295f1bf.py
275
3.984375
4
def square_of_sum(n): sum = 0 for k in range(0,n+1): sum += k return sum**2 def sum_of_squares(n): sum = 0 for k in range(0,n+1): sum += k**2 return sum def difference(n): return square_of_sum(n) - sum_of_squares(n)
bbd3c7e878116923f0d011ce6b6ccd547b69be82
Neczy/tech_task
/json_file/json_open.py
1,172
3.59375
4
#ещё не до конца, нужен валидатор и счетчик # -*- coding: utf-8 -*- import os import sys import json #статические переменные errors = list() user_input = input('Введите имя файла: ') #счетчик ошибок def ercount(): errors.append() # основная функция, потом в класс def open_json(): try: with open(user_input, "r", encoding='utf-8') as jfile: json1 = json.load(jfile) #print(json1) for key, value in json1.items(): print(key, value) types = value['Типы'] data = value['Данные'] def valid(): yy = [] ii = [] for y in types.values(): yy.append(y) for i in data.values(): ii.append(i) print(yy,ii) #if return yy,ii valid() except: print('Данного файла нет') pass #unit tests def utest(): pass open_json()
cb61b3d57fef83ce2bbb13997552fd1af600e0f8
awscott/teachingpythontokwan
/solutions/.sum_even_odd.py
882
4.3125
4
import sys # given a number return the sum of all the even numbers # the only point is to use your previously created methods in python and use them here def sum_even(number): """ sum up all the the even numbers between 0 and number inclusive return the result when you are finished """ total = 0 for i in range(0,number+1): if even(i): total += i return total def sum_odd(number): """ sum up all the the odd numbers between 0 and number inclusive return the result when you are finished """ total = 0 for i in range (0,number+1): if odd(i): total += i return total def even(x): """ this function should return True if the given number (x) is even otherwise False """ return int(x) % 2 == 0 def odd(x): """should return True if number is odd, else False """ return not int(x) % 2 == 0 if __name__ == '__main__': print(sum_even(sys.argv[1]))
02c81afc6cdc2986c9216571ade30f951b9d0315
madRebellion/Software-Development
/Python/PythonCourse/Day2/Operators_fStrings.py
1,300
4.21875
4
#----------------------------------------------------------------- # String indices and conversions #digit = input("Type in a two digit number: ") #firstDigit = int(digit[0]) #secondDigit = int(digit[1]) #print(firstDigit + secondDigit) #----------------------------------------------------------------- # BMI Calc 1.0 #weight = input("What is your weight in kg?\n") #height = input("What is your height in metres?\n") #bmi = int(weight)/float(height)**2 #print(int(bmi)) #----------------------------------------------------------------- # f-Strings #age = input("How old are you?\n") #years_left = (90 - int(age)) #months_left = years_left * 12 #weeks_left = years_left*52 #days_left = years_left * 365 # #print(f"You have {days_left} days left, {weeks_left} weeks, {months_left} months left.") #----------------------------------------------------------------- # Operators #print("Welcome to the tip calculator.") #bill = input("How much was the bill? £") #amount = float(bill) #tip = input("How much of a tip would you like to give? (10%, 12%, 15%) ") #tip_num = float(tip) #amount += (amount * tip_num/100) #people = input("How many people are you splitting for? ") #amount_per_person = amount / (int(people)) #result = round(amount_per_person, 2) #print(f"Each person owes £{result}")
4202325b897f0383f40bb946a924d5b2c4b962c4
jamolinav/Python-Spanish
/python/fundamentals/underscore.py
1,389
3.84375
4
import functools class Underscore: def map(self, iterable, callback): # tu código aqui lista = list(map(callback , iterable)) return lista def find(self, iterable, callback): # tu código aqui lista = list(map(lambda x: x if callback(x) else None , iterable)) lista = [i for i in lista if i ] return lista[0] if len(lista) > 0 else None def filter(self, iterable, callback): # tu código aqui lista = list(map(lambda x: x if callback(x) else None , iterable)) lista = [i for i in lista if i] return lista def reject(self, iterable, callback): # tu código lista = list(functools.reduce(callback, iterable)) return lista # has creado una libreria con 4 métodos # se crea la instancia de la clse _ = Underscore() # sí, estamos configurando una instancia a una variable que es un guión bajo evens = _.map([1,2,3], lambda x: x*2) # debe retornar [2,4,6] print (evens) evens = _.find([1,2,3,4,5,6], lambda x: x>4) # debe retornar el primer valor que es mayor que 4 print (evens) evens = _.filter([1,2,3,4,5,6], lambda x: x%2==0) # debe retornar [2,4,6] print (evens) evens = _.reject([1,2,3,4,5,6], lambda y, x: x%2==0) # debe retornar [1,3,5] print (evens) # debe retornar [2, 4, 6] después que termines de implementar el código de arriba
7a40df755c658a5ed3c158fd94ba2ada08fd8e04
joaoo-vittor/estudo-python
/revisao/aula1.py
281
3.96875
4
""" Tipos de dados str -> string int -> inteiro float -> real/ponto flutuante bool -> boolean """ print('João', type('João')) print('10', type('10')) print(10, type(10)) print(10.79, type(10.79)) print(True, type(True)) """ Operadores Artmeticos +, -, *, /, //, **, %, () """
b3b61fe51fee23d1d536bd2536b4ffce4281d3e2
emyhr/smoking_vis_data
/tobacco_sales.py
1,792
3.828125
4
import altair as alt import streamlit as st import pandas as pd import numpy as np sales_data = pd.read_csv('data/sales-of-cigarettes-per-adult-per-day.csv', header=0, names=[ 'Country', 'Code', 'Year', 'NumCig' ], dtype={'Country': str, 'Code': str, 'Year': 'Int64', 'NumCig': 'float64'}) sales_minyear = sales_data.loc[:, 'Year'].min() sales_maxyear = sales_data.loc[:, 'Year'].max() container = st.beta_container() with container: st.header('Tobacco sales trend in different countries') ''' This chart below shows average number of cigarettes sold per day in a particular country. For example, in 1980 in France, people used to buy on average 6 cigarettes per day. ''' sales_bycountry = st.multiselect('Select countries to plot', sales_data.groupby('Country').count().reset_index()['Country'].tolist(), default=['France', 'Germany', 'Spain']) slider = st.slider('Select a period to plot', int(str(sales_minyear)), int(str(sales_maxyear)), (1980, 2000)) sales_chart = alt.Chart(sales_data, height=500, width=700, title='Average number of cigarettes sold daily during chosen period of time').mark_line().encode( alt.X('Year', axis=alt.Axis(title='Years', tickCount=5)), alt.Y('NumCig', axis=alt.Axis(title='Avg daily sales of cigarretes')), alt.Color('Country') ).transform_filter( {'and': [{'field': 'Country', 'oneOf': sales_bycountry}, {'field': 'Year', 'range': slider}]} ) with container: st.altair_chart(sales_chart)
f4f758b327e013706e74b2f1ec0f5982982f6704
aseldan/aseldan.github.io
/primes.py
299
3.84375
4
def is_prime(n): if n<=1: return False else: for i in range(2,n): if n%i==0: return False else: return True def primes_below(n): l=[] for i in range (2,n): if is_prime(i): l.append(i) return l
d93aa4e748e31f984ee651fd9d68cc418fd3214b
gowentgonemax/InnovationPython_ravishah
/Task_7.py
3,322
4
4
'''1. Write a program that calculates and prints the value according to the given formula: Q= Square root of [(2*C*D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is a variable whose values should be input to your program in a comma-separated sequence.''' C = 50. H = 30. import math d_value = list(map(int, input("Enter the value of D: ").split(","))) for i in d_value: Q = math.sqrt((2*C*i)/H) print('Value of Q is:',Q) '''2. Define a class named Shape and its subclass Square. The Square class has an init function which takes length as argument. Both classes have an area function which can print the area of the shape where Shape’s area is 0 by default.''' print('*****Shape Question****') class Shape: def Area(self): return 0 class Square(Shape): def __init__(self,length=0): self.length = length def Area(self): print(self.length*self.length) ob = Square() print('The area of square is: ',ob.Area()) '''3. Create a class to find three elements that sum to zero from a set of n real numbers Input array: [-25,-10,-7,-3,2,4,8,10] Expected output: [[-10,2,8],[-7,-3,10]]''' print('*****Add sum****') import itertools class FindElements: def __init__(self,inputList): listSum =[] for subset in itertools.combinations(inputList,3): if sum(list(subset)) == 0: if list(subset) not in listSum: listSum.append(list(subset)) print(listSum) givenInput = [-25,-10,-7,-3,2,4,8,10] ob = FindElements(givenInput) '''4. Create a Time class and initialize it with hours and minutes. Create a method addTime which should take two Time objects and add them. E.g.- (2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min) Create another method displayTime which should print the time. Also create a method displayMinute which should display the total minutes in the Time. E.g.- (1 hr 2 min) should display 62 minute.''' print('*****Time CLass****') from datetime import timedelta class Time: def __init__(self,hours,minute): self.hours = hours self.minute = minute def AddTime(self,t1,t2): print(t1,t2) # t1 = [2,50] # t2 = [1,20] # obj = Time # obj.AddTime(t1,t2) '''5. Write a Person class with an instance variable “age” and a constructor that takes an integer as a parameter. The constructor must assign the integer value to the age variable after confirming the argument passed is not negative; if a negative argument is passed then the constructor should set age to 0 and print “Age is not valid, setting age to 0”. In addition, you must write the following instance methods: Sample Input for amIOld(): -1 4 10 16 18 64 38''' print('*****Age question****') class Person: def __init__(self,age): if age < 0: print('Age is not valid,setting age to zero') self.age = 0 else: self.age = age def yearPasses(self,value): print( 'Year passes',self.age+value) def amIOld(self): if 13 > self.age > 0: print('You are Young') elif 12 < self.age < 20: print('You are Teaanage') else: print('You are old') obj = Person(-2) obj.amIOld() obj.yearPasses(2)
a61dab2324121e5e9b9e194f50b3a216fae7b731
lagachea/expert-system
/tool.py
1,638
3.546875
4
def remove_charset(string, charset): ''' return a copy of string without chars from charset ''' copy = '' for i in range(len(string)): if not string[i] in charset: copy = copy + string[i] return(copy) def get_query(lines): ''' take the lines of the files and return the query if it is unique meaning only one line of query ''' query = [] for i in range(len(lines) - 1,0,-1): if lines[i][:1] == '?': query.append(lines[i][1:]) lenq = len(query) if lenq != 1: if lenq == 0: print('No query found') else: print('Only one query can be processed') exit() query = query[0] if query.isalpha() and query.isupper(): print('query found', query) return (query) print('Incorrect query') def get_knowledge(lines): ''' take the lines of the files and return the knowledge if it is unique meaning only one line of knowledge ''' knowledge = [] for i in range(len(lines) - 1,0,-1): if lines[i][:1] == '=': knowledge.append(lines[i][1:]) lenk = len(knowledge) if lenk != 1: if lenk == 0: print('No knowledge found') else: print('Only one knowledge can be true') exit() knowledge = knowledge[0] if knowledge.isalpha() and knowledge.isupper(): print('knowledge found', knowledge) return (knowledge) print('Incorrect knowledge') def get_propositions(lines): ''' take the lines of the files and return the propositions ''' return(lines)
5d7a55a04b8e75bf510c4253a81a3a9c71c0d01f
shovan99/snakeWaterGame
/helloWorld.py
2,841
3.90625
4
import random total_limit=10 current_limit=0 computer_point=0 your_point=0 while(current_limit<total_limit): print("press 's' for snake, press 'w' for water and press 'g' for gun") userInput=input() list=["s","w","g"] s=random.choice(list) if userInput==s: print("Tied") your_point+=1 computer_point+=1 print(your_point) print(computer_point) current_limit+=1 print("Remaining limit:",(total_limit-current_limit)) elif userInput=="s" and s=="w": print("computer wins this point") computer_point += 2 print(your_point) print(computer_point) current_limit += 1 print("Remaining limit:", (total_limit-current_limit)) elif userInput=="s" and s=="g": print("computer wins this point") computer_point += 2 print(your_point) print(computer_point) current_limit += 1 print("Remaining limit:", (total_limit-current_limit)) elif userInput=="w" and s=="s": print("you wins this point") your_point += 2 print(your_point) print(computer_point) current_limit += 1 print("Remaining limit:", (total_limit-current_limit)) elif userInput=="g" and s=="w": print("computer wins this point") computer_point += 2 print(your_point) print(computer_point) current_limit += 1 print("Remaining limit:", (total_limit-current_limit)) elif userInput=="w" and s=="g": print("you wins this point") your_point += 2 print(your_point) print(computer_point) current_limit += 1 print("Remaining limit:", (total_limit-current_limit)) elif userInput=="g" and s=="s": print("you wins this point") your_point += 2 print(your_point) print(computer_point) current_limit += 1 print("Remaining limit:", (total_limit-current_limit)) if your_point>computer_point: print("You are the winner") elif computer_point>your_point: print("Sorry!! computer wins the game.") else:print("Match Tied !!!") print("Game Over")
c84559f65e1580a4a633233e30719c20720bb790
dev-junseo/Python
/prime_num_checker.py.py
561
3.828125
4
num = int(input("소수 검사를 할 정수를 입력하시오 : ")) num_list = [] def make_num_list(number): if number == 2: num_list.append(number) return num_list elif number > 2: for i in range(2, number): num_list.append(i) return num_list count = 0 make_num_list(num) for i in range(len(num_list) - 1): num_1 = num_list[i] if num % num_1 == 0: count += 1 if count == 0: print("소수인가요? : True") elif count >= 1: print("소수인가요? : False")
c5051f6c71737b3ef21bacfc3114d227d5e40f68
MakeSchool-17/twitter-bot-python-beingadrian
/2_dictionary_words/vocab_game.py
683
3.984375
4
import random import os dict_file = open("/usr/share/dict/words", "r").readlines() def generate_random_word(): random_word = random.choice(dict_file).rstrip("\n") return random_word def print_with_style(word): print("="*len(word)) print(word.upper()) print("="*len(word)) if __name__ == "__main__": while True: random_word = generate_random_word() os.system('cls' if os.name == 'nt' else 'clear') print_with_style(random_word) user_input = input() if user_input == "q": break elif user_input == "s": # todo: show pass else: # next pass
5841080e3dada4db30b4a3a41b98215c0a554f96
jslhost/scrabble
/scrabble.py
1,762
3.90625
4
def scrabble() : import urllib #A text file containing French words liste = [] url = "http://jph.durand.free.fr/scrabble.txt" file = urllib.request.urlopen(url) for line in file: liste.append(line) mots_francais = set() for elt in liste[1:] : mots_francais.add(elt.decode('utf-8').strip()) #Points by letter dico = {1: ['A', 'E', 'I', 'O', 'N', 'R', 'T', 'L', 'S', 'U'], 2: ['D', 'G'], 3: ['B', 'C', 'M', 'P'], 4: ['F', 'H', 'V', 'W', 'Y'], 5: ['K'], 8: ['J', 'X'], 10: ['Q', 'Z']} #Initialization of dict of words and input letters mots = mots_francais letters = ref = input('Please enter your seven letters (capitalize) : \n') #Create a list verifying the match between letters and words liste_match = [] for mot in mots : mot_formé = [] letters = ref for letter in mot : if letter in letters : mot_formé.append(letter) letters = letters.replace(letter, '', 1) mot_joint = ''.join(mot_formé) liste_match.append(mot_joint) #Verify if the words match the initial list of words mots_possibles = [mot for mot in liste_match if mot in mots] #We count the points in score score = {} for mot in mots_possibles : count = 0 for letter in mot : for point, liste in dico.items() : if letter in liste : count += point score[mot] = count #We search the best score max_score = max(score, key = score.get) #Displaying print(f'\nThis is all the words you can make : \n{score} \n') print(f'This is the best word you can make : {max_score} \n')
05d5cb86ed4401440abe1afd31e6ee761f376060
pyomeca/bioptim
/bioptim/examples/getting_started/example_cyclic_movement.py
4,709
3.578125
4
""" This example is a trivial box that must superimpose one of its corner to a marker at the beginning of the movement and superimpose the same corner to a different marker at the end. Moreover, the movement must be cyclic, meaning that the states at the end and at the beginning are equal. It is designed to provide a comprehensible example of the way to declare a cyclic constraint or objective function A phase transition loop constraint is treated as hard penalty (constraint) if weight is <= 0 [or if no weight is provided], or as a soft penalty (objective) otherwise """ import platform from bioptim import ( BiorbdModel, Node, OptimalControlProgram, Dynamics, DynamicsFcn, Objective, ObjectiveFcn, ConstraintList, ConstraintFcn, BoundsList, OdeSolver, OdeSolverBase, PhaseTransitionList, PhaseTransitionFcn, Solver, ) def prepare_ocp( biorbd_model_path: str, n_shooting: int, final_time: float, loop_from_constraint: bool, ode_solver: OdeSolverBase = OdeSolver.RK4(), assume_phase_dynamics: bool = True, expand_dynamics: bool = True, ) -> OptimalControlProgram: """ Prepare the program Parameters ---------- biorbd_model_path: str The path of the biorbd model final_time: float The time at the final node n_shooting: int The number of shooting points loop_from_constraint: bool If the looping cost should be a constraint [True] or an objective [False] ode_solver: OdeSolverBase The type of ode solver used assume_phase_dynamics: bool If the dynamics equation within a phase is unique or changes at each node. True is much faster, but lacks the capability to have changing dynamics within a phase. A good example of when False should be used is when different external forces are applied at each node expand_dynamics: bool If the dynamics function should be expanded. Please note, this will solve the problem faster, but will slow down the declaration of the OCP, so it is a trade-off. Also depending on the solver, it may or may not work (for instance IRK is not compatible with expanded dynamics) Returns ------- The ocp ready to be solved """ bio_model = BiorbdModel(biorbd_model_path) # Add objective functions objective_functions = Objective(ObjectiveFcn.Lagrange.MINIMIZE_CONTROL, key="tau", weight=100) # Dynamics dynamics = Dynamics(DynamicsFcn.TORQUE_DRIVEN, expand=expand_dynamics) # Constraints constraints = ConstraintList() constraints.add(ConstraintFcn.SUPERIMPOSE_MARKERS, node=Node.MID, first_marker="m0", second_marker="m2") constraints.add(ConstraintFcn.TRACK_STATE, key="q", node=Node.MID, index=2) constraints.add(ConstraintFcn.SUPERIMPOSE_MARKERS, node=Node.END, first_marker="m0", second_marker="m1") # Path constraint # First node is free but mid and last are constrained to be exactly at a certain point. # The cyclic penalty ensures that the first node and the last node are the same. x_bounds = BoundsList() x_bounds["q"] = bio_model.bounds_from_ranges("q") x_bounds["q"][2, -1] = 1.57 # end with cube 90 degrees rotated x_bounds["qdot"] = bio_model.bounds_from_ranges("qdot") x_bounds["qdot"][:, -1] = 0 # Start and end without any velocity # Define control path constraint u_bounds = BoundsList() u_bounds["tau"] = [-100] * bio_model.nb_tau, [100] * bio_model.nb_tau # ------------- # # A phase transition loop constraint is treated as # hard penalty (constraint) if weight is <= 0 [or if no weight is provided], or # as a soft penalty (objective) otherwise phase_transitions = PhaseTransitionList() if loop_from_constraint: phase_transitions.add(PhaseTransitionFcn.CYCLIC) else: phase_transitions.add(PhaseTransitionFcn.CYCLIC, weight=10000) return OptimalControlProgram( bio_model, dynamics, n_shooting, final_time, x_bounds=x_bounds, u_bounds=u_bounds, objective_functions=objective_functions, constraints=constraints, ode_solver=ode_solver, phase_transitions=phase_transitions, assume_phase_dynamics=assume_phase_dynamics, ) def main(): """ Runs and animate the program """ ocp = prepare_ocp("models/cube.bioMod", n_shooting=30, final_time=2, loop_from_constraint=True) # --- Solve the program --- # sol = ocp.solve(Solver.IPOPT(show_online_optim=platform.system() == "Linux")) # --- Show results --- # sol.animate() if __name__ == "__main__": main()
812952260efa794766b8806c1ebcfe46c7169125
jaiswalIT02/pythonprograms
/Chapter-3 Loop/ifelse.py
172
3.734375
4
option=int(input("Enter 0 for 1 to 10 & 1 for 10 to 1 == ")) for i in range(1,11): if option==0: print(i) else: print(11-i)
503b7a75ee7915305ad9cb3e423c07198bd7f2e5
fluxgame/ALGS200x
/inversions.py
1,483
3.515625
4
# Uses python3 import sys def get_number_of_inversions_naive(a): count = 0 for i in range(0, len(a)): for j in range (0, len(a)): if i < j and a[i] > a[j]: count += 1 return count def merge(l, r, a): number_of_inversions = i = j = k = 0 # print(f"pre-merge: {a}, l: {l}, r: {r}") while i < len(l) and j < len(r): if l[i] <= r[j]: a[k] = l[i] i += 1 else: # print(f"{l[i]} > {r[j]}") # print(f"swapping {r[j]} and {a[k]}") # print(f"copy {r[j]} from r[{j}] to a[{k}]") a[k] = r[j] j += 1 number_of_inversions += (len(l) - i) k += 1 # print(f"post-merge: {a}, l: {l}, r: {r}") while i < len(l): a[k] = l[i] i += 1 k += 1 while j < len(r): a[k] = r[j] j += 1 k += 1 return number_of_inversions def get_number_of_inversions(a): number_of_inversions = 0 if len(a) <= 1: return number_of_inversions mid = len(a) // 2 left = a[:mid] right = a[mid:] number_of_inversions += get_number_of_inversions(left) number_of_inversions += get_number_of_inversions(right) number_of_inversions += merge(left, right, a) return number_of_inversions if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) b = n * [0] print(get_number_of_inversions(a))
baba8c39f58a588edeeffa32e760e0f5b008fab0
jiwon73/lecture_4_1
/lecture_4/try_except_zerodiv.py
325
3.5
4
try: a,b=input('두수를 넣으세요').split() result=(int(a)/int(b)) print(result) except ZeroDivisionError: print('0으로는 나눌 수 없습니다') except TypeError: print("지원하지 않는 연산자 입니다.") except Exception as e: print('오류 종류; {}'.format(e)) print('Test')
b6874fb47f4f173b235fb34838c2dd1fa6fb71e2
UnSi/2_GeekBrains_courses_algorithms
/Lesson 3/hw/task6.py
998
4.09375
4
# 6. В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами. # Сами минимальный и максимальный элементы в сумму не включать. from random import randint min_value = 1 max_value = 100 rand_array = [randint(min_value, max_value) for _ in range(10)] print(rand_array) max_value, min_value = min_value, max_value min_idx = 0 max_idx = 0 for i, number in enumerate(rand_array): if number > max_value: max_value, max_idx = number, i if number < min_value: min_value, min_idx = number, i if max_idx < min_idx: max_idx, min_idx = min_idx, max_idx sum_arr = 0 for i in rand_array[min_idx+1: max_idx]: sum_arr += i print(f"Минимамальное число: {min_value}, максимальное число: {max_value} , сумма элементов между ними: {sum_arr} ")
424031acc6fd3816f8b020226c8d190755dfb583
monlie/LeetCode
/173.py
835
3.859375
4
# Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None def bst(root, l): if root: bst(root.left, l) l.append(root.val) bst(root.right, l) class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.l = [] self.idx = 0 bst(root, self.l) def hasNext(self): """ :rtype: bool """ return self.idx < len(self.l) def next(self): """ :rtype: int """ val = self.l[self.idx] self.idx += 1 return val # Your BSTIterator will be called like this: # i, v = BSTIterator(root), [] # while i.hasNext(): v.append(i.next())
f95cace1d6f2a82110bd14b69f541b5bcedd0da0
bheki-maenetja/small-projects-py
/courses/python_data_structures_queues/Exercise Files/Ch03/03_03/End/queues.py
591
4.3125
4
class Queue: def __init__(self): self.items = [] def enqueue(self, item): """Takes in an item and inserts that item into the 0th index of the list that is representing the Queue. The runtime is O(n), or linear time, because inserting into the 0th index of a list forces all the other items in the list to move one index to the right. """ self.items.insert(0, item) def dequeue(self): pass def peek(self): pass def size(self): pass def is_empty(self): pass
d49e32dfb391de090ea4e79e13c10498666efe60
mysilver/COMP9321-Data-Services
/Week2_DataAccess/activity_3.py
2,256
3.859375
4
import json import pandas as pd from pymongo import MongoClient def read_csv(csv_file): """ :param csv_file: the path of csv file :return: A dataframe out of the csv file """ return pd.read_csv(csv_file) def print_dataframe(dataframe, print_column=True, print_rows=True): # print column names if print_column: print(','.join(dataframe.columns)) # print rows one by one if print_rows: for row in dataframe.itertuples(index=False, name=None): row = ','.join(str(col) for col in row) print(row) def write_in_mongodb(dataframe, mongo_host, mongo_port, db_name, collection): """ :param dataframe: :param mongo_host: Mongodb server address :param mongo_port: Mongodb server port number :param db_name: The name of the database :param collection: the name of the collection inside the database """ client = MongoClient(host=mongo_host, port=mongo_port) db = client[db_name] c = db[collection] # You can only store documents in mongodb; # so you need to convert rows inside the dataframe into a list of json objects records = json.loads(dataframe.T.to_json()).values() c.insert_many(records) def read_from_mongodb(mongo_host, mongo_port, db_name, collection): """ :param mongo_host: Mongodb server address :param mongo_port: Mongodb server port number :param db_name: The name of the database :param collection: the name of the collection inside the database :return: A dataframe which contains all documents inside the collection """ client = MongoClient(host=mongo_host, port=mongo_port) db = client[db_name] c = db[collection] return pd.DataFrame(list(c.find())) if __name__ == '__main__': db_name = 'comp9321' mongo_port = 27017 mongo_host = 'localhost' csv_file = 'Demographic_Statistics_By_Zip_Code.csv' # path to the downloaded csv file df = read_csv(csv_file) collection = 'Demographic_Statistics' print("Writing into the mongodb") write_in_mongodb(df, mongo_host, mongo_port, db_name, collection) print("Querying the database") df = read_from_mongodb(mongo_host, mongo_port, db_name, collection) print_dataframe(df)
cf22a711febb18730bb37da217883aa67910570b
Tomolo997/Fri-mag
/programiranje/Chapter_Two.py
2,193
4.21875
4
#Data structures # collection of data elements, that is structured in some way # 6 types of sequences # tuples # list # .. # tuples => cannot change it # list => can change it #e Python has a basic notion of a kind of data structure called a container, which is basically any object #that can contain other objects # sequence operations # indexing # slicing # adding # multiplying # chacking for memberships # indexing x = [1,2,5123,221] print(x[1]) # prints => 2 print("greetins"[2]) # prints => e # slicing print("mada faka"[3:7]) # prints => a fa # you supply two indices as limits for your slice # [0:10:2] => from 0 to 10 , but every second number # [8:3:-1] => from 8 to 3 , but backwards #adding sequances #>>> [1, 2, 3] + [4, 5, 6] #[1, 2, 3, 4, 5, 6] # multiplication # 'python' * 5 #'pythonpythonpythonpythonpython' #>>> [42] * 10 #[42, 42, 42, 42, 42, 42, 42, 42, 42, 42] # none , empty lists and initilization # initialize a list of lenth 10 #[None]*10 # permissions # in operatior # permisions = "rw" # "w" in permision => true # lenth #len(numbers) #maximum number # max(numbers) #minimum number # min(numbers) # LISTS # Lists are mutable # list("Hello") => ['H', 'e', 'l', 'l', 'o'] # Basic list operations #item assingment x = [1,1,1] x[1] = 2 print(x) #=> ]1,2,1] #deleting elements del x[1] #=> deletes the second element # assinging to slice >>> name = list('Perl') >>> name ['P', 'e', 'r', 'l'] >>> name[2:] = list('ar') >>> name ['P', 'e', 'a', 'r'] # List methods #append => list.append(2), add to the end #count => list.count(1), how many 1's are there in the list #extend => a.extend(b) , add a list to b list #index => list.index("baby") => show me the index of baby #insert => list.insert(3,"four"), insert "four" at the index 3 #pop => x.pop() => pop from the stack, remove from the start #remove => x.remove("baby") => remove the specific from list #reverse => reverse the list #sort => sort the specific list #Tuples #they can be used as keys in mappings #Cant be changed (1,2,3) #tuple function , change list to a tuple
2ef3eeba8a596cc80488a1ee34e7c021a3602b5e
yoonwoolee/efp
/3-13.py
673
4
4
#!/usr/bin/env python if __name__ == '__main__': principal = input('What is the principal amount? ') rate = input('What is the rate: ') number_of_years = input('What is the number of years: ') number_of_times = input('What is the number of times the interest\nis compounded per year: ') money = principal * ( 1 + (rate /100.0) / number_of_times) ** ( number_of_times * number_of_years ) output_string = '$' + str(principal) + ' invested at ' + str(rate) output_string += '% for ' + str(number_of_years) + ' years compounded ' output_string += str(number_of_times) +' times per year is $' + str(round(money,2)) print output_string
9227870c394ceb9683aed545141cb8cb3a44ae67
dubeamit/Daily_Coding
/comp_num_strings.py
604
4.03125
4
#compare two strings(s1,s2) as numbers and return True if s1>s2 else return False (cannot convert to int) #eg: larger_than('334', '333')--> True #eg: larger_than('525','6666')--> False #eg: larger_than('11','0') --> True #eg: larger_than('10','10') --> False def larger_than(s1, s2): if len(s1) > len(s2): return True elif len(s1) < len(s2): return False for i in range(len(s1)): if s1[i] == s2[i]: continue elif s1[i] > s2[i]: return True else: return True return False print(larger_than('123','122'))
46bc6f63bff375cda10e82b48e730613ac77619d
zzeleznick/zzeleznick.github.io
/python-practice/test.py
2,894
4.1875
4
#!/usr/bin/env python3 import os import sys def parse_file(path): """ Parses the text file in the given path and returns space, tab & new line details. :arg path: Path of the text file to parse :return: A tuple with count of spacaes, tabs and lines. """ fd = open(path) i = 0 spaces = 0 tabs = 0 for i,line in enumerate(fd): spaces += line.count(' ') tabs += line.count('\t') #Now close the open file fd.close() #Return the result as a tuple return spaces, tabs, i + 1 def main(path): """ Function which prints counts of spaces, tabs and lines in a file. :arg path: Path of the text file to parse :return: True if the file exits or False. """ if os.path.exists(path): spaces, tabs, lines = parse_file(path) print("Spaces %d. tabs %d. lines %d" % (spaces, tabs, lines)) return True else: return False if __name__ == '__main__': if len(sys.argv) > 1: main(sys.argv[1]) else: sys.exit(-1) sys.exit(0) ''' When your script is run by passing it as a command to the Python interpreter, python myscript.py all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets ran. Unlike other languages, there's no main() function that gets run automatically - the main() function is implicitly all the code at the top level. In this case, the top-level code is an if block. __name__ is a built-in variable which evaluate to the name of the current module. However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing if __name__ == "__main__": ... If that code is being imported into another module, the various function and class definitions will be imported, but the main() code won't get run. As a basic example, consider the following two scripts: # file one.py def func(): print("func() in one.py") print("top-level in one.py") if __name__ == "__main__": print("one.py is being run directly") else: print("one.py is being imported into another module") # file two.py import one print("top-level in two.py") one.func() if __name__ == "__main__": print("two.py is being run directly") else: print("two.py is being imported into another module") Now, if you invoke the interpreter as python one.py The output will be top-level in one.py one.py is being run directly If you run two.py instead: python two.py You get top-level in one.py one.py is being imported into another module top-level in two.py func() in one.py two.py is being run directly Thus, when module one gets loaded, its __name__ equals "one" instead of __main__. '''
7d48a259074c2284cb04fceacca1bb1e34d3e68e
LMMilewski/learn_python
/metaclasses.py
2,650
3.5625
4
#!/usr/bin/python2.7 import logging log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) ######################################## simple class class Car(object): brand = "audi" def __init__(self, model, doors_count=5): self.model = model self.doors_count = doors_count def go(self): log.info("driving %s %s with %s doors", self.brand, self.model, self.doors_count) c = Car("a6") c.go() ######################################## how to do that w/o shortcut def go(self): log.info("driving %s %s with %s doors", self.brand, self.model, self.doors_count) def init(self, model, doors_count=5): self.model = model self.doors_count = doors_count attrs = {'__init__': init, 'go': go, 'brand': 'audi'} superclasses = (object,) Car2 = type("Car2", superclasses, attrs) c2 = Car2("a6") c2.go() ######################################## type is the top assert type(c) == Car assert type(Car) == type assert type(type) == type ######################################## creating metaclass & using it # metaclasses inherit from type class Meta(type): pass class Instance(object): __metaclass__ = Meta # Python 2 only ######################################## can override __new__ and __init__ class MyMeta(type): def __new__(meta, name, supers, attrs): log.info("executing MyMeta new") return type.__new__(meta, name, supers, attrs) def __init__(cls, name,supers, attrs): log.info("executing MyMeta init") class MyInstance(object): __metaclass__ = MyMeta def __init__(self): log.info("executing init in my instance") # note that __new__ and __init__ from MyMeta are executed when # MyInstance is created - not when instances are created log.info("creating instances") a1 = MyInstance() a2 = MyInstance() a3 = MyInstance() ######################################## mysterious class change ## You can return instance of another class from __new__ class Q(object): pass class W(object): pass class Other(Q, W): pass class BaseChange(type): def __new__(meta, name, bases, attrs): log.info("meta = %s, name = %s, bases = %s, attrs = %s", meta, name, bases, attrs) return Other class X(object): __metaclass__ = BaseChange def __init__(self): log.info("X init called") def foo(self): pass x = X() ## X.__init__ is not called # If __new__() does not return an instance of cls, then the new # instance’s __init__() method will not be invoked. log.info("class of x: %s", x.__class__) # prints Other log.info("superclasses of X: %s", x.__class__.__bases__) # prints Q, W
ddaf922da8a981b54d066f7c9adafb0e18be2b16
c0fec0de/anytree
/anytree/search.py
7,330
3.59375
4
""" Node Searching. .. note:: You can speed-up node searching, by installing https://pypi.org/project/fastcache/ and using :any:`cachedsearch`. """ from anytree.iterators import PreOrderIter def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None): """ Search nodes matching `filter_` but stop at `maxlevel` or `stop`. Return tuple with matching nodes. Args: node: top node, start searching. Keyword Args: filter_: function called with every `node` as argument, `node` is returned if `True`. stop: stop iteration at `node` if `stop` function returns `True` for `node`. maxlevel (int): maximum descending in the node hierarchy. mincount (int): minimum number of nodes. maxcount (int): maximum number of nodes. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> findall(f, filter_=lambda node: node.name in ("a", "b")) (Node('/f/b'), Node('/f/b/a')) >>> findall(f, filter_=lambda node: d in node.path) (Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e')) The number of matches can be limited: >>> findall(f, filter_=lambda node: d in node.path, mincount=4) # doctest: +ELLIPSIS Traceback (most recent call last): ... anytree.search.CountError: Expecting at least 4 elements, but found 3. ... Node('/f/b/d/e')) >>> findall(f, filter_=lambda node: d in node.path, maxcount=2) # doctest: +ELLIPSIS Traceback (most recent call last): ... anytree.search.CountError: Expecting 2 elements at maximum, but found 3. ... Node('/f/b/d/e')) """ return _findall(node, filter_=filter_, stop=stop, maxlevel=maxlevel, mincount=mincount, maxcount=maxcount) def findall_by_attr(node, value, name="name", maxlevel=None, mincount=None, maxcount=None): """ Search nodes with attribute `name` having `value` but stop at `maxlevel`. Return tuple with matching nodes. Args: node: top node, start searching. value: value which need to match Keyword Args: name (str): attribute name need to match maxlevel (int): maximum descending in the node hierarchy. mincount (int): minimum number of nodes. maxcount (int): maximum number of nodes. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> findall_by_attr(f, "d") (Node('/f/b/d'),) """ return _findall( node, filter_=lambda n: _filter_by_name(n, name, value), maxlevel=maxlevel, mincount=mincount, maxcount=maxcount, ) def find(node, filter_=None, stop=None, maxlevel=None): """ Search for *single* node matching `filter_` but stop at `maxlevel` or `stop`. Return matching node. Args: node: top node, start searching. Keyword Args: filter_: function called with every `node` as argument, `node` is returned if `True`. stop: stop iteration at `node` if `stop` function returns `True` for `node`. maxlevel (int): maximum descending in the node hierarchy. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> find(f, lambda node: node.name == "d") Node('/f/b/d') >>> find(f, lambda node: node.name == "z") >>> find(f, lambda node: b in node.path) # doctest: +ELLIPSIS Traceback (most recent call last): ... anytree.search.CountError: Expecting 1 elements at maximum, but found 5. (Node('/f/b')... Node('/f/b/d/e')) """ return _find(node, filter_=filter_, stop=stop, maxlevel=maxlevel) def find_by_attr(node, value, name="name", maxlevel=None): """ Search for *single* node with attribute `name` having `value` but stop at `maxlevel`. Return tuple with matching nodes. Args: node: top node, start searching. value: value which need to match Keyword Args: name (str): attribute name need to match maxlevel (int): maximum descending in the node hierarchy. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d, foo=4) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> find_by_attr(f, "d") Node('/f/b/d') >>> find_by_attr(f, name="foo", value=4) Node('/f/b/d/c', foo=4) >>> find_by_attr(f, name="foo", value=8) """ return _find(node, filter_=lambda n: _filter_by_name(n, name, value), maxlevel=maxlevel) def _find(node, filter_, stop=None, maxlevel=None): items = _findall(node, filter_, stop=stop, maxlevel=maxlevel, maxcount=1) return items[0] if items else None def _findall(node, filter_, stop=None, maxlevel=None, mincount=None, maxcount=None): result = tuple(PreOrderIter(node, filter_, stop, maxlevel)) resultlen = len(result) if mincount is not None and resultlen < mincount: msg = "Expecting at least %d elements, but found %d." raise CountError(msg % (mincount, resultlen), result) if maxcount is not None and resultlen > maxcount: msg = "Expecting %d elements at maximum, but found %d." raise CountError(msg % (maxcount, resultlen), result) return result def _filter_by_name(node, name, value): try: return getattr(node, name) == value except AttributeError: return False class CountError(RuntimeError): def __init__(self, msg, result): """Error raised on `mincount` or `maxcount` mismatch.""" if result: msg += " " + repr(result) super(CountError, self).__init__(msg)
15cfbabbd993274f6233b0766fed1f4c9831d9e2
strozzi1/cs325-Algorithms
/assign3/closest_unsorted.py
1,239
3.625
4
import random from random import randint def find(a, x, k): ##params: array, comparison number, number of near numbers diffarray = [abs(y-x) for y in a] #array of the difference between each element and x ksmallest = quickselect(k, diffarray) #print("k: ", ksmallest) #return pivot index = [g for g,j in enumerate(diffarray) if j < ksmallest] for i,g in enumerate(diffarray, 0): if g == ksmallest: #print(i, g) index.append(i) #print(index) index.sort() final=[ ] #initialize final for i in range(0,len(index)): final.append(a[index[i]]) #print( final) return final def quickselect(k,a): #from class returns number at sorted index if a == [] or k>len(a) or k==0: return [] else: #i=random.randint(0,len(a)-1) #a[0],a[i]=a[i],a[0] pivot=a[0] left = [x for x in a if x < pivot ] splitP=len(left) if splitP==k-1: return pivot elif splitP>k-1: return quickselect(k,left) else: right = [x for x in a[1:] if x >= pivot] return quickselect(k-(splitP+1),right)
f1aa094f568d8d8e5b09d2a476b26911a3256691
Anaa29/Python-codes
/Rangoli(turtle).py
215
3.6875
4
from turtle import * bgcolor("black") speed(0) for i in range(8): for col in ('red','cyan','white','magenta','yellow'): color(col) circle(100) right(10) hideturtle()
4fee3f2529c5d12558fbe2cea660b6ee6d57c57e
pascalmouret/nand2tetris
/06/assembler/symbols.py
485
3.53125
4
from typing import Dict, Optional class SymbolTable(): def __init__(self, defaults: Dict[str, int]) -> None: self.next_variable = 16 self.table = defaults def address_for_symbol(self, symbol: str) -> int: if symbol not in self.table: self.table[symbol] = self.next_variable self.next_variable += 1 return self.table[symbol] def add_label(self, label: str, address: int) -> None: self.table[label] = address
6c8832b62d67e7762e2f53d327159e53409cf381
Mnandala1/rajab-kassim
/TRIAL.py
4,336
4.28125
4
''' #EXCERCISE 1 message = 'hi my name is Rajab learning python' print(message) print('\n') mylist = message.split() print(mylist) mylist.sort() print(mylist) print('\n') message = 'I hope I can master it' print(message.title()) name = "Ada Lovelace" print(name.upper()) print(name.lower()) first_name = 'Rajab' second_name = 'Kassim' full_name = first_name + " " + second_name #CONCATENATE print(full_name) #EXCERCISE 2 name = 'john pombe magufuli' print("Hello"" " + name +" " "would you like to learn some Python today?") print(name.title()) print(name.lower()) print(name.upper()) print('\n') name = 'Albert Eistein' message = 'once said, “A person who never made amistake never tried anything new.”' print(name+" "+message) age = '23' message ='happy ' +age+ 'rd Birthday' print(message) age = 23 message = "Happy " + str(age) + "rd Birthday!" print(message) print(5+3) print(11-3) print(4*2) print(8/1) bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles[0].title()) print(bicycles[1].title()) print(bicycles[2].title()) print(bicycles[3].title()) print('\n') print(bicycles[-1].title()) #return the last value print(bicycles[-2].title()) #return the second from last value print(bicycles[-3].title()) #return the 3rd fromlast value print(bicycles[-4].title()) #return the first value message = 'my first bcycle was a bicycles[0]' print(message) #EXCERCISE 3 friends = ['juma','ally','seif','noya','jose','fau','aneth','bahati'] print(friends[0].title()) print(friends[1].title()) print(friends[2].title()) print(friends[3].title()) print(friends[4].title()) print(friends[5].title()) print(friends[6].title()) print(friends[7].title()) print('\n') message = 'Hello how are you ' print(message + friends[0].title(), '\n') print(message + friends[1].title(), '\n') print(message + friends[2].title(), '\n') print(message + friends[3].title(), '\n') print(message + friends[4].title(), '\n') print(message + friends[5].title(), '\n') print(message + friends[6].title(), '\n') print(message + friends[7].title(), '\n') friends[0] = 'waziri' #modify the list friends[1] = 'mrisho' print(friends) friends.append('nasri') #adds new item friends.insert(7,'Rajab') print(friends) del friends[2] #delete item print(friends) motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) popped_motorcycle = motorcycles.pop() print(motorcycles) print(popped_motorcycle) motorcycles.remove('honda') print(motorcycles) #EXCERCISE 3-4 guest_list = ['juma','ally','seif','noya','jose','fau','aneth','Rajab','bahati'] message = ' you are welcome for dinner on 23rd' print( guest_list[0] + message, '\n') print( guest_list[1] + message, '\n') print( guest_list[2] + message, '\n') print( guest_list[3] + message, '\n') print( guest_list[4] + message, '\n') print( guest_list[5] + message, '\n') print( guest_list[6] + message, '\n') print( guest_list[7] + message, '\n') print( guest_list[8] + message, '\n') message_1 = 'the following guest wont attend ' print(message_1 + guest_list[0]+ ", " +guest_list[4]+ ", " +guest_list[6] ) print('\n') guest_list = ['asha','ally','seif','noya','zai','fau','mariam','Rajab','bahati'] message_2 = 'new guests are ' print( guest_list[0] + message, '\n') print( guest_list[1] + message, '\n') print( guest_list[2] + message, '\n') print( guest_list[3] + message, '\n') print( guest_list[4] + message, '\n') print( guest_list[5] + message, '\n') print( guest_list[6] + message, '\n') print( guest_list[7] + message, '\n') print( guest_list[8] + message, '\n') print("we have found bigger table and decided to add new guests") guest_list.insert(0,'shabani') guest_list.insert(5,'ramadhani') guest_list.append('pinde') print(guest_list) message = ' you are welcome for dinner on 23rd' print( guest_list[0] + message, '\n') print( guest_list[1] + message, '\n') print( guest_list[2] + message, '\n') print( guest_list[3] + message, '\n') print( guest_list[4] + message, '\n') print( guest_list[5] + message, '\n') print( guest_list[6] + message, '\n') print( guest_list[7] + message, '\n') print( guest_list[8] + message, '\n') print( guest_list[9] + message, '\n') print( guest_list[10] + message, '\n') print( guest_list[11] + message, '\n') guest_list = ['juma','ally','seif','noya','jose','fau','aneth','Rajab','bahati'] guest_list.sort() print(guest_list) print(len(guest_list))'''
522602478a00c80c619341bcfa2d532ef5619f44
namth2015/python
/1.DataScience/2.BigO/Green18/lec11_ascending_sort.py
620
3.65625
4
def insertionAsc(a,n,x): j = n a.append(x) while j >= 0: if j == 0: break if a[j-1] <= x: break a[j] = a[j-1] j -= 1 a[j] = x return a def insertionSort(a): m = len(a) if m == 1: return a[0] for i in range(1,len(a)): x = a[i] b = insertionAsc(a,i,x) c = b[:m] return c # Input & Output n = int(input()) a = [] a.append(input().split()) a = a[0] for i in range(len(a)): a[i] = int(a[i]) c = insertionSort(a) if len(a) == 1: print(a[0]) else: for i in c: print(i, end = ' ')
20f0004c76d606ab9c632f57620e33554679d5e7
melthewarrior12/.spyder-py3
/proj04.py
10,997
4.3125
4
''' Project 4 play the game of "Craps" player is promted for inputs to play the game which is computed within the functions main function plays the game calling other functions to shorten the main main will play through first roll - win, loss or point if the first roll results in point, the dice are rolled again cases are presented if the subsequent roll is win, loss, or neither if subsequent roll is neither the dice will be rolled again after each win the player will be asked to play again if play again is chosen, the player can add to balance and make a wager''' from cse231_random import randint # the cse231 test random for Mimir testing def display_game_rules(): print('''A player rolls two dice. Each die has six faces. These faces contain 1, 2, 3, 4, 5, and 6 spots. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3, or 12 on the first throw (called "craps"), the player loses (i.e. the "house" wins). If the sum is 4, 5, 6, 8, 9, or 10 on the first throw, then the sum becomes the player's "point." To win, you must continue rolling the dice until you "make your point." The player loses by rolling a 7 before making the point.''') def get_bank_balance(): '''Prompt player for initial bank balance (from which wagering will be added or subtracted) the player-entered bank balance is returned as an int''' balance = input("Enter an initial bank balance (dollars):") return int(balance) def add_to_bank_balance(balance): '''Prompts the player for an amount to add to the balance. The balance is returned as an int.''' add_balance = int(input()) return int(balance + add_balance) def get_wager_amount(): '''prompts the player for a wager on a particular roll the wager is returned as an int''' wager = input(" Enter a wager (dollars):") return int(wager) def is_valid_wager_amount(wager, balance): '''checks that the wager is less than or equal to the balance; returns True if it is; False otherwise''' while balance != 0: if wager <= balance: return True else: return False def roll_die(): '''rolls random number 1-6 and assigns numbers to dice''' die2_value = randint(1,6) return die2_value def calculate_sum_dice(die1_value, die2_value): '''sums the values of thr two die and returns the sum as an int''' sum_dice = int(die1_value) + int(die2_value) return int(sum_dice) def first_roll_result(sum_dice): '''Function determines the result on the first roll of the pair of dice. a string is returned. you are required to use at least one boolean operator "or" or "and" in this function. 1 if the sum is 7 or 11 on the roll, the player wins and "win" is returned. 2 if the sum is 2, 3, or 12 on the first throw (called "craps"), the player loses (i.e. the "house" wins) and "loss" is returned. 3 if the sum is 4, 5, 6, 8, 9, or 10 on the first throw, then the sum becomes the player's point and "point" is returned''' if sum_dice == 7 or sum_dice == 11: return "win" elif sum_dice == 2 or sum_dice == 3 or sum_dice == 12: return "loss" else: point_value = 0 point_value = sum_dice + point_value return "point" def subsequent_roll_result(sum_dice, point_value): '''Determines the result on the subsequent rolls of the pair of dice. a string is returned. 1 if sum_dice is the point_value, then "point" is returned 2 if sum_dice is 7 then "loss" is returned 3 otherwise, "neither" is returned''' if sum_dice == 7: return "loss" elif sum_dice == point_value: return "point" else: return "neither" def main(): '''takes no input returns nothing call the functions from here that, the game is played in this fucntion''' game_over = False display_game_rules() balance = get_bank_balance() while game_over != True: #prompt for wager wager = get_wager_amount() #check if wager is ok if is_valid_wager_amount(wager, balance) == False: print(" Error: wager > balance. Try again.") continue #otherwise play game else: roll1 = roll_die() roll2 = roll_die() print(" Die 1:", roll1) print("Die 2:", roll2) sum_dice = calculate_sum_dice(roll1, roll2) print("Dice sum:", sum_dice) if first_roll_result(sum_dice) == "win": print("Natural winner.") print("You WIN!") balance = balance + wager print("Balance:", (balance)) #prompt for another game play = input("Do you want to continue? ") if play == "yes": willadd = (input("Do you want to add to your balance?")) if willadd == "yes": balance = add_to_bank_balance(input("Enter how many dollars to add to your balance:")) print("Balance", balance) wager = get_wager_amount() else: continue else: print("Game is over.") game_over = True break if first_roll_result(sum_dice) == "loss": print("Craps.") print("You lose.") balance = balance - wager print("Balance:", (balance)) #prompt for another game play = input("Do you want to continue? ") if play == "yes": willadd = (input("Do you want to add to your balance?")) if willadd == "yes": balance = add_to_bank_balance(input("Enter how many dollars to add to your balance:")) print("Balance", balance) wager = get_wager_amount() else: continue else: print("Game is over.") game_over = True break if first_roll_result(sum_dice) == "point": print("*** Point:", sum_dice) point_value = sum_dice roll1 = roll_die() roll2 = roll_die() print("Die 1:", roll1) print("Die 2:", roll2) sum_dice = calculate_sum_dice(roll1, roll2) print("Dice sum:", sum_dice) if subsequent_roll_result(sum_dice, point_value) == "loss": print("You lose.") balance = balance - wager print("Balance:", (balance)) #prompt for another game play = input("Do you want to continue? ") if play == "yes": willadd = (input("Do you want to add to your balance?")) if willadd == "yes": balance = add_to_bank_balance(input("Enter how many dollars to add to your balance:")) print("Balance", balance) wager = get_wager_amount() else: print("Game is over.") game_over = True break if subsequent_roll_result(sum_dice, point_value) == "point": print("You matched your Point.") print("You WIN!") balance = balance + wager print("Balance:", (balance)) #prompt for another game play = input("Do you want to continue? ") if play == "yes": willadd = (input("Do you want to add to your balance?")) if willadd == "yes": balance = add_to_bank_balance(input("Enter how many dollars to add to your balance:")) print("Balance", balance) wager = get_wager_amount() continue else: print("Game is over.") game_over = True break while subsequent_roll_result(sum_dice, point_value) == "neither": roll1 = roll_die() roll2 = roll_die() print("Die 1:", roll1) print("Die 2:", roll2) sum_dice = calculate_sum_dice(roll1, roll2) print("Dice sum:", sum_dice) if subsequent_roll_result(sum_dice, point_value) == "loss": print("You lose.") balance = balance - wager print("Balance:", (balance)) #prompt for another game play = input("Do you want to continue? ") if play == "yes": willadd = (input("Do you want to add to your balance?")) if willadd == "yes": balance = add_to_bank_balance(input("Enter how many dollars to add to your balance:")) print("Balance", balance) wager = get_wager_amount() else: print("Game is over.") game_over = True break if subsequent_roll_result(sum_dice, point_value) == "point": print("You matched your Point.") print("You WIN!") balance = balance + wager print("Balance:", (balance)) #prompt for another game play = input("Do you want to continue? ") if play == "yes": willadd = (input("Do you want to add to your balance?")) if willadd == "yes": balance = add_to_bank_balance(input("Enter how many dollars to add to your balance:")) print("Balance", balance) wager = get_wager_amount() else: print("Game is over.") game_over = True continue if __name__ == "__main__": main()
ec660ce11461e8748f50fecfeae5e53a582230fa
QPromise/DataStructure-UsingPython
/7.图形结构/CH07_05.py
2,734
3.8125
4
MAXSIZE=10 #定义队列的最大容量 front=-1 #指向队列的前端 rear=-1 #指向队列的末尾 class Node: def __init__(self,x): self.x=x #顶点数据 self.next=None #指向下一个顶点的指针 class GraphLink: def __init__(self): self.first=None self.last=None def my_print(self): current=self.first while current!=None: print('[%d]' %current.x,end='') current=current.next print() def insert(self,x): newNode=Node(x) if self.first==None: self.first=newNode self.last=newNode else: self.last.next=newNode self.last=newNode #队列数据的存入 def enqueue(value): global MAXSIZE global rear global queue if rear>=MAXSIZE: return rear+=1 queue[rear]=value #队列数据的取出 def dequeue(): global front global queue if front==rear: return -1 front+=1 return queue[front] #广度优先查找法 def bfs(current): global front global rear global Head global run enqueue(current) #将第一个顶点存入队列 run[current]=1 #将遍历过的顶点设置为1 print('[%d]' %current, end='') #打印出该遍历过的顶点 while front!=rear: #判断当前的队伍是否为空 current=dequeue() #将顶点从队列中取出 tempnode=Head[current].first #先记录当前顶点的位置 while tempnode!=None: if run[tempnode.x]==0: enqueue(tempnode.x) run[tempnode.x]=1 #记录已遍历过 print('[%d]' %tempnode.x,end='') tempnode=tempnode.next #声明图的边线数组 Data=[[0]*2 for row in range(20)] Data =[[1,2],[2,1],[1,3],[3,1],[2,4], \ [4,2],[2,5],[5,2],[3,6],[6,3], \ [3,7],[7,3],[4,5],[5,4],[6,7],[7,6],[5,8],[8,5],[6,8],[8,6]] run=[0]*9 #用来记录各顶点是否遍历过 queue=[0]*MAXSIZE Head=[GraphLink]*9 print('图的邻接表内容:') #打印图的邻接表内容 for i in range(1,9): #共有8个顶点 run[i]=0 #把所有顶点设置成尚未遍历过 print('顶点%d=>' %i,end='') Head[i]=GraphLink() for j in range(20): if Data[j][0]==i: #如果起点和链表头相等,则把顶点加入链表 DataNum = Data[j][1] Head[i].insert(DataNum) Head[i].my_print() #打印图的邻接标内容 print('广度优先遍历的顶点:') #打印广度优先遍历的顶点 bfs(1) print()
e4ce1ea0a3a39c6b01044283ec4a1b13c228408b
Juaquigm/Pruebita
/Prueba.py
256
3.65625
4
print("Esto es una prueba para ver si funciona: ") input("Introduzca un numero: ") #Supongamos un ejemplo que esto es editado en la pagina web print("Esto es de la página web") #Esto esta hecho en el Visual Studio print("Esto es del editor visual Studio")
0cd98062fad1f4f8671a1ae40666a71cb4c546c0
tommparekh/Py.WebCrawler
/webcrawler.py
2,706
3.546875
4
#Create a web crawler example from Udacity course. import requests from bs4 import BeautifulSoup import time import urllib #Open an article start_url = "https://en.wikipedia.org/wiki/Special:Random" end_url = "https://en.wikipedia.org/wiki/Philosophy" def continue_crawl(search_history, target_url, max_step=25): #if the most recent article in the search_history is the target article the search should stop and the function should return False #If the list is more than 25 urls long, the function should return False #If the list has a cycle in it, the function should return False #otherwise the search should continue and the function should return True. if search_history[-1] == target_url: print("We've found the target article!") return False elif len(search_history) > max_step: print("The search has gone on suspiciously long, aborting search!") return False elif search_history[-1] in search_history[:-1]: print("We've arrived at an article we've already seen, aborting search!") return False else: return True #Find the first link in the article def find_first_link(url): # get the HTML from "url", use the requests library response = requests.get(url) html = response.text # feed the HTML into Beautiful Soup soup = BeautifulSoup(html, 'html.parser') # find the first link in the article #soup.find(id='mw-content-text').find(class_="mw-parser-output").p.a['href'] first_link = None content_div = soup.find(id="mw-content-text").find(class_="mw-parser-output") # Find the first anchor tag that's a direct child of a paragraph. # It's important to only look at direct children, because other types # of link, e.g. footnotes and pronunciation, could come before the # first link to an article. Those other link types aren't direct # children though, they're in divs of various classes. for element in content_div.find_all("p", recursive=False): if element.find("a", recursive=False): first_link = element.find("a", recursive=False).get('href') break # return the first link as a string, or return None if there is no link if not first_link: return first_link = urllib.parse.urljoin('https://en.wikipedia.org/', first_link) return first_link article_chain = [start_url] while continue_crawl(article_chain, end_url): # download html of last article in article_chain # find the first link in that html first_link = find_first_link(article_chain[-1]) print(first_link) if not first_link: # add the first link to article_chain print("We've arrived at an article with no links, aborting search!") break article_chain.append(first_link) # delay for about two seconds #btime.sleep(2)
d5162b2eeb4763a7b22da4ef3a79b50e95beff2e
ATLS1300-CoFo1/Examples
/FINAL-nextPiece.py
2,288
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 26 12:01:00 2020 @author: Dr. Z Keypress refresh for GENERATIVE ART GALLERIES When creating your art, this will allow a keystroke to be added in that will clear your screen. In the code following, you can generate the next piece. I recommend organizing your code so that each drawing is contained in a function Then, after every keypress, you call a specific function. =============== TO TEST THIS CODE =================== Select the window and hit the 'n' key to change the background color from the original light blue to white. """ import random from turtle import * #import the library of commands that you'd like to use #import winsound from pydub.playback import _play_with_simpleaudio as Play from pydub import AudioSegment #Create a panel to draw on. setup() panel = Screen() panel.clear() # "refreshes" the panel w = 600 # width of panel h = 600 # height of panel panel.setup(width=w, height=h) #600 x 600 is a decent size to work on. panel.setworldcoordinates(0, w, h, 0) panel.bgcolor('light blue') def close(): bye() def drawImg(): global panel panel.clear() panel.bgcolor('gray') circle = Turtle(shape='circle') colormode(255) red = [255,0,0] circle.color('black',tuple(red)) circle.up() circle.goto(100,100) for i in range(50): circle.stamp() circle.right(30) circle.fd(8) red[0] -= 5 if red[0]<0: red[0]=0 circle.color('black',tuple(red)) panel.delay(3000) panel.clear() #panel.onkey(panel.clear,'n') panel.onkey(close,'Escape') def clear(): panel.clear() panel.onkey(drawImg,'1') panel.onkey(close,'Escape') # Set a background color run = True # =============== Call your first drawing function here or draw your first artpiece here =============== #panel.onkey(panel.clear,'n') # the screen will clear when the assigned letter is pressed(here I put n) panel.onkey(drawImg,'1') # will animate # =============== Call your next function here or draw your next piece here ================= listen() # turn on listeners done() # this should be the last line of code! You can stop your code running by clicking the red x in the window.
2577468e47b8bb52274532b33afd097916490a3d
eunjungchoi/algorithm
/leetcode/most_liked/49_group_anagrams.py
1,160
3.984375
4
# Given an array of strings strs, group the anagrams together. You can return the answer in any order. # # An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. # # # # Example 1: # # Input: strs = ["eat","tea","tan","ate","nat","bat"] # Output: [["bat"],["nat","tan"],["ate","eat","tea"]] # Example 2: # # Input: strs = [""] # Output: [[""]] # Example 3: # # Input: strs = ["a"] # Output: [["a"]] # # # Constraints: # # 1 <= strs.length <= 104 # 0 <= strs[i].length <= 100 # strs[i] consists of lower-case English letters. import collections from typing import List class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: result = collections.defaultdict(list) for item in strs: result[''.join(sorted(item))].append(item) return result.values() # 47 / 47 test cases passed. # Status: Accepted # Runtime: 28 ms # Memory Usage: 13.8 MB # # Your runtime beats 96.32 % of python3 submissions. # Your memory usage beats 78.92 % of python3 submissions. # <파이썬 알고리즘 인터뷰> 참고.
897e78f9178aa37a0fd28ca166f1bc727c56588f
leohujx/leetCode
/397.py
889
3.890625
4
# coding:utf-8 # 397. Integer Replacement # https://leetcode.com/problems/integer-replacement/description/ ''' 在n向1的转变过程中,如果n为偶数,那一定是/2;当n为奇数的时候,n+1或者n-1,这两个都有可能. 所以我们用dfs来进行搜索,搜索过程中取n+1和n-1小的那个.注意用记忆化搜索,这样可以节省大量的时间. ''' class Solution(object): def integerReplacement(self, n): """ :type n: int :rtype: int """ check = {} def dfs(num): if num in check: return check[num] if num == 1: return 0 if num % 2 == 0: check[num] = dfs(num/2)+1 return check[num] check[num] = min(dfs(num+1)+1, dfs(num-1)+1) # 取小的那个方案 return check[num] return dfs(n)
96b16d3f976c5a87d55935b3da36cdd953aeada7
alexsks65536/Python-base
/lesson08/lesson8-1.py
1,490
3.625
4
''' 1. Написать функцию email_parse(<email_address>), которая при помощи регулярного выражения извлекает имя пользователя и почтовый домен из email адреса и возвращает их в виде словаря. Если адрес не валиден, выбросить исключение ValueError #>>> email_parse('someone@geekbrains.ru') {'username': 'someone', 'domain': 'geekbrains.ru'} #>>> email_parse('someone@geekbrainsru') Traceback (most recent call last): File "<stdin>", line 1, in <module> ... raise ValueError(msg) ValueError: wrong email: someone@geekbrainsru Примечание: подумайте о возможных ошибках в адресе и постарайтесь учесть их в регулярном выражении; имеет ли смысл в данном случае использовать функцию re.compile()? ''' import re class email_error(Exception): def __init__(self, text): self.txt = text email_list = ['whitesnake@yandex.ru', 'someone@geekbrainsru', 'someone @geekbrains.ru'] for email in email_list: try: if not re.findall(r'^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$', email): raise email_error("You give wrong e-mail!") except ValueError: print("Error type of value!") except email_error as mr: print(mr) else: em = re.split(r'@', email) address = {'username': em[0], 'domain': em[1]} print(address)
866697cbf17faa2752a36b29578f5d093fb8196b
wantwantwant/tutorial
/L3函数(重要)/作业2---4.py
417
4.0625
4
# 输出斐波拉切数列(1, 1, 2, 3, 5, 8, 13, 21, ...) print('1、','1、',end='') def fibs(num): print def fibs(num): result = [0, 1] for i in range(2, num): result.append(result[-2] + result[-1]) return result print(fibs(9)) def fibs(num): if num == 1: return 1 else: return fibs(num - 1) + fibs(num - 2) for i in range(10): print (fibs(i))
20bde4f3178844c32dc7521ce36dbd91eb7f6390
kristinhelps/Kal_Academy
/Homework_2_Classification_Challenge.py
8,614
3.84375
4
# Classification template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns # sklearn preprocessing for dealing with categorical variables from sklearn.preprocessing import LabelEncoder # Importing the dataset - only using dataset = pd.read_csv('application_train.csv') X = dataset.iloc[:, 2:11].values y = dataset.iloc[:, 1].values #Describing the Dataset print('Training data shape: ', dataset.shape) dataset.head() dataset.describe() dataset.columns #Training data shape: (307511, 122) #For this exercise, using Predictor Columns 'NAME_CONTRACT_TYPE', 'CODE_GENDER','FLAG_OWN_CAR', # 'FLAG_OWN_REALTY', 'CNT_CHILDREN', 'AMT_INCOME_TOTAL','AMT_CREDIT', #'AMT_ANNUITY','AMT_GOODS_PRICE' #Exploratory Data Analysis...following along from kaggle 'gentle intro' #Imbalance noted, more people paid their loans back than those who did not dataset['TARGET'].value_counts() dataset['TARGET'].astype(int).plot.hist(); # Function to calculate missing values by column# Funct def missing_values_table(df): # Total missing values mis_val = df.isnull().sum() # Percentage of missing values mis_val_percent = 100 * df.isnull().sum() / len(df) # Make a table with the results mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1) # Rename the columns mis_val_table_ren_columns = mis_val_table.rename( columns = {0 : 'Missing Values', 1 : '% of Total Values'}) # Sort the table by percentage of missing descending mis_val_table_ren_columns = mis_val_table_ren_columns[ mis_val_table_ren_columns.iloc[:,1] != 0].sort_values( '% of Total Values', ascending=False).round(1) # Print some summary information print ("Your selected dataframe has " + str(df.shape[1]) + " columns.\n" "There are " + str(mis_val_table_ren_columns.shape[0]) + " columns that have missing values.") # Return the dataframe with missing information return mis_val_table_ren_columns # Missing values statistics missing_values = missing_values_table(dataset.iloc[:, 2:11]) missing_values.head(20) #OUTPUT: Your selected dataframe has 9 columns. #There are 2 columns that have missing values. # Missing Values % of Total Values #AMT_GOODS_PRICE 278 0.1 #AMT_ANNUITY 12 0.0 #Column DataTypes, Number of each type of column b/c can only do ML on numbers dataset.iloc[:, 2:11].dtypes.value_counts() #Datatypes Output #object 4 #float64 4 #int64 1 # Number of unique classes in each object column dataset.iloc[:, 2:11].select_dtypes('object').apply(pd.Series.nunique, axis = 0) #Encoding Categorical Variables # Create a label encoder object le = LabelEncoder() le_count = 0 #New variable training_set b/c in loop at line 95 I'm modifying the training set training_set = dataset.iloc[:, 2:11] # Iterate through the columns for col in training_set: if training_set[col].dtype == 'object': # If 2 or fewer unique categories if len(list(training_set[col].unique())) <= 2: # Train on the training data le.fit(training_set[col]) # Transform both training and testing data training_set[col] = le.transform(training_set[col]) # Keep track of how many columns were label encoded le_count += 1 print('%d columns were label encoded.' % le_count) # 3 columns were label encoded #If I had NOT done label encoding and just used one-hot, then I would have #expanded the 4 object columns to 12 columns vs 6 columns # one-hot encoding of categorical variables training_set = pd.get_dummies(training_set) print('Training Features shape: ', training_set.shape) #Iterate through columns to describe the data and look for outliers #for col in training_set: # print(training_set[col].describe()) #for col in training_set: # (training_set[col].plot.hist()) # plt.xlabel(col) # plt.show() #NAME_CONTRACT_TYPE = SIGNIFICANTLY more Cash Loans than Revolving Loans #OWN_CAR = ROUGHLY 2/3 DO NOT OWN A CAR #OWN_REALTY = ROUGHLY2/3 DO OWN REAL ESTATE #CHILDRENT = MOST PEOPLE HAVE 0 OR 1, THERE IS AT LEAST ONE OUTLIER WITH 19... #INCOME_TOTAL = SEVERAL OUTLIERS MAKING $10M - $100M #AMT_CREDIT = MOST PEOPLE HAVE UNDER $100K OF CREDIT #AMT_ANNUITY = MOST PEOPLE HAVE UNDER $50K #AMT_GOODS_PRICE = ROUGHLY $100K #GENDER = ROUGHLY TWICE AS MANY FEMALES # Taking care of missing data from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0) imputer = imputer.fit(training_set) training_set = imputer.transform(training_set) #KERNEL_SVM - KILLED MY COMPUTER #RANDOM FOREST CLASSIFICATION # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(training_set, y, test_size = 0.25, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Fitting Random Forest Classification to the Training set from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0) classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) #CM RESULTS RANDOM FOREST - SEEMS TO DO THE BEST OUT OF THE 3 THAT I RAN #69444 1343 #5833 258 # Fitting Decision Tree Classification to the Training set *ENTROPY from sklearn.tree import DecisionTreeClassifier classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0) classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) #CM RESULTS DECISION TREE - ONLY SLIGHTLY WORSE THAN RANDOM FOREST #65850 4937 #5437 654 # Fitting Naive Bayes to the Training set from sklearn.naive_bayes import GaussianNB classifier = GaussianNB() classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) #CM RESULTS NAIVE BAYS - THIS IS TERRIBLE #581 70206 #20 6071 # Visualising the Training set results #KEEP GETTING THIS ERROR, DON'T KNOW HOW TO FIX #ValueError: Number of features of the model must match the input. Model n_features is 11 and input n_features is 2 """from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Random Forest Classification (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() # Visualising the Test set results from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Random Forest Classification (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()"""
3751e938ae0ebbfa7ced14dc001055f4feb9a7c0
boknowswiki/mytraning
/lintcode/python/1512_minimum_cost_to_hire_k_works.py
1,556
3.53125
4
#!/usr/bin/python -t # heap # 对每一组的quality和wage计算时薪,按照时薪排序。 # 对于合法的k个数,为了满足条件,每个人的工资都大于初始工资,且成比例,所以每个人的时薪一定是这k个人中最高的那个人的时薪(否则最高的人不满足初始工资)。 # 所以对每个人的时薪找k个quality和最小的且时薪低于这个人的即可。 # 利用优先队列即可完成上述操作。 import heapq class Solution: """ @param quality: an array @param wage: an array @param K: an integer @return: the least amount of money needed to form a paid group """ def mincostToHireWorkers(self, quality, wage, K): # Write your code here workers = sorted([float(w) / q, q] for w, q in zip(wage, quality)) res = float('inf') qsum = 0 heap = [] for r, q in workers: heapq.heappush(heap, -q) qsum += q if len(heap) > K: qsum += heapq.heappop(heap) if len(heap) == K: res = min(res, qsum * r) return res # Python, sort by wage quality ratio, then maintain k workers by removing the largest quality worker. # 可以刪掉quality最大的人的原因是,題目的條件一。選中的k個人裡面,每個人要支付的ratio是一樣的(最大的那個ratio),所以這k個人誰quality多就代表我要多quality的錢。踢掉quality最多的人來減少我的支出。Loop從小ratio到大ratio,記錄每個進來和離開的人的quality。
ccbd8516f1f473129b1ab6c749b45d8ab2df4c79
SkarletA/ejercicios
/raiz_digital.py
670
3.9375
4
""" Ejercicios 20.- Dado un número natural N, se calcula la raíz digital de N sumando los dígitos que lo componen. El proceso se repite sobre el nuevo número hasta que el resultado obtenido tiene un sólo dígito. Este último número es la raíz digital del número N. Ejemplo: 347 ->3 + 4 + 7 = 14 -> 1 + 4 -> 5 -> Raíz digital (347) = 5. Escribir un programa que calcule la raíz digital de un número. """ n= int(input("Escribir un numero natural: ")) while (n //10 != 0): acum=0 aux_n=n while (aux_n // 10 != 0): mod=aux_n%10 acum+=mod aux_n //= 10 acum+=aux_n n = acum print("La raiz digital es :".format(n))
0652955a435b72fbbe93a73e863ab309f1fa3c0a
sumitsk1/Old-Python-Codes
/guess the name and age.py
199
3.890625
4
name=input("Enter your name") age=int(input("How old you are")) if (name=="sumit") and 16<age<30: print("Welcome to you for 6 days holidays") else: print("Sorrry your not allowed")
6b0c5f93f58b93e425032dd64bc523de14a8f24b
DoxMeister/TileTraveller
/tile_traveller.py
2,296
3.96875
4
#Define the grid 3*3 def can_go(n,s,e,w): counter = 0 ret = "You can travel: " if n : ret += "(N) orth" counter += 1 if s: if counter == 1 or 2 or 3 or 4: ret += " or " ret += "(S) outh" counter += 1 if e: if counter == 1 or 2 or 3 or 4: ret += " or " ret += "(E) ast" counter += 1 if w: if counter == 1 or 2 or 3 or 4: ret += " or " ret += "(W) est" counter += 1 ret += "." return print(ret) def go_north(y): y += 1 return y def go_south(y): y -= 1 return y def go_east(x): x += 1 return x def go_west(x): x -= 1 return x y_grid = 1 x_grid = 1 n = "(N) orth" s = "(S) outh" e = "(E) ast" w = "(W) est" while True: if y_grid == 1 and x_grid == 1: can_go(1,0,0,0) elif y_grid == 2 and x_grid == 1: can_go(1,1,0,0) elif y_grid == 3 and x_grid == 1: can_go(0,1,1,0) elif y_grid == 1 and x_grid == 2: can_go(1,0,0,0) elif y_grid == 3 and x_grid == 2: can_go(0,0,1,1) elif y_grid == 1 and x_grid == 3: print("Victory!") break elif y_grid == 2 and x_grid == 3: can_go(1,1,0,0) elif y_grid == 3 and x_grid == 3: can_go(0,0,1,1) elif x_grid == 2 and y_grid == 2: can_go(0,1,0,1) direction = str(input("Direction: ")) if direction == "n" or direction == "N": y_grid = go_north(y_grid) elif direction == "s" or "S": y_grid = go_south(y_grid) elif direction == "e" or "E": x_grid = go_east(x_grid) elif direction == "w" or "W": x_grid = go_west(x_grid) print("Not a valid direction!") #direction = str(input("Direction: ")) print("(" + str(x_grid) + ", " + str(y_grid) + ")") #Starts in (1,1) #Displays the directions for which there are adjacent tiles that the player can travel to in each round #Enters the first letter for the direction player wants to go to. Capitalized or small #If the player enters invalid direction, print "Not a valid direction!" and allows the player to enter the direction again #Tile (3,1) is the victory location. When entered progra notifies player of their victory and quits running
cfd119ab152c7b50d87d2a5430bda810972523de
ikeshou/Kyoupuro_library_python
/src/mypkg/basic_algorithms/around_quick_sort.py
5,568
3.5
4
""" (参考) <Algorithm Introduction vol.1 p.24-35, p.140-152, 177-180> クイックソートテク関連の基本的な関数の詰め合わせ (命名は C++ STL algorithm による) randomized_select(seq, k, begin, end): O(n) E = seq[k] とする 特定の要素 E よりも小さい全ての要素が E よりも前になり、 E 以上の全ての要素がEよりも後になるように seq[begin:end] を並び替える (破壊、不安定) nth_element(seq, i, begin, end): O(n) randomized_select を用いて (seq[begin:end] に存在することがわかっている) i 番目の順序統計量を求める (i = 0, 1, ..., n-1) quick_sort(seq, begin, end): O(nlgn) randomized_select を用いて seq[begin:end] をソートする (破壊、不安定) """ import random from typing import TypeVar, Callable, List, Tuple, Union T = TypeVar('T') Num = Union[int, float] # verified @AOJ ALDS1_6_B # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_6_B&lang=ja def randomized_select(L: List[Num], pivot_ind: int, begin: int=-1, end: int=-1) -> int: """ pivot = L[pivot_ind] とする。 O(n) で 'pivot 未満の要素 ... pivot ... pivot 以上の要素' となるよう L を破壊的に並び替える。 最後に基準値の pivot がおさまった場所のインデックスを返す。 begin <= pivot_ind < end の要請はあるが、begin, end の指定により L[begin:end] に対象を絞り L[pivot_ind] 未満 / 以上に並べ替えることもできる。 Args: L (list) pivot_ind (int) begin, end (int): L の [begin, end) 半開区間を考える。デフォルトでは L[0:n] となる Returns: int: 最後に基準値の pivot がおさまった場所のインデックス Raises: IndexError: 0 <= begin <= pivot_ind < end <= len(L) でないとき Examples: >>> seq = [1, 9, 2, 7, 5, 6, 4, 8, 3, 0] >>> randomized_select(seq, 4) 5 >>> seq [1, 2, 0, 4, 3, 5, 7, 8, 9, 6] >>> randomized_select(seq, 3, begin=3, end=9) 4 >>> seq [1, 2, 0, 3, 4, 5, 7, 8, 9, 6] """ if begin == -1 and end == -1: begin, end = 0, len(L) if not begin <= pivot_ind < end <= len(L): raise IndexError(f"randomized_select(): indices should be 0 <= begin <= pivot_ind < end <= len(L). got pivot_ind={pivot_ind}, begin={begin}, end={end}.") # [begin]...[end] が対象範囲である end -= 1 pivot = L[pivot_ind] L[pivot_ind], L[end] = L[end], L[pivot_ind] # i: 確定済みのバッファ先頭。ループ開始時点で pivot 未満であると判明しているところの先端を指す。 i = begin - 1 # j: 斥候。ループ開始時にここより前は検査済となっている。 # begin ... end - 1 を動けば良い。(end は最初の swap の結果 pivot 自身がいるため探索しなくて良い) for j in range(begin, end): if L[j] <= pivot: i += 1 L[j], L[i] = L[i], L[j] L[i+1], L[end] = L[end], L[i+1] return i+1 def nth_element(L: List[Num], i: int, begin: int=-1, end: int=-1) -> Num: """ O(n) で randomized_select を用いて L の i 番目の順序統計量を求める (i = 0, 1, ..., n - 1) [begin, end) に i 番目の順序統計量が存在する Args: L (list) i (int): start from 0 begin, end (int): [begin, end) に i 番目の順序統計量が存在する Returns: int: i 番目の順序統計量 (i = 0, 1, ..., n - 1) Raises: IndexError: 0 <= begin <= i < end <= len(L) でないとき Examples: >>> seq = [1, 9, 2, 7, 5, 6, 4, 8, 3, 0] >>> nth_element(seq, 0) == sorted(seq)[0] True >>> nth_element(seq, 4) == sorted(seq)[4] True """ if begin == -1 and end == -1: begin, end = 0, len(L) if not 0 <= begin <= i < end <= len(L): raise IndexError(f"nth_element(): i should be 0 <= begin <= i < end <= len(L). got i={i}, begin={begin}, end={end}.") if end - begin == 1: return L[begin] # pivot_ind は begin ... end -1 から選ばれてほしい mid = randomized_select(L, random.randint(begin, end-1), begin, end) if mid == i: return L[mid] elif mid < i: return nth_element(L, i, begin=mid+1, end=end) else: return nth_element(L, i, begin=begin, end=mid) # verified @AOJ ALDS1_6_C # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_6_C&lang=ja def quick_sort(L: List[Num], begin: int, end: int) -> None: """ O(nlgn) で randomized_select を用いて L[begin:end] を 破壊的に不安定でクイックソートする Args: L (list) begin, end (int) Raises: IndexError: 0 <= begin <= end <= len(L) でないとき Examples: >>> seq = [3, 5, 2, 1, 0, 3] >>> quick_sort(seq, 0, 6) >>> seq [0, 1, 2, 3, 3, 5] """ if not 0 <= begin <= end <= len(L): raise IndexError(f"quick_sort(): begin and end should be 0 <= begin <= end <= len(L). got begin: {begin} end: {end}") if end - begin > 1: # pivot_ind は begin ... end -1 から選ばれてほしい mid = randomized_select(L, random.randint(begin, end - 1), begin, end) quick_sort(L, begin, mid) quick_sort(L, mid+1, end) if __name__ == "__main__": import doctest doctest.testmod()
e730b539643d37b303182e2f463cf6b9751d754b
Lstanislao/Proyecto-Indexing
/tables.py
3,809
3.640625
4
from funciones import pedirPelicula peliculas = [ ] titulos = [ ] codigos = [ ] def agregarPelicula(): global peliculas peli = pedirPelicula() peliculas.append(peli) index = peliculas.index(peli) titulo = peli[2].lower() codigo = peli[1] agregarTitulo(titulo, index) insertarCodigo(codigo, index) def agregarTitulo(titulo, index): global titulos print(titulos) palabras = titulo.split(" ") for palabra in palabras: if palabra != "": posicion = buscar(palabra, titulos) if posicion == False: insertarTitulo(palabra, index) else: indices = titulos[posicion][1] newIndices = [] print(indices) for indice in indices: newIndices.append(indice) newIndices.append(index) print(newIndices) titulos[posicion][1] = newIndices print('titulos: ', titulos) def ordenarTitulos(): global titulos titulos = sorted(titulos, key=lambda fila: fila[0]) def buscar(buscado, arreglo): izquierda = 0 derecha = len(arreglo) - 1 while izquierda <= derecha: mitad = (izquierda + derecha) // 2 elementoDelMedio = arreglo[mitad][0] if elementoDelMedio == buscado: return mitad if buscado < elementoDelMedio: derecha = mitad - 1 else: izquierda = mitad + 1 return False def insertarTitulo(newPalabra, index): global titulos # AQUI CREO QUE NO SE PUEDE HACER UN SOLO PROCEDDIMIENTO PARA INSERTAR TANTAO CODIGO COMO TITULO PORQUE NECESITAS MODIFICAR LA VARIABLE GLOBAL izquierda = 0 derecha = len(titulos) - 1 # medio = (izquierda + derecha) // 2 while izquierda <= derecha: mitad = (izquierda + derecha) // 2 elementoDelMedio = titulos[mitad][0] if elementoDelMedio == newPalabra: return mitad if newPalabra < elementoDelMedio: derecha = mitad - 1 else: izquierda = mitad + 1 # print('soy izquierda ', izquierda) # print('soy derecha ', derecha) # INSERTAR Y ACOMODAR LOS INDICES if izquierda >= len(titulos) or len(titulos) == 0: titulos.append([newPalabra, [index]]) else: temporal = titulos[izquierda] titulos[izquierda] = [newPalabra, [index]] # print(temporal) maxi = len(titulos) # print(maxi) # print(izquierda+1) print(izquierda, " TITULO ", derecha) for i in range((izquierda+1), maxi): aux = titulos[i] titulos[i] = temporal temporal = aux titulos.append(temporal) def insertarCodigo(newCodigo, index): global codigos izquierda = 0 derecha = len(codigos) - 1 while izquierda <= derecha: mitad = (izquierda + derecha) // 2 elementoDelMedio = codigos[mitad][0] if elementoDelMedio == newCodigo: return mitad if newCodigo < elementoDelMedio: derecha = mitad - 1 else: izquierda = mitad + 1 if izquierda >= len(codigos) or len(codigos) == 0: codigos.append([newCodigo, index]) else: temporal = codigos[izquierda] codigos[izquierda] = [newCodigo, index] print(izquierda, " CODIGO ", derecha) maxi = len(codigos) for i in range((izquierda), maxi): aux = codigos[i] codigos[i] = temporal temporal = aux codigos.append(temporal) print('codigos: ', codigos) ordenarTitulos() seguir = 1 while seguir != 0: agregarPelicula() print("peliculas: ", peliculas) seguir = int(input("si no desea seguir agregado coloque 0")) print(peliculas)
2b017f6f993a63460f63a6b1712df3ca648d8f81
SujeethJinesh/Computational-Physics-Python
/In Class/jan_19.py
189
4.0625
4
def ask_for_input(): odd = int(input("Enter an odd number: ")) even = int(input("Enter an even number: ")) if odd%2 == 1 and even%2 == 0: print "Nice job!" else: print "You suck."
1f09596ea5b2f7076f2e87d66086663f5ac847b3
Taburetkastol/PythonLabs
/Lab3/main.py
1,614
3.59375
4
# 4 задание def count(number): k = 0 for i in range(1, number): if number % i == 0: k = k + 1 return k def biggest_number(a, b): k = 0 l = list() m = list() for i in range(a, b - 1): if k < count(i): k = count(i) for i in range(a, b - 1): if count(i) == k: l.append(i) m.append(k) return list(zip(l, m)) a = int(input()) b = int(input()) print(biggest_number(a, b)) # 5 задание def unique(a): for i in range(0, len(a) - 1): for j in range(i + 1, len(a)): if int(a[i]) == int(a[j]): return False return True a = input().split(" ") print(unique(a)) # 6 задание def empty(*params): str = params[0] for i in (1, len(params)-1): str = set(params[i]) & set(str) if not str: return True else: return False a = input().split(" ") b = input().split(" ") c = input().split(" ") if empty(a, b, c) == True: print(“True”) else: print(“False”) # треугольник паскаля def current_row(n): a = [] for i in range(0, n): if i == 0 or i == n - 1: a.append(1) else: c_row = current_row(n - 1) a.append(c_row[i - 1] + c_row[i]) return a def pascal(n): a = [] for i in range(0, n): a.append(current_row(i + 1)) return a n = int(input()) l = pascal(n) for i in range(0, n): print(l[i])
87bc2075b57a6eba9f00321e7244f74e40365e42
AlvaroLopez-Jurado/python_template
/sample/strings_example.py
764
3.875
4
class StringsExamples(object): """A class to play with the strings""" @staticmethod def concat_strings(strings): if(len(strings)< 2 or len(strings)>10 ): raise TypeError("Maximo numero de strings 10 y minimo 2") for x in range(len(strings)): if(type(strings[x]) is not str): raise TypeError("Solo concatena strings") if(strings[x].replace(" ", "").isdigit()): raise TypeError("Solo concatena strings") if(len(strings[x])>10): raise TypeError("El tamano maximo de un string es 10") finalString = "" for x in range(len(strings)): finalString += strings[x] return finalString.replace(" ", "");
c0b88f692f1b8bd4bc5284e1c3015093e5ca7bdf
sanath777/Python
/perfectSquare.py
158
4
4
import math n=int(input("Enter a number")) a=int(math.sqrt(n)) if (a**2==n): print("Perfect Square") else: print("Not Perfect Square")
5185d78b2060db631367ddd66c3159e00d6e6609
DrDoobie/python
/python intro/calculator/calc.py
932
3.9375
4
result = float success = bool def mainFunc (): var1 = input("Input First Number: ") var2 = input("Input Second Number: ") calcType = input("What do you want to calculate for? ") if calcType != "sum" and calcType != "product" and calcType != "difference" and calcType != "quotient": print("Try using keywords; sum, product, difference or quotient.") success = 0 else: success = 1 if calcType == "sum": result = float(var1) + float(var2) if calcType == "product": result = float(var1) * float(var2) if calcType == "difference": result = float(var1) - float(var2) if calcType == "quotient": result = float(var1) / float(var2) if success == 1: print(result) retry() else: retry() def retry (): var3 = input("Try again? ") if var3 == "yes": mainFunc() else: exit() mainFunc()
e14b119af11e15de775b922d1c5ec9d43e6be7e1
MikeOcc/MyProjectEulerFiles
/Euler_4_157d.py
913
3.515625
4
# # Problem 157 # from time import time from math import floor from math import ceil from Functions import RetFact def diophantine(a,b,P,n): #10**n*b = a * (b*P - 10**n) # a = 10**n*b/(b*P - 10**n) return 10**n*( b + a)==a*b*P #for i in xrange(1,10): st = time() n= 1 a,b =0,0 N = 9 ctr = 0 for n in xrange(9,N+1): tenN = 10**n for P in xrange(1,2): #2*10**n+1): bmin = int((tenN*1./P)+1) if bmin==0:bmin=1 #print "bmax",bmax #print "P:",P,bmin # print for b in xrange(bmin,2*tenN+1): # if (b*P - tenN <= 0): # print "neg",b,P,tenN # continue #for a in xrange(1,b+1): a = tenN*b/(b*P - tenN) if a<b:continue if diophantine(a,b,P,n): ctr+=1 print ctr,P,tenN,")",b,a,":",RetFact(b),RetFact(a) #break print n,ctr print "Total for n<=",N,"is", ctr print "Process time is", time() - st
2cb69131a49cf7a7868f29a146ac59aa4ca6939b
BoredPotatoDev/PLD-40-Programs
/Exercise_17_Pie_Eating_Contest.py
122
3.609375
4
x = int(input("Input weight in pounds: ")) if x in range(30,250): print("Accepted!") else: print("Denied!")
dcba69a83322ce8d8ddc00b38c38fc493d56dc9e
Marciodm/check-bad-words
/check_file.py
659
3.84375
4
def read_file(): """Abre o arquivo .txt a ser verificado.""" with open(r'files\text_file.txt') as file: contents = file.read() # print(contents) check_file(contents) def check_file(text_check): """Abre o arquivo contendo as palavras a serem procuradas""" with open(r'files/bad_file.txt') as bad_words: contents = bad_words.read() contents = contents.split('\n') print(contents) for name in contents: if name in text_check: print(text_check.count(name), 'Bad words found.') print(name) else: print('Bad words not found.') break read_file()
bcf39cdcb5840be298dce57bf45fe6e44d7c7c04
insigh/Practical-ReinforcemntLearning
/windows/toutiao4/3.py
4,483
3.6875
4
""" 5 5 3 hello help high p a b h m f h e c p o i l l h b g h o n h x c m l """ # from collections import defaultdict # # # class Cell(): # def __init__(self, value): # self.value = value # self.visited = False # # def __str__(self): # return '{},{}'.format(self.value, self.visited) # # # class Solution: # def build_trie(self, words): # dictionary = {} # char_count = defaultdict(int) # for i, word in enumerate(words): # d = dictionary # for char in word: # if char not in d: # d[char] = {} # d = d[char] # d[1] = i # char_count[word[0]] += 1 # return dictionary, char_count # # def findWords(self, board, words): # """ # :type board: List[List[str]] # :type words: List[str] # :rtype: List[str] # """ # board_mem = defaultdict(list) # _board = [] # # words = list(set(words)) # nrow = len(board) # ncol = len(board[0]) # # preprocess board # i, j = 0, 0 # for i in range(nrow): # board_row = [] # for j in range(ncol): # board_mem[board[i][j]].append((i, j)) # board_row.append(Cell(board[i][j])) # _board.append(board_row) # trie_dic, char_count = self.build_trie(words) # # def find_valid_neighbors(coord, dic): # i, j = coord[0], coord[1] # neighbor_coords = [] # if i >= 1 and _board[i - 1][j].value in dic and not _board[i - 1][j].visited: # neighbor_coords.append((i - 1, j)) # if i < nrow - 1 and _board[i + 1][j].value in dic and not _board[i + 1][j].visited: # neighbor_coords.append((i + 1, j)) # if j >= 1 and _board[i][j - 1].value in dic and not _board[i][j - 1].visited: # neighbor_coords.append((i, j - 1)) # if j < ncol - 1 and _board[i][j + 1].value in dic and not _board[i][j + 1].visited: # neighbor_coords.append((i, j + 1)) # return neighbor_coords # # def recursive_func(dic, coord): # if 1 in dic: result.add(words[dic[1]]) # for (i, j) in find_valid_neighbors(coord, dic): # _board[i][j].visited = True # recursive_func(dic[_board[i][j].value], (i, j)) # _board[i][j].visited = False # # result = set() # for first_c in trie_dic.keys(): # prev_len = len(result) # for coord in board_mem[first_c]: # _board[coord[0]][coord[1]].visited = True # recursive_func(trie_dic[first_c], coord) # _board[coord[0]][coord[1]].visited = False # if len(result) - prev_len == char_count[first_c]: break # found all chars # return list(result) class Solution: def findWords(self, board, words): if not boards or not words: return [] tries = {} for word in words: d = tries for ch in word: if ch not in d: d[ch] = {} d = d[ch] d[1] = True # print(tries) M, N = len(board), len(board[0]) if not M * N: return [] self.res = [] for i in range(M): for j in range(N): self.dfs(board, tries, i, j, "") return self.res def dfs(self, board, tree, i, j, prefix): if 1 in tree and prefix not in self.res: self.res.append(prefix) if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or board[i][j] not in tree or board[i][j] == "*": return else: tmp = board[i][j] board[i][j] = "*" self.dfs(board, tree[tmp], i + 1, j, prefix + tmp) self.dfs(board, tree[tmp], i - 1, j, prefix + tmp) self.dfs(board, tree[tmp], i, j - 1, prefix + tmp) self.dfs(board, tree[tmp], i, j + 1, prefix + tmp) board[i][j] = tmp m, n, k = list(map(int, input().strip().split())) # print(m, n, k) words = list(input().strip().split()) # print(words) boards = [] for i in range(n): row = list(input().strip().split()) boards.append(row) # print(boards) res = Solution().findWords(boards, words) for item in res: print(item)
471937550451a925ca51bcba63acb172964c58ae
Yash-barot25/DataStructresInPython
/Sets/setchallenge.py
433
3.96875
4
text = input("Enter something:\n").upper() # text_char = list(text) # consonants = set() # # for i in text: # if i not in 'AEIOU ': # consonants.add(i) # print(sorted(text_char)) # print(sorted(consonants)) # set_value = set("a", "e", "i", "o", "u") set_value = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U", " "} input_text = set(text) final_set = input_text.difference(set_value) print(final_set)
e2a1b92f5aa9a8bb02bf9f2299e7c0ba11bb8e21
muralimohanreddy319/Competitive-Programming
/week4_exam/consecutive.py
431
3.59375
4
def consecutive(num): if(num==0): return 0 binary = bin(num)[2:].strip() # print binary if num < 0: limit = len('{0:b}'.format(num)) binary = ('{0:b}'.format(num + (1 << 32)))[-limit:] res = binary.split('1')[:-2] if(res==[]): return 0 return max(len(str)+1 for str in res) print consecutive(55) print consecutive(-5) print consecutive(0) print consecutive(12354) print consecutive(6) print consecutive(256)
1f930cf89f9e1574ed19affc18c499dacef5a3a1
gohan-1/speech-to-wave
/Documents/python itern/extra works/search/search.py
160
3.828125
4
n=raw_input("enter the whole string") b=raw_input("enter the word you want to search") l1=n.split() for i in range(len(l1)): if l1[i]==b: print i+1
30ba44ef2e9c7715e1f711f48c3e9e8cdc3ba689
ZacharyRanes/30-Days-Of-Python
/day_11/day11_exercises.py
662
3.796875
4
# Write a function which checks if all the items of the list are of the same data type. def same_type(list): last_type = type(list[0]) for i in list: if type(i) != last_type and type(i) is not None: return False last_type = type(i) return True print(same_type([3, 4, 5])) print(same_type([3, 4, 5.5])) # Write a function which check if provided variable is a valid python variable from keyword import iskeyword def valid_variable(item): return item.isidentifier() and not iskeyword(item) print(valid_variable('print')) print(valid_variable('2x')) print(valid_variable('type_good')) print(valid_variable('not'))
63a94d9cd97349533d038354d9398227cab3c8c5
homo-sapiens94/Bites_of_py
/158/int_list.py
790
3.5
4
from statistics import mean, median class IntList(list): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @property def mean(self): return mean(self) @property def median(self): return median(self) def _check_int(self, num): try: if type(num) == list: return [int(i) for i in num] return int(num) except(ValueError, TypeError): raise TypeError def append(self, num): num = self._check_int(num) super().append(num) def __add__(self, num): num = self._check_int(num) return super().__add__(num) def __iadd__(self, num): num = self._check_int(num) return super().__iadd__(num)
1ccc8629a29844fa51a231bb023f52910229949a
kfisc88-lsc-repos/chapter_8
/ch8_p3_kfischer.py
1,998
4.03125
4
""" Author: Kelley Fischer File: ch8_p3_kfischer.py This is a simple text editor that allows a user to open, create, edit, and save text documents. """ from breezypythongui import EasyFrame import tkinter.filedialog class TextEdit(EasyFrame): def __init__(self): EasyFrame.__init__(self, title = "Text Editor") # Create the menu bar menuBar = self.addMenuBar(row = 0, column = 0) # Create the "File" menu option and add menu items appMenu = menuBar.addMenu("File") appMenu.addMenuItem("New", self.newFile) appMenu.addMenuItem("Open", self.openFile) appMenu.addMenuItem("Save", self.saveFile) # Creates text area for document text self.outputArea = self.addTextArea("", row = 1, column = 0, columnspan = 10, width = 80, height = 15, wrap = "word") # Creates a new text file def newFile(self): self.setTitle("new document") self.outputArea.setText("") # Saves the current text file def saveFile(self): fList = [("Text files", "*.txt")] fileName = tkinter.filedialog.asksaveasfilename(parent = self, filetypes = fList) file = open(fileName, 'w') file.write(self.outputArea.getText()) file.close() self.setTitle(fileName) # Opens the open file dialog to open an existing file def openFile(self): """Pops up an open file dialog, and if a file is selected displays its text in the text area and its pathname in the title bar.""" fList = [("Text files", "*.txt")] fileName = tkinter.filedialog.askopenfilename(parent = self, filetypes = fList) if fileName != "": file = open(fileName, 'r') text = file.read() file.close() self.outputArea.setText(text) self.setTitle(fileName) def main(): """Instantiates and pops up the window.""" TextEdit().mainloop() if __name__ == "__main__": main()
0a1f063bb1b724432f477cc449e94d720001c050
lilaboc/leetcode
/2068.py
605
3.828125
4
# https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/ from collections import Counter class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: c1, c2 = Counter(word1), Counter(word2) cs = set(c1.keys()).union(set(c2.keys())) for i in cs: if abs(c1.get(i, 0) - c2.get(i, 0)) > 3: return False return True print(Solution().checkAlmostEquivalent("aaaa", "bccb")) print(Solution().checkAlmostEquivalent("abcdeef", "abaaacc")) print(Solution().checkAlmostEquivalent("cccddabba", "babababab"))
784e0806f5e102cc4efaa1ea9af16cd795cf43c3
yanyanrunninggithub/Leetcode-Python
/heap.py
3,763
3.703125
4
#minheap--->k largest, heapq is min heap #maxheap--->k smallest #703. Kth Largest Element in a Stream #approach1: using heapq class KthLargest(object): def __init__(self, k, nums): """ :type k: int :type nums: List[int] """ self.k = k self.heap = nums heapq.heapify(self.heap)#heapq is a minheap while len(self.heap) > k: heapq.heappop(self.heap) def add(self, val):#o(logK) """ :type val: int :rtype: int """ if len(self.heap)<self.k: heapq.heappush(self.heap,val) else: heapq.heappush(self.heap,val) heapq.heappop(self.heap) return self.heap[0] #approach 2: using list time O(nlogn) def __init__(self, k: int, nums: List[int]): self.k = k self.nums = nums self.min_heap = nums self.min_heap.sort() if len(self.min_heap)>k: self.min_heap.pop(0) def add(self, val: int) -> int: self.min_heap.append(val) self.min_heap.sort() if len(self.min_heap)>self.k: self.min_heap.pop(0) return self.min_heap[0] #20210622 amazon phone interview: get the kth star's name which its distance is kth smallest in the list #time complexity: O(k + (n-k)*Logk) def getKSmall(list): max_heap = [] for i in range(k): max_heap.append(list[i]) for j in range(k,len(list)): max_heap.sort().reverse()#create a max heap, heap[0] is the biggest if list[i]<max_heap[0]: max_heap.pop(0)#The time complexity of heap push/pop is o(logk)and we do it N - k times max_heap.append(list[i]) return max_heap[0] #347. Top K Frequent Elements #approach 1: map O(N)+o(NlogN) class Solution(object): def topKFrequent(self, nums, k): map = {} for i in range(len(nums)): if nums[i] not in map.keys(): map.update({nums[i]:nums.count(nums[i])}) ans = [] for num in dict(sorted(map.items(),key=lambda x:x[1],reverse=True)):#num is a key if k<=0: break ans.append(num) k -=1 return ans #approach 2:minheap o(N)+O(Nlogk) class Solution(object): def topKFrequent(self, nums, k): map = {} for i in range(len(nums)): if nums[i] not in map.keys(): map.update({nums[i]:nums.count(nums[i])}) return heapq.nlargest(k, map.keys(), key=map.get) #414. Third Maximum Number (distinct) def thirdMax(self, nums: List[int]) -> int: #min heap res = [] if len(nums)<3: return max(nums) for i in range(len(nums)): if nums[i] not in res:#check distinct or not if len(res)<3: res.append(nums[i]) elif len(res)==3 and nums[i]>res[0]:#using elif, in case of previous line append res.pop(0) res.append(nums[i]) res.sort() if len(res)<3: return res[-1] return res[0] #1046. Last Stone Weight #Aproach 2:maxheap using list: time O(nlogn) space o(1) def lastStoneWeight(self, stones: List[int]) -> int: #max-heap stones.sort() while len(stones)>=2: x1 = stones[-1] x2 = stones[-2] stones.pop() stones.pop() if x1!=x2: stones.append(x1-x2) stones.sort() if len(stones) == 1: return stones[0] else: return 0 #Aproach 2:minheap using heapq def lastStoneWeight(self, stones: List[int]) -> int: heap=[] for stone in stones: heapq.heappush(heap,-stone)#min-heap, but using its negative val, so the biggest digitive num is smallest negetive val while len(heap)>=2: x1 = heapq.heappop(heap) x2 = heapq.heappop(heap) if x1 != x2: heapq.heappush(heap,(x1-x2)) return -heap[-1] if heap else 0
655cc9466d07ed8746ecf6143226e52ba116200f
lnrd/testedogit
/dados.py
788
3.59375
4
lista = [1,2,3,4,5,6,7,8,9,10] dic1 = {"Jack":"Elasticidade", "Fiona": "Fogo", "Finn":"Heroi"} dic2 = {"Princesa Bubblegun":"Inteligencia", "Marceline": "Voo", "Jack":"Faz bons sanduiches"} dic1.update(dic2) #atualiza o dicionario print(dic1) #Verifica se os dicionarios compartilham copias em comum def mergeWithoutOverlap(dic1,dic2): novodict = dic1.copy() for key in dic2: if key in dic1: raise ValueError, "Os dois dicionarios compartilham chaves!" novodict[key] = dic2[key] return dic2 import copy listOne = [{"nome":"Joao", "cidade":"parnaiba"},1, "tomate", 3.0] listTwo = listOne[:] listThree = copy.deepcopy(listOne) listOne.append("culumin") listOne[0]["cidade"] = "Buriti dos Lopes, Piaui" print(listOne,listTwo, listThree) import os print(getcwd())
1303f42c28ac2f87d81c27c9574c66b34b07d0a2
buyi823/learn_python
/learn_python/loop.py
143
3.65625
4
names=['michael','kobe','james'] for name in names: print(name) sum = 0 for x in[1,2,3,4,5,6,7,8,9,10]: sum = sum+x print(sum)
a02aa6df9274c4a8270a8714148b9df5a6aab4f1
Vovchik22/Python_test
/carloop.py
576
3.765625
4
cars = 100 space_in_a_car = 4 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capasity = cars_driven * space_in_a_car average_passenger_per_car = passengers / cars_driven print ("There are", cars, "cars availeble") print ("There are only", drivers, "drivers available") print ("There will be", cars_not_driven, "empty cars today") print ("We can transport", carpool_capasity, "people today") print ("We have", passengers, "the carloop today") print ("we need to put about", average_passenger_per_car, "in each car")
436005b7fbec19aba89649bfc9ab5ae5adb03dd2
YaserMarey/algos_catalog
/dynamic_programming/minimum_number_of_modifications.py
1,777
3.671875
4
# Given strings s1 and s2, we need to transform s1 into s2 by deleting and inserting characters. # Write a function to calculate the count of the minimum number of deletion and insertion operations. # Solution: We can finding the length of the Longest common subsequence and subtracting that form the the total length # Longest common subsequence pattern def LCS(s1, s2): n1, n2 = len(s1), len(s2) dp = [[0 for _ in range(n2 + 1)] for _ in range(n1 + 1)] maxLength = 0 for i in range(1, n1 + 1): for j in range(1, n2 + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) maxLength = max(maxLength, dp[i][j]) return maxLength # TODO I have another slightly different implemention for LCS but it raises exception wiht this, FIX it def main(): s1 = "abc" s2 = "fbc" c1 = LCS(s1, s2) print("Minimum deletions needed: " + str(len(s1) - c1)) print("Minimum insertions needed: " + str(len(s2) - c1)) s1 = "abdca" s2 = "cbda" c1 = LCS(s1, s2) print("Minimum deletions needed: " + str(len(s1) - c1)) print("Minimum insertions needed: " + str(len(s2) - c1)) # s1 = "passport" s2 = "ppsspt" c1 = LCS(s1, s2) print("Minimum deletions needed: " + str(len(s1) - c1)) print("Minimum insertions needed: " + str(len(s2) - c1)) # print("Testcase 1 is {0} for array {1}, since it is calculated as {2} and it should be {3}" # .format('Pass' if BS(A, 0, len(A) - 1, 3) == brute_force(A, 3) else 'Fail', A, BS(A, 0, len(A) - 1, 3), # brute_force(A, 3))) if __name__ == '__main__': main()
cf29b7f50472f6f5a9229c7f2ac198041f2e1d47
rafaelmakaha/competition-programming
/codeforces/tep/contest/04contest/a.py
248
3.75
4
f = input() s = input() st = input() ans = "" for c in st: i = f.find(c.lower()) if c.isnumeric(): ans = ans + c elif c.isupper(): ans = ans + s[i].upper() else: ans = ans + s[i].lower() print(ans)