text
stringlengths
37
1.41M
""" This program is an example demonstrating finding duplicate files across many diirectories. At the end it print out list of duplicate files in the directories. Run this program is as shown below: $ python duplicate_file_finder.py dir1 dir2 dir3 dir4 ..... Eg. $ python duplicate_file_finder.py dir1 /test1 /test2 Author: Nipun Talukdar """ import os import sys import glob import hashlib import shutil def file_checksum(filename): f = open(filename, 'r') if (f != None) : x = f.read() md5 = hashlib.md5() md5.update(x) f.close() return md5.hexdigest() return 0 def get_regular_files(dirname, regular_files): dirlist = [] try: files = os.listdir(dirname) for fname in files: realpath = dirname + '/' + fname if os.path.isfile(realpath): regular_files.append(realpath) elif os.path.isdir(realpath): dirlist.append(realpath) except OSError as oe: pass for dirfound in dirlist: get_regular_files(dirfound, regular_files) if len(sys.argv) > 1: dirs = set() i = 1 while i < len(sys.argv): dirs.add(sys.argv[i]) i = i + 1 regfiles = [] for dir in dirs: get_regular_files(dir , regfiles) checksum_list = {} for fpath in regfiles: checksum = file_checksum(fpath) if checksum not in checksum_list: checksum_list[checksum] = [] checksum_list[checksum].append(fpath) i = 1 for checksum in checksum_list: if len(checksum_list[checksum]) > 1: print 'Duplicate list ' + str(i) for fpath in checksum_list[checksum]: print fpath print '------\n-----' i = i + 1 i = 1 for checksum in checksum_list: if len(checksum_list[checksum]) == 1: print 'Unique file ' + str(i) + checksum_list[checksum][0]
''' Given A, B, C, find whether C is formed by the interleaving of A and B. Example: 1: A = "ab" B = "cd" C = "acdb" Here, C can be formed by the interleaving of A and B 2: A = "ab" B = "cd" C = "adbc" Here, C cannot be formed by the interleaving of A and B as 'd' and 'c' are coming out of orders in C. 2: A = "ab" B = "cd" C = "acd" Here, C cannot be formed by the interleaving of A and B as 'b' is missing in C ''' def is_interleaving(first, second, interleaved): if len(first) + len(second) != len(interleaved): return False; if len(first) == 0: return second == interleaved if len(second) == 0: return first == interleaved # interleaved must start with 0th char of first or second string if not first[0] == interleaved[0] and not second[0] == interleaved[0]: return False i = len(first) + 1 j = len(second) + 1 k = 0 matrix = [] while k < j: matrix.append([False] * i) k += 1 # 0 char from first, 0 char from second is equal 0 # char from interleaved matrix[0][0] = True # Now check how much of interleaved string can be formed # by using 0 char from second and all others from first k = 1 while k < i: if matrix[0][k - 1] and (first[k - 1] == interleaved[k - 1]): matrix[0][k] = True else: break k += 1 # Now check how much of interleaved string can be formed # by using 0 char from first and all others from second k = 1 while k < j: if matrix[0][0] and (second[k - 1] == interleaved[k - 1]): matrix[k][0] = True else: break k += 1 # Now we successively find out if interleaved[:n+m] can be formed # by interleaving first n chars from first and m chars from second # m varies from 1 to len(first) # n varies from 1 to len(second) # When we are on xth row of the matrix, we are actually trying to # check if (x - 1) chars from second string have been already seen, # and for that to happen, x - 2 chars have to be already present # in some prefix of interleaved. k = 1 ksecond_matched = False while k < j: #checking for a prefix of interleaved which can be formed #with k chars from second l = 1 ksecond_matched = matrix[k][0] while l < i: if not ksecond_matched: if matrix[k-1][l] and interleaved[k + l - 1] == second[k-1]: matrix[k][l] = True ksecond_matched = True else: # we have already matched k chars from second, check if a prefix # of length k + x can be obtained which is interleaved with # first k and x chars from second and first respectively if matrix[k][l - 1] and interleaved[k + l - 1] == first[l-1]: matrix[k][l] = True l += 1 k += 1 return matrix[j - 1][i - 1] test_data = [['a', 'b', 'ab', True], ['ab', '', 'ab', True], ['abc', 'd', 'abcd', True], ['ab', 'cd', 'abcd', True], ['ab', 'cd', 'abcde', False], ['ab', 'cde', 'aced', False], ['ab', 'cde', 'abcd' , False], ['ab', 'cde', 'aecdb', False], ['ab', 'cde', 'abcde', True]] for row in test_data: if is_interleaving(row[0], row[1], row[2]) != row[3]: print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Failed for ', row else: print 'Passed for', row
''' Topological sort with DFS: Start with any node in graph and add it to the head of a list L, if the node is not in L already do a DFS on the node's children (denoted by nodech) if nodech has children if some children are already in L, add nodech before \ the children with lowest index in the L else add the nodech to the tail of L if some children of nodech are not already on the L do DFS on each of them Finally L will contain the topologically sorted list of nodes ''' import unittest class Graph(object): def __init__(self): self.__nodes__ = set() def add_node(self, node): self.__nodes__.add(node) def iter(self): return iter(self.__nodes__) class Node(object): def __init__(self, identifier): self.__out_going__ = set() self.__in_coming__ = set() self.__identifier__ = identifier def add_incoming(self, node): if self.__identifier__ == node.__identifier__: return self.__in_coming__.add(node) node.__out_going__.add(self) def add_outgoing(self, node): if self.__identifier__ == node.__identifier__: return self.__out_going__.add(node) node.__in_coming__.add(self) def iterout(self): return iter(self.__out_going__) def iterin(self): return iter(self.__in_coming__) @property def value(self): return self.__identifier__ def __str__(self): outgoing = ','.join([str(x.__identifier__) for x in self.__out_going__]) incoming = ','.join([str(x.__identifier__) for x in self.__in_coming__]) return 'id={}, incoming={}, outgoing={}'.format(self.__identifier__, incoming, outgoing) def startdfs(node, visited, L): itero = node.iterout() try: while True: nodeo = itero.next() dfs(nodeo, visited, L) except StopIteration: pass def dfs(node, visited, L): if node in visited: return visited.add(node) already_seen = [] not_seen = [] try: itero = node.iterout() while True: nodeo = itero.next() if nodeo in visited: already_seen.append(nodeo) else: not_seen.append(nodeo) except StopIteration: pass if already_seen: # Some of the children were already added, # Ensure this node inserted before all of its children index where_to_insert = min([L.index(a) for a in already_seen]) L.insert(where_to_insert, node) else: L.append(node) for not_seen_node in not_seen: dfs(not_seen_node, visited, L) def topological_sort_dfs(graph): L = [] itern = graph.iter() visited = set() try: while True: node = itern.next() if node not in visited: visited.add(node) L.insert(0,node) startdfs(node, visited, L) except StopIteration: pass return L class MyTest(unittest.TestCase): def test_one(self): nodes = [] i = 0 while i < 10: nodes.append(Node(i)) i += 1 nodes[0].add_outgoing(nodes[1]) nodes[0].add_outgoing(nodes[2]) nodes[0].add_outgoing(nodes[9]) nodes[1].add_outgoing(nodes[3]) nodes[1].add_outgoing(nodes[4]) nodes[1].add_outgoing(nodes[5]) nodes[6].add_outgoing(nodes[7]) nodes[6].add_outgoing(nodes[9]) nodes[7].add_outgoing(nodes[8]) nodes[7].add_outgoing(nodes[9]) nodes[8].add_outgoing(nodes[9]) gr = Graph() for node in nodes: gr.add_node(node) L = [x for x in topological_sort_dfs(gr)] self.assertTrue(L.index(nodes[0]) < L.index(nodes[1])) self.assertTrue(L.index(nodes[0]) < L.index(nodes[2])) self.assertTrue(L.index(nodes[0]) < L.index(nodes[9])) self.assertTrue(L.index(nodes[7]) < L.index(nodes[8])) self.assertTrue(L.index(nodes[8]) < L.index(nodes[9])) i = 0 nodes = [] while i < 3: nodes.append(Node(i)) i += 1 nodes[0].add_outgoing(nodes[1]) nodes[1].add_outgoing(nodes[2]) gr = Graph() for node in nodes: gr.add_node(node) L = [x for x in topological_sort_dfs(gr)] self.assertTrue(L.index(nodes[0]) < L.index(nodes[1])) self.assertTrue(L.index(nodes[1]) < L.index(nodes[2])) if __name__ == '__main__': unittest.main()
#!/usr/bin/python import re notLetters = ('\'','"', ',', '.', '!', ' ', '\n','-','(',')',';',':','?','/','@','$','#','&',) count = 0 img = raw_input("what file? ") with open('data/'+str(img)+'.txt') as f: while True: c = f.read(1) if not c: break if c not in notLetters: #print c.upper() count += 1 print count count = 0 with open('data/'+str(img)+'.txt') as f: while True: c = f.read(1) if not c: break if re.match('^[a-zA-Z0-9]',c): #print c.upper() count += 1 print count
 import random ranTar=[0, 2, -2, 6, -6, 10, -10] #CJS 12/17/2016 sets=1 global frodo frodo = list() print ranTar[0] print frodo for x in range(1,sets+1, 1): random.shuffle(ranTar)#mix up the order frodo = frodo+[ranTar[0]] frodo = frodo+[ranTar[1]] frodo = frodo+[ranTar[2]] frodo = frodo+[ranTar[3]] frodo = frodo+[ranTar[4]] frodo = frodo+[ranTar[5]] frodo = frodo+[ranTar[6]] print frodo print frodo print len(frodo)
def sierpinski(n): pattern = draw(n, 'L', 0) return pattern def draw(n, pattern, idx): """ Recursive function to draw the fractal until n is reached """ if idx == n: return pattern else: return draw(n, make_triangle(pattern), idx + 1) def make_triangle(pattern): """ Takes the pattern, then puts the pattern repeated twice horizontally underneath it """ return "\n".join([pattern, next_to_each_other(pattern)]) def next_to_each_other(pattern): """ Takes the pattern, pads it to its widest point + 1, then appends the same pattern horizontally """ lines = pattern.splitlines() widest = len(max(lines, key=len)) + 1 for idx, line in enumerate(lines): lines[idx] = line.ljust(widest) + lines[idx] return "\n".join(lines) level0 = 'L' assert sierpinski(0) == level0 print(sierpinski(0)) level1 = ''' L L L '''.strip() assert sierpinski(1) == level1 print(sierpinski(1)) level2 = ''' L L L L L L L L L '''.strip() assert sierpinski(2) == level2 print(sierpinski(2)) level3 = ''' L L L L L L L L L L L L L L L L L L L L L L L L L L L '''.strip() assert sierpinski(3) == level3 print(sierpinski(3)) level4 = ''' L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L '''.strip() assert sierpinski(3) == level3 print(sierpinski(3))
# Form an array using np.arange which contains all even numbers. 10 to 30 import numpy as np array=np.arange(10,30,2) print("Array of all the even from 10 to 30") print(array)
# Get [1, 4, 5] from [[1, 2], [3, 4], [5, 6]] using indexing import numpy as np def extract(a_list): return a_list[0][0],a_list[1][1],a_list[2,0] arraylist = np.array([[1,2],[3,4],[5,6]]) print(extract(arraylist))
a=str(input("sA:")) b=str(input("sB:")) c=b.split(" ") n=c.count(a) if (n==1): print("子字串判斷為:YES") else: print("子字串判斷為:NO")
n=int(input("輸入一正整數:")) if(n%2==0 and n%11==0 and n%5!=0 and n%7!=0): print("%d為新公倍數?Yes"%n) else: print("%d為新公倍數?No"%n)
'''NON-RECURSIVE''' # def binpower(a,n): # res = 1 # cur = a # while n>0: # if n&1: # res *= cur # cur *= cur # n>>=1 # return res '''RECURSIVE''' def recubinpower(a,n): if n is 1: return a res = recubinpower(a,n//2) return res*res*(a if n%2 is not 0 else 1) a, n = input().split() a, n = int(a), int(n) # print(binpower(a,n)) print(recubinpower(a,n))
x = 0 if x < .0: print 'x must be atleat 0!' elif x == 0: print 'x equals to 0!' else: print 'x great than 0!'
user = raw_input('Enter login name:') print 'Your login is:', user num = raw_input('Now enter a number:') print 'Doubling your number: %d' % (int(num) * 2) help(raw_input)
#Desconto com juros, conforme escolha da forma de pagamento. print("{:=^40}".format(" LOJAS HELENA ")) preço = float(input("Digite o preço das compras R$ ")) print('''Formas de pagamento: [1] À VISTA - NO DINHEIRO OU CHEQUE [2] À VISTA - NO CARTÃO [3] 2 X NO CARTÃO [4] 3 X OU + NO CARTÃO ''') opção = int(input("Qual é a sua opção? ")) if opção == 1: total = preço - (preço * 10) / 100 elif opção == 2: total = preço - (preço * 5) / 100 elif opção == 3: total = preço parcela = total / 2 print("Sua compra será parcelada em 2x de R$ {:.2f} - SEM JUROS ".format(parcela)) elif opção == 4: total = preço + (preço * 20) / 100 totalparc = int(input("Quantas parcelas? ")) parcela = total / totalparc print("Sua compra será parcelada em {}x de R$ {:.2f} - COM JUROS ".format(totalparc, parcela)) else: total = preço print("OPÇÃO INVÁLIDA DE PAGAMENTO. Tente novamente!") print(" Sua compra de R$ {:.2f} vai custar R$ {:.2f} no final".format(preço, total))
student = { "name": "Arpista Banerjee", "age": "19", "location": "Kolkata", } student.clear() print(student) student = { "name": "Arpista Banerjee", "age": "19", "location": "Kolkata", } x = student.copy() print(x) a = ('key1', 'key2', 'key3') b = 0 dict1 = dict.fromkeys(x, y) print(dict1) student = { "name": "Arpista Banerjee", "age": "19", "location": "Kolkata", } x = car.get("model") print(x) car = { "brand": "Audi", "model": "R8", "year": 200 } x = car.items() print(x) car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.keys() print(x) """ Created on Mon Jul 12 20:00:24 2021 @author: arpis """
import numpy as np a = np.array([4, 10, 12, 23, -2, -1, 0, 0, 0, -6, 3, -7]) #1 print("There are", len(a[a < 0]), "negative numbers.") #2 print("There are", len(a[a > 0]), "positive numbers.") #3 b = a[a>0] print("There are", len(b[b%2 ==0]), "positive even numbers.") #4 c = a + 3 print("Adding 3 to each data point give the positive numbers would be:", c[c>0]) #5 a_squared = a ** 2 print("If we square every value in a, the number mean would be:", a_squared.mean(), "THe new standard deviation would be:", a_squared.std()) #6 a_centered = a - (a.mean()) print("The centered data is:", a_centered, "The mean of the centered data is:", a_centered.mean()) #7 a_z_score = (a - (a.mean()))/(a.std()) print("The z-scores of each point are:", a_z_score) # Life w/o numpy to life with numpy ## Setup 1 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Use python's built in functionality/operators to determine the following: # Exercise 1 - Make a variable called sum_of_a to hold the sum of all the numbers in above list sum_of_a = sum(a) a_array = np.array(a) print("The sum of a is:", a_array.sum()) # Exercise 2 - Make a variable named min_of_a to hold the minimum of all the numbers in the above list min_of_a = min(a) print("The minimum of a is:", a_array.min()) # Exercise 3 - Make a variable named max_of_a to hold the max number of all the numbers in the above list max_of_a = max(a) print("The maximum of a is:", a_array.max()) # Exercise 4 - Make a variable named mean_of_a to hold the average of all the numbers in the above list mean_of_a = sum(a)/len(a) print("The mean of a is:", a_array.mean()) # Exercise 5 - Make a variable named product_of_a to hold the product of multiplying all the numbers in the above list together def product(list): result = 1 for item in list: result = result * item return result product_of_a = product(a) print("The product of a is", a_array.prod()) # Exercise 6 - Make a variable named squares_of_a. It should hold each number in a squared like [1, 4, 9, 16, 25...] def squared(list): new_list = [] for item in list: item = item ** 2 new_list.append(item) return new_list squares_of_a = squared(a) print("The square of all the values in a is:", np.square(a_array)) # Exercise 7 - Make a variable named odds_in_a. It should hold only the odd numbers def find_odd(list): list_of_odds = [] for item in list: if item % 2 != 0: list_of_odds.append(item) return list_of_odds odds_in_a = find_odd(a) print("The odd numbers in a are:", a_array[a_array% 2 != 0]) # Exercise 8 - Make a variable named evens_in_a. It should hold only the evens. def find_even(list): list_of_even = [] for item in list: if item % 2 == 0: list_of_even.append(item) return list_of_even evens_in_a = find_even(a) print("The even numbers in a are:", a_array[a_array% 2 == 0]) ## What about life in two dimensions? A list of lists is matrix, a table, a spreadsheet, a chessboard... ## Setup 2: Consider what it would take to find the sum, min, max, average, sum, product, and list of squares for this list of two lists. b = [ [3, 4, 5], [6, 7, 8] ] # Exercise 1 - refactor the following to use numpy. Use sum_of_b as the variable. **Hint, you'll first need to make sure that the "b" variable is a numpy array** sum_of_b = 0 for row in b: sum_of_b += sum(row) b_matrix = np.array(b) print("The sum of b", np.sum(b_matrix)) # Exercise 2 - refactor the following to use numpy. min_of_b = min(b[0]) if min(b[0]) <= min(b[1]) else min(b[1]) print("The min of b is", np.min(b_matrix)) # Exercise 3 - refactor the following maximum calculation to find the answer with numpy. max_of_b = max(b[0]) if max(b[0]) >= max(b[1]) else max(b[1]) print("The max of b is", np.max(b_matrix)) # Exercise 4 - refactor the following using numpy to find the mean of b mean_of_b = (sum(b[0]) + sum(b[1])) / (len(b[0]) + len(b[1])) print("The sum of b is", np.sum(b_matrix)) # Exercise 5 - refactor the following to use numpy for calculating the product of all numbers multiplied together. product_of_b = 1 for row in b: for number in row: product_of_b *= number print("The product of b is", np.prod(b_matrix)) # Exercise 6 - refactor the following to use numpy to find the list of squares squares_of_b = [] for row in b: for number in row: squares_of_b.append(number**2) print("The square of every value in b is:", np.square(b_matrix)) # Exercise 7 - refactor using numpy to determine the odds_in_b odds_in_b = [] for row in b: for number in row: if(number % 2 != 0): odds_in_b.append(number) print("The odd values in b are:", b_matrix[b_matrix % 2 != 0]) # Exercise 8 - refactor the following to use numpy to filter only the even numbers evens_in_b = [] for row in b: for number in row: if(number % 2 == 0): evens_in_b.append(number) print("The even values in b are:", b_matrix[b_matrix % 2 == 0]) # Exercise 9 - print out the shape of the array b. print("The shape of b is:", np.shape(b_matrix)) # Exercise 10 - transpose the array b. transposed_matrix = [[0,0], [0 ,0], [0 ,0]] for i in range(len(b)): for j in range(len(b[0])): transposed_matrix[j][i] = b[i][j] print("The transpoed b matrix is:", b_matrix.transpose()) # Exercise 11 - reshape the array b to be a single list of 6 numbers. (1 x 6) list_of_b = [] for i in range(len(b)): for j in range(len(b[0])): list_of_b.append(b[i][j]) print("The single list is:", b_matrix.tolist()[0]) # Exercise 12 - reshape the array b to be a list of 6 lists, each containing only 1 number (6 x 1) six_lists = [] for i in range(len(b)): for j in range(len(b[0])): six_lists.append(b[i][j]) def list_of_lists(list): return [[item] for item in list] list_of_six_lists = list_of_lists(six_lists) print("The list of lists is:", b_matrix.reshape(6, 1).tolist()) ## Setup 3 c = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # HINT, you'll first need to make sure that the "c" variable is a numpy array prior to using numpy array methods. # Exercise 1 - Find the min, max, sum, and product of c. c_array = np.array(c).flatten() print("Min:", c_array.min(), "\n Max:", c_array.max(), "\n Sum:", c_array.max(), "\n Product:", c_array.prod()) # Exercise 2 - Determine the standard deviation of c. print("\n Standard Deviation:", c_array.std()) # Exercise 3 - Determine the variance of c. print("\n Variance:", c_array.var()) # Exercise 4 - Print out the shape of the array c c_matrix = np.array(c) print("C matrix", c_matrix) print(c_matrix.shape) # Exercise 5 - Transpose c and print out transposed result. print(c_matrix.transpose()) # Exercise 6 - Get the dot product of the array c with c. print(np.dot(c_matrix, c_matrix)) # Exercise 7 - Write the code necessary to sum up the result of c times c transposed. Answer should be 261 c_transpose = np.transpose(c_matrix) product_of_c = c_matrix * c_transpose print(np.sum(c_matrix*c_transpose)) # Exercise 8 - Write the code necessary to determine the product of c times c transposed. Answer should be 131681894400. print(product_of_c.prod()) ## Setup 4 d = [ [90, 30, 45, 0, 120, 180], [45, -90, -30, 270, 90, 0], [60, 45, -45, 90, -45, 180] ] # Exercise 1 - Find the sine of all the numbers in d d_matrix = np.array(d) print(np.sin(d_matrix)) # Exercise 2 - Find the cosine of all the numbers in d print(np.cos(d_matrix)) # Exercise 3 - Find the tangent of all the numbers in d print(np.tan(d_matrix)) # Exercise 4 - Find all the negative numbers in d print(d_matrix[d_matrix <0]) # Exercise 5 - Find all the positive numbers in d print(d_matrix[d_matrix > 0]) # Exercise 6 - Return an array of only the unique numbers in d. print(np.unique(d_matrix)) # Exercise 7 - Determine how many unique numbers there are in d. print("There are", len(np.unique(d_matrix)), "unique values in d.") # Exercise 8 - Print out the shape of d. print("The shape of d is:", np.shape(d_matrix)) # Exercise 9 - Transpose and then print out the shape of d. d_tranpose = d_matrix.transpose() print("The shape of d transposed is:", np.shape(d_tranpose)) # Exercise 10 - Reshape d into an array of 9 x 2 print(d_matrix.reshape(9,2))
sum = 0 while True : num = int( input(" Enter Any Number : ")) sum = sum + num print(" Press 1 For Add Another Number ") choice = int( input(" Enter Your Choice : ")) if choice != 1: break print(" Sum of Given Number : " , sum )
year = int( input(" Enter Any Year : " )) # Normal year :- 365 days = 52 Weeks + 1 Day # Leap Year :- 366 days = 52 Weeks + 2 Day totaldays = ( year - 1 ) * 365 totaldays += ( year - 1 ) // 4 totaldays -= ( year - 1 ) // 100 totaldays += ( year - 1 ) // 400 rem = totaldays % 7 result = " On 1st January, " + str(year) + " has " if rem == 0 : result += "Monday" else: if rem == 1 : result += "Tuesday" else: if rem == 2 : result += "Wednesday" else : if rem == 3 : result += "Thursday" else: if rem == 4 : result += "Friday" else: if rem == 5 : result += "Saturday" else : result += "Sunday" result += "." print( result )
hours = int( input(" Enter Hours : ")) minute = int( input(" Enter Minute : ")) minutes = hours * 60 + minute print(" Total Minute : " , minutes)
num = int( input(" Enter Any Number : ")) isprime = True range = num - 1 div = 2 while div <= range : if num % div == 0 : isprime = False div += 1 if isprime : print(" Given Number is Prime ") else : print(" Given Number is Composite ")
num = int( input(" Enter Any Five Digit Number : ")) temp = num rem = temp % 10 result = ( ( rem + 1 ) % 10 ) temp = temp // 10 rem = temp % 10 result = ( ( rem + 1 ) % 10 ) * 10 + result temp = temp // 10 rem = temp % 10 result = ( ( rem + 1 ) % 10 ) * 100 + result temp = temp // 10 rem = temp % 10 result = ( ( rem + 1 ) % 10 ) * 1000 + result temp = temp // 10 rem = temp % 10 result = ( ( rem + 1 ) % 10 ) * 10000 + result temp = temp // 10 print(" Result : " , result )
n1 = 432 n2 = 423 ans = n1 + n2 print(" The Answer : ans ") print(" The Answer : ", ans) print(" [ " , n1 , " + " , n2 , " = " , ans , " ] ")
print("how much miles you run...??") e=int(input()) f=e/1.60934 print(f"kilometers ranned: {e} converted to miles:{f}\n")
def check_validation(place, x, y): valid = True # 상하좌우 확인 directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] for d in directions: nx = x + d[0] ny = y + d[1] if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: continue if place[ny][nx] == 'P': # print(nx, ny, place[ny][nx]) valid = False break if valid: # 상상, 하하, 좌좌, 우우 확인 for d in directions: nx = x + d[0] * 2 ny = y + d[1] * 2 if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: continue if place[ny][nx] == 'P': if place[y+d[1]][x+d[0]] != 'X': valid = False break if valid: # 좌상 nx = x - 1 ny = y - 1 if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: pass else: if place[ny][nx] == 'P': if place[y-1][x] != 'X' or place[y][x-1] != 'X': valid = False if valid: # 우상 nx = x + 1 ny = y - 1 if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: pass else: if place[ny][nx] == 'P': if place[y-1][x] != 'X' or place[y][x+1] != 'X': valid = False if valid: # 좌하 nx = x - 1 ny = y + 1 if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: pass else: if place[ny][nx] == 'P': if place[y][x-1] != 'X' or place[y+1][x] != 'X': valid = False if valid: # 우하 nx = x + 1 ny = y + 1 if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: pass else: if place[ny][nx] == 'P': if place[y+1][x] != 'X' or place[y][x+1] != 'X': valid = False return valid def solution(places): answer = [] for place in places: valid = True for y in range(5): for x in range(5): if place[y][x] == 'P': valid = check_validation(place, x, y) if not valid: break if not valid: break if valid: answer.append(1) else: answer.append(0) return answer places = [["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPXX", "OXXXP", "POOXX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]] print(solution(places))
#! /usr/bin/env python # Revised Connection Example with Information retrival import socket print "Creating socket" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "done" print "Looking up port number" port = socket.getservbyname('http','tcp') print "done" print "Connecting to remote host on port %d ...." %port s.connect(("www.google.com",port)) print "done" print "Connected from:", s.getsockname() print "Connected to:", s.getpeername()
""" 言語処理100本ノック 2015 第1章: 準備運動 05. n-gram 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ. """ def n_gram(text_sequence,n): """ 与えられたシーケンス(文字列やリストなど)からn-gramを作成 Args: text_sequence: 任意のシーケンス(文字列やリストなど) n: n-gramのn Raise: 特になし Return: n-gram(リスト形式) Note:  特になし """ n_gram = [] sequence_index = 0 while sequence_index < len(text_sequence): n_gram_element = text_sequence[sequence_index:sequence_index+n] if len(n_gram_element) == n: n_gram.append(n_gram_element) sequence_index += 1 return n_gram # # 関数の呼び出し # text_sequence = "I am an NLPer" splited_text_sequence = text_sequence.split(' ') # 単語bi-gram print(n_gram(splited_text_sequence,2)) # 文字bi-gram print(n_gram(text_sequence, 2))
""" 言語処理100本ノック 2015 第1章: 準備運動 06. 集合 "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,'se'というbi-gramがXおよびYに 含まれるかどうかを調べよ. """ def n_gram(text_sequence, n): """ (05と共通)与えられたシーケンス(文字列やリストなど)からn-gramを作成 Args: str: 任意のシーケンス(文字列やリストなど) n: n-gramのn Raise: 特になし Return: n-gram(リスト形式) Note:  特になし """ n_gram = [] sequence_index = 0 while sequence_index < len(text_sequence): n_gram_element = text_sequence[sequence_index:sequence_index+n] if len(n_gram_element) == n: n_gram.append(n_gram_element) sequence_index += 1 return n_gram # # 関数の呼び出し # str_seq_1 = "paraparaparadise" str_seq_2 = "paragraph" X = frozenset(n_gram(str_seq_1,2)) Y = frozenset(n_gram(str_seq_2,2)) #frozenset({'ap', 'pa', 'ar', 'ad', 'di', 'se', 'is', 'ra'}) #frozenset({'ap', 'ph', 'pa', 'ar', 'ag', 'gr', 'ra'}) #和集合 print(X.union(Y)) #積集合 print(X.intersection(Y)) #差集合 print(X.difference(Y)) #'se'というbi-gramがXおよびYに含まれるかどうか print('se' in X) print('se' in Y)
""" 言語処理100本ノック 2015 第1章: 準備運動 07. テンプレートによる文生成 引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ. """ def template(x,y,z): """ 指定された引数x、y、zをテンプレートに埋め込んで文字列を生成 Args: x,y,z: テンプレートに埋め込むデータ Raise: 特になし Return: テンプレートに引数で指定されたデータを埋め込んだ文字列 Note:  特になし """ return "{0}時の{1}は{2}".format(x,y,z) # # 関数の呼び出し # x = 12 y = "気温" z = 22.4 print(template(x,y,z))
""" This script opens a simple GUI that allows a user to find the proper bike size for different sorts of bikes using the cyclist's measurements and preferences.""" from Tkinter import * import ttk import bikesizecalculator # Calls the bikesizecalculator method. Used for the button press def findbikes(): search_types = [] for bicycle_type in bicycle_types: if bicycle_types_selected[bicycle_type].get() == '1': search_types.append(bicycle_type) querystring = bikesizecalculator.generate_craigslist_query(search_types, inseam.get() ) query.set(querystring) # create root window object root = Tk() root.title("Bike Finder") # The types of bicycles that can be searched for, and a dictionary to store whether # each type of bike was selected bicycle_types = ["Touring", "Commuter", "Track", "Road", "Mixte"] number_of_types = len(bicycle_types) bicycle_types_selected = dict(zip(bicycle_types, [0]* number_of_types)) # Creates a main window using ttk, with appropriate grid and padding mainframe = ttk.Frame(root, padding="2 2 5 5") mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) # variable that stores the person's height in cm inseam = IntVar() query = StringVar() # dynamically creates checkbox buttons for bike types # manages the grid and creates 2 columns of checkboxes current_column = 1 current_row = 1 item_number = 0 for bicycle_type in bicycle_types: # for each bike type, create a checkbox and move to the next row indicator = StringVar() bicycle_types_selected[bicycle_type] = indicator ttk.Checkbutton(mainframe, text=bicycle_type, variable=indicator).grid( row=item_number/2, column=item_number%2, sticky=W) item_number += 1 current_row = item_number/2 + 2 # Create a slider to select height in centimeters slider = Scale(mainframe, label="Inseam in inches", from_=27, to=37, orient=HORIZONTAL, tickinterval=1, length=450, variable = inseam) slider.grid(column=0, row=current_row, sticky=W, columnspan=2) current_row += 1 # Button that is used to call the generation of the query findbutton = ttk.Button(mainframe, text='Find Bikes!', command=findbikes) findbutton.grid(column=0, row=current_row, sticky=E) current_row += 1 # on the last row, display the query query_entry = ttk.Entry(mainframe, textvariable=query) query_entry.grid(column=0, row=current_row, sticky=W, columnspan=2) # for each of the object created, do magic grid operation for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) root.mainloop()
n = int(input("enter the no.\n")) fact=1 if(n==1 or n==0): print("factorial",fact) elif(n<0): "enter a positive integer" else: for i in range(n): fact = fact*n n=n-1 print("factorial of {} is:".format(n),fact)
year = int(input("enter the year:\n")) if((year%400 == 0) or ((year%100 != 0) and (year%4 == 0))): print(year,"is leap year") else: print(year, "not a leap year")
# # @lc app=leetcode id=201 lang=python # # [201] Bitwise AND of Numbers Range # # https://leetcode.com/problems/bitwise-and-of-numbers-range/description/ # # algorithms # Medium (35.72%) # Total Accepted: 79.9K # Total Submissions: 223.5K # Testcase Example: '5\n7' # # Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND # of all numbers in this range, inclusive. # # Example 1: # # # Input: [5,7] # Output: 4 # # # Example 2: # # # Input: [0,1] # Output: 0 # class Solution(object): def rangeBitwiseAnd(self, m, n): """ :type m: int :type n: int :rtype: int """ mask = 2**32-1 while m & mask != n & mask: mask = mask << 1 return m & mask
import pandas as pd import numpy as np # Numpy Examples import numpy as np Nump_Array = np.array([[1,2,3],[4,5,6]]) print(Nump_Array) Nump_Array+=2 print(Nump_Array) #declare list of values list_of_strings = ["5","6","7","8","9", "10"] #declare empty list to store converted values result = [] #'not memory effiecent' for string in list_of_strings: result.append(int(string)) print(result) #'memory efficent' can change first param to int, str, float result = map(float,list_of_strings) print(list(result))
''' Program to turn off n number of bits ''' import my_util as util def turnoff_n_bits(num, pos, no_of_bits): return num & ~ ( (2 ** no_of_bits - 1) << (pos - no_of_bits) ) if __name__ == '__main__': num = int(input("Enter Number: ")) print('BINARY REPRESENTATION: ', util.decimal_to_binary(num)) pos = int(input('Enter Position: ')) no_of_bits = int(input('Enter Number of bits to turn off: ')) result = turnoff_n_bits(num, pos, no_of_bits) print('Result - {} | Binary - {}'.format(result, util.decimal_to_binary(result)))
# Ali Shahdi # Coding test from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import urllib2 import json # Class for handling REST APIs class RESTHandler(BaseHTTPRequestHandler): # Generating the header for HTTP response def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() # Respond to GET requests def do_GET(self): # Ignore faivcon requests if self.path == '/favicon.ico': pass else: # Generate the header self._set_headers() # Send geocoding requests using Google and HERE APIs and parse the lat/lng results for the address jsonOutput = self.geoCode() # Send back the result to the requester self.wfile.write(jsonOutput) # Not doing anything on REST POST requests def POST(self): pass # Geocoding the address def geoCode(self): # Get the address from the requester URL path address = self.path # Try using Google APIs first (failure to connect be simulated by changing this URL) try: # Google geocoding API GET request geoURL = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyDzVSbsHjzNyN6LEcASEJ29Cmrj9ET4qZo" % address request = urllib2.urlopen(geoURL) jsonResponse = json.loads(request.read()) # If the returned staus is OK parse lat/lng and return the values if jsonResponse['status'] == 'OK': plat = jsonResponse['results'][0]['geometry']['location']['lat'] plng = jsonResponse['results'][0]['geometry']['location']['lng'] # Creating the JSON output from the lat/lng info data = {} data['status'] = 'OK' data['lat'] = plat data['lng'] = plng data['source'] = 'Google' jsonOutput = json.dumps(data) return jsonOutput # Google servers responded but the address was invalid else: data = {} data['status'] = 'Invalid' data['source'] = 'Google' jsonOutput = json.dumps(data) return jsonOutput # Google servers cannot be reaced, trying to use HERE APIs as the backup (catching all the exceptions) except: try: print("Google failed trying HERE") #HERE geocoding API GET request geoURL = "https://geocoder.cit.api.here.com/6.2/geocode.json?app_id=ykrI6wAjdahtpMwgZxhh&app_code=t1R7EyxS-G_q-VT78OcikA&searchtext=%s" % address request = urllib2.urlopen(geoURL) jsonResponse = json.loads(request.read()) # Check to see if the result is valid and return the values if len(jsonResponse['Response']['View']) > 0: plat = jsonResponse['Response']['View'][0]['Result'][0]['Location']['DisplayPosition']['Latitude'] plng = jsonResponse['Response']['View'][0]['Result'][0]['Location']['DisplayPosition']['Longitude'] # Creating the JSON output from the lat/lng info data = {} data['status'] = 'OK' data['lat'] = plat data['lng'] = plng data['source'] = 'HERE' jsonOutput = json.dumps(data) return jsonOutput else: # HERE servers has responded but the address was invalid data = {} data['status'] = 'Invalid' data['source'] = 'HERE' jsonOutput = json.dumps(data) return jsonOutput # Both APIs are failing except: data = {} data['status'] = 'Disconnected' jsonOutput = json.dumps(data) return jsonOutput # Running the HTTP server on PORT 8888 def runServer(serverClass = HTTPServer, handlerClass = RESTHandler, port = 8888): address = ('', port) httpServer = serverClass(address, handlerClass) print 'Starting the http server on port %d ...' % port try: httpServer.serve_forever() except KeyboardInterrupt: pass print 'Stopping the HTTP server ...' httpServer.server_close() # __main__ if __name__ == "__main__": runServer()
from PIL import Image, ImageDraw import random as random my_map = Image.new('RGB', (600, 600), color=(0, 0, 0)) draw = ImageDraw.Draw(my_map) with open('elevation_small.txt') as file: # Use file to refer to the file object data = file.readlines() elevations = [[int(each) for each in line.split()] for line in data] def get_max_and_min(elevations): minimum = elevations[0][0] maximum = elevations[0][0] for each in elevations: for point in each: if point < minimum: minimum = point if point > maximum: maximum = point return (minimum, maximum) def convert_elevations_to_brightness(elevations, minimum, maximum): brightness_big_list = [] row_of_brightness = [] for row in elevations: for elevation in row: brightness = round(((elevation - minimum) / (maximum-minimum)) * 255) row_of_brightness.append(brightness) brightness_big_list.append(row_of_brightness) row_of_brightness = [] return brightness_big_list def draw_map(brightness_big_list): for y, row in enumerate(brightness_big_list, 0): for x, brightness in enumerate(row, 0): my_map.putpixel((x, y), (brightness, brightness, brightness)) def taking_greedy_path(): x = 0 y = random.randint(0, len(elevations)) point = (elevations[x][y]) while x < (len(elevations) - 1): upper_right = abs((elevations[x+1][y-1]) - point) middle_right = abs((elevations[x+1][y]) - point) lower_right = abs((elevations[x+1][y+1]) - point) choose_smallest_elevation = min(upper_right, middle_right, lower_right) if choose_smallest_elevation == upper_right: y -= 1 x += 1 point = (elevations[x][y]) my_map.putpixel((x, y), (255, 0, 0)) elif choose_smallest_elevation == middle_right: x += 1 point = (elevations[x][y]) my_map.putpixel((x, y), (255, 0, 0)) elif choose_smallest_elevation == lower_right: y += 1 x += 1 point = (elevations[x][y]) my_map.putpixel((x, y), (255, 0, 0)) list_info = get_max_and_min(elevations) minimum = list_info[0] maximum = list_info[1] brightness = convert_elevations_to_brightness(elevations, minimum, maximum) draw_map(brightness) taking_greedy_path() my_map.save('map.png')
# --- Lists---- # int, str : building blocks # list: data structures # list is a collection of items in a particular order # inside a list: numbers, strings, numbers and strings # -- creating list #0 #1 #2 #3 bicycles = ['trek','cannon','redline','specialized'] #-4 #-3 #-2 #-1 print(bicycles) print(type(bicycles)) # print(dir(bicycles)) # -- accessing elements # index starts with 0 # print(type(bicycles[0])) # print(bicycles[0].title()) # print(bicycles[2]) # negative indexes # print(bicycles[-4]) # -- using individual items from a list message = "My first bicycle was a "+bicycles[0].title()+"." print(message)
#사용자로부터 하나의 값을 입력받은 후 해당 값에 20을 뺀 값을 출력하라. 단 값의 범위는 0~255이다. 0보다 작은 값이되는 경우 0을 출력해야 한다. user = input("입력값: ") num = int(user) - 20 if num > 255: print(255) elif num < 0: print(0) else: print(num)
import sys max = -sys.maxsize -1 min = sys.maxsize num = [8,7,3,2,9,4,1,6,5] for i in range(len(num)): if min >= num[i]: min = num[i] if max <= num[i]: max = num[i] print("최댓값 :", max) print("최솟값 :", min)
def pow_xy(x,y): res = x**y return res print("3 * 2**4 + 5 =",(3 * pow_xy(2,4) +5))
import turtle as t t.shape("turtle") t.write(t.position()) t.forward(100) t.write(t.position()) t.left(90) t.forward(100) t.write(t.position()) t.write(t.position()) t.forward(100) t.write(t.position()) t.left(90) t.forward(100) t.write(t.position()) import turtle as t t.shape("turtle") t.write(t.position()) t.forward(100) t.write(t.position()) t.left(90) t.forward(100) t.write(t.position()) import turtle as t t.shape("turtle") t.write(t.position()) t.forward(100) t.write(t.position()) t.left(90) t.forward(100) t.write(t.position())
import turtle as t def draw_pos(x,y): t.clear() t.setpos(x,y) t.stamp() hl = -(t.window_height() / 2) tm = 0 while True: d = (9.8 * tm**2) / 2 ny = y - int(d) if ny > hl: t.goto(x,ny) t.stamp() tm = tm + 0.3 else: break t.setup(500, 600) t.shape("circle") t.shapesize(0.3, 0.3, 0) t.penup() s = t.Screen() s.onscreenclick(draw_pos) s.listen()
import random import math from problemGenerator.Node import Node import matplotlib.pyplot as plt class Generator: """ This class is used to generate random problems to the Multiple Knapsack Problem for Package Delivery Drones ... Attributes ---------- nodes : List<Node> a list of Node objects randomly generated maxRange: this is the highest value a node's coordinates rangeMultiplyer : highest value added to maxRange noOfNodes : number of nodes to be randomly generated noOfPackages : number of packages to be randomly generated nodemaxRangeRatio: value between 0 and 1 which is multiplied with rangeMultiplyer to give a value which determines the spread distance of nodes. distribution: setting for controlling the distribution of the nodes. uniform = pseudo-randomly generated across the range clustered = problem is randomly created with dense clusters of nodes Methods ------- generateNodes() randomly generates the number of nodes specified by noOfNodes attribute """ nodes = [] maxRange = 10 rangeMultiplyer = 100 clusterToRangeRatio = .25 clusterDeviationFromPoint = 5 def __init__(self, noOfNodes=10, noOfPackages=5 , nodemaxRangeRatio=.5, distribution="uniform" ): self.noOfNodes = noOfNodes self.noOfPackages = noOfPackages if not(distribution == "uniform" or distribution == "clustered"): print("distribution should be either 'uniform' or 'clustered' defaulting to uniform") distribution = "uniform" self.distribution = distribution if nodemaxRangeRatio <= 0: nodemaxRangeRatio = 0.01 self.nodemaxRangeRatio = nodemaxRangeRatio def uniformGeneration(self): for _ in range(self.noOfNodes): node = Node() node.random(0, self.maxRange) self.nodes.append(node) fig, ax1 = plt.subplots(1,1) for node in self.nodes: x, y = node.str() ax1.set_xlim([0,150]) ax1.set_ylim([0,150]) ax1.scatter(x,y, alpha=0.8) plt.show() def createClusterCenters(self): numberOfClusters = math.floor(self.maxRange * self.clusterToRangeRatio) clusterCenters = [] for _ in range(numberOfClusters): cluster = Node() cluster.random(0, self.maxRange) clusterCenters.append(cluster) self.nodes.append(cluster) return clusterCenters def clusteredGeneration(self): clusterCenters = self.createClusterCenters() for _ in range(self.noOfNodes): node = Node() clusterIndex = random.randint(0, len(clusterCenters) - 1 ) Node.deepCopy(clusterCenters[clusterIndex], node) node.xCoord += (random.random() * self.clusterDeviationFromPoint) node.yCoord += (random.random() * self.clusterDeviationFromPoint) self.nodes.append(node) fig, ax1 = plt.subplots(1,1) for node in self.nodes: x,y = node.str() ax1.set_xlim([0,150]) ax1.set_ylim([0,150]) ax1.scatter(x,y, alpha=0.8) plt.show() def generateNodes(self): upperLimit = 10 self.maxRange = self.maxRange + math.floor(self.rangeMultiplyer * self.nodemaxRangeRatio) print (self.maxRange) if self.distribution == "uniform": self.uniformGeneration() else: self.clusteredGeneration()
# Crash Course in Python # Author: Breanna McBean # How to create plots using Python # May 28, 2019 ############################################## # Plotting in Python import numpy as np import pandas as pd import matplotlib.pyplot as plt # The package matplotlib allows you to create plots similar to the way you would in MATLAB # Create a simple plot # plt.plot([1,2,3,4]) # Giving "plot(x)" only one input causes is to plot (1,1), (2,2), (3,3), (4,4) # plt.ylabel('some numbers') # Similar commands can be used to add the x axis label and a title # plt.show() # Use the "show()" function to create the plot # Note: I will comment out all of the "show()" functions because it is easiest to have only one # run at a time # You can change the style of the plots # plt.figure() # Using the "figure()" function is like the one in MATLAB. It allows you to generate more than one figure # at a time and allows for different settings on each one # plt.plot([1,2,3,4], [1,4,9,16], 'ro') # Here, we will plot (1,1), (2,4), (3,9), (4,16) using red dots # plt.axis([0, 6, 0, 20]) # This creates axis ranges (x will be 0 to 6, y will be 0 to 20) # plt.show() # You can also plot multiple elements on the same plot # plt.figure() # t = np.arange(0., 5., 0.2) # evenly sampled time at 200ms intervals # plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') # red dashes, blue squares and green triangles # plt.show() # You can also plot functions and use subplots # def f(t): # return np.exp(-t) * np.cos(2*np.pi*t) # # t1 = np.arange(0.0, 5.0, 0.1) # t2 = np.arange(0.0, 5.0, 0.02) # # plt.figure() # plt.subplot(211) # # (Number of rows, number of columns, subplot number) # plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') # plt.subplot(212) # plt.plot(t2, np.cos(2*np.pi*t2), 'r--') # plt.show() # Check out https://matplotlib.org/users/pyplot_tutorial.html for more info on ways you can modify graphs and for # things like using nonlinear axes and other types of plots. ############################################## # Using Pandas data frames to create plots # # Histograms # # Let's look at the ages of people aboard the Titanic # survival_data = pd.read_csv("TitanicSurvival.csv") # print(survival_data.loc[0]) # # age_data = survival_data["age"].dropna() # # Age has NaN values for where age was not recorded. This "dropna" removes all of those entries # plt.figure(1) # plt.hist(age_data) # plt.xlabel("Age") # plt.ylabel("Count") # plt.text(0, 100, r"$\mu$=" + str(round(age_data.mean(), 2)) + "\n" + r"$\sigma$=" + str(round(age_data.std(), 2))) # # The "text(x,y,text)" command allows us to add "text" starting at the (x,y) coordinate of the plot. # # Here, we added mean and standard deviation. # # The 'r' tells it to interpret it using TeX. # # The "round(num,dec)" command allows us to round to "dec" decimal places # plt.show() # Let's look at the difference in survival rate by class survival_data = pd.read_csv("TitanicSurvival.csv") # Get x axis labels group_names = survival_data["passengerClass"].unique() print(group_names) # Use the function we previously created to turn a string into a 0 or 1 def StringtoBoolean(status): if status == "no": return 0 elif status == "yes": return 1 survival_data["bool_survived"] = survival_data["survived"].apply(StringtoBoolean) classes = survival_data.groupby("passengerClass") print(classes.first()) # Find averages for y axis x = classes["bool_survived"].mean() averages = [x[0], x[1], x[2]] y_pos = np.arange(len(averages)) # Create the plot plt.bar(y_pos, averages, align='center', alpha=0.5) plt.xticks(y_pos, group_names) plt.ylabel('Survival Rate') plt.show()
def ex1(): num=int(input("inputnumber")) x=0 while x < num: x+=1 print(x) def ex2(): num=int(input("inputnumber")) x=0 while x < num: x+=1 if n%x ==0: print(x)
""" The "Cell Layout": | 11 | 7 12 | 4 8 13 | 2 5 9 14 | 1 3 6 10 15 """ def log(arg): # Reminder foo.bar don't like print! print(arg) pass def solution(x, y): """ Retrieve the value at location (x,y) in that cell layout above. """ # Use something like the radial axis, or what we'll call a "diagonal stripe" # First create the zero-referenced row & column x0 = x - 1 y0 = y - 1 # x0, y0 = x - 1, y - 1 # The "stripe", or "radius", is just the sum of the two. stripe = x0 + y0 log(stripe) # Sort out the first/ leftmost entry in the stripe stripe_start = 1 + sum([(k + 1) for k in range(stripe)]) log(stripe_start) # The answer just is that leftmost entry, plus the x-offset # And remember they want it as a string! return str(stripe_start + x0) def solution(x, y): """ Retrieve the value at location (x,y) in that cell layout above. """ # One-liner edition: return str(x + sum([(k + 1) for k in range(x + y - 2)])) # Google's (Public) Tests assert (solution(5, 10) == '96') # My Tests assert (solution(1, 1) == "1") assert (solution(1, 2) == "2") assert (solution(2, 1) == "3") assert (solution(1, 3) == "4") assert (solution(2, 2) == "5") assert (solution(3, 1) == "6") assert (solution(1, 4) == "7") assert (solution(2, 3) == "8") assert (solution(3, 2) == "9") assert (solution(4, 1) == "10") assert (solution(1, 5) == "11") assert (solution(2, 4) == "12") assert (solution(3, 3) == "13") assert (solution(4, 2) == "14") assert (solution(5, 1) == "15")
''' 15 puzzle problem States are defined as string representations of the pieces on the puzzle. Actions denote what piece will be moved to the empty space. States must always be immutable. We will use strings, but internally most of the time we will convert those strings to lists, which are easier to handle. For example, the state (string): '1-2-3-4 5-6-7-8 9-10-11-12 13-14-15-e' will become (in lists): [['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '10', '11','12], ['13','14','15','e']] ''' import sys sys.path.append('../../../simpleai') # if you didn't install simpleai package, just clone the repo and append it to the path from simpleai.search import astar, uniform_cost, depth_first, limited_depth_first, breadth_first, iterative_limited_depth_first GOAL = '''1-2-3-4 5-6-7-8 9-10-11-12 13-14-15-e''' ## easy ### INITIAL = '''1-e-2-4 5-7-3-8 9-6-11-12 13-10-14-15''' ### Case 1 ### # INITIAL = '''11-5-12-14 # 15-2-e-9 # 13-7-6-1 # 3-10-4-8''' # # ### Case 2 ### # INITIAL = '''13-5-8-3 # 7-1-9-4 # 14-10-6-15 # 2-12-11-e''' def list_to_string(list_): return '\n'.join(['-'.join(row) for row in list_]) def string_to_list(string_): return [row.split('-') for row in string_.split('\n')] def find_location(rows, element_to_find): '''Find the location of a piece in the puzzle. Returns a tuple: row, column''' for ir, row in enumerate(rows): for ic, element in enumerate(row): if element == element_to_find: return ir, ic # we create a cache for the goal position of each piece, so we don't have to # recalculate them every time goal_positions = {} rows_goal = string_to_list(GOAL) # for 15 nums nums = [str(i) for i in range(1, 16)] nums.append('e') for number in nums: goal_positions[number] = find_location(rows_goal, number) class FifteenPuzzleProblem(): def __init__(self, initial_state=None): self.initial_state = initial_state def actions(self, state): '''Returns a list of the pieces we can move to the empty space.''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') actions = [] if row_e > 0: actions.append(rows[row_e - 1][col_e]) if row_e < 3: actions.append(rows[row_e + 1][col_e]) if col_e > 0: actions.append(rows[row_e][col_e - 1]) if col_e < 3: actions.append(rows[row_e][col_e + 1]) return actions def result(self, state, action): '''Return the resulting state after moving a piece to the empty space. (the "action" parameter contains the piece to move) ''' rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') row_n, col_n = find_location(rows, action) rows[row_e][col_e], rows[row_n][col_n] = rows[row_n][col_n], rows[row_e][col_e] return list_to_string(rows) def is_goal(self, state): '''Returns true if a state is the goal state.''' return state == GOAL def cost(self, state1, action, state2): '''Returns the cost of performing an action. No useful on this problem, i but needed. ''' return 1 def heuristic(self, state): '''Returns an *estimation* of the distance from a state to the goal. We are using the manhattan distance. ''' rows = string_to_list(state) distance = 0 # for 15 nums # nums = [str(i) for i in range(1, 16)] # nums.append('e') for number in nums: row_n, col_n = find_location(rows, number) print(find_location(rows, number)) row_n_goal, col_n_goal = goal_positions[number] distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal) return distance def main(): # to record running time import time start = time.time() #### Uncomment an algorithm to use #### # result = depth_first(FifteenPuzzleProblem(INITIAL), 1) result = breadth_first(FifteenPuzzleProblem(INITIAL), 1) # result = limited_depth_first(FifteenPuzzleProblem(INITIAL), depth_limit=8) # result = iterative_limited_depth_first(FifteenPuzzleProblem(INITIAL),1) end = time.time() def report_result(result): count = 1 for action, state in result.path(): print("**** STEP NUMBER: {} ****".format(count)) count += 1 print('Move number', action) print(state) # Running time print("\ntime taken: ", end - start) report_result(result) # visualize the solution using pygraph module, to use pygraph see: http://github.com/iamaziz/pygraph try: from pygraph.dgraph import PyGraph except ImportError: pass name = 'easy-BFS' def vizit(name): g = PyGraph() for i in range(len(result.path())): try: a1, s1 = result.path()[i] a2, s2 = result.path()[i+1] r = [s1, a2, s2] relation = ' '.join(r) g.add_relation(relation) except IndexError: pass g.draw_graph("15-puzzle-{}".format(name), orientation="LR") # vizit(name) if __name__ == '__main__': main()
import numpy as np def read_mask(file): """Read in a Polar Stereographic mask file. Args: file (string): full path to a Polar Stereographic mask file Returns: A tuple containing data, extent, hemisphere data: a two-dimensional numpy array, nrows x ncolumns extent: A tuple containing (lonmin, lonmax, latmin, latmax) in km hemisphere: 1 for Northern, -1 for Southern Examples: data, extent, hemisphere = read_mask("masks/pole_n.msk") """ dtype = np.uint8 # Python is in row-major order so the vertical dimension comes first if "12n" in file: hemisphere = 1 dims = 896, 608 extent = (-3850000, 3750000, -5350000, 5850000) if "12s" in file: hemisphere = -1 dims = 664, 632 extent = (-3950000, 3950000, -3950000, 4350000) if "25n" in file or "pole_n" in file or \ "region_n" in file or "N17" in file: hemisphere = 1 dims = 448, 304 extent = (-3850000, 3750000, -5350000, 5850000) if "25s" in file or "region_s" in file: hemisphere = -1 dims = 332, 316 extent = (-3950000, 3950000, -3950000, 4350000) if "ntb" in file: hemisphere = 1 dtype = np.uint16 dims = 448, 304 extent = (-3850000, 3750000, -5350000, 5850000) if "stb" in file: hemisphere = -1 dtype = np.uint16 dims = 332, 316 extent = (-3950000, 3950000, -3950000, 4350000) if "region" in file: # the "region" files have a 300-byte header that we need to skip over dt_header = ('header', np.uint8, 300) dt_data = ('data', np.uint8, dims[0] * dims[1]) dt = np.dtype([dt_header, dt_data]) data = np.fromfile(file, dtype=dt) data = np.reshape(data['data'], dims) else: data = np.fromfile(file, dtype=dtype, count=dims[0] * dims[1]) data = np.reshape(data, dims) return data, extent, hemisphere
def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna) def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ return len(dna1) > len(dna2) def count_nucleotides(dna, nucleotide): """ (str, str) -> int Return the number of occurrences of nucleotide in the DNA sequence dna. >>> count_nucleotides('ATCGGC', 'G') 2 >>> count_nucleotides('ATCTA', 'G') 0 """ count_n = 0 for i in dna: if nucleotide == i: count_n += 1 return count_n def contains_sequence(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna2 occurs in the DNA sequence dna1. >>> contains_sequence('ATCGGC', 'GG') True >>> contains_sequence('ATCGGC', 'GT') False """ return dna2 in dna1 def is_valid_sequence(dna): """(str)->bool Return True if DNA sequence has only valid ATCG letters. >>> is_valid_sequence('ATCGGC') Trune >>> is_valid_sequence('AHTC') False """ valid = True for i in dna: if i not in 'ATCG': valid = False return valid def insert_sequence(dna1, dna2, pos): """(srt,str,int) -> str Return string of dna1 inserted in dna1 at specified position. >>> insert_sequence('CCGG','AT', 2) 'CCATGG' >>> insert_sequence('CCGG','AT',0) 'ATCCGG' >>> insert_sequence('CATGG','CCA', 5) 'CATGGCCA """ new_dna = dna1[:pos] + dna2 + dna1[pos:] return new_dna def get_complement(dna): """(str)->str Return the DNA complement for each DNA in given string. >>>get_complement('A') 'T' >>>get_coplement('T') 'A' >>>get_coplement('G') 'C' """ if dna == 'A': return 'T' elif dna == 'T': return 'A' elif dna == 'C': return 'G' elif dna == 'G': return 'C' def get_complementary_sequence(dna): """(str)->str Return the complement DNA sequence for the input. >>>get_complementary_sequence('AT') 'TA' >>>get_complementary_sequence('GATTACT') 'CTAATGA' """ comp = '' for i in dna: comp = comp + get_complement(i) return comp
#!/usr/bin/env python import argparse import re import sys def find_color(data, color): bags = [] for k in data: if color in data[k]: bags.append(k) return bags def count_containing_bags(data, color): """ Depth First Search Recursive """ # print(path) total = 1 if data[color] == {}: return total for c in data[color]: count = data[color][c] total += count * count_containing_bags(data, c) return total def main(args): """ """ rules = dict() baggage = dict() with open(args.input, 'r') as fh: d = fh.read() rules = d.split('\n') # store baggage rules for r in rules: (bag, contents) = r.split(' bags contain ') baggage[bag] = dict() if contents == 'no other bags.': # bag contents is the empty dictionary continue for c in contents.split(','): c = c.rstrip().lstrip() r = re.match('(\d+) (\w+ \w+) bag.*', c) count, color = r.groups() baggage[bag][color] = int(count) gold_containers = find_color(baggage, 'shiny gold') # Grab all bags that contain the a bag that can hold gold for g in gold_containers: gold_containers += find_color(baggage, g) containers = baggage['shiny gold'] # Walking a tree and multiplying nodes # Don't count root shiny gold bag s = count_containing_bags(baggage, 'shiny gold') - 1 print(s) if __name__ == '__main__': desc = 'Advent 7a' parser = argparse.ArgumentParser(description=desc) parser.add_argument('--input', type=str, help='Puzzle Input') args = parser.parse_args() main(args)
#!/usr/bin/env python import argparse def main(args): costs = list() with open(args.input, 'r') as fh: for line in fh: line = line.rstrip() costs.append(int(line)) for z, entry in enumerate(costs): diff1 = 2020 - entry for y, entry2 in enumerate(costs): if y == z: continue diff2 = diff1 - entry2 if diff2 in costs: if entry + entry2 + diff2 == 2020: print(entry, entry2, diff2, entry * entry2 * diff2) if __name__ == '__main__': desc = 'Advent 1a' parser = argparse.ArgumentParser(description=desc) parser.add_argument('--input', type=str, help='Puzzle Input') args = parser.parse_args() main(args)
print("Bienvenidos al transformador de Farenheit a Celsius.") Faren = float(input("Introduce grados Farenheit: ")) Cel = (Faren - 32) / 1.8 print("{} grados Farenheit son {} grados Celsius".format(Faren, Cel))
#Crear un programa que guarde e imprima varias listas y sean múltiplos de 2, de 3, de 5 y de 7. lista_user = input("Introduce un numero: (Escribe 'go' para iniciar) ") lista_numeros = [] while lista_user != 'go': if lista_user.isdigit(): lista_numeros.append(int(lista_user)) lista_user = (input("Introduce un numero: (Escribr 'go' para inciar) ")) print(lista_numeros) multiplos_dos = [] multiplos_tres = [] multiplos_cinco = [] multiplos_siete = [] for car in lista_numeros: if car % 2 == 0: multiplos_dos.append(car) if car % 3 == 0: multiplos_tres.append(car) if car % 5 == 0: multiplos_cinco.append(car) if car % 7 == 0: multiplos_siete.append(car) print(f"multiplos de dos: {multiplos_dos}") print(f"multiplos de tres: {multiplos_tres}") print(f"multiplos de cinco: {multiplos_cinco}") print(f"multiplos de siete: {multiplos_siete}")
pokemon_elegido = input("¿Contra que pokemon quieres luchar? (Squirtle / Charmander / Bulbasaur):").upper() vida_enemigo = 0 ataque_enemigo = 0 vida_picachu = 100 if pokemon_elegido == "SQUIRTLE": vida_enemigo = 90 ataque_enemigo = 8 nombre_pokemon = "SQUIRTLE" elif pokemon_elegido == "CHARMANDER": vida_enemigo = 80 ataque_enemigo = 7 nombre_pokemon = "CHARMANDER" elif pokemon_elegido == "BULBASAUR": vida_enemigo = 100 ataque_enemigo = 9 nombre_pokemon = "BULBASAUR" while vida_picachu >0 and vida_enemigo >0: ataque_elegido = input("¿Que ataque quieres hacer? ( Chispazo / Bola voltio)").upper () if ataque_elegido == "CHISPAZO": vida_enemigo -= 20 elif ataque_elegido == "BOLA VOLTIO": vida_enemigo -= 32 print("La vida de {} es ahora de {}".format(nombre_pokemon, vida_enemigo)) vida_picachu -= ataque_enemigo print("{} te hace {} de daño".format(nombre_pokemon, ataque_enemigo)) print("La vida de Picachu es de {}".format(vida_picachu)) print("El combate ha terminado") if vida_picachu > 0: print("Has ganado") else: print("Has perdido")
#Crear un programa que le repita al usuario lo que dice pero con todas las vocales cambiadas por i. frase_user = input("Introduzca una frase: ") frase_modificada = [] vocales = ["a", "A", "e", "E", "o", "O", "u", "U"] for car in frase_user: if car in vocales: frase_user = frase_user.replace(car, "i") print(frase_user)
# -*- coding: utf-8 -*- """ Created on Fri Jun 11 23:48:35 2021 @author: Saptarshi Question - The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate the span of stock’s price for all n days. The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. """ arr = list(map(int,input().split())) n = len(arr) stack = [] ans = [] for i in range(n): if len(stack)==0: ans.append(-1) elif len(stack)>0 and stack[-1][0] > arr[i]: ans.append(stack[-1][1]) elif len(stack) > 0 and stack[-1][0] <=arr[i]: while len(stack) > 0 and stack[-1][0] <=arr[i]: stack.pop() if len(stack) == 0: ans.append(-1) else: ans.append(stack[-1][1]) stack.append([arr[i] , i]) for i in range(len(ans)): ans[i] = i - ans[i] print(ans) #O(n) representation by Stack.
import tkinter as tk from tkinter import ttk mainwindow = tk.Tk() mainwindow.title("Combo box") label1 = ttk.Label(mainwindow, text="Label") label1.grid(column=0, row=0) name = tk.StringVar() # Tkinter isn't dynamically typed like Python proper fontsize = tk.StringVar() def pushbutton(): act.configure(text="Size: " + fontsize.get()) # ------------------- Textbox --------------------------- ttk.Label(mainwindow, text="Text:").grid(column=0, row=0) name_entered = ttk.Entry(mainwindow, width=24, textvariable=name) name_entered.grid(column=0, row=1) act = ttk.Button(mainwindow, text="Size: ", command=pushbutton) act.grid(column=2, row=1) # ------------------------------------------------------- # -------------------- Combo box ------------------------ ttk.Label(mainwindow, text="Size:").grid(column=1, row=0) fontsize_selected = ttk.Combobox(mainwindow, width=12, textvariable=fontsize) fontsize_selected['values'] = (6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 48) fontsize_selected.grid(column=1, row=1) fontsize_selected.current(0) # ------------------------------------------------------- name_entered.focus() mainwindow.mainloop()
import math def get_average(li): if not li: return float('NaN') sum = 0 for num in li: sum += num mean = sum / len(li) return mean def test_get_average(): assert math.isclose(get_average([1,2,3,4]), 2.5) def test_get_average_empty_list(): assert math.isnan(get_average([]))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: maxschallwig """ import requests url = "http://finance.yahoo.com/quote/AAPL?p=AAPL" response = requests.get(url) Indicators = ["Previous Close", "Open", "Bid", "Ask", "Day's Range", "52 Week Range", "Volume", "Avg. Volume", "Market Cap", "Beta", "PE Ratio (TTM)", "EPS (TTM)", "Earnings Date", "Dividend & Yield", "Ex-Dividend Date", "1y Target Est"] print(response) print(response.status_code) #get the html code - call the text element #print(response.text) #give it a variable called htmlText htmlText = response.text #we want to split by the previous close manually #print(htmlText.split("Previous Close")) #example showing how split works #everytime 'b' occurs its going to create a new element in the list #stringExample = "ABSFDFenf" #print(stringExample.split("S")) # splitList = htmlText.split("Previous Close") #length of split list - 3 multiple occurences print(len(splitList)) #stringExample = "AGbCbDbE" #print(stringExample.split("b"))
# -*- coding: utf-8 -*- """ hw2/fermat.py Created on Mon Sep 15 22:07:28 2014 @author: lauren """ #1 def check_fermat(a,b,c,n): if (c**n) == (a**n) + (b**n): print 'Holy Smokes, Fermat was wrong!' else: print 'No, that doesnt work' #2 def inputs(): a = raw_input('Value a?') b = raw_input('Value b?') c = raw_input('Value c?') n = raw_input('Value n?') return a,b,c,n nums = inputs() print nums check_fermat(int(nums[0]),int(nums[1]),int(nums[2]),int(nums[3]))
""" ArrayQueue.py Queue (FIFO) - Array Implementation - fized size Queue - keep a head and tail pointer and cycle both enqueue(key) | O(1) dequeue() | O(1) is_empty() | O(1) """ class ArrayQueue: def __init__(self, capacity): self.capacity = capacity + 1 self.head = 0 self.tail = 0 """ There is no concept of fixed capacity array in Python, so we initialize a list with None values """ self.queue = [None] * self.capacity def is_empty(self): return self.head == self.tail def is_full(self): return self.increment(self.tail) == self.head def enqueue(self, data): if self.is_full(): raise Exception("Queue is full."); self.queue[self.tail] = data self.tail = self.increment(self.tail) def dequeue(self): if self.is_empty(): raise Exception("Queue is empty."); key = self.queue[self.head] self.queue[self.head] = None self.head = self.increment(self.head) return key def increment(self, pointer): if pointer + 1 < self.capacity: return pointer + 1 else: return 0 def decrement(self, pointer): if pointer > 0: return pointer - 1 else: return self.capacity - 1 def __str__(self): return str(self.queue) if __name__ == "__main__": Q = ArrayQueue(7) for i in range(0,7): Q.enqueue(i) print(Q) print("dequeued {}".format(Q.dequeue())) print("dequeued {}".format(Q.dequeue())) print("dequeued {}".format(Q.dequeue())) print(Q) for i in range(8,11): print("enqueued {}".format(i)) Q.enqueue(i) print(Q)
# Python Program for n-th Fibonacci number number=int(input()) def fibonacci(n): if n < 0: print("Enter Positive number") if n == 1: return 0 elif n == 2: return 1 else: num1=0 num2=1 for i in range(1,number): next_number=num1+num2 num1=num2 num2=next_number return (next_number) print(fibonacci(number))
# Method1 - Class based """ In the below program, it is mandatory to implement the __enter__ and the __exit__ methods. After the __enter__ method ends, the code in the with block will be executed. Finally, the Context Manager will call the __exit__ method. """ class FileHandler(): def __init__(self, file_name, file_mode): self._file_name = file_name self._file_mode = file_mode def __enter__(self): self._file = open(self._file_name, self._file_mode) return self._file def __exit__(self, exc_type, exc_value, exc_traceback): self._file.close() if __name__ == "__main__": with FileHandler('test.txt', 'w') as f: f.write('Test')
palabra=[] let=0 print 'ingrese la palabra que desea analizar: ' palabra = raw_input() print (palabra) for bocal in palabra: if bocal=='a': let += 1 print("a-1") if bocal=='e': let += 1 print("e-1") if bocal=='i': let += 1 print("i-1") if bocal=='o': let += 1 print("o-1") if bocal=='u': let += 1 print("u-1") print ("Cantidad de vocales en la palabra:", let)
# coding=utf-8 def euler_method(f, t0, x0, t1, h): """Explizites Euler-Verfahren. Einfachstes Verfahren zur numerischen Lösung eines Anfangswertproblems x' = f(t, x), x(t0) = x0 durch Berechnung von tk = t0 + k*h, k = 0, 1, 2, ... xk+1 = xk + h*f(tk, xk), k + 0, 1, 2, ... :param f: zu lösendes Anfangswertproblem x' = f(t, x), x(t0) = x0 :param t0: Anfangs-Zeitpunkt t0 :param x0: Anfangswert x0 :param t1: End-Zeitpunkt t1 :param h: Diskretisierungs-Schrittweite h > 0 :return: Liste von Approximationen an den diskreten Zeitpunkten k """ t = t0 x = x0 approx = [[t, x]] for k in range(0, 1 + int((t1 - t0)/h)): t = t0 + k*h x = x + h*f(t, x) approx.append([t, x]) return approx
''' Instead of creating new objects setting the same attributes every time, Prototype method include prototyping the common objects into a cache and clones it to give a new instance. Later on the distinct attributes can be changed. ''' import copy class Player: name = None def set_name(self, name): self.name = name def set_skill(self, stricker_skill, midfielder_skill, defender_skill): self.stricker_skill = stricker_skill self.midfielder_skill = midfielder_skill self.defender_skill = defender_skill def clone(self): return copy.copy(self) class Striker(Player): def print_status(self): print("Striker, Name: {}, Skill: {}".format(self.name, self.stricker_skill)) class MidFielder(Player): def print_status(self): print("Midfielder, Name: {}, Skill: {}".format(self.name, self.midfielder_skill)) class Defender(Player): def print_status(self): print("Defender, Name: {}, Skill: {}".format(self.name, self.defender_skill)) # prototype class PlayerPrototype: players = {} @staticmethod def load_prototype(): # stricker prototype stricker = Striker() stricker.set_skill(90, 40, 10) # midfielder prototype midfielder = MidFielder() midfielder.set_skill(60, 90, 70) # defender prototype defender = Defender() defender.set_skill(15, 60, 90) PlayerPrototype.players = { 'STRICKER': stricker, 'MIDFIELDER': midfielder, 'DEFENDER': defender, } @staticmethod def get_player(player_type): return PlayerPrototype.players.get(player_type).clone() def main(): # loading all prototypes PlayerPrototype.load_prototype() # loading stricker striker1 = PlayerPrototype.get_player('STRICKER') striker1.set_name('Max') striker1.print_status() # loading another stricker striker2 = PlayerPrototype.get_player('STRICKER') striker2.set_name('John') striker2.print_status() # loading midfielder midfielder = PlayerPrototype.get_player('MIDFIELDER') midfielder.set_name('Jason') midfielder.set_skill(40, 100, 90) midfielder.print_status() if __name__ == '__main__': main()
num = input("Digite um número inteiro: ") numInt = int(num) result = (numInt // 10) % 10 print("O dígito das dezenas é",result)
def convert (full_name): printing_list=[] container_list= list(full_name.upper()) printing_list.append(container_list[0]) for i in range (0, len(container_list)): if (container_list[i]=="-"): printing_list.append(container_list[i+1]) else: continue print(''.join(printing_list)) def main(): while True: full_name=input("Input full name: ") convert(full_name) main() # make input to list # make all into capital letters # append first letter to a new list # use loop to get the letter after "-" and append it # join the appended letters then print it
import random from Pokemon_Proj.pokemon_battle_class import YourPokemon from Pokemon_Proj.pokemon_general_class import Pokemon player_info = {} player_location = [0, 0] Your_pokemon = [YourPokemon("Pikachu", 5, "thunder", "Female", 8000, 0, 2000), YourPokemon("Bulbasaur", 5, "grass", "Male", 6000, 0, 2800), YourPokemon("Squirtle", 5, "water", "Female", 7000, 0, 2050), YourPokemon("Charmander", 5, "fire", "Male", 9000, 0, 3000)] def input_player(player_info): player_name = input("Your name: ").title() player_info ["Name"] = player_name player_age = int(input("Age: ")) player_info ["Age"] = player_age player_gender = input("Gender: ").title() player_info ["Gender"] = player_gender def verify(): question=input("Are these info(s) correct?\n1. Yes\n2. No\n") if question == "1": print("Hi {}".format(player_info["Name"])) print("#You're given 4 pokemon") print("#You are in a 10x10 grid") print("#You can move one grid to the direction you insert and pokemon will appear randomly which you'll battle") move_player(player_location) elif question == "2": input_player(player_info) verify() else: print("Choose from the list!") verify() def main(): ans = input("Pokemon simulator..\n1. Play\n2. Exit\nChoice: ") if ans == "1": input_player(player_info) print("Player info:") for i in player_info.keys(): values = player_info[i] print("{} = {}".format(i, values)) verify() elif ans == "2": print("Bye~") else: print("Choose from list...") main() def move_player(player_location): while True: print("(up=u, left=l, right=r, down=d)") direction = input("Direction: ") add_location(player_location, direction) def add_location(player_location, direction): if direction == "u": check_location(player_location, direction) player_location[1] = player_location[1]+1 print(player_location) meet_pokemon_location(player_location) elif direction == "d": check_location(player_location, direction) player_location[1] = player_location[1]-1 print(player_location) meet_pokemon_location(player_location) elif direction == "l": check_location(player_location, direction) player_location[0]=player_location[0]-1 print(player_location) meet_pokemon_location(player_location) elif direction == "r": check_location(player_location, direction) player_location[0] = player_location[0]+1 print(player_location) meet_pokemon_location(player_location) else: print("Choose from option!") move_player(player_location) def check_location(player_location, direction): if direction == "u": if (player_location[1]+1) > 5: print("End of map, choose another direction") move_player(player_location) else: return player_location elif direction == "d": if player_location[1]-1 < -5: print("End of map, choose another direction") move_player(player_location) else: return player_location elif direction == "l": if player_location[0]-1 < -5: print("End of map, choose another direction") move_player(player_location) else: return player_location elif direction == "r": if player_location[0]+1 > 5: print("End of map, choose another direction") move_player(player_location) else: return player_location def meet_pokemon_location(player_location): enemy_chance = random.randint(0,100) if enemy_chance >= 85: the_enemy = enemy_pokemon() battle_menu(Your_pokemon, the_enemy) else: move_player(player_location) def enemy_pokemon(): Random_pokemon = [Pokemon("Pidgey", 5, "flying", "Female", 7000, 1000), Pokemon("Ratata", 5, "normal", "Male", 5000, 1000), Pokemon("Caterpie", 5, "bug", "Female", 4000, 1000), Pokemon("Weedle", 5, "bug", "Male", 8000, 1000), Pokemon("Jude the Banisher", 100, "Lecturer", "Alpha Male", 10000, 30000)] x = Random_pokemon[random.randint(0,4)] print("A/An {} has appeared!".format(x.display_name())) return x def battle_menu(Your_pokemon, the_enemy): print("What do you want to do:\n1. Enemy info\n2. Battle\n3. Catch\n4. Run") battle_catch_run=input("Number of choice: ") if battle_catch_run == "1": the_enemy.display_info() battle_menu(Your_pokemon, the_enemy) elif battle_catch_run == "2": battle(Your_pokemon, the_enemy) elif battle_catch_run == "3": catch(the_enemy) elif battle_catch_run == "4": run(the_enemy) else: print("Choose action from options!") battle_menu(Your_pokemon, enemy_pokemon) def battle(Your_pokemon, the_enemy): z = int(choose_pokemon(Your_pokemon, the_enemy)) x = int(the_enemy.get_hp()) y = Your_pokemon[z].hp while x > 0 and y > 0: if y > 0: print("{} attack!".format(Your_pokemon[z].name)) x = int(x) - int(Your_pokemon[z].damage) print("Enemy hp: "+str(x)+"\n") if x > 0: print("{} attack!".format(the_enemy.name)) y = y-the_enemy.damage print("Your pokemon's hp: "+str(y)+"\n") else: continue Your_pokemon[z].hp = y if x <= 0: print("The enemy has fainted!") exp_before = Your_pokemon[z].get_exp() Your_pokemon[z].add_exp() print("{} gained {} exp\n".format(Your_pokemon[z].name, int(Your_pokemon[z].get_exp())-int(exp_before))) if Your_pokemon[z].get_exp() >= 100: print("{} level up!".format(Your_pokemon[z].name)) Your_pokemon[z].add_level() Your_pokemon[z].add_damage() move_player(player_location) elif y <= 0: print("Your pokemon has fainted!") Your_pokemon.remove(z) end_of_game() print("Pokemon(s) left {}".format(len(Your_pokemon))) print("Your other pokemon are afraid to fight because you fight recklessly...") print("You decided to run..\n") move_player(player_location) def end_of_game(): if len(Your_pokemon) == 0: print("Game Over!") def choose_pokemon(Your_pokemon, the_enemy): print("Your pokemon: ") for i in range (0, len(Your_pokemon)): print("{}. {}".format(i+1, Your_pokemon[i].display_name())) ans = input("Action:\n1. Info of your pokemon\n2. Choose pokemon\n3. Back\nYour action: ") if ans == "1": Your_pokemon[choose_poke_number(Your_pokemon)].display_info() choose_pokemon(Your_pokemon, the_enemy) elif ans == "2": return choose_poke_number(Your_pokemon) elif ans == "3": battle_menu(Your_pokemon, the_enemy) else: choose_pokemon(Your_pokemon, the_enemy) def choose_poke_number(Your_pokemon): pokenum=input("Input your pokemon number:\n") try: if int(pokenum)==0: print("Choose from the list!") choose_poke_number(Your_pokemon) else: return int(pokenum)-1 except: print("Choose from the list!") choose_poke_number(Your_pokemon) def catch(the_enemy): if len(Your_pokemon)<=5: chance=random.randint(0, 100) if chance>=70: print("You successfully catch {}".format(the_enemy.display_name())) Your_pokemon.append(YourPokemon(the_enemy.name, the_enemy.get_level(), the_enemy.type, the_enemy.gender, the_enemy.hp, 0, the_enemy.damage)) move_player(player_location) else: print("You failed to catch {}".format(the_enemy.display_name())) battle_menu(Your_pokemon, the_enemy) else: print("Can't catch anymore pokemon, max number of pokemon = 6!") battle_menu(Your_pokemon, the_enemy) def run(the_enemy): chance=random.randint(0, 100) if chance>=60: print("You got away safely...") move_player(player_location) else: print("You failed to run away...") battle_menu(Your_pokemon, the_enemy) main()
math_txt=open('C:\Binus CS\math_expression.txt', 'r') infix=(math_txt.read()).split() print(infix) postfix=[] operator=[] def precedence(x): if x=="+" or x=="-" : return 1 elif x=="*" or x=="/": return 2 elif x=="(": return 0 def type(i): if i=="+" or i=="-" or i=="*" or i=="/": return "operator" elif i=="(" or i==")": return "parenthesis" elif i==" ": return "empty" else: return "operand" def main(): for i in range(0, len(infix)): type_of_thing=type(infix[i]) if type_of_thing=="operand": postfix.append(infix[i]) elif type_of_thing=="operator": while len(operator)!=0 and precedence(infix[i]) <= precedence(operator[-1]) : postfix.append(operator.pop()) operator.append(infix[i]) elif type_of_thing=="parenthesis": if infix[i]=="(": operator.append(infix[i]) elif infix[i]==")": while operator[-1]!="(": the_pop=operator.pop() postfix.append(the_pop) operator.pop() while i==len(infix)-1 and len(operator)!=0: the_pop=operator.pop() postfix.append(the_pop) print(postfix) print(''.join(postfix)) print(operator) main()
import unittest from moving_average import MovingAverage class TestMovingAverage(unittest.TestCase): def setUp(self): self.moving_average = MovingAverage() def test_compute_moving_average_example_1(self): result = self.moving_average.compute(3, [0, 1, 2, 3]) output = [0, 0.5, 1, 2] self.assertEqual(result, output) def test_compute_moving_average_example_2(self): result = self.moving_average.compute(5, [0, 1, -2, 3, -4, 5, -6, 7, -8, 9]) output = [0, 0.5, -0.3333333333333333, 0.5, -0.4, 0.6, -0.8, 1, -1.2, 1.4] self.assertEqual(result, output) def test_compute_fails_with_non_int_window_size(self): err_msg = 'window_size must be an int' with self.assertRaises(TypeError) as err: self.moving_average.compute('3', [0, 1, 2, 3]) self.assertEqual(str(err.exception), err_msg) def test_compute_fails_with_non_list_values(self): err_msg = 'values nust be an array' with self.assertRaises(TypeError) as err: self.moving_average.compute(3, '[0, 1, 2, 3]') self.assertEqual(str(err.exception), err_msg) def test_compute_fails_with_an_empty_list_values(self): err_msg = 'values cannot be an empty array' with self.assertRaises(ValueError) as err: self.moving_average.compute(3, []) self.assertEqual(str(err.exception), err_msg) def test_compute_fails_with_window_size_smaller_than_2(self): err_msg = 'window_size cannot be less than 2' with self.assertRaises(ValueError) as err: self.moving_average.compute(1, [0, 1, 2, 3]) self.assertEqual(str(err.exception), err_msg) def test_compute_fails_with_values_smaller_than_2(self): err_msg = 'values cannot have less than 2 items' with self.assertRaises(ValueError) as err: self.moving_average.compute(3, [0]) self.assertEqual(str(err.exception), err_msg) def test_compute_fails_with_window_size_greater_than_values_list(self): err_msg = 'window_size cannot be greater than the values array size' with self.assertRaises(ValueError) as err: self.moving_average.compute(5, [0, 1, 2, 3]) self.assertEqual(str(err.exception), err_msg) def test_compute_fails_with_values_list_is_not_float(self): err_msg = 'found a non-float value. values must be a list of floating point numbers' with self.assertRaises(TypeError) as err: self.moving_average.compute(3, [0, '1', 2, 3]) self.assertEqual(str(err.exception), err_msg) if __name__ == '__main__': unittest.main()
#Знайти максимальний елемент серед мінімальних елементів стовпців матриці. import random m = int(input("Input M:")) n = int(input("Input N:")) numbers = [[0] * n for i in range(m)] for i in range(m): for j in range(n): numbers[i][j] = random.randint(1,30) for i in range(m): for j in range(n): print("%4d"%numbers[i][j],end=" ") print() array_of_min = [] t = 0 p = 0 min = numbers[t][p] for j in range(n): for i in range(m): if numbers[i][j]< min: min = numbers[i][j] if i == m-1 and j < n: array_of_min.append(min) min = numbers[p+1][t+1] print() for item in array_of_min: print("%4d "%item,end="") print() print() print(" The maximum element among the minimum elements of the matrix columns is: %d"%max(array_of_min))
#У списку випадкових цілих чисел поміняти місцями мінімальний і максимальний елементи. import random n = int(input("Input N ")) numbers = [] print("Our list: ") for i in range(n): numbers.append(random.randint(1,10)) print("%2d " %numbers[i], end ="") print() print("Our new list: ") id_min_elem = numbers.index(min(numbers)) id_max_elem = numbers.index(max(numbers)) temp = numbers[id_min_elem] numbers[id_min_elem] = numbers[id_max_elem] numbers[id_max_elem] = temp for item in numbers: print("%2d " %item, end ="") print()
""" h=int(input('身長(cm)は?>>')) / 100 w=float(input('体重(kg)は?>>')) bmi = w / h /h print(f'BMIは{bmi:.1f}です') """ h,w =int(input('身長(cm)は?>>')) / 100,\ float(input('体重(kg)は?>>')) print(f'BMIは{w/h**2:.1f}です')
ages=[28,50,'ひみつ',20,78,25,22,10,'無回答',33] samples=list() for data in ages: if not isinstance(data,int): #数値でないデータはスキップ continue if data < 20 or data >= 30: continue samples.append(data) print(samples)
height=input('身長(cm)を入力してください>') weight=input('体重(kg)を入力してください>') height=float(height)/100 weight=float(weight) bmi=weight/height**2 print('BMI:',bmi) if bmi>=25: result='肥満' elif bmi>=18.5: result='標準体重' else: result='痩せ型' print(result)
import random input('Enterで対決開始') while True: mydice=[] pcdice=[] mresult=0 presult=0 for i in range(3): mydice[i]=random.randint(1,6) pcdice[i]=random.randint(1.6) mresult += mydice[i] presult += pcdice[i] print('あなたの出目') print(mydice) print('コンピューターの出目') print(pcdice) if mresult < presult: print(f'{mresult}対{presult}であなたの負け') elif mresult > presult: print(f'{mresult}対{presult}であなたの勝ち') else: print(f'{mresult}対{presult}であいこ') yn=input('もう一度対決しますか?<y/n>>>') if yn == n: print('対決を終了します') break
#def eat(breakfast,lunch='ラーメン',dinner='カレー'): def eat(breakfast,lunch,dinner='カレー',desserts=()): print('朝は{}を食べました'.format(breakfast)) print('昼は{}を食べました'.format(lunch)) print('夜は{}を食べました'.format(dinner)) for d in desserts: print('おやつに{}を食べました'.format(d)) """ eat(breakfast='納豆ごはん',dinner='カレーうどん') eat(dinner='カレーうどん',breakfast='納豆ごはん') eat('納豆ごはん',dinner='カレーうどん') #eat(dinner='カレーうどん','納豆ごはん') print('hoge','huga',sep='&',end='!') """ eat('トースト','パスタ','カレー',('アイス','チョコ','パフェ'))
name=input('あなたの名前を教えてください>>') print('{}さん、こんにちは'.format(name)) food=input('{}さんの好きな食べ物を教えてください>>'.format(name)) if food == 'カレー': print('素敵です。カレーは最高ですよね!!') else: print('私も{}が好きですよ'.format(food))
import pygame from pygame.sprite import Sprite class Bullet(Sprite): """Bullet类用来管理飞船发射的子弹""" def __init__(self,ai_setting,screen,ship): """子弹对象,位置和飞船一致""" #super(Bullet,self).__init__() super().__init__() #初始化父类 self.screen=screen #在(0,0)处创建一个表示子弹的矩形,再设置正确的位置 self.rect=pygame.Rect(0,0,ai_setting.bullet_width, ai_setting.bullet_height) self.rect.centerx=ship.rect.centerx #子弹位置和飞船位置一致 self.rect.top=ship.rect.top #用小数表示的子弹位置 self.y=float(self.rect.y) self.color=ai_setting.bullet_color self.speed_factor=ai_setting.bullet_speed_factor def update(self): """向上移动子弹""" #更新表示子弹位置的小数值 self.y-=self.speed_factor #更新表示子弹的rect的位置 self.rect.y=self.y def draw_bullet(self): """在屏幕上显示子弹""" pygame.draw.rect(self.screen, self.color, self.rect)
grade={} homepage=input('欢迎光临学生成绩信息管理系统!按任意键继续\n') while homepage: menu=('1.录入','2.查询','3.修改','4.删除','5.总览','6.退出') for feature in menu: print(feature) number=('1','2','3','4','5','6') order=input('请输入您想要操作的序号:') if order in number: num=int(order) while num==1: name=input('请输入学生姓名:') sorce=float(input('请输入学生成绩:')) grade[name]=sorce exit=input('录入成功!按y继续录入,按任意键返回主菜单\n') if exit=='y': continue else: print('欢迎回到主菜单') break while num==2: name=input('请输入您要查询的学生姓名:') if name in grade: print('%s的成绩为:%.2f'%(name,grade[name])) exit=input('查询成功!按y继续查询,按任意键返回主菜单\n') if exit=='y': continue else: print('欢迎回到主菜单') break else: print('查无此人,请重新输入') exit2=input('按y继续查询,按任意键返回主菜单\n') if exit2=='y': continue else: print('欢迎回到主菜单') break while num==3: name=input('请输入您要修改成绩的学生姓名:') if name in grade: sorce=float(input('请输入新的成绩:')) grade[name]=sorce print('修改成功!') exit=input('按y继续修改,按任意键返回主菜单\n') if exit=='y': continue else: print('欢迎回到主菜单') break else: print('查无此人,请重新输入') exit2=input('按y继续修改,按任意键返回主菜单\n') if exit2=='y': continue else: print('欢迎回到主菜单') break while num==4: name=input('请输入您要删除信息的学生姓名:') if name in grade: grade.pop(name) print('删除成功!') exit=input('按y继续删除,按任意键返回主菜单\n') if exit=='y': continue else: print('欢迎回到主菜单') break else: print('查无此人,请重新输入') exit2=input('按y继续删除,按任意键返回主菜单\n') if exit2=='y': continue else: print('欢迎回到主菜单') break while num==5: print(grade) exit=input('查询成功!按任意键返回主菜单\n') if exit: break if num==6: print('感谢您的使用,再见!') break elif order not in number: print('输入有误,请输入序号1~6') continue
import os import sqlite3 class Database: def __init__(self, dat_file): self.file_path = dat_file self.connection, self.cursor = None, None self.db_connect() # MANAGE CONNECTION def db_connect(self): self.connection = sqlite3.connect(self.file_path) self.cursor = self.connection.cursor() print("Database connected: " + os.path.abspath(self.file_path)) def close(self): self.connection.commit() self.connection.close() def commit(self): self.connection.commit() # INSERTS def insert_user(self, name): query = "INSERT INTO api_user(name) VALUES (?)" params = (name,) self.cursor.execute(query, params) return self.cursor.lastrowid def insert_course(self, name, course): query = "INSERT INTO api_course(name, description, price, lectures, difficulty) VALUES (?, ?, ?, ?, ?)" params = (name, course['description'], course['price'], course['lectures'], course['difficulty']) self.cursor.execute(query, params) return self.cursor.lastrowid def insert_course_user(self, course_user): query = "INSERT INTO api_courseuser(course_id, user_id, rating, date) VALUES (?, ?, ?, ?)" params = (course_user['course'], course_user['user'], course_user['rating'], course_user['date']) self.cursor.execute(query, params) return self.cursor.lastrowid def insert_keyword(self, word): query = "INSERT INTO api_keyword(word) VALUES (?)" params = (word,) self.cursor.execute(query, params) return self.cursor.lastrowid def insert_course_keyword(self, course_id, keyword_id): query = "INSERT INTO api_coursekeyword(course_id, keyword_id) VALUES (?, ?)" params = (course_id, keyword_id) self.cursor.execute(query, params) return self.cursor.lastrowid def insert_rec_people_buy(self, course_id, rec_id, number): query = "INSERT INTO api_recommendationpeoplebuy(course_id, recommended_course_id, number) VALUES (?, ?, ?)" params = (course_id, rec_id, number) self.cursor.execute(query, params) return self.cursor.lastrowid def insert_rec_similar_courses(self, course_id, rec_id, number): query = "INSERT INTO api_recommendationsimilarcourse(course_id, recommended_course_id, number) VALUES (?, ?, ?)" params = (course_id, rec_id, number) self.cursor.execute(query, params) return self.cursor.lastrowid def insert_rec_for_user(self, user_id, rec_id, number): query = "INSERT INTO api_recommendationforuser(user_id, recommended_course_id, number) VALUES (?, ?, ?)" params = (user_id, rec_id, number) self.cursor.execute(query, params) return self.cursor.lastrowid # GETS # 0course_id 1name 2description 3price 4lectures 5difficulty 6- 7date 8rating 9-0 10user_id def get_all_courses_with_users(self): query = "SELECT * FROM api_course INNER JOIN api_courseuser a on api_course.id = a.course_id" self.cursor.execute(query) rows = self.cursor.fetchall() result = dict() for row in rows: if result.get(row[0]) is None: result[row[0]] = { 'name': row[1], 'description': row[2], 'price': row[3], 'lectures': row[4], 'difficulty': row[5], 'users': [] } user = { 'id': row[10], 'rating': row[8], 'date': row[7], } result[row[0]]['users'].append(user) return result def get_user_courses_except(self, user_id, course_id): query = "SELECT course_id FROM api_courseuser WHERE user_id = ? and course_id != ?" params = (user_id, course_id) self.cursor.execute(query, params) rows = self.cursor.fetchall() result = [] for row in rows: result.append(row[0]) return result def get_similar_courses(self, course_id): query = """SELECT course_id, keyword_id, name, description, price, difficulty, lectures FROM (SELECT course_id, keyword_id FROM api_coursekeyword WHERE course_id != ? AND keyword_id IN (SELECT keyword_id FROM api_coursekeyword WHERE course_id = ?)) INNER JOIN api_course on id = course_id """.strip() params = (course_id, course_id) self.cursor.execute(query, params) rows = self.cursor.fetchall() result = {} for row in rows: if result.get(row[0]) is None: result[row[0]] = { 'name': row[2], 'description': row[3], 'price': row[4], 'lectures': row[6], 'difficulty': row[5], 'match': 0 } result[row[0]]['match'] += 1 return result def get_all_courses(self): query = "SELECT * FROM api_course" self.cursor.execute(query) rows = self.cursor.fetchall() result = dict() for row in rows: result[row[0]] = { 'name': row[1], 'description': row[2], 'price': row[3], 'lectures': row[4], 'difficulty': row[5], } return result def get_all_users(self): query = "SELECT u.id, a.course_id FROM api_user u INNER JOIN api_courseuser a on u.id = a.user_id" self.cursor.execute(query) rows = self.cursor.fetchall() result = dict() for row in rows: if result.get(row[0]) is None: result[row[0]] = [] result[row[0]].append(row[1]) return result def get_course_users(self, course_id): query = "SELECT cu.user_id FROM api_course c INNER JOIN api_courseuser cu on c.id = cu.course_id WHERE c.id = ?" params = (course_id, ) self.cursor.execute(query, params) rows = self.cursor.fetchall() result = [] for row in rows: result.append(row[0]) return result def get_user_courses(self, user_id): query = "SELECT cu.course_id FROM api_user u INNER JOIN api_courseuser cu on u.id = cu.user_id WHERE u.id = ?" params = (user_id,) self.cursor.execute(query, params) rows = self.cursor.fetchall() result = [] for row in rows: result.append(row[0]) return result def get_keywords(self): query = "SELECT word FROM api_keyword" self.cursor.execute(query) rows = self.cursor.fetchall() result = [] for row in rows: result.append(row[0]) return result # DELETES def delete_users(self): query = "DELETE FROM api_user" self.cursor.execute(query) def delete_courses(self): query = "DELETE FROM api_course" self.cursor.execute(query) def delete_course_users(self): query = "DELETE FROM api_courseuser" self.cursor.execute(query) def delete_course_keywords(self): query = "DELETE FROM api_coursekeyword" self.cursor.execute(query) def delete_keywords(self): query = "DELETE FROM api_keyword" self.cursor.execute(query) def delete_rec_people_buy(self): query = "DELETE FROM api_recommendationpeoplebuy" self.cursor.execute(query) def delete_rec_similar(self): query = "DELETE FROM api_recommendationsimilarcourse" self.cursor.execute(query) def delete_rec_for_user(self): query = "DELETE FROM api_recommendationforuser" self.cursor.execute(query) def delete_all(self): self.delete_course_users() self.delete_course_keywords() self.delete_users() self.delete_courses() self.delete_keywords() self.delete_rec_people_buy() self.delete_rec_similar() self.delete_rec_for_user()
# Random Functions l1 = [1,2,3,4,5,6] import random as rd a =rd.choice([1,2,3,4,5,6]) a # Generate random flot number between 0<=random<1 b=rd.random() b # genearte radon interger for given range (doesnt work for float values) #it include last item and no step but in randrange not include last item and have step. c=rd.randint(2,6) c # generate a random interger number in given range d=rd.randrange(10,100) d # generate a random interger number with given step e=rd.randrange(10,100,5) e # Generate random floating number in given range f = rd.uniform(3,5) f #Shuffle values in l1 rd.shuffle(l1) l1 # seed means random number will be fixed for that particular seed value. x1= rd.random() x1 rd.seed(5) x2= rd.random() x2 rd.seed(7) x3= rd.random() x3 rd.seed(1) x4= rd.random() x4 rd.seed(5) x9= rd.random() x9 rd.seed(3) x6= rd.random() x6 rd.seed(7) x7= rd.random() x7
lst = ['football', 'handball', 'basketball', 1, 0.3 ] print(lst[0],type(lst[0])) print(lst[-1],type(lst[-1])) print(lst[-2],type(lst[-2]))
#Bruce Keller Task 2 -- Draft Project in a .py file #9/26/21 import requests def weather_data(query): api_key = "869668849cd4ddcff800a4cf956b06e3" base_url = "http://api.openweathermap.org/data/2.5/weather?" complete_url = base_url + "appid=" + api_key + "&" + query res=requests.get(complete_url); return res.json(); def display_results(weathers,city): print("{}'s temperature: {}°C ".format(city,weathers['main']['temp'])) print("Wind speed: {} m/s".format(weathers['wind']['speed'])) print("Description: {}".format(weathers['weather'][0]['description'])) print("Weather: {}".format(weathers['weather'][0]['main'])) def main(): city=input('Enter the city:') print() try: query='q='+city; w_data=weather_data(query); display_results(w_data, city) print() except: print('City name not found') if __name__=='__main__': main()
height = int(input()) perDay = int(input()) perNight = int(input()) print((height - perNight - 1) // (perDay - perNight) + 1)
hours1 = int(input()) minutes1 = int(input()) seconds1 = int(input()) hours2 = int(input()) minutes2 = int(input()) seconds2 = int(input()) print((hours2 - hours1) * 3600 + (minutes2 - minutes1) * 60 + seconds2 - seconds1)
# https://leetcode-cn.com/leetbook/read/linked-list/jy291/ # 时间复杂度: # addAtHead,addAtTail:O(1) # get,addAtIndex,delete:O(min(k,n−k)),其中k指的是元素的索引 # 空间复杂度:所有的操作都是O(1) class ListNode: def __init__(self, val): self.val = val self.next= None self.pre = None class DoubleLinkList: def __init__(self): self.size = 0 self.head = ListNode(0) # 哨兵节点 self.tail = ListNode(0) # 哨兵节点 self.head.next = self.tail self.tail.pre = self.head def get(self, index): """ Get the value of the index-th node in the linked list. If the index is invalid, return -1 """ # choose the fastest way: to move from the head # or to move from the tail if index < 0 or index >= self.size: return -1 if index < self.size - index: cur = self.head for i in range(index+1): # 因为哨兵节点的存在 index + 1 cur = cur.next else: cur = self.tail for i in range(self.size-index): cur = cur.pre return cur.val def addAtIndex(self, index, val): """ Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. """ if index > self.size: return if index < 0: index = 0 if index < self.size - index: pred = self.head for i in range(index): pred = pred.next succ = pred.next else: succ = self.tail for j in range(self.size-index): succ = succ.pre pred = succ.pre # insert addnode = ListNode(val) addnode.pre = pred addnode.next = succ pred.next = addnode succ.pre = addnode self.size += 1 def addAtHead(self, val): """ Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. """ self.addAtIndex(0, val) def addAtTail(self, val): """ Append a node of value val to the last element of the linked list """ self.addAtIndex(self.size, val) def deleteAtIndex(self, index): """ Delete the index-th node in the linked list, if the index is valid. """ if index < 0 or index >= self.size: return if index < self.size - index: pred = self.head for i in range(index): pred = pred.next succ = pred.next.next else: succ = self.tail for j in range(self.size-index-1): succ = succ.pre pred = succ.pre.pre pred.next = succ succ.pre = pred self.size -= 1 if __name__ == '__main__': doublelinklist = DoubleLinkList() doublelinklist.addAtIndex(0, 0) doublelinklist.addAtIndex(1, 1) doublelinklist.addAtIndex(2, 2) print(doublelinklist.get(0), doublelinklist.get(1), doublelinklist.get(2)) doublelinklist.deleteAtIndex(1) print(doublelinklist.get(1)) doublelinklist.addAtHead(4) print(doublelinklist.get(0)) doublelinklist.addAtTail(5) print(doublelinklist.get(3))
# 快速排序:取一个元素,使元素p归位,列表被p分成两部分,左边都比p小,右边都比p大,递归完成排序 # 时间复杂度 nlogn 每一层复杂度是n # 缺点:1.递归最大深度 2.最坏情况 倒序排列,每次都是少一个数字 时间复杂度高 (加入随机化) import random # 框架 # def quick_sort(data, left, right): # if left < right: # mid = partition(data, left, right) # quick_sort(data, mid+1, right) # quick_sort(data, left, mid-1) def partition(li, left, right): tmp = li[left] while left < right: while left < right and li[right] >= tmp: #从右边找比tmp小的数 right -= 1 li[left] = li[right] while left < right and li[left] <= tmp: #从左边找比tmp大的数 left += 1 li[right] = li[left] #tmp归位 li[left] = tmp return left def quick_sort(li, left, right): if left < right: #至少两个元素 mid = partition(li, left, right) quick_sort(li, mid+1, right) quick_sort(li, left, mid-1) li = [random.randint(0,100) for i in range(10)] print(li) quick_sort(li, 0, len(li)-1) print(li)
from datetime import datetime def linearSearch(list, target): #returns the index position of the number we are searching #if not found returns None for i in range(0, len(list)): if list[i] == target: return i return None def verify(list, target_num): start = datetime.now() linearSearch(list, target_num) end = datetime.now() time_taken = end - start print("Time taken to complete: ", time_taken ) targetNumber = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19,20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 46, 47, 48, 49, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 46, 47, 48, 49, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 46, 47, 48, 49, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 46, 47, 48, 49, 33, 34, 35, 36, 37, 38, 39,40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 101] verify(targetNumber, 101)
num = input() if (int(num[0]) + int(num[2])) / 2 == int(num[1]): print('Вы ввели красивое число') else: print('Жаль, вы ввели обычное число')
stone_bunch1 = int(input()) stone_bunch2 = int(input()) stone_bunch3 = int(input()) while stone_bunch3 != 0 or stone_bunch2 != 0 or stone_bunch1 != 0: bunch = int(input()) stone = int(input()) if bunch == 1: stone_bunch1 -= stone print(stone_bunch1, stone_bunch2, stone_bunch3) elif bunch == 2: stone_bunch2 -= stone print(stone_bunch1, stone_bunch2, stone_bunch3) else: stone_bunch3 -= stone print(stone_bunch1, stone_bunch2, stone_bunch3)
degree = int(input()) count = 0 if degree == 1: print('Степень 0') elif degree <= 0 or degree % 2 > 0: print('НЕТ') else: while degree % 2 == 0: count += 1 degree //= 2 if degree == 1: print('Степень', count) elif degree % 2 != 0: print('НЕТ')
from random import randrange print('Введите количество камней в куче № 1:') bunch1 = int(input()) print('Введите количество камней в куче № 2:') bunch2 = int(input()) sign = 0 if bunch1 > 2: x = bunch1 - 2 bunch_number = 1 bunch1 -= x elif bunch2 == 1 and bunch1 == 1: x = 1 bunch_number = 1 bunch1 -= x else: x = bunch2 - 2 bunch_number = 2 bunch2 -= x print('ИИ взял из кучи №', bunch_number, x, 'шт. камней') print('осталось =', bunch1, bunch2) while bunch1 > 0 or bunch2 > 0: bunch_number = int(input()) y = int(input()) if bunch_number == 2: while y > bunch2: y = int(input()) bunch2 -= y else: while y > bunch1: y = int(input()) bunch1 -= y print('Вы взяли из кучи №', bunch_number, y, 'шт. камней') print('осталось =', bunch1, bunch2) sign = 1 if bunch1 == 0: x = bunch2 bunch_number = 2 bunch2 -= x elif bunch2 == 0: x = bunch1 bunch_number = 1 bunch1 -= x else: if (bunch1 % 2 == 0 and bunch2 % 2 == 0) or (bunch1 == 1 and bunch2 == 1): bunch_number = randrange(1, 2) if bunch_number == 1: x = randrange(1, bunch1) bunch1 -= x else: x = randrange(1, bunch2) bunch2 -= x else: if bunch_number == 1: x = bunch2 - 1 bunch_number = 2 bunch2 -= x else: x = bunch1 - 1 bunch_number = 1 bunch1 -= x print('ИИ взял из кучи №', bunch_number, x, 'шт. камней') print('осталось =', bunch1, bunch2) sign = 0 if sign == 0: print('ИИ выиграл!') else: print('Вы выиграли!')
total_price = 0 number_of_items = int(input("Number of Items: ")) while number_of_items < 0: number_of_items = int(input("Invalid number of items!\nNumber of Items: ")) for i in range(1, number_of_items + 1): price = float(input(f"Price of Item {i}: ")) total_price += price if total_price > 100: total_price *= 0.1 print(f"Total price for {number_of_items} item/s is ${total_price:.2f}")
fo = open("data.txt",'w+') print ("Name of the file: ", fo.name) # Assuming that the file contains these lines # TechBeamers # Hello Viewers!! seq="TechBeamers\nHello Viewers!!" fo.writelines(seq ) fo.seek(0,0) for line in fo: print("brrr") print (line) fo.close()
f = open("Class Illustrations/demo.txt","a") # note I use linux, so I need to use a forward slash, for windows its backlash # case 1 f.write("yooo") f = open("Class Illustrations/demo.txt","r") # note I use linux, so I need to use a forward slash, for windows its backlash n = f.readlines() print(n) for i in n: print(i) # case 2 # n= f.readlines() # print(n) # # case 3 # n= f.readlines() # print(n) # # case 4 # n= f.readlines() # print(n) f.close()
# count the number of vovels in the text file f =open("Lab programs/prog13/progText.txt","r") s = f.read() def countVovels(s): s= s.lower() count =0 for ch in s: if (ch=="a" or ch=="e"or ch=="i" or ch=="o" or ch=="u"): count+=1 return count print("number of vovels= ", countVovels(s))
def arithmetic(a,b): sum= a+b product= a*b difference= a-b quotient= a/b remainder= a%b return sum, product, difference, quotient, remainder a= int(input("Enter number 1:")) b= int(input("Enter number 2:")) sum,product,difference,quotient,remainder=arithmetic(a,b) print("Sum:",sum,"\nProduct:",product,"\nDifference:",difference,"\nQuotient:",quotient,"\nRemainder:",remainder)
def print_numbers(lower_limit,upper_limit): print("Even numbers:") for x in range(lower_limit,upper_limit): if x%2 == 0: print(x) print("Odd numbers:") for x in range(lower_limit,upper_limit): if x%2 != 0: print(x) upper_limit=int(input("Enter upper limit:")) lower_limit=int(input("Enter lower limit:")) print_numbers(lower_limit,upper_limit)