text
stringlengths
37
1.41M
""" See https://turing.cs.hbg.psu.edu/txn131/graphcoloring.html Examples of Execution: python3 GraphColoring.py -data=GraphColoring_1-fullins-3.json python3 GraphColoring.py -data=GraphColoring_1-fullins-3.json -variant=sum """ from pycsp3 import * n, edges, colorings, multiColorings = data # n is the number of nodes -- multi-coloring not taken into account for the moment colorings = colorings if colorings else [] # c[i] is the color assigned to the ith node c = VarArray(size=n, dom=range(n)) satisfy( [abs(c[i] - c[j]) >= d for (i, j, d) in edges], # nodes with preassigned colors [c[i] == colors[0] for (i, colors) in colorings if len(colors) == 1], # nodes with subsets of prefixed colors [c[i] in colors for (i, colors) in colorings if len(colors) > 1] ) if not variant(): minimize( # minimizing the greatest used color index (and, consequently, the number of colors) Maximum(c) ) elif variant("sum"): minimize( # minimizing the sum of colors assigned to nodes Sum(c) ) """ Comments 1) when d is 1, abs(x - y) >= d is automatically simplified into x != y """
""" My son came to me the other day and said, "Dad, I need help with a math problem." The problem went like this: - We're going out to dinner taking 1-6 grandparents, 1-10 parents and/or 1-40 children - Grandparents cost $3 for dinner, parents $2 and children $0.50 - There must be 20 total people at dinner and it must cost $20 How many grandparents, parents and children are going to dinner? Execution: python3 Dinner.py """ from pycsp3 import * # g is the number of grandparents g = Var(range(1, 7)) # p is the number of parents p = Var(range(1, 11)) # c is the number of children c = Var(range(1, 41)) satisfy( g * 6 + p * 2 + c * 1 == 40, g + p + c == 20 )
""" Consider two groups of men and women who must marry. Consider that each person has indicated a ranking for her/his possible spouses. The problem is to find a matching between the two groups such that the marriages are stable. A marriage between a man m and a woman w is stable iff: - whenever m prefers an other woman o to w, o prefers her husband to m - whenever w prefers an other man o to m, o prefers his wife to w In 1962, David Gale and Lloyd Shapley proved that, for any equal number n of men and women, it is always possible to make all marriages stable, with an algorithm running in O(n^2). Nevertheless, this problem remains interesting as it shows how a nice and compact model can be written. Execution: python3 StableMarriage.py -data=StableMarriage-example.json """ from pycsp3 import * w_rankings, m_rankings = data # ranking by women and men n = len(w_rankings) Men, Women = range(n), range(n) # wf[m] is the wife of the man m wf = VarArray(size=n, dom=Women) # hb[w] is the husband of the woman w hb = VarArray(size=n, dom=Men) satisfy( # spouses must match Channel(wf, hb), # whenever m prefers an other woman o to w, o prefers her husband to m [(m_rankings[m][o] >= m_rankings[m][wf[m]]) | (w_rankings[o][hb[o]] < w_rankings[o][m]) for m in Men for o in Women], # whenever w prefers an other man o to m, o prefers his wife to w [(w_rankings[w][o] >= w_rankings[w, hb[w]]) | (m_rankings[o][wf[o]] < m_rankings[o][w]) for w in Women for o in Men] ) """ Comments 1) one could add two redundant constraints AllDifferent on wf and hb 2) one could replace Channel(wf, hb) with: # each man is the husband of his wife [hb[wf[m]] == m for m in Men], # each woman is the wife of her husband [wf[hb[w]] == w for w in Women], 3) global constraints involved in general expressions are externalized by introducing auxiliary variables. By using the compiler option, -useMeta, this is no more the case but the generated instance is no more in the perimeter of XCSP3-core """
""" Problem 110 on CSPLib Examples of Execution: python3 PeacableArmies.py -data=10 -variant=m1 python3 PeacableArmies.py -data=10 -variant=m2 """ from pycsp3 import * n = data or 6 if variant("m1"): def less_equal(i1, j1, i2, j2): if (i1, j1) == (i2, j2): return b[i1][j1] + w[i1][j1] <= 1 if i1 < i2 or (i1 == i2 and j1 < j2): if i1 == i2 or j1 == j2 or abs(i1 - i2) == abs(j1 - j2): # maybe we can simplify something here return b[i1][j1] + w[i2][j2] <= 1, w[i1][j1] + b[i2][j2] <= 1 # b[i][j] is 1 if a black queen is in the cell at row i and column j b = VarArray(size=[n, n], dom={0, 1}) # w[i][j] is 1 if a white queen is in the cell at row i and column j w = VarArray(size=[n, n], dom={0, 1}) satisfy( # no two opponent queens can attack each other [less_equal(i1, j1, i2, j2) for (i1, j1, i2, j2) in product(range(n), repeat=4)], # ensuring the same numbers of black and white queens Sum(b) == Sum(w) ) maximize( # maximizing the number of black queens (and consequently, the size of the armies) Sum(b) ) if variant("m2"): def different(i1, j1, i2, j2): if i1 < i2 or (i1 == i2 and j1 < j2): if i1 == i2 or j1 == j2 or abs(i1 - i2) == abs(j1 - j2): return x[i1][j1] + x[i2][j2] != 3 # x[i][j] is 1 (resp., 2), if a black (resp., white) queen is in the cell at row i and column j. It is 0 otherwise. x = VarArray(size=[n, n], dom={0, 1, 2}) # nb is the number of black queens nb = Var(dom=range(n * n // 2)) # nw is the number of white queens nw = Var(dom=range(n * n // 2)) satisfy( # no two opponent queens can attack each other [different(i1, j1, i2, j2) for (i1, j1, i2, j2) in product(range(n), repeat=4)], # counting the number of black queens Count(x, value=1) == nb, # counting the number of white queens Count(x, value=2) == nw, # ensuring equal-sized armies nb == nw ) maximize( # maximizing the number of black queens (and consequently, the size of the armies) nb )
""" See QAPLib and https://en.wikipedia.org/wiki/Quadratic_assignment_problem Example of Execution: python3 QuadraticAssignment.py -data=QuadraticAssignment_qap.json python3 QuadraticAssignment.py -data=QuadraticAssignment_example.txt -dataparser=QuadraticAssignment_Parser.py """ from pycsp3 import * weights, distances = data # facility weights and location distances all_distances = {d for row in distances for d in row} n = len(weights) table = {(i, j, distances[i][j]) for i in range(n) for j in range(n) if i != j} # x[i] is the location assigned to the ith facility x = VarArray(size=n, dom=range(n)) # d[i][j] is the distance between the locations assigned to the ith and jth facilities d = VarArray(size=[n, n], dom=lambda i, j: all_distances if i < j and weights[i][j] != 0 else None) satisfy( # all locations must be different AllDifferent(x), # computing the distances [(x[i], x[j], d[i][j]) in table for i, j in combinations(range(n), 2) if weights[i][j] != 0] ) minimize( # minimizing summed up distances multiplied by flows d * weights ) """ Comments 1) d * weights is possible because d is of type 'ListVar' and because None values (and associated coeffs) will be discarded 2) weights * d is also possible because weights is of type 'ListInt' and because None values (and associated coeffs) will be discarded 3) one can also write of course: Sum(d[i][j] * weights[i][j] for i, j in combinations(range(n), 2) if weights[i][j] != 0) 4) the model is only valid for symmetric instances (the obtained bound must then be multiplied by two) TODO a more general model (for non systematically symmetric instances) """
""" Dad wants one-cent, two-cent, three-cent, five-cent, and ten-cent stamps. He said to get four each of two sorts and three each of the others, but I've forgotten which. He gave me exactly enough to buy them; just these dimes." How many stamps of each type does Dad want? A dime is worth ten cents. -- J.A.H. Hunter Execution: python3 Dimes.py """ from pycsp3 import * # x is the number of dimes x = Var(range(26)) # 26 is a safe upper bound # s[i] is the number of stamps of value 1, 2, 3, 5 and 10 according to i s = VarArray(size=5, dom={3, 4}) satisfy( s * [1, 2, 3, 5, 10] == x * 10 ) """ Comments 1) [1, 2, 3, 5, 10] * s cannot work (because the list of integers if not built from cp_array) one should write: cp_array(1, 2, 3, 5, 10) * s 2) there are two solutions """
""" Given a edge-weighted directed graph with possibly many cycles, the task is to find an acyclic sub-graph of maximal weight. Examples of Execution: python3 GraphMaxAcyclic.py -data=GraphMaxAcyclic_example.json python3 GraphMaxAcyclic.py -data=GraphMaxAcyclic_example.json -variant=cnt python3 GraphMaxAcyclic.py -data=GraphMaxAcyclic_example.txt -dataparser=GraphMaxAcyclic_Parser.py """ from pycsp3 import * n, arcs = data valid_arcs = [(i, j) for i in range(n) for j in range(n) if i != j and arcs[i][j] != 0] valid_numbers = [len([(i, j) for i in range(n) if (i, j) in valid_arcs]) for j in range(n)] # x[i] is the number associated with the ith node; arcs are only possible from greater to lower numbers (nodes) x = VarArray(size=n, dom=range(n)) # a[i][j] is 1 iff the arc from i to j is selected a = VarArray(size=[n, n], dom=lambda i, j: {0, 1} if (i, j) in valid_arcs else None) satisfy( # different numbers must be associated to nodes AllDifferent(x) ) if not variant(): satisfy( # ensuring acyclicity iff(x[i] > x[j], a[i][j] == 1) for (i, j) in valid_arcs ) elif variant("cnt"): satisfy( # ensuring acyclicity [imply(x[i] <= x[j], a[i][j] == 0) for (i, j) in valid_arcs], [Count(a[:, j], value=1) <= 3 for j in range(n) if valid_numbers[j] > 3] ) maximize( # maximising the summed weight of selected arcs Sum(a[i][j] * arcs[i][j] for (i, j) in valid_arcs) ) """ Comments 1) a possible variant "smart ? elif variant("smart"): # c[i][j] is the cost of the link between i and j (whatever the direction) c = varArray(size=[n, n], dom=lambda i, j: {arcs[i][j], arcs[j][i]}, when=lambda i, j: (arcs[i][j] != 0 or arcs[j][i] != 0) and i < j) ... TODO """
''' Task: 1. Open a page http://SunInJuly.github.io/execute_script.html. 2. Read the value for the variable x. 3. Calculate the mathematical function of x. 4. Scroll down the page. 5. Enter the answer in the text field. 6. Select the checkbox "I'm the robot". 7. Switch the radiobutton "Robots rule!". 8. Click on the "Submit" button. ''' from selenium import webdriver import math import time try: browser = webdriver.Chrome() browser.get('http://SunInJuly.github.io/execute_script.html') x_text = browser.find_element_by_id('input_value') x = int(x_text.text) result = math.log((abs(12*math.sin(x)))) input = browser.find_element_by_tag_name("input") browser.execute_script("return arguments[0].scrollIntoView(true);", input) input.send_keys(str(result)) option1 = browser.find_element_by_css_selector("[for='robotCheckbox']") option1.click() option2 = browser.find_element_by_css_selector("[for='robotsRule']") option2.click() button = browser.find_element_by_css_selector('.btn') button.click() finally: time.sleep(30) browser.quit()
num1 = 10 num2 = 20 print(num1 + num2) for i in range(15) print(i) print("c罗牛逼') jdfj dfdsd s dd dfsd ds sdf sfd
# --> Write a program to count the number of even and odd numbers from a series of numbers. # -> Sample : numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # -> Number of even numbers: 5 # -> Number of odd numbers: 4 # Input Format # 4 1 2 3 4 # Output Format # 2 -> even count # 2 -> odd count n=int(input()) even=[] odd=[] for i in range(0,n): num=int(input()) if(num%2==0): even.append(num) else: odd.append(num) print(len(even)) print(len(odd))
user = input('请输入用户名: ') if user == 'zyz': print('hello, %s' % user) elif user == 'zzz': print('hi, %s' % user) else: print('您不在我们的系统中,请先注册!同意扣1,不同意扣2') if int(input())==1: print('注册连接为:xxxx.xx') else: print("一边玩去")
import sys from cs50 import get_string # Check user if user provided exactly one argument if len(sys.argv) == 1: print("You did not enter an argument for the encryption key.") print("Please restart the program with one non negative integer in the command-line-argument.") elif len(sys.argv) > 2: print("You did enter more than one argument for the encryption key.") print("Please restart the program with one non negative integer in the command-line-argument.") # declare key variable as an int from string provided as command-line-argument key = int(sys.argv[1]) # prompt user for plaintext string plain = get_string("plaintext: ") # print ciphertext print("ciphertext: ", end="") for char in plain: # check vor uppercase letter if char.isupper(): print("{}".format(chr((ord(char) - ord("A") + key) % 26 + ord("A"))), end="") # check vor uppercase letter elif char.islower(): print("{}".format(chr((ord(char) - ord("a") + key) % 26 + ord("a"))), end="") # print all other input else: print("{}".format(char), end="") print()
#magic methods - implement operator overloading #special methods - dunder e.g. __init__ , when creating class objects #BROKEN CODE def __repr__ (self): #unambigous representation of object #debugging and logging for developers def __str__ (self): #readable representation to end User ############################################ Example ############################################ def__repr__(self): #{} are placeholders return "Employee('{}','{}',{})".format(self.first, self.last, self.pay) #sring that prints object def __str__ (self): #when using method, have () return '{}-{}'.format(self.fullname(),self.last) ###################################################### print (repr(emp_1)) === print(emp_1.__repr__()) print (str(emp_1)) === print(emp_1.__str__()) ###################################################### ################### ######__add__###### Emulating Numeric Types ################### print(1+2) === print(int.__add__(1,2)) def __add__(self.other): return self.pay + other.play print(emp_1 + emp_2) ################### ######__len__###### Emulating Numeric Types ################### print(len('test')) === print('test'.__len__()) def __len__(self): return len (self.fullname()) print(len(emp_1)) ###################################################### return NotImplemented #in def #Not an error, falls back on other objects #becasue other objects may how know to handle this, else error
from functional import Transform t = "Expected:{} Given:{} Test:{}" def run_map(): input_list = [1, 2, 3, 4] expected_output = ['1', '2', '3', '4'] print_result(expected_output, Transform.map(input_list, lambda x: str(x))) input_list = [1, 2, 3, 4] expected_output = ['1', '4', '9', '16'] print_result(expected_output, Transform.map(input_list, lambda x: str(x ** 2))) def run_filter(): input_list = [i for i in range(100)] expected_output = [i for i in range(0, 100, 3)] print_result(expected_output, Transform.filter(input_list, lambda x: x % 3 == 0)) input_list = [i for i in range(20)] expected_output = [0, 1, 2, 3, 5, 8, 13] print_result(expected_output, Transform.filter(input_list, lambda x: x in [0, 1, 2, 3, 5, 8, 13])) def print_result(expected_output, output_object): print(t.format(format_list(expected_output), format_list(output_object), expected_output == output_object)) def format_list(l: list): if type(l) is int: return l if len(l) > 5: text = str(l[:2]) + str(l[-2:]) text = text.replace('[', '').replace(']', '...', 1) return '[' + text return str(l) class Obj: def __init__(self, name): self.name = name if __name__ == "__main__": # run_map() run_filter() pass
#namedtuple are also similiar to tuple and are immutable Point =namedtuple('Point',list('abcd')) new=Point(1,5,1,6) print (type(new),new) #printing fields in namedtuple print (new._fields) #converting namedtuple to ordereddict print (new._asdict()) #new._replace to replace the values in namedtuple print (new._replace(d=78)) #new namedtuple color=namedtuple('color','red green blue') print (color._fields) ##merging to namedtuples pixel=namedtuple('pixel',color._fields+new._fields) new_pixel=pixel(1,5,1,2,0,0,255) print (new_pixel) ##dictionary to namedtuple dict={'a':5,'b':8,'c':1,'d':6} tup=Point(**dict) ## namedtuple with classes class point(namedtuple('point','x y')): @property def hypot(self): return (self.x**2+self.y**2)**.5 def __str__(self): return "Point x = %f y = %f z = %f "%(self.x,self.y,self.hypot) print (point(3.0,4.0));
import random; import time; y=time.time(); class SnakesLadders: p1,p2,k,counter=0,0,0,0; def __init__(self): self.Ladders=Ladders={2:38,7:14,8:31,15:26,21:42,28:84,36:44,51:67,71:91,78:98,87:94} self.Snakes=Snakes={16:6,46:25,49:11,62:19,64:60,74:53,89:68,92:88,95:75,99:80}; def game_over(self,player): return "Player %d Wins!."%player; def end_of_game(self,x): if x>100: x=100-(x-100); return x; def play(self,die1,die2): self.die1,self.die2=die1,die2; self.k=self.k+1; if self.k%2==1: print self.p1,die1,die2; self.p1+=die1+die2; if self.p1>100: self.p1=self.end_of_game(self.p1); if self.p1 in self.Ladders: self.p1=self.Ladders[self.p1]; elif self.p1 in self.Snakes: self.p1=self.Snakes[self.p1]; if self.p1==100: self.game_over(1); exit(1); if die1==die2: self.k=self.k-1; return "Player 1 is on square %d"%self.p1; if self.k%2==0: print self.p2,die1,die2; self.p2+=die1+die2; if self.p2>100: self.p2=self.end_of_game(self.p2); if self.p2 in self.Ladders: self.p2=self.Ladders[self.p2]; elif self.p2 in self.Snakes: self.p2=self.Snakes[self.p2]; if self.p2==100: self.game_over(2); exit(1); if die1==die2: self.k=self.k-1; return "Player 2 is on square %d"%self.p2;
def clasificador(): num=input ("dime un numero") if num%2==0: if num%3==0: print "etiqueta verde" else:print "etiqueta roja" else: if num%3==0: print "etiqueta amarilla" else: print"negro" clasificador()
#se pide un num obtener x pantalla la suma de digitos del numero def suma(): num=input('dime un num') cadena=str(num) longi=len(cadena) suma=0 for i in range(0,longi,1): suma=suma+int(cadena[i:i+1]) print suma suma()
# How many seconds in 42 minutes and 42 seconds ans1 = 42*60+42 print('There are {0} seconds in {1}'.format(ans1,'42 minutes and 42 seconds')) # How many miles are there in 10 kilometers? 1 mi = 1.61 km ans2 = 10/1.61 print('There are {0:.3f} miles in {1}'.format(ans2, '10 kilometers')) # If you run 10 km in 42 min 42 seconds what is your avg pace? ansmeter = (10/ans1)*1000 ansmile = ans2/ans1 print('Your average speed was {0:.3f} meters per second, or {1:.5f} miles per second'.format(ansmeter,ansmile)) # What is the volume of a sphere with radius 5? pi=3.14159 r = 5 vol = r**3*pi*4/3 print('The volume of a sphere with radius {0} is {1:.2f}'.format(r,vol)) # 24.95$ per book, book stores get a 40% discount. Shipping costs 3$ for the first copy and 0.75$ for each additional copy. What is the wholesale cost for 60 copies? ncopies = 60 pricebook = 24.95 discount = 0.40 firstship = 3 shippingplus = 0.75 wholesale = ncopies*(24.95*discount)+(ncopies-1)*shippingplus+firstship print('The wholesale cost of {0} books at a {1:.0f}% discount is ${2:.2f}'.format(ncopies,discount*100,wholesale)) # Easy pace = 8:15 per mile, Tempo pace = 7:12 per mile, you leave at 6:52am, when do you get home? 1 mile easy, 3 miles tempo, 1 mile easy amtime = 0 easypace = 8*60+15 tempopace = 7*60+12 morningrunlength = 2*easypace+3*tempopace morningtime = 6*60*60 + 52*60 combinedtime = (morningrunlength+morningtime)/60 while combinedtime/60 > 1: combinedtime = combinedtime-60 amtime +=1 print('If you leave at 6:52am, you will return at {0}:{1:.0f}am'.format(amtime,combinedtime)) #print a grid shape using by making a function def printbox(rows,columns): rows = rows*5 columns = columns*5 i = 0 j = 0 while i < rows+1: if i%5 == 0: if j%5 == 0: if j == columns: print('+') i+=1 j=0 continue else: print('+', end=' ') else: print('-', end=' ') else: if j%5 == 0: if j == columns: print('|') i+=1 j=0 continue else: print('|', end=' ') else: print(' ', end=' ') j+=1 printbox(2,10)
# Iteration # 7-1 # Square roots with Newton's method import math def sqroot(a,x): epsilon = 0.0001 y = (x+a/x)/2 if abs(x-y) < epsilon: return y else: x = y return sqroot(a,x) def test_square_root(): print('') dash = '-'*42 for x in range(10): if x == 0: print(dash, '\n{:^5s}{:^12s}{:^15s}{:^10s}'.format('a','mysqrt(a)','math.sqrt(a)','diff')) print(dash) else: a=sqroot(x,x/2) b=math.sqrt(x) c=abs(sqroot(x,x/2)-math.sqrt(x)) print('{:^5d}{:^10f}{:^17f}{:^10f}'.format(x,a,b,c),) print(dash) test_square_root() ''' old code - learned how to do columns above # # for x in range(25): # sq = x # diff = abs(sqroot(sq,5)-math.sqrt(sq)) # print("The square root of {0} is approximately {1:.4f} according to my function, with a diff of {2} from math.sqrt()".format(sq,sqroot(sq,5),diff)) ''' # 7-2 # repeating eval until user types 'done' def eval_loop(done): while done != "done": evalme = input("What would you like to evaluate? ") print(eval(evalme)) done = input("Type done to quit, or press enter: ") if done == 'done': return evalme # print(eval_loop('')) # 7-3 # Srinivasa Ramanujan 1/pi def calculatePi(n, lastvalue): epsilon = 10**-323 if n == 0: print('ran n=0') lastvalue = 2*math.sqrt(2)*1103/9801 print(lastvalue) return calculatePi(n+1,lastvalue) elif abs(1/math.pi-lastvalue) < epsilon: print('found inverse pi on k = {0}, or {1} steps'.format(n,n+1)) return 1/lastvalue else: lastvalue = lastvalue + ((2*math.sqrt(2))/9801)*((math.factorial(4*n))*(1103+26390*n))/((math.factorial(n)**4)*396**(4*n)) print(lastvalue,n) return calculatePi(n+1,lastvalue) print(calculatePi(0,0)) # Incredibly accurate inverse pi algorithim. to 10^-323 at 4 steps
for case in range(int(input())): R, str = input().split() alphanumeric = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\$%*+-./:" P = "" for i in str: if i not in alphanumeric: continue P += i*int(R) print(P)
word = input() chroa = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="] count = 0 index = 0 check = False while index<len(word): check = False for i in chroa: if word[index:index+3].find(i) != -1: count += 1 index = index+len(i) check = True break if check == False: count += 1 index += 1 print(count)
# Priority Queue by deque # 1 1 9 1 1 1 # 4 2 3 1 for case in range(int(input())): N, M = map(int, input().split()) print_list = list(map(int, input().split())) target = print_list[M] print_order = list() for i in range(len(print_list)): if print_list[i] == while q: while max(q) != q[0]: q.append(q[0]) q.pop(1) order.append(q.pop(1))
word = input() delay = 0 for i in word: if i == 'S': delay += 8 continue elif (ord(i)-ord('A')) >= 19 and (ord(i)-ord('A')) <= 21: delay += 9 continue elif (ord(i)-ord('A')) >= 22 and (ord(i)-ord('A')) <= 25: delay += 10 continue delay += int((ord(i)-ord('A'))/3.0)+3 print(delay)
S = input() alpha = "abcdefghijklmnopqrstuvwxyz" for a in alpha: print(S.find(a), end=' ')
class FibonacciNode: degree = 0 p = None child = None mark = False left = None right = None def __init__(self, k): self.key = k def __iter__(self): """ generate a list of children of the node for iteration """ self.children = [] self.index = 0 if self.child is not None: child = self.child while True: self.children.append(child) if child != self.child.left: child = child.right else: break return self def next(self): if self.index < len(self.children): self.index = self.index + 1 return self.children[self.index - 1] else: raise StopIteration def insert(self, x): """ insert x to the left of node :param x: :return: """ x.left = self.left x.right = self self.left.right = x self.left = x def concatenate(self, x): """ concatenate two lists represented by the node and x, x mustn't be None :param x: :return: """ self.left.right = x.right x.right.left = self.left self.left = x x.right = self def remove(self): self.left.right = self.right self.right.left = self.left def add_child(self, y): self.degree = self.degree + 1 y.mark = False y.p = self if self.child is None: self.child = y y.left = y y.right = y else: self.child.insert(y) print("y.left.key = {}, y.right.key = {}".format(y.left.key, y.right.key)) def remove_child(self, y): self.degree = self.degree - 1 if y.right == y: self.child = None elif y == self.child: self.child = y.left y.remove() else: y.remove() class FibonacciHeap: def __init__(self): self.n = 0 self.minimum = None def __iter__(self): """ generate a list of children of the node for iteration :return: """ self.root_list = [] self.index = 0 if self.minimum is not None: root = self.minimum while True: self.root_list.append(root) if root != self.minimum.left: root = root.right else: break return self def next(self): if self.index < len(self.root_list): self.index = self.index + 1 return self.root_list[self.index - 1] else: raise StopIteration def __repr__(self): s = '' x = self.minimum if x is not None: while True: s = s + '\t' + str(x.key) if x == self.minimum.left: break else: x = x.right return s else: return '' def insert(self, x): """ insert the node x into the root list of fibonacci heap :param x: :return: """ x.p = None if self.minimum is None: self.minimum = x x.left = x x.right = x else: self.minimum.insert(x) if x.key < self.minimum.key: self.minimum = x self.n = self.n + 1 def minimum(self): return self.minimum def union(self, h): cat = FibonacciHeap() if self.minimum is None: return h elif h.minimum is None: return self else: self.minimum.concatenate(h.minimum) if self.minimum.key <= h.minimum.key: cat.minimum = self.minimum else: cat.minimum = h.minimum cat.n = self.n + h.n return cat def extract_min(self): z = self.minimum if z is not None: for child in z: self.insert(child) z.remove() if z == z.right: self.minimum = None else: self.minimum = z.right self.consolidate() self.n = self.n - 1 return z def consolidate(self): D = self.n // 2 A = [None] * (D + 1) left = self.minimum.left w = self.minimum for w in self: x = w d = x.degree print('w.key = {}'.format(w.key)) print('w.degree = {}'.format(w.degree)) while A[d] is not None: y = A[d] if x.key > y.key: x, y = y, x self.link(y, x) A[d] = None d = d + 1 A[d] = x self.minimum = None for i in A: if i is not None: self.insert(i) @staticmethod def link(y, x): y.remove() x.add_child(y) def decrease_key(self, x, k): if k > x.key: print("new key is greater than current key") return x.key = k y = x.p if y is not None and x.key < y.key: self.cut(x, y) self.cascading_cut(y) if x.key < self.minimum.key: self.minimum = x def cut(self, x, y): y.remove_child(x) x.mark = False self.insert(x) def cascading_cut(self, y): z = y.p if z is not None: if y.mark is False: y.mark = True else: self.cut(y, z) self.cascading_cut(z) def delete(self, x): self.decrease_key(x, float("-Inf")) self.extract_min()
from typing import Any, Optional class LinkedListNode: def __init__(self, key: Any): self.key: Any = key self.prev: Optional[LinkedListNode] = None self.next: Optional[LinkedListNode] = None class LinkedList: def __init__(self, key=None): self.head: Optional[LinkedListNode] = None self.size: int = 0 self.key = key def empty(self) -> bool: return self.size == 0 def search(self, key: Any) -> Optional[LinkedListNode]: node = self.head while node and node.key != key: node = node.next return node def insert(self, node: LinkedListNode) -> None: self.size = self.size + 1 node.next = self.head if self.head: self.head.prev = node self.head = node node.prev = None def delete(self, node: LinkedListNode) -> None: self.size = self.size - 1 if node.prev: node.prev.next = node.next else: self.head = node.next if node.next: node.next.prev = node.prev def extract(self, node: LinkedListNode) -> LinkedListNode: self.delete(node) return node
#!/usr/bin/env python def comparable(a, b, x): """ Given two segments a and b that are comparable at x, determine whether a is above b or not. Assume that neither segment is vertical """ p1 = a[0] p2 = a[1] p3 = b[0] p4 = b[1] x4 = p4[0] x3 = p3[0] v1 = (p2[0] - p1[0], p2[1] - p1[1]) v2 = ( (x4 - x3) * (p2[0] - p4[0]) + (x4 - x) * (p4[0] - p3[0]), (x4 - x3) * (p2[1] - p4[1]) + (x4 - x) * (p4[1] - p3[1])) result = v1[0] * v2[1] - v2[0] * v1[1] if result == 0: print("a intersects b at the vertical line") elif result > 0: print("a is above b") else: print("b is above a")
#!/usr/bin/env python # coding=utf-8 def three_sum(array): """ Given an array `array` of n integers, find one triplet in the array which gives the sum of zero. `array` must be in increasing order """ n = len(array) for i in range(n - 2): j = i + 1 k = n - 1 while k >= j: if array[i] + array[j] + array[k] == 0: return array[i], array[j], array[k] elif array[i] + array[j] + array[k] > 0: k = k - 1 else: j = j + 1
from unittest import TestCase from Queue import Queue, EmptyException, FullException class TestQueue(TestCase): def test_enqueue_and_dequeue(self): queue = Queue(3) queue.enqueue(1) queue.enqueue(2) with self.assertRaises(FullException): queue.enqueue(3) self.assertEqual(1, queue.dequeue()) self.assertEqual(2, queue.dequeue()) with self.assertRaises(EmptyException): queue.dequeue() def test_empty(self): queue = Queue(2) self.assertTrue(queue.empty()) def test_full(self): queue = Queue(2) queue.enqueue(1) self.assertTrue(queue.full()) queue = Queue(1) self.assertTrue(queue.full()) def test_capacity(self): queue = Queue(5) self.assertEqual(4, queue.capacity())
from Queue import Queue, FullException, EmptyException class Deque(Queue): """ whereas a Queue allows insertion at one end and deletion at the other end, a Deque(double-ended Queue) allows insertion and deletion at both ends """ def __init__(self, size): super().__init__(size) def enqueue_tail(self, x): self.enqueue(x) def dequeue_head(self): return self.dequeue() def enqueue_head(self, x): if self.full(): raise FullException() else: if self.head == 0: self.head = self.size - 1 else: self.head = self.head - 1 self.data[self.head] = x def dequeue_tail(self): if self.empty(): raise EmptyException() else: if self.tail == 0: self.tail = self.size - 1 else: self.tail = self.tail - 1 return self.data[self.tail]
class FullException(Exception): pass class EmptyException(Exception): pass class Stack(list): def __init__(self, size): super(Stack, self).__init__([None] * size) self.top = -1 self.size = len(size) def push(self, x): if self.full(): raise FullException("This stack is full") else: self.top = self.top + 1 self[self.top] = x def pop(self, *args, **kwargs): if self.empty(): raise EmptyException('This stack is empty') else: self.top = self.top - 1 return self[self.top + 1] def empty(self): return self.top == -1 def full(self): return self.top == self.size - 1 # def multipop(self, k): # l = [] # while not self.empty() and k > 0: # # l.append(self.pop()) # return l
from queue import Queue from graph import Graph, Vertex def wrestlers(wrestlersList, rivalriesList): """ There are two types of professional wrestlers: "babyfaces" ("good guys") and "heels" ("bad guys"). Between any pair of professional wrestlers, there may or may not be a rivalry. Given a list of professional wrestlers and a list of pairs of wrestlers for which there are rivalries, determine whether it is possible to designate some of the wrestlers as babyfaces and There remainder as heels such that each rivalry is between a babyfaces and a heel. """ d = dict() vertices = [None] * len(wrestlersList) edges = [None] * len(rivalriesList) for i in range(len(wrestlersList)): vertices[i] = Vertex(wrestlersList[i]) d[wrestlersList[i]] = vertices[i] for i in range(len(rivalriesList)): w1, w2 = rivalriesList[i] edges[i] = (d[w1], d[w2]) g = Graph(vertices, edges, False) for u in g.vertices: u.type = 0 for u in g.vertices: if u.type == 0: if not _bfs(g, u): return False return True def _bfs(g, s): s.type = 1 q = Queue(2 * len(g.vertices)) q.put(s) while not q.empty(): u = q.get() for v in g.adj[u]: if u.type == v.type: return False elif v.type == 0: if u.type == 1: v.type = 2 else: v.type = 1 q.put(v) return True
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def split(text, delimiter): l = [] tmp = "" i = 0 while i < len(text): # print(tmp) if text[i] != delimiter[0]: tmp = tmp+text[i] i += 1 continue s = True for j,d in enumerate(delimiter): if i+j>len(text) or text[i+j] != d: s = False break if s: l.append(tmp) tmp = "" i = i+len(delimiter) else: tmp = tmp+text[i] i += 1 l.append(tmp) return l def splitmany(texty, delimiter): r = [] for text in texty: r.append(split(text, delimiter)) return r texty = ["jmeno, prijmeni, email, cislo", "aaa,aaaa, a,a ,a, a"] vysledky = [["jmeno", "prijmeni", "email", "cislo"], ["aaa,aaaa", "a,a ,a", "a"]] tmp = splitmany(texty, ", ") if tmp == vysledky: print("Test prošel!", tmp) else: print("Test neprošel!", tmp) for i, test in enumerate(texty): tmp = split(test, ", ") if tmp == vysledky[i]: print("Test prošel!", tmp) else: print("Test neprošel!", tmp)
from concurrent.futures import ThreadPoolExecutor, wait, as_completed from time import sleep from random import randint def return_after_5_secs(num): sleep(randint(1, 5)) return "Return of {}".format(num) if __name__ == '__main__': pool = ThreadPoolExecutor(5) futures = [] for x in range(5): futures.append(pool.submit(return_after_5_secs, x)) for x in as_completed(futures): print(x.result()) # the numbers return in different order as completed... it returns whatever completes frist. # The as_completed() function takes an iterable of Future objects and starts yielding values as soon as the futures start resolving. The main difference between the aforementioned map method with as_completed is that map returns the results in the order in which we pass the iterables. That is the first result from the map method is the result for the first item. On the other hand, the first result from the as_completed function is from whichever future completed first.
#!/usr/bin/python #brute force import sys from collections import namedtuple import random Item = namedtuple('Item', ['index', 'size', 'value']) def knapsack_solver(items, capacity): ratiolist = [] index = [] value = [] size = [] iamtuple = [] for i in range(0, len(items)): col = [items[i].index, items[i].size, items[i].value, items[i].value/items[i].size] iamtuple.append(((items[i].index),(items[i].size), (items[i].value), (items[i].value/items[i].size))) print(col) #print(iamtuple) #how to access without naming them print(iamtuple) if __name__ == '__main__': if len(sys.argv) > 1: capacity = int(sys.argv[2]) file_location = sys.argv[1].strip() file_contents = open(file_location, 'r') items = [] for line in file_contents.readlines(): data = line.rstrip().split() items.append(Item(int(data[0]), int(data[1]), int(data[2]))) file_contents.close() print(knapsack_solver(items, capacity)) else: print('Usage: knapsack.py [filename] [capacity]')
count =0 for x in range (1,5): for y in range(1,5): for z in range(1,5): if (x!=y and y!=z and x!=z): count +=1 print(x*100+y*10+z) print('共有',count,'个三位数')
digital = 0 character = 0 other = 0 blank = 0 i=input() for ch in i: if (ch >= '0' and ch <= '9'): digital +=1 elif ((ch >= 'a' and ch <= 'z') or (ch > 'A' and ch <= 'Z')): character +=1 elif (ch == ' '): blank +=1 else: other +=1 print('数字个数:'+str(digital)) print('英文字母个数:'+str(character)) print('空格个数: '+str(blank)) print('其他字符个数:'+str(other))
import numpy as np a =np.zeros((3,3)) print('请输入9个整数:') for i in range(3): for j in range(3): a[i][j]=(float(input())) sum = 0 for i in range(3): for j in range(3): if(i==j): sum += a[i][j] print('对角线之和:',sum)
x = str(input()) def func(x): x = list(x) small = 0 big = 0 for y in x: if y.islower() == True: small += 1 elif y.isupper(): big += 1 return (small, big) print(func(x))
def ExtractData4rmCSV(csvfilepath): """ This function's purpose is to convert a csv file containing signal values into a single dataFrame """ import csv import numpy as np import matplotlib.pyplot as plt import pandas as pd import datetime content = [] with open(csvfilepath, newline='') as csvfile: csv_read = csv.reader(csvfile,delimiter=',',quoting=csv.QUOTE_NONNUMERIC) for row in csv_read: content.append(row) numrows = len(content) numcols = len(content[0]) print('content consists of %d rows and %d columns' %(numrows,numcols)) signames = content[0] dataset = content[1:numrows] df = pd.DataFrame(dataset) dflastrow = len(df)-1 df = df.drop([dflastrow], axis=0) df.columns = signames df.shape[0] # number of rows in a dataframe df.shape[1] # number of cols in a dataframe maxtime_sec = max(df['Time']) time = str(datetime.timedelta(seconds=round(max(df['Time'])))) time_splt = time.split(":") print('dataFrame shape: %d by %d (rows by columns)\n' %(df.shape[0],df.shape[1])) print('These are the signals found in the csv file\n'), print(signames) print('\n The test ran for %d seconds, which is %s hours, %s minutes, and %s seconds!\n' %(maxtime_sec, time_splt[0], time_splt[1], time_splt[2])) print(type(df)) return df
class Path(object): #定义Path,每一个Path类代表到达当前step的一个路径,如果是在init位置,path_history为空,则赋值当前step def __init__(self,step,goal,path_history = None): self.step = step #第一个点 if not path_history: self.path_memory = [step] else: self.path_memory = path_history.path_memory + [step] self.heuristic = ( (goal[0] - step[0]) ** 2 + (goal[1] - step[1]) **2 ) **0.5 self.gn_astar = len(self.path_memory) self.gn_greedy = 0 self.fn_astar = self.heuristic + self.gn_astar self.fn_greedy = self.heuristic + self.gn_greedy def path_explore(step): x_move = [-1,0,1,1,1,0,-1,-1] y_move = [1,1,1,0,-1,-1,-1,0] step_explored = [] for i in range(8): newstep = [step[0]+x_move[i],step[1]+y_move[i]] step_explored.append(newstep) return step_explored #边界判定 def boundary(step,mapsize,blocks): if (step[0]>0 and step[0]<mapsize[0] and step[1]>0 and step[1]<mapsize[1]\ and (step not in blocks)): return True else: return False def greedysearch(mapsize, blocks, init, goal): """Returns: - path: a list with length n (the number of steps) and each element of the list is a position in the format (xi, yi). Or a nx2 matrix. """ init_path = Path(init,goal) frontier = [init_path] explored = [] blocklist = list(list(i) for i in blocks) while True: frontier = sorted(frontier, key=lambda x: x.fn_greedy) current_path = frontier.pop(0) if current_path.heuristic == 0: return current_path.path_memory step_list = path_explore(current_path.step) for step in step_list: bound = boundary(step,mapsize,blocklist) if (bound and (step not in explored)): path_new = Path(step, goal, current_path) explored.append(step) frontier.append(path_new) def astarsearch(mapsize, blocks, init, goal): """Returns: - path: a list with length n (the number of steps) and each element of the list is a position in the format (xi, yi). Or a nx2 matrix. """ init_path = Path(init, goal) frontier = [init_path] explored = [] blocklist = list(list(i) for i in blocks) while True: frontier = sorted(frontier, key=lambda x: x.fn_astar) current_path = frontier.pop(0) if current_path.heuristic == 0: return current_path.path_memory step_list = path_explore(current_path.step) for step in step_list: if boundary(step, mapsize, blocklist) and step not in explored: path_new = Path(step, goal, current_path) explored.append(step) frontier.append(path_new)
""" Problem 1 - A stock trader wants to trade in securities that match certain conditions. For some securities, it would be if it crosses a limit value, for some if it goes below the limit value (possibly for shorting). You are given a dictionary of securities and their limit values and a condition as a dictionary. The problem is to idiomatically solve the problem of which securities he needs to buy according to his conditions. """ # Stocks of interest stocks = ['REL','INF','GLB','ACC','JIN','TRA','PAC'] # His conditions, given as the dictionary entry # 'SYMBOL': (limit value, comparison operator) stock_limits = {'REL' : (1200, '>='), 'INF': (2500, '>'), 'GLB': (850, '<'), 'ACC': (1330, '=='), 'JIN': (720, '<='), 'TRA': (1800, '>='), 'PAC': (95, '>')} # Input - Current Market Price of the securities stock_prices = {'REL': 1222, 'INF': 2312, 'GLB': 829, 'ACC': 1335, 'JIN': 755, 'TRA': 1889, 'PAC': 85} # Problem - Get the list of securities he should trade on. # Here is a basic implementation def stocks_to_trade(conditions, prices): """ Find stocks to trade in """ stocks = [] for stock in conditions: limit, check = conditions[stock] # Apply the condition - Use operator module to # match the string to the condition price = prices[stock] ok = eval('%d %s %d' % (price, check, limit)) if ok: stocks.append(stock) print 'Stocks to trade are',stocks if __name__ == "__main__": stocks_to_trade(stock_limits, stock_prices)
#-*-*-coding: utf-8 ## {{{ http://code.activestate.com/recipes/496884/ (r10) """ Amaze - A completely object-oriented Pythonic maze generator/solver. This can generate random mazes and solve them. It should be able to solve any kind of maze and inform you in case a maze is unsolveable. This uses a very simple representation of a mze. A maze is represented as an mxn matrix with each point value being either 0 or 1. Points with value 0 represent paths and those with value 1 represent blocks. The problem is to find a path from point A to point B in the matrix. The matrix is represented internally as a list of lists. Have fun :-) """ import sys import random import json from colors import * class MazeError(Exception): """ An exception class for Maze """ pass class Maze(object): """ A class representing a maze """ def __init__(self, rows=[[]]): self._rows = rows self.__validate() self.__normalize() def __str__(self): s = '\n' for row in self._rows: for item in row: if item == 0: line = ''.join((G + ' ' + W, G + ' ' + W, G + ' ' + W)) elif item == 1: line = ''.join((R + ' ' + W, R + ' ' + W, R + ' ' + W)) elif item == '*': line = ''.join((O + ' ' + W, O + '*' + W, O + ' ' + W)) elif item == '+': line = ''.join((B + ' ' + W, B + '+' + W, B + ' ' + W)) else: line = ''.join((W + ' ' + W, W + str(item) + W, W + ' ' + W)) s = ''.join((s, line)) s = ''.join((s,'\n')) # s += '-'*len(s) + '\n' return s def save(self): json.dump(self._rows, open('maze.json','w')) def __validate(self): """ Validate the maze """ # Get length of first row width = len(self._rows[0]) widths = [len(row) for row in self._rows] if widths.count(width) != len(widths): raise MazeError('Invalid maze!') self._height = len(self._rows) self._width = width def __normalize(self): """ Normalize the maze """ # This converts any number > 0 in the maze to 1 for x in range(len(self._rows)): row = self._rows[x] row = list(map(lambda x: min(int(x), 1), row)) self._rows[x] = row def getHeight(self): """ Return the height of the maze """ return self._height def getWidth(self): """ Return the width of the maze """ return self._width def validatePoint(self, pt): """ Validate the point pt """ x,y = pt w = self._width h = self._height # Don't support Pythonic negative indices if x > w - 1 or x<0: raise MazeError('x co-ordinate out of range!') if y > h - 1 or y<0: raise MazeError('y co-ordinate out of range!') pass def getItem(self, x, y): """ Return the item at location (x,y) """ self.validatePoint((x,y)) w = self._width h = self._height # This is based on origin at bottom-left corner # y-axis is reversed w.r.t row arrangement # Get row row = self._rows[h-y-1] return row[x] def setItem(self, x, y, value): """ Set the value at point (x,y) to 'value' """ h = self._height self.validatePoint((x,y)) row = self._rows[h-y-1] row[x] = value def getNeighBours(self, pt): """ Return a list of (x,y) locations of the neighbours of point pt """ self.validatePoint(pt) x,y = pt h = self._height w = self._width # There are eight neighbours for any point # inside the maze. However, this becomes 3 at # the corners and 5 at the edges poss_nbors = (x-1,y),(x-1,y+1),(x,y+1),(x+1,y+1),(x+1,y),(x+1,y-1),(x,y-1),(x-1,y-1) nbors = [] for xx,yy in poss_nbors: if (xx>=0 and xx<=w-1) and (yy>=0 and yy<=h-1): nbors.append((xx,yy)) return nbors def getExitPoints(self, pt): """ Return a list of exit points at point pt """ # Get neighbour list and return if the point value # is 0 exits = [] for xx,yy in self.getNeighBours(pt): if self.getItem(xx,yy)==0: exits.append((xx,yy)) return exits def getRandomExitPoint(self, pt): """ Return a random exit point at point (x,y) """ return random.choice(self.getExitPoints(pt)) def getRandomStartPoint(self): """ Return a random point as starting point """ return random.choice(self.getAllZeroPoints()) def getRandomEndPoint(self): """ Return a random point as ending point """ return random.choice(self.getAllZeroPoints()) def getAllZeroPoints(self): """ Return a list of all points with zero value """ points = [] for x in range(self._width): for y in range(self._height): if self.getItem(x,y)==0: points.append((x,y)) return points def calcDistance(self, pt1, pt2): """ Calculate the distance between two points """ # The points should be given as (x,y) tuples self.validatePoint(pt1) self.validatePoint(pt2) x1,y1 = pt1 x2,y2 = pt2 return pow( (pow((x1-x2), 2) + pow((y1-y2),2)), 0.5) def calcXDistance(self, pt1, pt2): """ Calculate the X distance between two points """ # The points should be given as (x,y) tuples self.validatePoint(pt1) self.validatePoint(pt2) x1, y1 = pt1 x2, y2 = pt2 return abs(x1-x2) def calcYDistance(self, pt1, pt2): """ Calculate the Y distance between two points """ # The points should be given as (x,y) tuples self.validatePoint(pt1) self.validatePoint(pt2) x1, y1 = pt1 x2, y2 = pt2 return abs(y1-y2) def calcXYDistance(self, pt1, pt2): """ Calculate the X-Y distance between two points """ # The points should be given as (x,y) tuples self.validatePoint(pt1) self.validatePoint(pt2) x1, y1 = pt1 x2, y2 = pt2 return abs(y1-y2) + abs(x1-x2) def getData(self): """ Return the maze data """ return self._rows ## end of http://code.activestate.com/recipes/496884/ }}}
""" Prime number generation """ import random from itertools import cycle,imap,dropwhile,takewhile def is_prime(n): """ Is the number 'n' prime ? """ prime = True for i in range(2,int(pow(n,0.5))+1): if n % i==0: prime = False break return prime def prime_solution_a(n): count, numbers = 0, [] while count<n: num = random.randrange(1,1000) if num not in numbers and is_prime(num): numbers.append(num) count += 1 return numbers def prime_solution_b(n): sieve = lambda n: not any(n % num==0 for num in range(2, int(pow(n,0.5))+1)) nums = set() for i in takewhile(lambda x:len(nums)<=20, dropwhile(sieve,imap(random.randrange,cycle([1]), cycle([100])))): nums.add(i) return nums if __name__ == "__main__": print prime_solution_a(20) print prime_solution_b(20)
def printMultiplication(dan): for item in range(1, 10): result = "{} * {} = {}".format(dan, item, item * dan) print(result) for item in range(2, 10): printMultiplication(item) print("-------------")
import numpy as np def mean(x): return np.sum(x)/len(x) def std(x): return (np.sum([(x[i]-mean(x))**2 for i in range(len(x))])*1/len(x))**0.5
for i in range(10): if (i < 10 and i > 5): print(8%3) else: print("Unbroken 1") for i in range(10): if i == 5: break else: print("Unbroken 2")
class HashTables: #these are the implementations of dictionaries by assigning a value to a key def __init__(self): self.size = 10 self.keys = [None] * self.size #index all through the bucket self.values =[None] * self.size #values all through the bucket def insert(self, key, data): index = self.hashFunction(key) #handling possible collisions, is not None means if there is already an index in that position while self.keys[index] is not None: if self.keys[index] == key: self.values[index] = data return #rehash by linear probing by checking for other index position index = (index +1 ) % self.size #insert these new data self.keys[index] = key self.values[index] = data def get(self, key): index = self.hashFunction(key) while self.keys[index] is not None: if self.keys[index] == key: return self.values[index] index = (index + 1) % self.size return None #this is incase the key is not found def hashFunction(self, key): sum = 0 for x in range(len(key)): sum = sum + ord(key[x]) return sum % self.size h = HashTables() h.insert('Demola','Software engineer') h.insert('Country', 'Nigeria') h.insert('age',22) h.insert('religion','christianity') print(h.get('Demola'))
# FIFO : first in first out class Queue: def __init__(self): self.queue = [] def is_empty(self): return self.queue == [] # O(1) running time complexity def enqueue(self, data): #means add data to the queue self.queue.append(data) # O(N) running time complexity def dequeue(self): if self.size_queue() < 1: return -1 data = self.queue[0] del self.queue[0] return data # O(1) running time complexity def peek(self): return self.queue[0] def size_queue(self): return len(self.queue) queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) queue.enqueue(4) print('Size of queue: %d' % queue.size_queue()) print('Dequeued item: %d' % queue.dequeue()) print('Peek: %d' % queue.peek()) print('Size of queue: %d' % queue.size_queue()) print('Dequeued item: %d' % queue.dequeue()) print('Peek: %d' % queue.peek()) print('Size of queue: %d' % queue.size_queue()) print('Dequeued item: %d' % queue.dequeue()) print('Peek: %d' % queue.peek())
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ # create set for tracking potential telemarketers potential_telemarketers = set() # iterate through calls and add calling number to telemarketer set for call in calls: potential_telemarketers.add(call[0]) # iterate through calls and remove receiving number from telemarketer set for call in calls: receiving_number = call[1] if receiving_number in potential_telemarketers: potential_telemarketers.remove(receiving_number) # iterate through texts and remove sending and receiving number from telemarketer set for text in texts: sending_number = text[0] receiving_number = text[1] if sending_number in potential_telemarketers: potential_telemarketers.remove(sending_number) if receiving_number in potential_telemarketers: potential_telemarketers.remove(receiving_number) # create array with final phone numbers, sort, and print output = [] for number in potential_telemarketers: output.append(number) print("These numbers could be telemarketers: ") for n in sorted(output): print(n)
import math def shortest_path(graph, start_node, end_node): if start_node == end_node: return [start_node] node_distances = dict() unvisited = set() # build our result and unvisited dictionaries for node in graph.intersections: cost_to_goal = get_cost_to_goal(graph, node, end_node) node_distances[node] = [float('inf'), cost_to_goal] unvisited.add(node) # update start_node path cost to 0 node_distances[start_node][0] = 0 # create path dictionary to track which nodes connect path = dict() while unvisited: # select the next node to visit based on which one has the smallest path cost min_node = None for node in unvisited: if not min_node: min_node = node else: if node_distances[min_node][0] > node_distances[node][0]: min_node = node # visit all neighbors (connecting intersections) of the node selected below neighbors = graph.roads[min_node] for neighbor in neighbors: if neighbor in unvisited: # calculate updated path cost of traveling to neighbor from current node path_cost = node_distances[min_node][0] + get_cost_to_goal(graph, min_node, neighbor) heuristic = node_distances[neighbor][1] distance_to_neighbor = path_cost + heuristic if node_distances[neighbor][0] > distance_to_neighbor: # update the path cost associated with visiting this neighbor next node_distances[neighbor][0] = distance_to_neighbor # update our path from min_node -> neighbor path[neighbor] = min_node # mark selected node as visited unvisited.remove(min_node) # iterate through path to build output output = [] # start at end_node node = end_node while node != start_node: if node in path: output.insert(0, node) node = path[node] # insert start node so long as we're sure a path exists if len(output): output.insert(0, start_node) # return path return output # Uses Euclidean Distance to calculate cost to goal heuristic def get_cost_to_goal(graph, start_node, end_node): start_x_y = graph.intersections[start_node] goal_x_y = graph.intersections[end_node] dist = math.sqrt(math.pow(start_x_y[0] - goal_x_y[0], 2) + math.pow(start_x_y[1] - goal_x_y[1], 2)) return round(dist)
# Task 1 - Solution locations = {'North America': {'USA': ['Mountain View']}} locations['North America']['USA'].append('Atlanta') locations['Asia'] = {'India': ['Bangalore']} locations['Asia']['India'].append('New Delhi') locations['Asia']['China'] = ['Shanghai'] locations['Africa'] = {'Egypt': ['Cairo']} # Task 2 - Solution # Part 1 - A list of all cities in the USA in alphabetic order. print (1) usa_sorted = sorted(locations['North America']['USA']) for city in usa_sorted: print (city) # Part 2 - All cities in Asia, in alphabetic order print (2) asia_cities = [] for country, cities in locations['Asia'].items(): for city in cities: asia_cities.append('{} - {}'.format(city, country)) asia_sorted = sorted(asia_cities) for city in asia_sorted: print (city)
# Recursive Solution def add_one(arr): """ :param: arr - list of digits representing some number x return a list with digits represengint (x + 1) """ # Base case if arr == [9]: return [1, 0] # A simple case, where we just need to increment the last digit if arr[-1] < 9: arr[-1] += 1 # Case when the last digit is 9. else: '''Recursive call''' # We have used arr[:-1], that means all elements of the list except the last one. # Example, for original input arr=[1,2,9], we will pass [1,2] in next call. arr = add_one(arr[:-1]) + [0] return arr
class Node: def __init__(self, newData, pointer): self.pointer = pointer self.data = newData def getData(self): return self.data def changeData(self, data): self.data = data def addNode(self, newNode): self.pointer.append(newNode) def rmNode(self, index): del self.pointer[index] def getXNode(self, index): if(index<len(pointer)): return pointer[index] trunk = Node("Main", [None]) students = Node("Students", [None]) freshman = Node("Freshman", [None]) sophomores = Node("Sophomores", [None]) juniors = Node("Juniors", [None]) seniors = Node("Seniors", [None]) people = [Node("Person 1", [None]), Node("Person 2", [None]), Node("Person 3", [None]), Node("Person 4", [None]), Node("Person 5", [None]), Node("Person 6", [None]), Node("Person 7", [None]), Node("Person 8", [None]), Node("Person 9", [None]), Node("Person 10", [None]), Node("Person 11", [None]), Node("Person 12", [None]), Node("Person 13", [None]), Node("Person 14", [None]), Node("Person 15", [None]), Node("Person 16", [None])] trunk.addNode(students) students.addNode(freshman) students.addNode(sophomores) students.addNode(juniors) students.addNode(seniors) i = 0; for item in people: if(i<4): freshman.addNode(item) i+=1 elif(i<8): sophomores.addNode(item) i+=1 elif(i<12): juniors.addNode(item) i+=1 elif(i<16): seniors.addNode(item) i+=1 students.rmNode(0) for year in students.pointer: year.rmNode(0) for student in juniors.pointer: print(student.getData())
import math import torch from torch import autograd import torch.nn as nn class SelfAssessmentFunction(autograd.Function): """ Implements two linear layers, one called 'main' and one called 'sass' (for 'self-assessment'). The main layer behaves just like a regular linear layer. The sass layer behaves like a linear layer on the forward pass, but it uses a custom backward method to calculate its gradient: The gradient the sass layer receives from backpropagation is ignored completely. It is replaced with the result of a custom loss function: It uses MLEloss, with the absolute values of the gradient of the main layer as the target. This new loss function is then used to calculate the gradient of the sass layer. As a result, the sass layer learns to approximate the average absolute gradient of the main layer. Each neuron in the sass layer reacts to a different subset of the neurons in the main layer, which is controlled by output_to_sass_mean_compression. """ @staticmethod def forward(ctx, input, weight_main, bias_main, weight_sass, bias_sass, output_to_sass_mean_compression): # Both feed-forward portions are just the result of applying the respective layer to the input output_main = input.mm(weight_main.t()) output_main += bias_main.unsqueeze(0).expand_as(output_main) output_sass = input.mm(weight_sass.t()) output_sass += bias_sass.unsqueeze(0).expand_as(output_sass) ctx.save_for_backward(input, weight_main, bias_main, weight_sass, bias_sass, output_sass, output_to_sass_mean_compression) return output_main, output_sass @staticmethod def backward(ctx, grad_main, grad_sass): input, weight_main, bias_main, weight_sass, bias_sass, output_sass, output_to_sass_mean_compression = ctx.saved_tensors grad_input = grad_weight_main = grad_bias_main = grad_weight_sass = grad_bias_sass = grad_output_to_sass_mean_compression = None # Perform normal gradient calculations on the main layer grad_weight_main = grad_main.t().mm(input) grad_bias_main = grad_main.sum(0) # For the sass layer, ignore the grad_sass and recompute it: # The grad_sass is computed through MLELoss, with the absolute of the gradient of the main neurons as the target. # Each neuron in sass measures a subset of the main neurons. This mapping is done by output_to_sass_mean_compression. target = grad_main.abs().mm(output_to_sass_mean_compression) grad_sass = (output_sass - target) * 2 # Apply this new gradient grad_weight_sass = grad_sass.t().mm(input) grad_bias_sass = grad_sass.sum(0) # Calculate the gradient for the input grad_input = grad_main.mm(weight_main) return grad_input, grad_weight_main, grad_bias_main, grad_weight_sass, grad_bias_sass, grad_output_to_sass_mean_compression class SelfAssessment(nn.Module): """ Implements a linear layer as well as a self-assessment layer, which is a second linear layer that is trained to predict the gradient of the first linear layer. If add_sass_features_to_output=True, the results of both layers are combined into a single tensor. Otherwise they are returned separately. The parameter sass_features specifies the number of different self-assessment neurons, which must be a multiple of out_features. For example: If you set sass_features=1 and add_sass_features_to_output=False, this module behaves like a normal linear layer, but you will get a secondary output that predicts the average absolute gradient of the entire layer. If you set out_features=200, sass_features=10, add_sass_features_to_output=True, you end up with an output vector of size 210. 200 of those are normal results of the linear layer, while the remaining 10 are predictions of the mean absolute gradient of the 10 blocks of 20 neurons. These 10 additional predictions may improve network performance because subsequent layers can use them as an estimate for how reliable the 10*20 main neurons are for the given example. Note for interpretation: A higher value of the self-assessment means that the network is less sure of itself. (The value measures how much the network expects to learn from the new data.) """ def __init__(self, in_features, out_features, sass_features=1, add_sass_features_to_output=False): super().__init__() self.in_features = in_features self.out_features = out_features self.sass_features = sass_features self.add_sass_features_to_output = add_sass_features_to_output if float(out_features) % float(sass_features) != 0: raise ValueError("The number of output features (out_features) must be a multiple of the number of self-assessment features (sass_features).") # Create one layer for the calculation itself, and another for the self assessment self.weight_main = nn.Parameter(torch.Tensor(out_features, in_features)) self.bias_main = nn.Parameter(torch.Tensor(out_features)) self.weight_sass = nn.Parameter(torch.Tensor(sass_features, in_features)) self.bias_sass = nn.Parameter(torch.Tensor(sass_features)) self.reset_parameters() # Create a mapping that compresses features from the main layer by taking the means of a subset of them. # This is needed to calculate the gradient of MSE-loss for all sass features at the same time. self.output_to_sass_mean_compression = torch.zeros(out_features, sass_features, requires_grad=False) main_per_sass = out_features / sass_features for i in range(out_features): j = int(i / main_per_sass) self.output_to_sass_mean_compression[i,j] = 1.0 / main_per_sass # Create mappings that combine output_main and output_sass into a single tensor self.output_combiner_main = torch.zeros(out_features, out_features + sass_features, requires_grad=False) self.output_combiner_sass = torch.zeros(sass_features, out_features + sass_features, requires_grad=False) for i in range(out_features): self.output_combiner_main[i,i] = 1.0 for i in range(sass_features): self.output_combiner_sass[i,out_features+i] = 1.0 def reset_parameters(self): # main nn.init.kaiming_uniform_(self.weight_main, a=math.sqrt(5)) fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight_main) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias_main, -bound, bound) # sass nn.init.kaiming_uniform_(self.weight_sass, a=math.sqrt(5)) fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight_sass) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(self.bias_sass, -bound, bound) def forward(self, input): output_main, output_sass = SelfAssessmentFunction.apply(input, self.weight_main, self.bias_main, self.weight_sass, self.bias_sass, self.output_to_sass_mean_compression) if self.add_sass_features_to_output: combined_output = output_main.mm(self.output_combiner_main) + output_sass.mm(self.output_combiner_sass) return combined_output else: return output_main, output_sass def extra_repr(self): return 'in_features={}, out_features={}, sass_features={}'.format( self.in_features, self.out_features, self.sass_features )
#!/usr/local/bin/python3 """ fo=open('newdemo.txt','w') print(fo.mode) print(fo.readable()) print(fo.writable()) fo.close() """ """ #if we don't have any file and then we have to open it on write mode my_content=["This is a data\n""This is a data\n"] fo=open('newdemo1.txt','w') #fo.write("This is first line and iam still on training\n") #print(fo.mode) fo.writelines(my_content) fo.close() """ """ my_content=["This is first line","This is second line","This is third line"] fo=open("with_loop.txt",'a') for each_line in my_content: fo.write(each_line+"\n") """ """ #reading a text file fo=open("with_loop.txt",'r') data=fo.read() print(data) fo.close() """ """ #reading atext file with line by line fo=open("with_loop.txt",'r') print(fo.readline()) fo.close() """ """ #printing the type of data fo=open("with_loop.txt",'r') data=fo.read() fo.close() print(type(data)) """ """ #reading the file in list which the output in a file is print in list fo=open("with_loop.txt",'r') data=fo.readlines() fo.close() #print(data) for each in range(3): print(data[each]) """ #reading teh last line in a file fo=open("with_loop.txt",'r') data=fo.readlines() fo.close() print(data[-1])
#!/usr/local/bin/python3 """ import os path=input("Enter your path: ") if os.path.isfile(path): print(f"The given path is: {path} is a file") else: print(f"The given path is: {path} is a directory") """ import os path=input("Enter your path: ") if os.path.exists(path): print(f"Given path: {path} is valid") if os.path.isfile(path): print(f"The Givn path {path} is a file") else: print(f"The Given path {path} is a directory") else: print(f"Given path: {path} is not existing in host")
#!/usr/local/bin/python3 import os path="/root/python/section10" print(os.path.basename(path)) print(os.path.dirname(path)) path1="/home" path2="redhat" print(os.path.join(path1,path2)) ''' path2="/root/python/section10" print(os.path.split(path2)) print(os.path.getsize(path2)) print(os.path.exists(path2)) if os.path.exists(path2): print("path exists") else: print("path not exists") ''' if os.path.isfile(path): print("your path is not file") else: print("your path is directory")
#!/usr/local/bin/python3 """ num=eval(input("Enter the number: ")) if num==1: print("one") if num==2: print("two") if num==3: print("three") if num==4: print("four") if num not in [1,2,3,4,5,6,7,8,9,10]: print(f"your number is not there in 1-10 range: {num}") """ """ num=eval(input("Enter your number: ")) if num in [1,2,3,4]: if num==1: print("one") elif num==2: print("two") elif num==3: print("three") elif num==4: print("four") else: print("your number is not there in list") """ num=eval(input("Enter your number: ")) num_word={1:'one',2:'two',3:'three',4:'four'} if num in [1,2,3,4]: print(num_word.get(num)) else: print("enter in 1-4 range:")
#!/usr/local/bin/python3 usr_string=input("Enter your string: ") usr_conf=input("Do you want to convert your string into lower case say yes or no: ") if usr_conf=="yes": print(usr_string.lower())
#!/usr/local/bin/python3 import os req_file=input("Enter your filename to search: ") for r,d,f in os.walk("/"): for each_file in f: if each_file==req_file: print(os.path.join(r,each_file))
""" #This is a simple arithmetic script a=24 b=27 sum=a+b print(f"The sum of {a} and {b} is: {sum}") """ #This script is all about the arithmetic operations a=24 b=32 sum=a+b print(f"The sum of {a} and {b} is: {sum}")
import numpy as np import matplotlib.pyplot as plt import colorsys import sys K = 3 # number of centroids to compute numClusters = 3 # actual number of clusters to generate ptsPerCluster = 80 # number of points per actual cluster xCenterBounds = (-1, 1) # lower and upper limits within which to place actual cluster centers # Randomly place cluster centers within the span of xCenterBounds. centers = np.random.random_sample((numClusters,)) centers = centers * (xCenterBounds[1] - xCenterBounds[0]) + xCenterBounds[0] # Initialize array of data points. points = np.zeros((numClusters * ptsPerCluster,)) # Normally distribute ptsPerCluster points around each center. stDev = 0.15 for i in range(numClusters): points[i*ptsPerCluster:(i+1)*ptsPerCluster] = ( stDev * np.random.randn(ptsPerCluster) + centers[i]) # Randomly select K points as the initial centroid locations. centroids = np.zeros((K,)) indices = [] while len(indices) < K: index = np.random.randint(0, numClusters * ptsPerCluster) if not index in indices: indices.append(index) centroids = points[indices] # Assign each point to its nearest centroid. Store this in classifications, # where each element will be an int from 0 to K-1. classifications = np.zeros((points.shape[0],), dtype=np.int) def assignPointsToCentroids(): for i in range(points.shape[0]): smallestDistance = 0 for k in range(K): distance = abs(points[i] - centroids[k]) if k == 0: smallestDistance = distance classifications[i] = k elif distance < smallestDistance: smallestDistance = distance classifications[i] = k assignPointsToCentroids() # Define a function to recalculate the centroid of a cluster. def recalcCentroids(): for k in range(K): if sum(classifications == k) > 0: centroids[k] = sum(points[classifications == k]) / sum(classifications == k) # Generate a unique color for each of the K clusters using the HSV color scheme. # Simultaneously, initialize matplotlib line objects for each centroid and cluster. hues = np.linspace(0, 1, K+1)[:-1] fig, ax = plt.subplots() clusterPointsList = [] centroidPointsList = [] for k in range(K): clusterColor = tuple(colorsys.hsv_to_rgb(hues[k], 0.8, 0.8)) clusterLineObj, = ax.plot([], [], ls='None', marker='x', color=clusterColor) clusterPointsList.append(clusterLineObj) centroidLineObj, = ax.plot([], [], ls='None', marker='o', markeredgecolor='k', color=clusterColor) centroidPointsList.append(centroidLineObj) iterText = ax.annotate('', xy=(0.01, 0.01), xycoords='axes fraction') # Define a function to update the plot. def updatePlot(iteration): for k in range(K): xDataNew = points[classifications == k] clusterPointsList[k].set_data(xDataNew, np.zeros((len(xDataNew),))) centroidPointsList[k].set_data(centroids[k], 0) iterText.set_text('i = {:d}'.format(iteration)) plt.savefig('./images/{:d}.png'.format(iteration)) plt.pause(0.5) dataRange = np.amax(points) - np.amin(points) ax.set_xlim(np.amin(points) - 0.05 * dataRange, np.amax(points) + 0.05 * dataRange) ax.set_ylim(-1, 1) iteration = 0 updatePlot(iteration) plt.ion() plt.show() # Execute and animate the algorithm with a while loop. Note that this is not the # best way to animate a matplotlib plot--the matplotlib animation module should be # used instead, but we will use a while loop here for simplicity. lastCentroids = centroids + 1 while not np.array_equal(centroids, lastCentroids): lastCentroids = np.copy(centroids) recalcCentroids() assignPointsToCentroids() iteration += 1 updatePlot(iteration) pythonMajorVersion = sys.version_info[0] if pythonMajorVersion < 3: raw_input("Press Enter to continue.") else: input("Press Enter to continue.")
width = int(input("Width of multiplication table: ")) height = int(input("Height of multiplication table: ")) print ("") # Print the table. for i in range(1, height + 1): for j in range(1, width + 1): print ("{0:>4}".format(i*j), end="") print ("")
import sys class Stack(): def __init__(self): self.stack = [] def push(self, num): self.stack.append(num) def pop(self): if self.stack == []: return -1 else: return self.stack.pop() def size(self): return len(self.stack) def empty(self): if self.stack == []: return 1 else: return 0 def top(self): if self.stack == []: return -1 else: return self.stack[-1] stack = Stack() N = int(sys.stdin.readline().rstrip()) for i in range(N): str = sys.stdin.readline().rstrip().split(' ') if str[0] == 'push': stack.push(str[1]) elif str[0] == 'pop': print(stack.pop()) elif str[0] == 'size': print(stack.size()) elif str[0] == 'empty': print(stack.empty()) elif str[0] == 'top': print(stack.top())
test = input().strip() cnt = test.count(' ') if test == '': print(0) elif cnt == 0: print(1) else: print(cnt+1)
year = int(input()) if year%4 ==0 and (year%100 != 0 or year%400 ==0): print('1') else: print('0')
N, M, V = map(int,input().split()) matrix = [[0]*(N+1) for _ in range(N+1)] for _ in range(M): link= list(map(int,input().split())) matrix[link[0]][link[1]] = 1 matrix[link[1]][link[0]] = 1 # print(matrix) def dfs(current_node, row, foot_print): foot_print += [current_node] for search_node in range(len(row[current_node])):# 해당 행에 대해서 반복 # 해당 행의 열을 증가 시켜가며 연결되어있고 방문안한 것 찾기 if row[current_node][search_node] == 1 and search_node not in foot_print: dfs(search_node, row, foot_print) return foot_print def bfs(start): queue = [start] foot_print = [start] while queue: current_node = queue.pop(0) for search_node in range(len(matrix[current_node])): # 해당 행에 대해서 반복 # 해당 행의 열을 증가 시켜가며 연결되어있고 방문안한 것 찾기 if matrix[current_node][search_node] == 1 and search_node not in foot_print: foot_print += [search_node] queue += [search_node] return foot_print print(*dfs(V,matrix,[])) # list를 풀어주는 역할(*) print(*bfs(V))
textTweet = "#ea5 ahi vamos con todo" # print (textTweet) counter = 0 x = 0 while x == 0 : enterText = input("ingrese su texto: ") if enterText == str('maquina') : counter += 1 print (enterText + ' ' + str(counter))
# coding: utf-8 import re napis = "kod pocztowy: 61-695 Poznań" # .+ przynajmniej jedno wystąpienie dowolnego znaku #pattern = r".+\d{2}-\d{3}.+" pattern = r"(?P<kod>\d{2}-\d{3})" # zwróci cały napis #print(re.match(pattern, napis)) match = re.search(pattern, napis) print(match) print(match.groups()) print(match.group())
""" """ import numpy as np from visualization.graph_visualizer import draw_graph from visualization.board_visualizer import DrawBoard class Node: """ Board structure: Every node has up to 8 neighbors, indexed from 0-7 with 0 starting from the upper left corner then 1..7 moving clockwise """ def __init__(self, id, occupied=False, player=False): self.id = id self.occupied = occupied self.player = player self.neighbors = np.empty(8, dtype=object) self.score = [0]*8 # -1 if win is not possible in that direction ## TODO - remove self.BOARD, use l/w values in recursion to control size, use self.BOARD to keep references to initialized nodes class Connect4: def __init__(self): self.HEIGHT = 6 self.WIDTH = 7 self.BOARDTEST = np.empty((self.HEIGHT, self.WIDTH), dtype=object) self.BOARD = np.ones((self.HEIGHT + 2, self.WIDTH + 2), dtype=np.bool) # 6 rows, 7 columns self.BOARD[0, :], self.BOARD[-1,:], self.BOARD[:,0], self.BOARD[:,-1] = [False]*4 # Board represented by connections stemming from # self.upper_left_corner (1,1) in self.BOARD, ends at (-2,-2) in self.BOARD self.ids = self._id_generator() self.upper_left_corner = Node(next(self.ids)) def _id_generator(self): for i in range(1, self.WIDTH*self.HEIGHT + 1): # 1 id for each node yield i def reward_eval(self): """Only used by RL algorithms that require non-binary reward functions""" raise NotImplementedError def step(self): raise NotImplementedError def reset_board(self): self._propagate(self.upper_left_corner, x=1, y=1) def _propagate(self, node, x, y): if not node.neighbors[0]: pass """ def _propagate(self, node, x, y): # if 2 functions have the same inputs, they can likely be merged def _recurse(node, neighbor, x, y): if not node.neighbors[neighbor]: node.neighbors[neighbor] = Node(next(self.ids)) self._propagate(node.neighbors[neighbor], x, y) def _check_neighbor(): pass # use changes in x,y to check if neighbors already created target node # verify on paper that it works for all 8 neighbor cases before implementing if x < 0 or x > self.WIDTH or y < 0 or y > self.HEIGHT: return left_col = self.BOARD[:, x-1].any() right_col = self.BOARD[:, x+1].any() upper_row = self.BOARD[y-1, :].any() lower_row = self.BOARD[y+1, :].any() if upper_row: if left_col: if not _check_neighbor(): if not _check_neighbor(): _recurse(node, 0, x - 1, y - 1) _recurse(node, 1, x, y - 1) if right_col: _recurse(node, 2, x + 1, y - 1) if right_col: _recurse(node, 3, x + 1, y) if lower_row: if right_col: _recurse(node, 4, x + 1, y + 1) _recurse(node, 5, x, y + 1) if left_col: _recurse(node, 6, x - 1, y + 1) if left_col: _recurse(node, 7, x - 1, y) """ def visualize_graph(self, output_path='../output/test_connect4_graph_viz.png'): # ensure filename ends with .png draw_graph(root=self.upper_left_corner, node_obj_representation=Node, output_path=output_path) def visualize_board(self): """ Created to visualize the state of a game board via a charting tool (e.g. bokeh) """ parameters = {'width': self.WIDTH, 'height': self.HEIGHT, 'root': self.upper_left_corner, 'output_path':"../output/test_connect4_board_viz.html"} DrawBoard(params=parameters) if __name__ == '__main__': env = Connect4() env.reset_board() #env.visualize_board() will not work until converted to TicTacToe environment structure
""" BREAKS REQUIRES SETUP - see README Given the root of a graph, the object that represents a node in the graph, and the output file path, this algorithm can recursively visualize the nodes and connection in any graph Created for visualizing trees (e.g. move histories) - not good for densely connected graphs *This program was developed to maximize user control in creating a graph visualization Notes to help you understand test_graph_viz.png: Any node with value of root_id-# are placeholder nodes that represent empty neighboring nodes (based on node.neighbors) Nodes with a value of # are nodes that have been assigned a real value Node values are their id numbers, assigned at their creation Next steps: 1) Allow for customization of node/edge features (e.g. fill color) 2) Test if this algorithm works with no neighbors (i.e. empty ~ []) """ ### Made redundant by bokeh board visualization - need to find alternative use for this code ### (perhaps visualizing move history?) import os import pydotplus as pydot from config import GRAPHVIZ_BIN_PATH class NodeAttributes: # can be replaced with a dataclass from Python 3.7 def __init__(self, node_color=None, edge_color=None): self.node_color = node_color self.edge_color = edge_color class DrawGraph: def __init__(self, root, node_obj_representation, output_path): graph_representation = convert_to_graph_representation(root, node_obj_representation) visualizer_input = [graph_representation[0], graph_representation[1:]] # input format for visualizer: [root, children] ~ [root, [[root (child 1), child 1 child 1], child 2,...]] self.graph = pydot.Dot(graph_type='digraph') self.graph.add_node(pydot.Node(visualizer_input[0], )) self.add_edges(visualizer_input[0], visualizer_input[1]) self.graph.write_png(output_path) def add_edges(self, parent, children): for child in children: if isinstance(child, list): self.graph.add_edge(pydot.Edge(parent, child[0])) self.add_edges(child[0], child[1:]) # first item of tuple is root of subtree else: self.graph.add_edge(pydot.Edge(parent, child)) def convert_to_graph_representation(root, node_obj_representation): output = [root.id] for child in root.neighbors: if isinstance(child, node_obj_representation): break else: # if loop was never broken (i.e. if no Node objects in list of children) for child_num in range(1, len(root.neighbors) + 1): output.append("{root}-{child_num}".format(root=root.id, child_num=child_num)) return output for child_num, child in enumerate(root.neighbors): if child: output.append(convert_to_graph_representation(child, node_obj_representation)) else: output.append("{root}-{child_num}".format(root=root.id, child_num=child_num)) return output def draw_graph(root, node_obj_representation, output_path=''): os.environ["PATH"] += os.pathsep + GRAPHVIZ_BIN_PATH DrawGraph(root, node_obj_representation, output_path)
""" Build environment with 3D node connections - top layer - 9 connected nodes bottom layer - 9 connected nodes for each connected node in the top layer (all connected to top node) """ from visualize_graph import draw_trees class Node: def __init__(self, id, value): self.id = id self.value = value self.neighbors = [] # allows for 8 neighbors assert len(self.neighbors) <= 8, "More than 8 neighbors for node {}".format(self.id) def id_generator(): for i in range(1, 81+1): # 9*9 possible positions yield i class UltimateTTT: def __init__(self): ids = id_generator() a = Node(next(ids), 1) print(a.id) b = Node(next(ids), 1) print(b.id) def create_nodes(self): raise NotImplementedError def step(self, node_id): self.check_win() raise NotImplementedError def check_win(self): raise NotImplementedError def draw_graph(self): draw_trees(self._get_graph()) def _get_graph(self): raise NotImplementedError game = UltimateTTT()
numbers = { 'Besnik Derda': '+355 555 2356', 'Axel Gera': '+355 444 5487', 'Era Korce': '+355 333 3568' } numbers['Besnik Derda'] = '+355 222 1234' numbers['Anna Derda'] = '+355 111 2327' print(numbers['Era Korce']) print(numbers.get('Era Korce')) for key in numbers: # same as "for key in numbers.keys()" print(key) for value in numbers.values(): print(value)
from random import randint n = int(input('Enter the number of rows: ')) m = int(input('Enter the number of columns: ')) matrix = [] # matrix is n x m for i in range(n): matrix.append([]) for j in range(m): matrix[i].append(randint(0, 9)) transpose = [] # transpose is m x n for j in range(m): transpose.append([]) for i in range(n): transpose[j].append(matrix[i][j]) print('Matrix:') for row in matrix: print(row) print('Matrix Transpose:') for row in transpose: print(row)
from random import randint # generates a random number (year) between 1500 and 2020 (inclusive) year = randint(1500, 2020) if year > 1548 and (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)): print(year, 'is a leap year') else: print(year, 'is not a leap year')
class Person: def __init__(self, name, birth_year): self.name = name self.birth_year = birth_year def to_string(self): print('Person name:', self.name) print('Birth Year:', self.birth_year) class Student(Person): def __init__(self, name, birth_year, major): super().__init__(name, birth_year) self.major = major def to_string(self): print('Student name:', self.name) print('Birth Year:', self.birth_year) print('Major:', self.major) class Instructor(Person): def __init__(self, name, birth_year, salary): super().__init__(name, birth_year) self.salary = salary def to_string(self): print('Instructor name:', self.name) print('Birth Year:', self.birth_year) print('Salary:', self.salary) if __name__ == '__main__': person = Person('Keni', 1990) student = Student('Deni', 1980, 'Electronic Engineering') instructor = Instructor('Prof. Beni', 1979, 35000) for i in (person, student, instructor): i.to_string() print()
with open('DNASequence.txt') as file: file_contents = file.read() ca = 0 for i in range(len(file_contents)-1): if file_contents[i:i+2] == 'ca': ca += 1 print('The sequence ca is repeated {} times.'.format(ca))
import sys def main_file_data_reader(file): read_lines: int = 0 read_word: int = 0 read_bytes: int = 0 max_line_length: int = 0 file_data = open(file, "r") for line in file_data: read_lines += 1 if len(line) > max_line_length: max_line_length = len(line) read_bytes += len(bytes(line, 'utf-8')) read_word += len(line.split()) file_data.close() print("Bytes : ", read_bytes, "\nWords : ", read_word, "\nLines : ", read_lines, "\nMax line length : ", max_line_length) if __name__ == '__main__': if len(sys.argv) != 2: print("Missing file input") exit(1) main_file_data_reader(sys.argv[1])
import math import random import sys from typing import List, Generator def generate_random_tree(tree_height: int) -> List: if tree_height < 0: raise ValueError('tree_height should be a positive number') upper_limit: int = int(math.pow(2, tree_height)) lower_limit: int = int(math.pow(2, tree_height - 1) + 1) leaves_number: int = random.randint(lower_limit, upper_limit) root: List = ['1', None, None] if leaves_number < 2: return root generate_tree_nodes(root, 1, leaves_number) return root def generate_tree_nodes(tree: List, previous_node: int, nodes_limit: int) -> List: left_node: int = 2 * previous_node right_node: int = 2 * previous_node + 1 if previous_node > nodes_limit: return tree if left_node <= nodes_limit: tree[1] = [str(left_node), None, None] if right_node <= nodes_limit: tree[2] = [str(right_node), None, None] generate_tree_nodes(tree[1], left_node, nodes_limit) generate_tree_nodes(tree[2], right_node, nodes_limit) def bfs_traveling(tree: List) -> Generator: flatten_function = lambda nodes: [item for sublist in filter(None, nodes) for item in sublist] to_visit: List = tree.copy() tmp: List = tree.copy() while len(to_visit) > 0: for i in range(0, len(to_visit)): if not isinstance(to_visit[i], List): yield to_visit[i] for i in range(len(to_visit) - 1, -1, -1): if isinstance(to_visit[i], str): tmp.pop(i) to_visit = flatten_function(tmp) tmp = to_visit.copy() def dfs_traveling(tree: List) -> Generator: if tree is None: yield None return yield tree[0] yield from dfs_traveling(tree[1]) yield from dfs_traveling(tree[2]) if __name__ == '__main__': if len(sys.argv) != 2: print("Usage : python tree.py tree_height") exit(1) tree = generate_random_tree(int(sys.argv[1])) print(tree) print(list(bfs_traveling(tree))) print(list(dfs_traveling(tree)))
import math import numpy as np from math import sqrt from scipy.stats import norm class touchscreenEvaluator: def __init__(self): self.past_distributions = {} def calc_score_spherical(self, actual_frame, estimated_frame): """ Calculates the accuracy of a frame distribution. It works by looking at the estimated_frame and applying a normal distribution map over the actual position, rewarding points for higher distributions around the actual point. :param actual_frame: :param estimated_frame: :return: The score of the corresponding board """ n = actual_frame.shape[0] * actual_frame.shape[1] actual = np.reshape(actual_frame, n) estimated = np.reshape(estimated_frame, n) total = sum(estimated) if any(estimated < -0.001) or total > 1.001 or total < 0.999: print("Estimated frame is not a probability distribution!") return 0 idx = np.nonzero(actual)[0].item() # item returns the int r_i = estimated[idx] return r_i / np.linalg.norm(estimated) def evaluate_touchscreen_hmm(self, touchscreenHMM, simulation): """ Calculates the accuracy of the students project. :param touchscreenHMM: An instance of a student's touchscreenHMM :return: The 'percentage accuracy' from the calc_score function over the whole screen, and the 'percentage accuracy' of just inputting the noisy location. """ score = 0 count = 0 frame = simulation.get_frame(actual_position=True) while frame: count += 1 student_frame = touchscreenHMM.filter_noisy_data(frame[0]) if np.isnan(np.sum(student_frame)) or not math.isclose(np.sum(student_frame), 1): print("Encountered NAN or the sum of the probability distribution is not 1. Check your frame.") score += 0 break score += self.calc_score_spherical(frame[1], student_frame) frame = simulation.get_frame(actual_position=True) #averaging all the counts if count == 0: return 0; #preventing nan return round(score / count, 3)
#9.4 Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer. name = raw_input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) a = handle.read() b = a.split("\n") c = {} for i in b: if i.startswith("From "): d = i.split() if d[1] not in c: c[d[1]] = 1 else: c[d[1]] = 1 + c[d[1]] #print c prolific_email = None email_count = 0 for e,f in c.items(): if f > email_count: prolific_email = e email_count = f print prolific_email, email_count
for t in range(int(input())): n=int(input()) s=input() if('I' in s): print("INDIAN") elif('Y' in s): print("NOT INDIAN") else: print("NOT SURE")
for t in range(int(input())): n=int(input()) fact=1 for i in range(1,n+1): if(n==1 or n==0): fact=fact*1 else: fact=fact*i print(fact)
for _ in range(int(input())): n=int(input()) lst=list() for i in range(n): x=int(input()) if(x in lst): lst.remove(x) else: lst.append(x) print(*lst)
from compare import compare from number_letter_counts_dict import data, data_num ''' If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. ''' def reader(n): res = {} for i in range(n): a = n % 10 if a: res[10 ** i] = a n //= 10 if not n: return res def to_words(n): ret = '' res = reader(n) if 100 in res: ret += '{} {}'.format(data[res[100]], data[100]) if 10 in res or 1 in res: ret += ' and ' if 10 in res: if res[10] == 1: ret += data[res[10] * 10 + res.get(1, 0)] return ret else: ret += data[res[10]*10] if res.get(1, 0): ret += '-' if 1 in res: ret += data[res[1]] return ret def lin_direct(n): nw = to_words(n) nw = nw.replace(' ', '').replace('-', '') return len(nw) def lin_not_direct(n): res = reader(n) ret = 0 if 100 in res: ret += (data_num[100] + data_num[res[100]]) if 10 in res or 1 in res: ret += 3 if 10 in res: if res[10] == 1: ret += data_num[10 + res.get(1, 0)] return ret else: ret += data_num[10 * res[10]] if 1 in res: ret += data_num[res[1]] return ret def wrapper_direct(f): def inner(n): result = 0 for i in range(1, n): result += f(i) return result return inner def hz(n): # n неважно. Счет до 999 включительно sum1 = sum(data_num[i] for i in range(1, 10)) sum2 = sum(data_num[i] for i in range(10, 20)) sum3 = sum(data_num[i] for i in range(20, 100, 10)) other1 = data_num[100] other2 = len('and') #other3 = len('one thousand') - 1 result = (other1 * 900 + # 9 раз по 100 раз слово hundred other2 * 891 + # 9 раз по 100 раз - 9 #other3 + sum1 * (100 + 10 * 9) + # 9 раз в каждой сотне # + 100 раз в своей сотне sum2 * 10 + # один раз в каждой сотне sum3 * 10 * 10) # десять раз в каждой сотне return result direct = wrapper_direct(lin_direct) direct.__name__ = 'direct' not_so_direct = wrapper_direct(lin_not_direct) not_so_direct.__name__ = 'not_so_direct' if __name__ == '__main__': compare(1000, direct, not_so_direct, hz)
from compare import compare from primeFactor import factorisation ''' #014 The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Which starting number, under one million, produces the longest chain? ''' def next_collatz(n): if n % 2 == 0: return n // 2 else: return 3 * n + 1 def length_of_chain(n, store={}): res = 0 while n > 1: res += 1 n = next_collatz(n) return res def wrapper(f): def inner(n): mmax = (1, 1) store = {} for i in range(1, n+1): foo = f(i, store) if foo > mmax[1]: mmax = (i, foo) #if not i % 5000: #print(i, mmax) return i, mmax return inner def alt_length(n, store): res = 0 temp_store = {n: 0} while n > 1: res += 1 n = next_collatz(n) if not n in store: temp_store[n] = res else: for i in temp_store: store[i] = (res - temp_store[i]) + store[n] break else: for i in temp_store: store[i] = res - temp_store[i] return res + store[n] def test(f): def inner(n): store = {} for i in range(1, n): print(i, f(i, store=store)) return inner direct = wrapper(length_of_chain) not_so_direct = wrapper(alt_length) if __name__ == '__main__': compare(5000000, not_so_direct)
from compare import compare from math import sqrt from time import time FN = 'primes.txt' def prime_numbers(max_n): # не очень удачная реализация вычислялки простых чисел prime = [2,3] number = 5 j = 1 while True: if j == 3: j = 1 continue else: j += 1 for i in prime: if number % i == 0: break else: prime.append(number) number += 2 if number > max_n: return prime[-1] def prime_numbers_old(max_n): # более "наивная" реализация, но работает быстрее with open(FN, 'w') as out: prime = [2,3] number = 5 j = 1 for_write = [2,3] # -- Вычисление простых чисел в инервале [1,100] ------- for j in range(48): for i in prime: if number % i == 0: break else: prime.append(number) for_write.append(number) number += 2 # их запись for num in for_write: out.write('{}\t'.format(num)) out.write('\n') # ------------------------------------------------------ for_write = [] # -- Вычисление простых чисел в инервале [101,max_n] --- while True: # Вычисление ведется в каждой сотне чисел поочереди for j in range(50): for i in prime: if number % i == 0: break else: prime.append(number) for_write.append(number) number += 2 # запись результата после перебора очередной сотни чисел for num in for_write: out.write('{}\t'.format(num)) out.write('\n') for_write = [] # если достигли max_n заканчиваем выполнение if number > max_n: return prime[-1] def more_prime_numbers(n=1): primes = get_primes() print(len(primes)) number = get_number_of_line() * 100 + 1 print(number) for_write = [] with open(FN, 'a') as out: for i in range(n): for j in range(50): for k in primes: if number % k == 0: break else: primes.append(number) for_write.append(number) number += 2 for num in for_write: out.write('{}\t'.format(num)) out.write('\n') for_write = [] return len(primes) def is_it_prime(n): if n == 1: return True if n % 2 == 0: return False for i in range(3, int(sqrt(n))+1, 2): if n % i == 0: return False else: return True def read_one_line(s): ret = [i.strip() for i in s.split('\t')] ret = [int(i) for i in ret if i] return ret def get_number_of_line(): with open(FN, 'r') as out: lines = out.readlines() return len(lines) def _get_primes(start=0, stop=0): ret = [] with open(FN, 'r') as out: lines = out.readlines() full = len(lines) if stop > full: raise ValueError('Where is not {} lines'.format(stop)) if stop: for line in lines[start:stop]: ret += read_one_line(line) else: for line in lines[start:]: ret += read_one_line(line) return ret def get_primes(first=0, last=0): if first and last: f = (lambda x: (x >= first) and (x <= last)) start = first // 100 stop = last // 100 + 1 elif first: start = first // 100 f = (lambda x: x >= first) stop = 0 elif last: stop = last // 100 + 1 f = (lambda x: x <= last) start = 0 else: stop = 0 start = 0 f = (lambda x: True) ret = _get_primes(start=start, stop=stop) return [i for i in ret if f(i)] def get_number(n): nums = get_primes() if len(nums) < n: raise ValueError('Has only {} numbers'.format(len(nums))) else: print('Has {} numbers.'.format(len(nums))) print('{} number is {}.'.format(n, nums[n-1])) return nums[n-1] if __name__ == '__main__': compare(1000, more_prime_numbers)
# First week Tuesday # Topic Covered # Classes # Class Function # Using of class attrbute # Public behavior # Inheritance # calling function of parent through inheritance OOP concepts class Book: def __init__(self, name, pages, author): self.name = name self.pages = pages self.author = author def print(self): print("Book Name: {0}\nPages: {1}\nAuthor: {2}\n ".format(self.name, self.pages, self.author)) class MathBook(Book): def print(self): print(self.author + " This function is calling through Inheritance") print("Enter Book Name : ") book_name = input() print("Enter Book Pages : ") pages = input() print("Enter Book's Author Name : ") author_name = input() b1 = Book(book_name, pages, author_name) b1.print() b1.pages = 100 b1.print() # print(b1.name) math_book = MathBook(b1.name, b1.pages, b1.author) math_book.print()
# Uses python3 import sys def fibonacci_last_digit(n): current = 0 next = 1 for x in range(n): oldNext = next next = (current + next) % 10 current = oldNext return current if __name__ == '__main__': #input = sys.stdin.read() input = "832564823476" n = int(input) + 2 n = n % 60 print(str(((fibonacci_last_digit(n)) -1) % 10) )
# This is an implementation of the factorial function def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) def main(): print(factorial(5)) # Press the green button in the gutter to run the script. if __name__ == '__main__': main()
x=[1,2,3,4,5,6,7,8,9] x.remove(x[5] ) print(x[2:7] )# upto the element the last elemtn not including lst element # use neagtive number to go the end of the list:::::: # use index funtion to print the index value of the list x.index(3) # use count funtion the no same data in there for ex- x.count(3) output=1 # use sort funtion to sort the list x.sort() #print(x) boom list is sorted # this same funtion can be sort alphatbetical as well # use append() funtion to join the list for ex= x.append(list name,or an element) #use insert() funtion to insert new element in the array for examaple #list[3,3,3243,5,5,65,,,67,7,67,] #x.insert(2,34) # in the above statement 2 is baseally is index position where we need to insert #34 is element we need insert in the list
def hotel_cost(nights): return 140*nights def plane_ride_cost(city): if city=="Charlotte": return 183 elif city=="Tampa": return 220 elif city=="Pittsburgh": return 222 elif city=="Los Angeles": return 475 plane_ride_cost("Tampa") def rental_car_cost(days): if days>=7: return (days*40)-50 elif days>=3: return (days*40) -20 else: return days*40 def trip_cost(city,days,spending_money): return (rental_car_cost(days)+hotel_cost(days)+plane_ride_cost(city)+spending_money) print(trip_cost("Los Angeles",5,600))
#Dictionaries- a dictionaries consist of keys and value # we use curly barce to create dictionaary example= dict={} test={"tushar":18,"parmod":24,"sad":20,"mitul":20} print(test) test["lemon"]=30 # to add the info in the dictonries print(test) del test["lemon"] # to delete the info in the dict print(test) test["tushar"]=35 # to change the existing information print(test)
arr=(2,4,5) ## ##for c1 in range(10): ## for c2 in range(10): ## for c3 in range(10): ## if (c1,c2,c3) == arr: ## print("found the combo: {}".format((c1,c2,c3))) ## break ## print(c1,c2,c3) ##string formating ##for (c1,c2,c3) in arr: ## if(c1,c2,c3)==arr: ## print(c1,c2,c3) def comgen(): for c1 in range(10): for c2 in range(10): for c3 in range(10): yield(c1,c2,c3)# you can use genrater anything you want for (c1,c2,c3) in comgen(): print(c1,c2,c3) if (c1,c2,c3)==arr: print("found the combo: {}".format((c1,c2,c3))) break
phrase = "A bird in the hand..." # Add your for loop for char in phrase: if char=="A" or char=="a": print ("X"), else: print (char), def digit_sum(n): new=0 while(n>0): r=n%10 n=n//10 new=new+r return new print(digit_sum(500))
class Matrix: # grid is a 2D list (maybe should use an array) grid = [] def __init__(self, height, width): self.height = height self.width = width self.fill_grid() # be optional?, user cast # fill the matrix with 0 to width * height - 1 def fill_grid(self): for i in range(self.height): self.grid.append(list()) for j in range(self.width): self.grid[i].append(i * self.width + j) def print_grid(self): for i in range(self.height): for j in range(self.width): print(self.grid[i][j], end = ' ') print('') def swap(self, pos1, pos2): p1 = self.convert(pos1) p2 = self.convert(pos2) # \ is a line break to allow a statement be on multiple lines self.grid[p1[0]][p1[1]], self.grid[p2[0]][p2[1]]\ = self.grid[p2[0]][p2[1]], self.grid[p1[0]][p1[1]] # convert ordered number to grid coordinate def convert(self, pos): h = pos // self.width w = pos % self.width return (h, w) def get_element(self, pos): coord = self.convert(pos) return self.grid[coord[0]][coord[1]] # reset elements to be ordered def reset(self): for i in range(self.height): for j in range(self.width): self.grid[i][j] = i * self.width + j # test_b = Matrix(3, 4) # # test_b.fill_grid() # # test_b.print_grid() # test_b.swap(2, 3) # test_b.print_grid() # print(test_b.get_element(7)) # print(test_b.get_element(2))
from timeit import default_timer as timer board = [ [0,0,0, 0,3,0, 0,0,0], [0,0,1, 0,7,6, 9,4,0], [0,8,0, 9,0,0, 0,0,0], [0,4,0, 0,0,1, 0,0,0], [0,2,8, 0,9,0, 0,0,0], [0,0,0, 0,0,0, 1,6,0], [7,0,0, 8,0,0, 0,0,0], [0,0,0, 0,0,0, 4,0,2], [0,9,0, 0,1,0, 3,0,0] ] def print_board(): global board for i in range(9): if i % 3 == 0 and i != 0: print ("- - - - - - - - - - -") for j in range(9): if j % 3 == 0 and j != 0: print("| ", end='') if j == 8: print (board[i][j]) else: print (str(board[i][j]) + " ", end='') def find_empty(): global board for i in range(9): for j in range(9): if board[i][j] == 0: return (i, j) # row, col return None def valid(num, pos): global board # Check row for i in range(9): if board[pos[0]][i] == num and pos[1] != i: return False # Check column for i in range(9): if board[i][pos[1]] == num and pos[0] != i: return False # Check box box_x = pos[1] // 3 box_y = pos[0] // 3 for i in range(box_y*3, box_y*3 + 3): for j in range(box_x*3, box_x*3 + 3): if board[i][j] == num and (i,j) != pos: return False return True def solve(): global board find = find_empty() if not find: return True else: row, col = find #print ("\rSolving... Row: %d, Col: %d" % (row+1,col+1), end='') for i in range(1, 10): if valid(i, (row, col)): board[row][col] = i if solve(): return True board[row][col] = 0 return False print_board() start = timer() solve() print("") print("Seconds to Solve: ", timer() - start) print ("") print ("_____________________") print_board()
import pandas as pd def multiplyNumbers(numbers, multiplier): newList = [] for item in numbers: newList.append(item * multiplier) return newList print(multiplyNumbers([1, 2, 3, 4], 10))