text
stringlengths
37
1.41M
""" Write a Python program to find intersection of two given arrays using Lambda. """ number_array1 = list(range(1, 20)) number_array2 = list(range(1, 10)) intersection = list(filter(lambda x: x in number_array1, number_array2)) print("Given arrays: \n {} \n {}".format(number_array1, number_array2)) print("\nIntersection of the given arrays: ", intersection)
""" Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string. """ def swap(x, y): a = y[:2] + x[2:] b = x[:2] + y[2:] return a + ' ' + b print(swap('abc', 'xyz'))
""" Write a Python program to create Fibonacci series upto n using Lambda. """ from functools import reduce fibonacciSeries = lambda n: reduce(lambda n, _: n + [n[-1] + n[-2]], range(n - 2), [0, 1]) print(fibonacciSeries(9))
""" Write a Python program to remove the characters which have odd index values of a given string. """ def removeOddIndex(input_string): output_string = '' for i in range(len(input_string)): if i % 2 == 0: output_string = output_string + input_string[i] return output_string print(removeOddIndex("Python"))
""" Write a Python script to check whether a given key already exists in a dictionary. """ def checkKey(input_dict, input_key): if bool(input_dict.get(input_key)): return 'key Exists !' else: return 'Key does not exists' dict = {'one': 1, 'two': 2} print(checkKey(dict, 'three'))
""" Write a python program to get a string from a given string where all occurrences of its first char have been changed to $, except the first char itself """ def replace(user_input): char = user_input[0] # first char user_input = user_input.replace(char, '$') # replaced all char with $ user_input = char + user_input[1:] # segregated first char and replaced by z return user_input print(replace('restart')) print(replace('arrange'))
# calcúlo de potência em kWh de aparelhos. # para trasnformar kWh em Joules só mudar para 3,6 * 10^6 potencia = int(input()) minutos_ligado = int(input()) tempo = minutos_ligado * 60 gasto = potencia * tempo kwh = gasto * 2.778 * 10 ** - 7 print(f'{kwh:.1f} kWh')
class Employee: def __init__(self, name='Default'): self.name = name self.address = 'Default' self.role = 'Default' self.manager = 'Default' # ID? def print_attr(self): # A custom print statement print('name:', self.name) print('address:', self.address) print('role:', self.role) print('manager:', self.manager) # print('id:', self.id) def set_name(self, name): self.name = name def get_name(self): return self.name def set_address(self, address): self.address = address def get_address(self): return self.address def set_role(self, role): self.role = role def get_role(self): return self.role def set_manager(self, manager): self.manager = manager def get_manager(self): return self.manager
import random numOfJavelinas = 300 lenOfWall = 600 javelinas = [] class Javelina( object ): def __init__( self ): self.position = 0 self.direction = '' self.ID = 0 self.endOfWall = False self.inTransit = False def __cmp__( self, other ): return cmp( self.position, other.position ) def __str__( self ): return str( self.position ) + ',' + self.direction def setDirection( self, direction ): self.direction = direction def reverseDirection( self ): if self.direction == 'l': self.direction = 'r' elif self.direction == 'r': self.direction = 'l' def toLeft( self ): if self.direction == 'l': return True else: return False def toRight( self ): if self.direction == 'r': return True else: return False def isDone( self ): return self.endOfWall def isInTransite( self ): return self.inTransit def moveOneFoot( self ): if self.toLeft() == True: self.position = self.position - 1 elif self.toRight() == True: self.position = self.position + 1 def dropJavelinas(): """Drop javelinas in random places along the wall.""" nums = random.sample( range(0, lenOfWall+1), numOfJavelinas ) ID = 1 for num in nums: javelina = Javelina() javelina.position = num if ( random.getrandbits(1) ): javelina.setDirection( 'l' ) else: javelina.setDirection( 'r' ) javelina.ID = ID ID += 1 javelinas.append( javelina ) def checkConflict( javelina, index ): """Check if the 'javelina' would bump into another one on its way.""" if javelina.toLeft() == True: # Moving to left next_index = index - 1 elif javelina.toRight() == True: # Moving to right next_index = index + 1 # check index range if next_index < 0 or next_index >= numOfJavelinas: return -1 # no conflict javelina2 = javelinas[ next_index ] if javelina2.position == 0 or javelina2.position == lenOfWall: return -1 distance = abs( javelina.position - javelina2.position ) if distance == 1 and javelina.direction != javelina2.direction: print 'javelina', javelina.ID, 'at position', javelina.position, \ 'conflicts with', 'javelina', javelina2.ID, 'at position', javelina2.position return next_index # a conflict detected else: return -1 # no conflict def clearWall(): timer = 0 end_wall_counter = 0 while ( end_wall_counter < numOfJavelinas ): timer += 1 for index, javelina in enumerate(javelinas): # if this javelina has reached to the end of wall, # no need to go further. if javelina.isDone() == True: continue if javelina.position == 0 or javelina.position == lenOfWall: print 'Javelina', javelina.ID, 'is done' end_wall_counter += 1 javelina.endOfWall = True else: neighbor_index = checkConflict( javelina, index ) if neighbor_index != -1: neighbor = javelinas[ neighbor_index ] javelina.inTransit = True neighbor.inTransit = True else: javelina.moveOneFoot() for javelina in javelinas: if javelina.inTransit == True: javelina.inTransit = False javelina.reverseDirection() index = 0 for javelina in javelinas: if index >= numOfJavelinas or (index+1) >= numOfJavelinas: break if javelina.position == javelinas[ index+1 ].position: javelina.reverseDirection() javelinas[ index+1 ].reverseDirection() index += 2 else: index += 1 javelinas.sort() print 'Total time (sec):', timer return timer def movingInOneTimeStep(): pass def main(): dropJavelinas() javelinas.sort() #printStatus() #print len(javelinas) time = clearWall() for javelina in javelinas: print javelina print 'Total time (sec):', time if __name__ == '__main__': main()
""" Methods all classes should define. Methods that are at the base of the class, but don't need to be defined in base_dice.py. These are things like :code:`str`, :code:`repr` and :code:`bool`. These are magic methods that any class should define to make Pythonic development easier. """ from __future__ import annotations from .._types import ChancesValue from .mapping import MappingDice class BasicDice(MappingDice): """Basic magic methods mixin class.""" def __repr__(self) -> str: """Repr format of Dice.""" name = type(self).__qualname__ values = {k: self[k] for k in sorted(self._chances)} return f"{name}[{self._total_chance}]({values!r})" def __str__(self) -> str: """Str format of Dice.""" name = type(self).__qualname__ keys = sorted(self._chances) max_k = len(str(max(keys))) sep = "\n " value = sep.join( f"{k: >{max_k}}" f": {float(self[k]): >5.1%}" f" {self[k].numerator: >2}" f"/{self[k].denominator: <2}".rstrip() for k in keys ) if not value: return f"{name}[{self._total_chance}]()" return f"{name}[{self._total_chance}]({sep}{value}\n)" def __bool__(self) -> bool: """Falsy if the only :ref:`ds-t-Chances Chance` is 0.""" if self._total_chance == 0: return False if len(self._chances) != 1: return bool(self._chances) return 0 not in self._chances def __contains__(self, item: object) -> bool: """ Is :ref:`ds-t-Chances Value` a possible :ref:`ds-t-Chances Chance`. This doesn't check if the :ref:`ds-t-Chances Value` is contained in the :ref:`ds-t-Internal Chances`. It checks if there is a potability of the dice. This is as some dice will show 0 as a :ref:`ds-t-Chances Value` with 0% :ref:`ds-t-Chances Chance`, however as it's not possible it doesn't make sense to say it's a :ref:`ds-t-Chances Chance` of the dice. """ if not isinstance(item, ChancesValue): return False return bool(self._chances.get(item))
""" Problem Description Given two integer array A and B, you have to pick one element from each array such that their xor is maximum. Return this maximum xor value. Problem Constraints 1 <= |A|, |B| <= 105 1 <= A[i], B[i] <= 109 Input Format First argument is an integer array A. Second argument is an integer array B. Output Format Return an integer denoting the maximum xor value as described in the question. Example Input Input 1: A = [1, 2, 3] B = [4, 1, 2] Example Output Output 1: 7 Example Explanation Explanation 1: Pick A[2] and B[0] because their xor value is maximum. 3 ^ 4 = 7 """ class Node: def __init__(self): self.children = {} # Will be a map of T/F--> Node self.leaf = False class Trie: def __init__(self): self.root = Node() def get_child(self, item, bit_index): if (item & (1 << bit_index)) != 0: return True return False @staticmethod def get_node(self): return Node() def insert(self, item): current_root = self.root for i in range(31, -1, -1): # 32 bit child = self.get_child(item, i) if not current_root.children.get(child): current_root.children[child] = self.get_node() current_root = current_root.children.get(child) current_root.leaf = True def get_xor(self, item): current_root = self.root ans = 0 for i in range(31, -1, -1): child = self.get_child(item, i) child_to_be_found = child ^ 1 if child_to_be_found in current_root.children: ans = ans + (1 << i) current_root = current_root.children[child_to_be_found] else: current_root = current_root.children[child] return ans class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def solve(self, A, B): trie = Trie() for item in A: trie.insert(item) ans = 0 for item in B: ans = max(ans, trie.get_xor(item)) return ans if __name__=='__main__': a=[1,2,3] b=[4,1,2] s=Solution() ans=s.solve(a,b) print(ans)
def merge_sort(A:list,beg:int,end:int)->None: """ A=[12,3,1,2,3,342,2324,5] beg=0,end=8 mid=(0+8)//2=4 B=[12,3,1,2,3,342,2324,5,4] beg=0,end=9 mid=(0+9)//2=4 :param A: :param beg: :param end: :return: """ if beg>=end: return mid = (beg+end)//2 merge_sort(A,beg,mid) merge_sort(A,mid+1,end) merge(A,beg,mid,end) def merge(a:list,beg:int,mid:int,end:int): left=a[beg:mid+1] right=a[mid+1:end+1] i=0 j=0 k=beg while i<len(left) and j<len(right): if left[i]<right[j]: a[k]=left[i] i+=1 k+=1 else : a[k]=right[j] j+=1 k+=1 while i<len(left): # print(k,i,a,left,beg) a[k]=left[i] i+=1 k+=1 while j<len(right): # print(k,j,a,right) a[k]=right[j] j+=1 k+=1 if __name__=="__main__": a=[-12,3,1,2,13,342,2324,5] merge_sort(a,0,len(a)-1) print(a)
""" Find if Given number is power of 2 or not. More specifically, find if given number can be expressed as 2^k where k >= 1. Input: number length can be more than 64, which mean number can be greater than 2 ^ 64 (out of long long range) Output: return 1 if the number is a power of 2 else return 0 Example: Input : 128 Output : 1 """ class Solution: # @param A : string # @return an integer def power(self, A): if A in ["0","1"]: return 0 return 1 if not (int(A)&(int(A)-1)) else 0
""" Problem Description Given a string A denoting a stream of lowercase alphabets. You have to make new string B. B is formed such that we have to find first non-repeating character each time a character is inserted to the stream and append it at the end to B. If no non-repeating character is found then append '#' at the end of B. Problem Constraints 1 <= length of the string <= 100000 Input Format The only argument given is string A. Output Format Return a string B after processing the stream of lowercase alphabets A. Example Input Input 1: A = "abadbc" Input 2: A = "abcabc" Example Output Output 1: "aabbdd" Output 2: "aaabc#" Example Explanation Explanation 1: "a" - first non repeating character 'a' "ab" - first non repeating character 'a' "aba" - first non repeating character 'b' "abad" - first non repeating character 'b' "abadb" - first non repeating character 'd' "abadbc" - first non repeating character 'd' Explanation 2: "a" - first non repeating character 'a' "ab" - first non repeating character 'a' "abc" - first non repeating character 'a' "abca" - first non repeating character 'b' "abcab" - first non repeating character 'c' "abcabc" - no non repeating character so '#' """ from collections import deque class Solution: # "abadbc" # @param A : string # @return a strings # B=a def solve(self, A): visited = {A[0]: 1} dq = deque() B = A[0] add_char = A[0] for char in A[1:]: if visited.get(char): visited[char] += 1 else: visited[char] = 1 if visited[char] < 2: dq.append(char) while dq: if add_char == '#' or visited[add_char] >= 2: add_char = dq.popleft() else: break if add_char != '#' and visited[add_char] >= 2: add_char = '#' B += add_char return B
"""Given a matrix of integers A of size N x M in which each row is sorted. https://www.interviewbit.com/problems/matrix-median/ Find an return the overall median of the matrix A. Note: No extra memory is allowed. Note: Rows are numbered from top to bottom and columns are numbered from left to right. Input Format The first and only argument given is the integer matrix A. Output Format Return the overall median of the matrix A. Constraints 1 <= N, M <= 10^5 1 <= N*M <= 10^6 1 <= A[i] <= 10^9 N*M is odd For Example Input 1: A = [ [1, 3, 5], [2, 6, 9], [3, 6, 9] ] Output 1: 5 Explanation 1: A = [1, 2, 3, 3, 5, 6, 6, 9, 9] Median is 5. So, we return 5. Input 2: A = [ [5, 17, 100] ] Output 2: 17 ``` Matrix=""" from bisect import bisect_right class Solution: # @param A : list of list of integers # @return an integer def find_min_max(self, A, r, c): minimum = A[0][0] maximum = A[0][c - 1] for i in range(r): minimum = min(minimum, A[i][0]) maximum = max(maximum, A[i][-1]) return minimum, maximum def find_no_of_small(self, A, end, item): beg = 0 while beg <= end: mid = beg + (end - beg) // 2 if A[mid] == item: return mid if A[mid] < item: beg = mid + 1 else: end = mid - 1 return 0 def binSearch(self, matrix, min_el, max_el, cntElBeforeMed): start = min_el end = max_el while start < end: mid = start + ((end - start) // 2) cnt = 0 for row in matrix: cnt += bisect_right(row, mid) if cnt > cntElBeforeMed: end = mid else: start = mid + 1 return start def findMedian(self, A): r = len(A) c = len(A[0]) minimum, maximum = self.find_min_max(A, r, c) small_count = (r * c) // 2 return self.binSearch(A, minimum, maximum, small_count)
def drone(route): """ IN: route, [3d coordinates] OUT: minimum fuel requirement to complete route drone: [dict] -> Int route = [{x:0, y:2, z:10}, {x:3, y:5, z:0}, {x:9, y:20, z:6}, {x:10, y:12, z:15}, {x:10, y:10, z:8}] X: Side to side (free movement) Y: Forward (free movement) Z: Altitude (pay one liter for 1' increase, receive 1 liter for 1' decrease) Example: 1st: {x:0, y:2, z:10} 2nd: {x:3, y:5, z:0} diff: +3 +3 -10 free free -10 (fuel remaining = 10) [{x:0, y:2, z:10}, {x:3, y:5, z:0}, {x:9, y:20, z:6}, {x:10, y:12, z:15}, {x:10, y:10, z:8}] z: 10 -> 0 -> 6 -> 15 -> 8 d alt -10 +6 +9 -7 cost 10 -6 -9 7 rem 10 4 -5 2 x x+10 x+4 x-5 x+2 10 -> 9 -> 8 Find min from running total -> that's your answer, default to 0 if never negative """ zc = [] # z coordinates for coordinate in route: zc.append(coordinate['z']) # check if needs to be 'z' rt = 0 # running total of fuel min_seen = 0 idx = 0 while idx < len(zc) - 1: rt -= zc[idx + 1] - zc[idx] min_seen = min(rt, min_seen) idx += 1 return min_seen * -1 route = [{'x':0, 'y':2, 'z':10}, {'x':3, 'y':5, 'z':0}, {'x':9, 'y':20, 'z':6}, \ {'x':10, 'y':12, 'z':15}, {'x':10, 'y':10, 'z':8}] print drone(route)
class Node(object): def __init__(self, data=None, left=None, right=None): """ """ self.data = data self.left = left self.right = right def __repr__(self): return "<__main__.Node object %d>" % (self.data) def get_min(self): """ Returns value of smallest node. >>> node4.get_min() 1 """ if not self: return None if self.left is None: return self.data else: return self.left.get_min() def get_max(self): """ Returns value of largest node. >>> node4.get_max() 7 """ if not self: return None if self.right is None: return self.data else: return self.right.get_max() def is_in_tree(self, value): """ Returns a boolean for whether the value is in the tree. >>> node4.is_in_tree(2) True >>> node4.is_in_tree(8) False """ if self.data == value: return True if value <= self.data: if self.left: return self.left.is_in_tree(value) else: if self.right: return self.right.is_in_tree(value) return False def print_in_order(self): """ Prints everything in the tree on a new line from smalles to largest >>> node4.print_in_order() 1 2 3 4 5 6 7 """ if self.left: self.left.print_in_order() print self.data if self.right: self.right.print_in_order() def get_children(self): """ Returns a list of children, if any, that a node has. Does not include None. >>> node4.get_children() [<__main__.Node object 2>, <__main__.Node object 6>] """ children = [] if self.left: children.append(self.left) if self.right: children.append(self.right) return children def dfs(self, value): """ Returns the node with the value or False if not found >>> node4.dfs(2) looking for: 2 checked 4 checked 6 checked 7 checked 5 <__main__.Node object 2> >>> node4.dfs(8) looking for: 8 checked 4 checked 6 checked 7 checked 5 checked 2 checked 3 checked 1 False """ print 'looking for: ', value to_visit = [self] while to_visit: node = to_visit.pop() if node.data == value: return node else: print 'checked', node.data to_visit += node.get_children() return False def bfs(self, value): """ Returns the node with the value or False if not found >>> node4.bfs(2) looking for: 2 checked 4 <__main__.Node object 2> >>> node4.bfs(8) looking for: 8 checked 4 checked 2 checked 6 checked 1 checked 3 checked 5 checked 7 False """ print 'looking for: ', value to_visit = [self] while to_visit: cur = to_visit.pop(0) if cur.data == value: return cur else: print 'checked', cur.data to_visit += cur.get_children() return False def is_valid(self): def ok(node, lt, gt): """ Check this node & recurse to children lt: left children must be <= this gt: right child must be >= this >>> Node.is_valid(node4) True >>> node6.left = node7 >>> node6.right = node5 >>> Node.is_valid(node4) False Reset to valid tree >>> node6.left = node5 >>> node6.right = node7 """ # base case: this isn't a node if not node: return True # base case: smaller than allowed if lt is not None and node.data > lt: return False # base case: bigger than allowed if gt is not None and node.data < gt: return False # general case: check our left child # all descendants of left child must be # less than our data if not ok(node.left, node.data, gt): return False # general case: check our right child # all descendants of right child must be # greater than our data if not ok(node.right, lt, node.data): return False return True return ok(self, None, None) def is_balanced(self): """ Returns a boolean for whether the tree is balanced i.e. the difference between the min leaf depth and the max leaf depth is 1 or less >>> node4.is_balanced() True >>> node18 = Node(18) >>> node17 = Node(17, None, node18) >>> node16 = Node(16, None, node17) >>> node15 = Node(15, None, node16) >>> node15.is_balanced() False """ depths = [] nodes = [(self, 0)] while len(nodes): node, depth = nodes.pop() if not node.left and not node.right: if depth not in depths: depths.append(depth) # Check for imbalances if len(depths) > 2: return False if len(depths) == 2 and abs(depths[0] - depths[1]) > 1: return False else: if node.left: nodes.append((node.left, depth + 1)) if node.right: nodes.append((node.right, depth + 1)) return True def find_second_largest(self): """ >>> node4.find_second_largest() <__main__.Node object 6> >>> node7.find_second_largest() """ if self is None or (self.left is None and self.right is None): return None current = self while current: if self.left and not self.right: return self.left.get_max() if current.right and (current.right.left is None and current.right.right is None): return current current = current.right node7 = Node(7) node5 = Node(5) node6 = Node(6, node5, node7) node1 = Node(1) node3 = Node(3) node2 = Node(2, node1, node3) node4 = Node(4, node2, node6) if __name__ == "__main__": import doctest doctest.testmod()
""" This program implements different methods of denoising an images and comparing the results obtained. There are two parts 'a' and 'b'. In part a we are using Gaussian blur and Median blur, in part b used bilateral filter for the same which is very effective at edges. """ import numpy as np import cv2 import matplotlib.pyplot as plt def denoising(image_path, part): # part a or b img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) h, w = img.shape if part == 1: # first filtering with Gaussian filter G_blur = cv2.GaussianBlur(img, (5, 5), 0) # now filtering with median filter(that uses laplacian) median_blur = cv2.medianBlur(img,9) plt.subplot(121), plt.imshow(median_blur, cmap='gray'), plt.title('Median') plt.subplot(122), plt.imshow(G_blur, cmap='gray'), plt.title('Gaussian') out = plt.show() return [out] """ we see that using gaussian filter the edges are also getting blurred and the image is not fully free from the impulsive noise but in median for kernel size greater than 3 noise has been removed completely """ # 2_b: we will denoise the image using bilateral filtering technique if part == 2: def gaussian(x, sigma): return (1.0/(2*np.pi*(sigma**2)))*np.exp(-(x**2)/(2*(sigma**2))) def distance(x1, y1, x2, y2): return np.sqrt(np.abs((x1-x2)**2-(y1-y2)**2)) def bilateral_filter(image, diameter, sigma_i, sigma_s): new_image = np.zeros(image.shape) for row in range(len(image)): for col in range(len(image[0])): wp_total = 0 filtered_image = 0 for k in range(diameter): for l in range(diameter): n_x =row - (diameter/2 - k) n_y =col - (diameter/2 - l) if n_x >= len(image): n_x -= len(image) if n_y >= len(image[0]): n_y -= len(image[0]) gi = gaussian(image[int(n_x)][int(n_y)] - image[row][col], sigma_i) gs = gaussian(distance(n_x, n_y, row, col), sigma_s) wp = gi * gs filtered_image = filtered_image + (image[int(n_x)][int(n_y)] * wp) wp_total = wp_total + wp filtered_image = filtered_image // wp_total new_image[row][col] = int(np.round(filtered_image)) return new_image return bilateral_filter(img, 5, 0.2, 0.4)
# Assigning int value to Variable x and then multiplying with 5 x = 5 print(x * 5) ##OP - 25 # Assigning string value to Variable yt and then multiplying with 5 yt = 'Youtube' print(yt * 5) ##OP - YoutubeYoutubeYoutubeYoutubeYoutube # if we create string Variable and then add brackets [] and pass the int value that int use as index of the string # The initial index of string is 0 print(yt[0]) # Y print(yt[1]) # o print(yt[2]) # u print(yt[3]) # t print(yt[4]) # u print(yt[5]) # b print(yt[6]) # e print(yt[7]) #IndexError: string index out of range #Becoz string index last value is 6 # if we pass -1 then it gives the value from the last print(yt[-1]) # e print(yt[-2]) # b print(yt[-3]) # u print(yt[-4]) # t print(yt[-5]) # u print(yt[-6]) # o print(yt[-7]) # y print(yt[-8]) #IndexError: string index out of range #Becoz string index last value is -7 # [inclusiveIndex : ExclusiveIndex] print(yt[0:5]) # Youtu print(yt[:5]) # Youtu print(yt[3:]) # tube print(yt[1:100]) # outube # String in Pythin is immutable We can not change after assignment; yt[0:3] = '555' # TypeError: 'str' object does not support item assignment yt[0] = 'R' # TypeError: 'str' object does not support item assignment # Find the Length of the string the length white space myName = 'Deepak Gupta' length = len(myName) print(length) ## OP = 12
m = input('Please input number 1\n') n = input('Please input number 2\n') o = input('Please input number 3\n') p = input('Please input number 4\n') q = input('Please input number 5\n') print('float of 1 equal ',float(m)) print('complex of 1 equal ',complex(m)) print('float of 2 equal ',float(n)) print('complex of 2 equal ',complex(n)) print('float of 3 equal ',float(o)) print('complex of 3 equal ',complex(o)) print('float of 4 equal ',float(p)) print('complex of 4 equal ',complex(p)) print('float of 5 equal ',float(q)) print('complex of 5 equal ',complex(q))
name = input('What is your name?\n') surname = input('What is surname?\n') collegeyears = input('What is collegeyears\n') code = input('What is your code\n') print('My name is :%s.' %name) print('My surname is :%s.' %surname) print('My collegeyears is :%s. ' %collegeyears) print('My code is :%s.,' %code)
""" Name: Alexis Steven Garcia Project: Space Invaders Date: October 8, 2018 Email: [email protected] """ import pygame from pygame.sprite import Sprite from pygame import Surface class Bunker(Sprite): """Represents bunker bits and pieces that can be destroyed""" def __init__(self, ai_settings, screen, row, col): """Create the bunker piece object""" super().__init__() self.screen = screen self.height = ai_settings.bunker_block_size self.width = ai_settings.bunker_block_size self.color = ai_settings.bunker_color # Surface is used to represent any image self.image = Surface((self.width, self.height)) self.image.fill(self.color) self.rect = self.image.get_rect() self.row = row self.col = col def update(self): """Draw the bits of the bunker to the screen""" self.screen.blit(self.image, self.rect) def create_bunker(ai_settings, screen, position): """Create a bunker built from smaller pieces""" bunker = pygame.sprite.Group() for row in range(5): for col in range(9): # Don't draw full rows of blocks on last two rows, to style the bunker if not ((row > 3 and (1 < col < 7)) or (row > 2 and (2 < col < 6)) or (row == 0 and (col < 1 or col > 7))): block = Bunker(ai_settings=ai_settings, screen=screen, row=row, col=col) block.rect.x = int(ai_settings.screen_width * 0.15) + (250 * position) + (col * block.width) block.rect.y = int(ai_settings.screen_height * 0.8) + (row * block.height) bunker.add(block) return bunker
import matplotlib.pyplot as plt import numpy as np import csv # Часть 1 """ x = [] y = [] with open('example.csv', 'r') as csvfile: plots = csv.reader(csvfile, delimiter=',') for row in plots: x.append(int(row[0])) y.append(int(row[1])) plt.plot(x, y, label='loaded from file') """ # Часть 2 x, y = np.loadtxt('Datasets\example.csv', delimiter=',', unpack=True) plt.plot(x, y) # настраиваем лэйблы под осями x и y plt.xlabel('X') plt.ylabel('Y') plt.legend() # название нашего графика plt.title('Interesting graph\nCheck it out') plt.show()
# Structure itérative # La boucle for # Exemple 1 : méthode Couet print('=' * 60) print('Exemple 1') print("Méthode Couet.") print('=' * 60) print('Auto-motivation') for i in range(5): print('Je suis le meilleur ' + str(i) + ' fois sur 5') print('Source : https://fr.wikipedia.org/wiki/M%C3%A9thode_Cou%C3%A9') # Exemple 2 : calculs pour sales gosses print('=' * 60) print('Exemple 2') print("Il y a les sales gosses et il y a Gauss") print('=' * 60) # pour les sales gosses print('Pour les sales gosses') total = 0 for num in range(101): print('Itération n°' + str(num)) total = total + num print(total) print('-' * 60) # pour Gauss print("Pour Gauss pas d'itération") total = 100 * 101 / 2 print(int(total)) # Exemple 3 : arguments de range() print('=' * 60) print('Exemple 3') print("Arguments de range()") print('=' * 60) print('De deux en deux') for i in range(0, 10, 2): print('i = ', i) print("On n'a pas atteint la borne finale, i =", i) print('-' * 60) print('Tout le monde descend') for i in range(10, 0, -1): print('i = ', i) print("On n'a pas atteint la borne finale, i =", i) # Ressources complémentaires # Documentation officielle : https://docs.python.org/3/reference/compound_stmts.html#for # Wiki : https://wiki.python.org/moin/ForLoop
#! python3 # mapIt.py - Launches a map in the browser # using an address from the # command line or clipboard import webbrowser, sys, pyperclip if len(sys.argv) > 1: # Get address from command line. address = ' '.join(sys.argv[1:]) else: # Get address from clipboard address = pyperclip.paste() while True: print('Which website would you like to access to?') menu = ''' 1) Google Maps 2) Amazon.fr 3) YouTube 4) Google traduction (EN -> FR) 5) Google traduction (FR -> EN) q) Quit ''' print(menu) choice = input('Your choice: ') if choice == '1': webbrowser.open('https://www.google.com/maps/place/' + address) elif choice == '2': webbrowser.open('https://www.amazon.fr/s/ref=nb_sb_noss_2?__mk_fr_FR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&url=search-alias%3Daps&field-keywords=' + address) elif choice == '3': webbrowser.open('https://www.youtube.com/results?search_query=' + address) elif choice == '4': address = address.split() address = '%20'.join(address) webbrowser.open('https://translate.google.com/?hl=fr#en/fr/' + address) elif choice == '5': address = address.split() address = '%20'.join(address) webbrowser.open('https://translate.google.com/?hl=fr#fr/en/' + address) elif choice == 'q': break else: print('Incorrect entry')
# Document Clustering using K-means clustering algorithm import random import math from dataset import data,doc_title # Distance calculation using Pearson Correlation Score def distance(v1,v2): # Sums sum1=sum(v1) sum2=sum(v2) # Sums of the squares sum1Sq=sum([pow(v,2) for v in v1]) sum2Sq=sum([pow(v,2) for v in v2]) # Sum of the products pSum=sum([v1[i]*v2[i] for i in range(len(v1))]) # Calculate r (Pearson score) num=pSum-(sum1*sum2/len(v1)) den=math.sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v1))) if den==0: return 0 return 1.0-num/den # The kmeans algorithm def kmeans(data,k): # To generate points for each word : (min count,maximum count) points=[] for i in range(len(data[0])): # For every word word_freq=[] for row in data: word_freq.append(row[i]) points.append((min(word_freq),max(word_freq))) # Generate random centroids cluster=[] for i in range(k): cluster.append([]) for j in range(len(data[0])): cluster[i].append(random.random()*(points[i][1]-points[i][0])+points[i][0]) # Finds centroid for each row prev=None curr=[] while True: for i in range(k): curr.append([]) for j in range(len(data)): row=data[j] minrow=0 for i in range(k): d=distance(cluster[i],row) if d<distance(cluster[minrow],row): minrow=i curr[minrow].append(j) # If clusters remain the same, break and come out of loop if prev==curr: break prev=curr # Move the centroids to the average of their members for i in range(k): avgs=[0.0]*len(data[0]) if len(curr[i])>0: for rowid in curr[i]: for m in range(len(data[rowid])): avgs[m]+=data[rowid][m] for j in range(len(avgs)): avgs[j]/=len(curr[i]) cluster[i]=avgs return curr print 'Enter the number of clusters required' k=input() clusters=kmeans(data,k) # To obtain the names of documents in cluster doc_cluster=[] for i in range(k): doc_cluster.append([]) for j in clusters[i]: if doc_title[j] not in doc_cluster[i]: doc_cluster[i].append(doc_title[j]) for i in doc_cluster: print i
import unittest from ordered_list import * class TestLab4(unittest.TestCase): def test_isempty(self): # test empty list list0 = OrderedList() self.assertTrue(list0.is_empty()) # test list with one item list0.add(1) self.assertFalse(list0.is_empty()) # list with more than one item list0.add(2) list0.add(3) self.assertFalse(list0.is_empty()) def test_add(self): # add to empty list list0 = OrderedList() list0.add(1) self.assertEqual(list0.python_list(), [1]) # add to non-empty list list0.add(2) list0.add(5) self.assertEqual(list0.python_list(), [1, 2, 5]) # add duplicate item list0.add(2) self.assertEqual(list0.python_list(), [1, 2, 5]) # add "in-between" item list0.add(3) self.assertEqual(list0.python_list(), [1, 2, 3, 5]) # add to front list0.add(0) self.assertEqual(list0.python_list(), [0, 1, 2, 3, 5]) def test_remove(self): # empty list list0 = OrderedList() self.assertFalse(list0.remove(0)) list0.add(0) # list with one item self.assertTrue(list0.remove(0)) list0.add(0) self.assertFalse(list0.remove(1)) list0.add(0) list0.add(1) list0.add(2) list0.add(3) # front of list self.assertTrue(list0.remove(0)) self.assertEqual(list0.python_list(), [1, 2, 3]) # rear of list self.assertTrue(list0.remove(3)) self.assertEqual(list0.python_list(), [1, 2]) list0.add(3) # middle of list self.assertTrue(list0.remove(2)) self.assertEqual(list0.python_list(), [1, 3]) list0.add(2) list0.add(4) list0.remove(3) # item greater than largest item in list self.assertFalse(list0.remove(5)) # item less than smallest item in list self.assertFalse(list0.remove(0)) # item in middle of list, but not present in list self.assertFalse(list0.remove(3)) def test_index(self): list0 = OrderedList() # empty list self.assertEqual(list0.index(0), None) list0.add(0) # one item list self.assertEqual(list0.index(0), 0) list0.add(1) list0.add(2) list0.add(4) list0.add(3) # multiple item list self.assertEqual(list0.index(0), 0) self.assertEqual(list0.index(4), 4) self.assertEqual(list0.index(2), 2) def test_pop(self): list0 = OrderedList() # empty list with self.assertRaises(IndexError): list0.pop(0) list0.add(1) # index too large with self.assertRaises(IndexError): list0.pop(2) # negative index with self.assertRaises(IndexError): list0.pop(-1) # one item list self.assertEqual(list0.pop(0), 1) self.assertEqual(list0.python_list(), []) list0.add(0) list0.add(1) list0.add(2) list0.add(3) list0.add(4) # multi item list self.assertEqual(list0.pop(0), 0) self.assertEqual(list0.python_list(), [1, 2, 3, 4]) self.assertEqual(list0.pop(3), 4) self.assertEqual(list0.python_list(), [1, 2, 3]) self.assertEqual(list0.pop(1), 2) self.assertEqual(list0.python_list(), [1, 3]) def test_search(self): # empty list list0 = OrderedList() self.assertFalse(list0.search(0)) # one item list list0.add(0) self.assertTrue(list0.search(0)) self.assertFalse(list0.search(1)) # multi item list list0.remove(0) list0.add(1) list0.add(2) list0.add(4) list0.add(5) self.assertTrue(list0.search(1)) self.assertTrue(list0.search(5)) self.assertTrue(list0.search(2)) # item below minimum item in list self.assertFalse(list0.search(0)) # item in middle of list, not present in list self.assertFalse(list0.search(3)) # item larger than largest list item self.assertFalse(list0.search(6)) def test_python_list(self): # empty list list0 = OrderedList() self.assertEqual(list0.python_list(), []) # one item list0.add(0) self.assertEqual(list0.python_list(), [0]) # multiple items list0.add(1) list0.add(2) list0.add(3) list0.add(4) self.assertEqual(list0.python_list(), [0, 1, 2, 3, 4]) def test_reverse_plist(self): # empty list list0 = OrderedList() self.assertEqual(list0.python_list_reversed(), []) # one item list0.add(0) self.assertEqual(list0.python_list_reversed(), [0]) # multi item list0.add(1) list0.add(2) list0.add(3) list0.add(4) self.assertEqual(list0.python_list_reversed(), [4, 3, 2, 1, 0]) def test_size(self): # empty list list0 = OrderedList() self.assertEqual(list0.size(), 0) # one item list0.add(0) self.assertEqual(list0.size(), 1) # multi item list0.add(1) list0.add(2) list0.add(3) list0.add(4) self.assertEqual(list0.size(), 5) def test_simple(self): t_list = OrderedList() t_list.add(10) self.assertEqual(t_list.python_list(), [10]) self.assertEqual(t_list.size(), 1) self.assertEqual(t_list.index(10), 0) self.assertTrue(t_list.search(10)) self.assertFalse(t_list.is_empty()) self.assertEqual(t_list.python_list_reversed(), [10]) self.assertTrue(t_list.remove(10)) t_list.add(10) self.assertEqual(t_list.pop(0), 10) if __name__ == '__main__': unittest.main()
import os import sys import random import pickle from Game import Game def save_game(game, filename): with open('saves/{}'.format(filename), 'wb') as f: pickle.dump(game, f) def load_game(filename): with open('saves/{}'.format(filename), 'rb') as f: return pickle.load(f) os.system("cls") print("Enter \"Start HEIGHT WIDTH BOMBS\" to start a new game") print("Enter \"Load FILENAME \" to load a game") command = input().split() if command[0] == "Start": height, width, bombs = int(command[1]), int(command[2]), int(command[3]) game = Game(height, width, bombs) elif command[0] == "Load": game = load_game(command[1]) else: print("Not a correct comand") sys.exit() while True: # Game cycle game.show_map(game.user_map) command = input().split() if command[0] == "Save": save_game(game, command[1]) else: game.make_move(int(command[1])-1, int(command[0])-1, command[2])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 24 16:16:10 2018 @author Frevel """ def get_primes(limit = 1000): """ Computes all primes up to limit. Uses the sieve of Erastothenes. limit (int) : Upper limit for value of prime number Returns list """ numbers = list(range(2, limit + 1)) for prime in numbers: multiple = 2 while prime * multiple <= limit: try: numbers.remove(prime * multiple) except Exception: pass # Ignore already deleted values multiple += 1 return numbers def prime_factors(n, primes): """ Computes the prime factors of n, if all prime factors appear in primes. n (int) : Number to get prime factors of primes (list) : prime numbers Returns list """ prime_factors = [] for factor in primes: while n % factor == 0: prime_factors.append(factor) n = n / factor if n > primes[-1]: print("Warning: Not enough primes provided!") return [] return prime_factors #print(prime_factors(600851475143, get_primes(10000))) print(prime_factors(int(input("Compute prime factors for number: ")), get_primes(int(input("Generate primes up to: ")))))
# Celsius('C) to Fahrenheit('F) Conversion c = input('Celsius:') c = float(c) f = c * 9 / 5 + 32 print("Fahrenheit:", f)
def count_orbits(orbit_map): queue = ['COM'] distance = 0 orbit_count = 0 while queue: next_queue = [] for planet in queue: orbit_count += distance if planet in orbit_map: next_queue.extend(orbit_map[planet]) distance += 1 queue = next_queue return orbit_count def main(): tree = {} with open('input.txt') as orbit_data: for orbit in orbit_data: center = orbit.split(')')[0] orbiter = orbit.split(')')[1].rstrip() if center in tree.keys(): tree[center].append(orbiter) else: tree[center] = [orbiter] print (count_orbits(tree)) if __name__ == "__main__": main()
ejercicio="""Dada una cadena cambiar las palabras que empiezan con una voca a mayuscula, Las palabras que empiezan por una consonante dividirlas si su longitud es par""" print(ejercicio) cad=input("cadena>>>")+" " pal="" nCad="" for i in cad: if i==' ': if pal!="": if pal[0] in "aeiou": nCad=nCad+pal.upper() elif pal[0].isalpha(): if len(pal)%2==0: lonPal=int(len(pal)) nCad=nCad+pal[0:lonPal//2]+" "+pal[lonPal//2:lonPal] else: nCad=nCad+pal else: nCad=nCad+pal pal="" nCad+=i else: nCad=nCad+i else: pal=pal+i print("La nueva cadena es: %s"%nCad)
#devuelve las palabras de una cadena en forma de lista def palabras(cad): pals=[] aux="" cad=cad+" " for i in range(len(cad)): if cad[i]!=' ': aux=aux+cad[i] else: pals.append(aux) aux="" return pals #devuelve el mensaje secreto de una lista de palabras def secretWord(lista): mensaje="" for i in range(len(lista)): mensaje=mensaje+lista[i][0] return mensaje #contar caracteres en una cadena def cuentaChr(cad,char): number=0 for i in range(len(cad)): if cad[i]==char: number+=1 return number #invierte cadena def invierte(cad): invertido="" for i in range(len(cad)): invertido=cad[i]+invertido return invertido #Reemplaza un char en una cadena def reemplaze(cad,charToReemp,char): cadNew="" for i in range(len(cad)): if cad[i] == charToReemp: cadNew+=char else: cadNew+=cad[i] return cadNew #El cifrado de cesar def cifradoCesar(message): cMessage="" for i in range(len(message)): numberCode=ord(message[i])+3 cMessage+=chr(numberCode) return cMessage def desCifradoCesar(message): eMessage="" for i in range(len(message)): numberCode=ord(message[i])-3 eMessage+=chr(numberCode) return eMessage
def llenarLista(n,mensaje=""): 'Hace llenar una lista de longitud n con mensaje como encabezado' lista=[] print(mensaje) for i in range(n): lista.append(int(input("[%d]: "%(i+1)))) return lista def mostrarLista(lista,mensaje=""): "Se muestra lista con mensaje como encabezado" print(mensaje) for i in lista: print("[%d]"%i,end="") print()
def llenaLista(n): print("Ingrese uno a uno los elementos del vector:") v=[] for i in range(n): v.append(int(input("v[%d]:"%i))) return v def mostrarLista(lista): for i in range(len(lista)): print("[%d]"%lista[i],end="") return #nicia el programa print("Dado un vector de n elementos, hacer rotar k elementos hacia la derecha") n=int(input("n:")) k=int(input("k:")) v=llenaLista(n) print("Lista ingresada: ",end="") mostrarLista(v) for i in range(k): aux=v[n-1] j=n-2 while j>-1: v[j+1]=v[j] j-=1 v[0]=aux print("\nEl resultado es: ",end="") mostrarLista(v)
#program takes SRIM output and converts to units of micrometer and MeV #C. B. Hamill September 2018 import math import matplotlib.pyplot as plt import sys def unit_conversion_energy(energy,energy_unit): #converts to MeV # print(energy) # print(energy_unit) if energy_unit == "keV": energy=energy/1000.0 # print(energy) return energy def unit_conversion_distance(distance,distance_unit): #converts to micrometer (10^-6) # print(distance) if distance_unit == "mm": distance = distance*1000.0 if distance_unit == "m": # 10^0 distance = distance*1000000.0 if distance_unit == "km": distance = distance*1000000000.0 if distance_unit == "A": #10^-10 distance = distance/10000.0 # print (distance) return distance def main(): # First prompt for file and open it # filename = input("Input file : ") #test test_string = " hello" test_string.strip() # print(test_string.strip()) # print(type(test_string)) filename=sys.argv[1] #takes in command line argument as input file in " " output_filename = filename[:-3] + 'dat' print(output_filename) filein = open(filename,"r") fileout = open(output_filename,"w") input_data = filein.readlines() # Read in whole file data_flag=0 for line in input_data: # print(line) # print("data flag value is:") # print (data_flag) if line.startswith ("-----") : # print() print("reached end of data") break if data_flag == 1: # line=line.strip() token = line.split(" ") # Split on blank space #splitting on blank space results in lots of empty arrays that can just be hard coded around token=filter(None,token) # print(token) # print(line) # print(token) # print(token[1]) #Each column is broken into an element token[0]=float(token[0]) token[2]=float(token[2]) token[3]=float(token[3]) token[4]=float(token[4]) token[6]=float(token[6]) token[8]=float(token[8]) # print(type(token[0])) #Functions called to convert to appropriate unit token[0]=unit_conversion_energy(token[0],token[1]) token[4]=unit_conversion_distance(token[4], token[5]) token[6]=unit_conversion_distance(token[6], token[7]) token[8]=unit_conversion_distance(token[8], token[9]) # for i in range(0,10): # print (i,token[i]) #for checking #convert units to keV # print(token[2]) # print(token) # print "value is {}".format(value) #Values written to output file fileout.write("{}\t{}\t{}\t{}\t{}\t{}\n".format(token[0],token[2],token[3],token[4],token[6],token[8])) if line.startswith (" --------------"): #Line before data appears data_flag = 1 print("data flag set to 1") # print(type(token[0])) filein.close() # Good practice fileout.close() #SRIM structure: (element number, variable) #0 - energy #1 - energy units #2 - dE/dx Elec - not to be converted #3 - dE/dx Nuclear - not to be converted #4 - Projected Range #5 - Projected Range Units #6 -Long Stragg #7 -Long Stragg unit #8 -Lateral Straggling #9 -Lateral Straggling unit main()
#!/usr/bin/env python ''' Made by Ethan Gyllenhaal ([email protected]) Last updated 23 AUG 2022 Script for converting haploid SNAPP input to diploid input. Quick and dirty script, takes in haploid SNAPP input and outputs diploid in that order, no flags. ''' import csv, sys # Generic function for reading tab delimited file in as a table and making a list of names # Input is the name of the text/tsv file def getData(name): import csv data=[] namelist=[] # opens the file fed into function with open(name) as text: # makes csv reader for file database = csv.reader(text, delimiter=' ') # for each line, append the data (in this case 0/1 entries) to one array and the names to another for line in database: data.append(list(line[2])) namelist.append(line[0]) # returns two lists return data, namelist # Main function for driving all operations and running the basic math to make "diploid" individuals def main(args): import csv # gets the data and names using getData function data, namelist = getData(sys.argv[1]) # sets a length variable for the data, i.e. number of loci length = len(data[0]) # initializes arrays for names and output data array array = [] names = [] # for each entry, get the name and add the "diploid" value for a given locus to the output array for i in range(0,len(data)//2): # a number for finding the data entries num = 2*i # temporary array for storing newly converted diploid data temp = [] # appends the sample name to the name list names.append(namelist[num]) # for each locus, add the two values together (i.e. 0/1 --> 0/1/2 format) for j in range(0,length): try: temp.append(int(data[num][j])+int(data[num+1][j])) except: temp.append('?') # append the temporary array to the output array array.append(temp) output = open(sys.argv[2], 'w') # puts together output, with some formatting for row in range(0,len(array)): output.write(names[row]+' '+''.join(str(e) for e in array[row])+'\n') if __name__ == '__main__': main(sys.argv)
print("------Update a tuple in python------") a=("Anana","Mango","Orange","Apple") b=list(a) b[1]="Banana" a=tuple(b) print(a)
# Python program to swap two variables using third variable a=input('Enter value of a:') b=input('Enter value of b:') temp=a a=b b=temp print('Value of a after swapping: {}'.format(a)) print('Value of b after swapping: {}'.format(b))
#WAP in python to add two matrices of size 3x3 using list. K=[] s=int(input("Enter the size of the first matrix:X*X: ")) print("Please enter the elements") for i in range(s): z=[] for j in range(s): z.append(int(input())) K.append(z) print(K) print("The first Matrix is:") for i in range(s): for j in range(s): print(K[i][j], end=" ") print() L=[] s=int(input("Enter the size of the second Matrix: Y*Y: ")) print("Please enter the elements") for i in range(s): z=[] for j in range(s): z.append(int(input())) L.append(z) print(L) print("The second Matrix is:") for i in range(s): for j in range(s): print(L[i][j], end=" ") print() finalMat=[[0,0,0],[0,0,0],[0,0,0]] for i in range(s): for j in range(len(K[0])): finalMat[i][j] = K[i][j] + L[i][j] print("The obtained final matrix is: ") for f in finalMat: print("Sum of the two Matrix is:", f)
#WAP in python to implement #multi-level #In this type of inheritance, a class can inherit from a child class or derived class. class MyFamily: def show_my_family(self): print("My family:") class Father(MyFamily): fathername="" def show_father(self): print(self.fathername) class Mother(MyFamily): mothername="" def show_mother(self): print(self.mothername) class Son(Father, Mother): def show_parent(self): print("My father is: ", self.fathername) print("My mother is: ", self.mothername) s1=Son() s1.fathername = "TOKPE Ahouanye Dodo" s1.mothername ="SOTODJI Rose" s1.show_my_family() s1.show_parent()
#Program in Python to implement #Single level class Parent: parentname="" childname="" def show_parent(self): print(self.parentname) class Child(Parent): def show_child(self): print(self.childname) ch1=Child() ch1.parentname = "TOKPE" ch1.childname="Kossi" ch1.show_parent() ch1.show_child()
""" Day 28: RegEx, Patterns, and Intro to Databases https://www.hackerrank.com/challenges/30-regex-patterns """ import unittest import re class Contacts(object): def __init__(self): self.contacts = [] def add(self, name, email): self.contacts.append( { "name": name, "email": email, } ) def filter(self): results = [] gmail_filter_re = re.compile(r"[a-z.]+@gmail\.com$") for contact in self.contacts: m = gmail_filter_re.match(contact["email"]) if m is None: continue results.append(contact["name"]) return sorted(results) if __name__ == '__main__': contacts = Contacts() N = int(input().strip()) for a0 in range(N): firstName, emailID = input().strip().split(' ') firstName, emailID = [str(firstName), str(emailID)] contacts.add(firstName, emailID) print("\n".join(contacts.filter())) class TestContacts(unittest.TestCase): def test_filter(self): contacts = Contacts() samples = [ ("riya", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("samantha", "[email protected]"), ("tanya", "[email protected]"), ] for item in samples: contacts.add(item[0], item[1]) self.assertEqual( ["julia", "julia", "riya", "samantha", "tanya"], contacts.filter() ) def test_filter_max(self): contacts = Contacts() samples = [ ("riya", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("samantha", "[email protected]"), ("tanya", "[email protected]"), ("riya", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("samantha", "[email protected]"), ("tanya", "[email protected]"), ("riya", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("samantha", "[email protected]"), ("tanya", "[email protected]"), ("riya", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("julia", "[email protected]"), ("samantha", "[email protected]"), ("tanya", "[email protected]"), ("riya", "[email protected]"), ("priya", "[email protected]"), ("preeti", "[email protected]"), ("alice", "[email protected]"), ("alice", "[email protected]"), ("alice", "[email protected]"), ] answer = [ "alice", "alice", "julia", "julia", "julia", "julia", "preeti", "priya", "riya", "riya", "samantha", "samantha", "tanya", "tanya", ] for item in samples: contacts.add(item[0], item[1]) self.assertEqual( answer, contacts.filter() )
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 25 15:48:00 2018 @author: Matt """ from scipy import * import numpy as np from scipy.special import * from time import time from matplotlib.pyplot import * import gaussxw as gs # ============================================================================= # First we Will imprt functions that we will be useing # calculate integrals using the 3 methods # Plot the results # ============================================================================= #define function to be integrated for erf def f(x): """takes an x value and returns the associated output of the function that gets integrated in the erf function""" return (2/sqrt(pi))*numpy.exp(-(x**2)) #define a function that integrates and function using trabezoidal rule def trap(g,x1,x2,n): """takes a function g a start value of x1, as stop value of x2, and a number of slices n and integrates useing the trapezoidal method""" H=(x2-x1)/n#steps for integral v=0.5*(g(x1)+g(x2))#end of the trapezoidal rule steps aren counted as heavily so add seperate for j in range (1,n):#add all of the double counted internal trapezoids v+=(g(x1+j*H)) return (v)*H #define a function that integrates any function using simpsons rule def simp(g,x1,x2,n): # ============================================================================= # """takes a function g a start value of # x1, as stop value of x2, and a number of # slices n and integrates useing simpson's # rule""" # ============================================================================= h=(x2-x1)/n v=g(x1)+g(x2)#endpoint weighted differently add first for k in range(1,n):#i even if k%2==0: v+=2*g(x1+k*h) else:#i odd v+=4*g(x1+k*h) I=(1/3)*h*(v)#sum and multiply by return I def gaussint(g,x1,x2,n): x,w=gausswx(n) xp=0.5*(x2-x1)*x+0.5(x2+x1) wp=0.5*(x2-x1) ret=g(xp) ret=ret*wp ret=sum(ret) return ret N=np.linspace(8,1000,1000-8+1,dtype=int) print(N) a=0 b=3 Itrap=np.empty(len(N)) Isimp=np.empty(len(N)) Igaus=np.empty(len(N)) for i in range (0,len(N)): Itrap[i]=trap(f,a,b,N[i]) Isimp[i]=simp(f,a,b,N[i]) Igaus[i]=gaussint(f,a,b,N[i])
# 运算符 """ 运算符分类 1.算数运算符 2.关系运算符 3.赋值运算符 4.逻辑运算符 5.位运算符 6.成员运算符 7.身份运算符 8.运算符优先级 """ # 算数运算符 ''' + 加 - 减 * 乘 / 除 % 取余 ** 幂 // 向下取整 ''' a = 100 b = 3 print(a + b, '+') print(a - b, '-') print(a * b, '*') print(a / b, '/') print(a % b, '%') print(a ** b, '**') print(a // b, '//') # 比较运算符 ''' == 等于 不会默认转换数据类型 >= 大于等于 <= 小于等于 != 不等于 > 大于 < 小于 逻辑运算符不会进行默认数据转换 ''' c = '3' print(b == c, '等于') # print(b >= c, '>=') # 报错 # 赋值运算符 ''' = += -= *= /= %= **= //= := 海象运算符 ''' l = len('12112312') print(l, 'l') # 逻辑运算符 ''' and 与 not 非 or 或 ''' # 成员运算符 ''' in not in ''' num1 = '3' num2 = '8' arr = ['1', '2', '3', '4'] if num1 in arr: print(num1, 'is in arr') else: print(num1, 'is not in arr') if num2 not in arr: print(num2, 'is not in arr') else: print(num2, 'is in arr') # 身份运算符 ''' 身份运算符用于比较两个对象的存储单元 is not is id()函数用于获取对象内存地址 is 与 == 区别: is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。 ''' if a is b: print('相同') else: print('不同') print(id(a), id(b), '内存地址') list1 = [1, 2, 3] list2 = list1 list3 = list1[:] print(list1 == list2) print(list1 is list2) print(list3 == list1, list3 is list1)
from tkinter import * from tkinter import messagebox from tkinter.messagebox import askquestion from tkinter.filedialog import askopenfile import smtplib, time, os root = Tk() server = StringVar() port = [587, 465] smtpObj = "" server_frame = Frame(borderwidth= 5) login_frame = Frame(padx = 5, bg = "grey") file_frame = Frame() help_frame = Frame(borderwidth= 3) filenamepath ="None Selected......" HelpTxt ="Before You use this application, you would be required to upload a .vtx file format which will contain the first name The application requires you to select a server eg. if your email Address is [email protected], then the server that should be selected will be the gmail server. After selecting the sever, the application requires to input the email and passwod of the operator(Check our privacy agreement on your account information), " Developer = "Batch mail was Developed by a Nigerian Software Developer named Adeniyi Olaitan Lekan As a si" Gmail = Radiobutton(server_frame, text="Gmail", variable = server, value="smtp.gmail.com", tristatevalue = "x", borderwidth = 2, relief = "groove" ) Yahoo = Radiobutton(server_frame, text="Yahoo", variable = server, value="smtp.mail.yahoo.com", tristatevalue = "x", borderwidth = 2, relief = "groove" ) Outlook = Radiobutton(server_frame, text="Outlook", variable = server, value="smtp-mail.outlook.com", tristatevalue = "x", borderwidth = 2, relief = "groove" ) ATaT = Radiobutton(server_frame, text="AT&T", variable = server, value="smtp.mail.att.net", tristatevalue = "x", borderwidth = 2, relief = "groove" ) Comcast = Radiobutton(server_frame, text="Comcast", variable = server, value="smtp.comcast.net", tristatevalue = "x", borderwidth = 2, relief = "groove" ) Verizon = Radiobutton(server_frame, text="Verizon", variable = server, value="smtp.verizon.net", tristatevalue = "x", borderwidth = 2, relief = "groove" ) def account(): if len(email_box.get()) >= 7 and len(password_box.get()) >= 8: emailadd = email_box.get() passcode = password_box.get() smtpObj.login(emailadd, passcode) else: messagebox.showerror("Error", "Please input an email and password you moronic id*ot") def openfile(): file = askopenfile(mode = "r", filetypes = [("Veritext file", "*.vtx")]) if file is not None: content = file.read() filenamepath = file.name file_label.configure(text= filenamepath) else: pass def login(): try: if len(server.get()) > 0: global smtpObj for i in range(2): smtpObj = smtplib.SMTP(server.get(), port[i]) if type(smtpObj) == smtplib.SMTP: smtpObj.ehlo() break if i == 0: starttls() else: continue account() else: messagebox.showerror("Error", "Please select a server") except: messagebox.showerror("Error", 'Check your Internet connection \n If Problem persists, refer to the administrator') def sendmail(): pass def quit(): answer = askquestion(title='Quit?', message='Really quit?') if answer=='yes': root.destroy() #Define File button and labels fileopen = Button(file_frame, text="Load file", font=("Calibri", 12), command= openfile) file_label = Label(file_frame,text=filenamepath, font=("Calibri", 12), relief="flat", highlightcolor = "black", highlightthickness = 1, padx= 20, highlightbackground ="red") #Defining Entry Labels password_box = Entry(login_frame, font=("Calibri", 10), width=15, show="*", highlightcolor = "black", highlightthickness = 2, borderwidth = 3) email_box = Entry(login_frame, font=("Calibri", 8), width=40, borderwidth = 3, highlightcolor = "black", highlightthickness = 2) mail_box = Text(font=("Calibri", 10), width=90, height=20, highlightcolor = "black", highlightthickness = 2, borderwidth = 3) #Defining Labels password_label= Label(login_frame, text="Enter Your Password: ", font=("Calibri", 12), relief="flat", highlightcolor = "black", highlightthickness = 1, highlightbackground ="red") email_label= Label(login_frame, text="Enter Your Email: ", font=("Calibri", 12)) #Defining login button login_but = Button(login_frame, text="Log In", font=("Calibri", 12), command= login) #Defining the Send message Button SendMsg = Button(text="Send Mail", font=("Calibri", 12)) #New window new_window = Toplevel() new_window.title("Help Menu") label = Label(new_window, text=HelpTxt) label.grid(row=0, column=0) #Defining the Help button help_but = Button(help_frame, text="Help", font=("Calibri", 12),command=new_window) #Grid Server name in Frame Gmail.grid(row= 0, column= 0, padx = 20) Yahoo.grid(row = 0, column=1, padx = 20) Outlook.grid(row = 0, column=2, padx = 20) ATaT.grid(row = 0, column=3, padx = 20) Comcast.grid(row = 0, column=4, padx = 20) Verizon.grid(row = 0, column=5, padx = 20) #Grid server_frame in window server_frame.grid(row=0, column= 0) #Grid login_labels and login_entries in login_frame email_label.grid(row= 0, column= 0) email_box.grid(row=0, column=1) password_label.grid(row= 0, column= 2) password_box.grid(row= 0, column= 3) login_but.grid(row=0, column = 4) #login_frame Gridding login_frame.grid(row=1, column= 0) #file frame Gridding file_frame.grid(row=2, column = 0) #file buttons and labels Gridding fileopen.grid(row=0, column = 0) file_label.grid(row=0, column= 1) #email buttons Gridding mail_box.grid(row=3, column = 0) #SendMsg to Window Gridding SendMsg.grid(row=4, column=0) #Help Frame Gridding help_frame.grid(row=5, column=0) #Help button Gridding help_but.grid(row=0, column=0, columnspan=5) root.protocol('WM_DELETE_WINDOW', quit) root.title("Batch-mail") root.geometry("700x600") mainloop()
import random import time import math ''' show time complexity ''' array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] #array = [423,5643,2345786,-345,567,43,-6,23,87,-4,783,7]#negatives #array = [423,5643,234.5786,345,56.7,43,6,23,87,4,783,7]#floats element = len(array) def TimeComplex(): pass def swap(array, i, j): if i != j: array[i], array[j] = array[j], array[i] def Bubblesort(array): if element == 1: return optimized = True for i in range(element - 1): if not optimized: break optimized = False for j in range(0, element - i - 1): if array[j] > array[j + 1]: swap (array, j, j + 1) optimized = True def Mergesort(array): if len(array) > 1: middle = len(array) // 2 left = array[:middle] right = array[middle:] Mergesort(left) Mergesort(right) i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: array[k] = left[i] i += 1 else: array[k] = right[j] j += 1 k += 1 while i < len(left): array[k] = left[i] i += 1 k += 1 while j < len(right): array[k] = right[j] j += 1 k += 1 def QuickPartition(array, low, high): i = (low - 1) pivot = array[high] for j in range(low, high): if array[j] < pivot: i = i + 1 array[i], array[j] = array[j], array[i] array[i + 1], array[high] = array[high], array[i + 1] return(i + 1) def Quicksort(array, low, high): if low >= high: return if low < high: pi = QuickPartition(array, low, high) Quicksort(array, low, pi - 1) Quicksort(array, pi + 1, high) def Insertionsort(array): for i in range(1, element): j = i while j > 0 and array[j] < array[j - 1]: swap(array, j, j - 1) j -= 1 #selection sort def Selectionsort(array): if element == 1: return for i in range(len(array)): mini_element = i for j in range(i + 1, len(array)): if array[mini_element] > array[j]: mini_element = j array[i], array[mini_element] = array[mini_element], array[i] #heap sort def heapify(array, element, i): high = i left = 2 * i + 1 right = 2 * i + 2 if left < element and array[i] < array[left]: high = left if right < element and array[high] < array[right]: high = right swap(array, i, high) if high != i: #array[i], array[high] = array[high], array[i] heapify(array, element, high) def Heapsort(array): for i in range(element // 2 - 1, -1, -1): heapify(array, element, i) for i in range(element - 1, 0, -1): swap(array, i, 0) #array[i], array[0] = array[0], array[i] heapify(array, i, 0) #shell sort def Shellsort(array): gap = element//2 while gap > 0: for i in range(gap, element): temporary = array[i] j = i while j >= gap and array[j - gap] > temporary: array[j] = array[j - gap] j -= gap array[j] = temporary gap //= 2 #comb sort def Nextgap(gap): gap = (gap * 10)//13 if gap < 1: return 1 return gap def Combsort(array): gap = element swapped_value = True while gap != 1 or swapped_value == 1: gap = Nextgap(gap) swapped_value = False for i in range(0, element - gap): if array[i] > array[i + gap]: array[i], array[i + gap] = array[i + gap], array[i] swapped_value = True #bucket sort def Bucketsort(array): bucket = [] for i in range(len(array)): bucket.append([]) for j in array: index_bucket = 0 bucket[index_bucket].append(j) #IndexError: list index out of range for i in range(len(array)): bucket[i] = sorted(bucket[i]) k = 0 for i in range(len(array)): for j in range(len(bucket[i])): array[k] = bucket[i][j] k += 1 return array ''' def InsertionBucketsort(bucket): for i in range(1, len(bucket)): up = bucket[i] j = i - 1 while j >= 0 and bucket[j] > up: bucket[j + 1] = bucket[j] j -= 1 bucket[j + 1] = up return bucket def Bucketsort(array): temp_array = [] slot = 10 for i in range(slot): temp_array.append([]) for j in array: #index_bucket = slot * j index_bucket = int(slot * j) #IndexError: list index out of range array[index_bucket].append(j) for i in range(slot): temp_array[i] = InsertionBucketsort(temp_array[i]) k = 0 for i in range(slot): for j in range(len(temp_array[i])): array[k] = temp_array[i][j] k += 1 return array ''' #counting sort def Countingsort(array): maximum = int(max(array)) minimum = int(min(array)) range_max_min = maximum - minimum + 1 count_array = [0 for _ in range(range_max_min)] out_array = [0 for _ in range(element)] for i in range(0, element): count_array[array[i] - minimum] += 1 for i in range(1, len(count_array)): count_array[i] += count_array[i - 1] for i in range(element - 1, -1, -1): out_array[count_array[array[i] - minimum] - 1] = array[i] count_array[array[i] - minimum] -= 1 for i in range(0, element): array[i] = out_array[i] return array #radix sort def RadixCountingsort(array, exp1): output = [0] * (element) count = [0] * (10) for i in range(0, element): index = (array[i] / exp1) count[int(index % 10)] += 1 for i in range(1, 10): count[i] += count[i - 1] i = element - 1 while i > 0: index = (array[i] / exp1) output[count[int(index % 10)] - 1] = array[i] count[int(index % 10)] -= 1 i -= 1 i = 0 for i in range(0, len(array)): array[i] = output[i] def Radixsort(array): max1 = max(array) exp = 1 while max1 / exp > 0: RadixCountingsort(array, exp) exp *= 10 return array #recursive bubble sort def RecursiveBubblesort(array, n): if n == 1: return for i in range(n - 1): if array[i] > array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] if n - 1 > 1: RecursiveBubblesort(array, n - 1) RecursiveBubblesort(array, n - 1) #LSD radix sort ''' https://brilliant.org/wiki/radix-sort/#:~:text=Radix%20sort%20is%20an%20integer,sort%20an%20array%20of%20numbers. https://www.growingwiththeweb.com/sorting/radix-sort-lsd/ ''' def countingSortByDigit(array, radix, exponent, minValue): bucketIndex = -1 buckets = [0] * radix output = [None] * len(array) for i in range(0, len(array)): bucketIndex = math.floor(((array[i] - minValue) / exponent) % radix) buckets[bucketIndex] += 1 for i in range(1, radix): buckets[i] += buckets[i - 1] for i in range(len(array) - 1, -1, -1): bucketIndex = math.floor(((array[i] - minValue) / exponent) % radix) buckets[bucketIndex] -= 1 output[buckets[bucketIndex]] = array[i] return output def LSDRadixsort(array, radix = 10): if len(array) == 0: return array minValue = array[0]; maxValue = array[0]; for i in range(1, len(array)): if array[i] < minValue: minValue = array[i] elif array[i] > maxValue: maxValue = array[i] exponent = 1 while (maxValue - minValue) / exponent >= 1: array = countingSortByDigit(array, radix, exponent, minValue) exponent *= radix return array run = True while run: if __name__ == '__main__': def remove(choice): return choice.replace(" ", "") print("(Bubble) Sort, (Merge) Sort, (Quick) Sort, (Insertion) Sort,") print("(Selection) Sort, (Heap) Sort, (Shell) Sort, (Comb) Sort,") print("(Bucket) Sort, (Counting) Sort, (Radix) Sort,") print("(Recursive Bubble) Sort, OR (Quit)") choice_msg = "What algorithm do you want to use?: " choice = input(choice_msg) if remove(choice.lower()) == "bubble": print("Unsorted array: ", array) Bubblesort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "merge": print("Unsorted array: ", array) Mergesort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "quick": print("Unsorted array: ", array) Quicksort(array, 0, element - 1) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "insertion": print("Unsorted array: ", array) Insertionsort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "selection": print("Unsorted array: ", array) Selectionsort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "heap": print("Unsorted array: ", array) Heapsort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "shell": print("Unsorted array: ", array) Shellsort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "comb": print("Unsorted array: ", array) Combsort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "bucket": print("Unsorted array: ", array) Bucketsort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "counting": print("Unsorted array: ", array) Countingsort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == 'radix': print("Unsorted array: ", array) Radixsort(array) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "recursivebubble": n = len(array) print("Unsorted array: ", array) RecursiveBubblesort(array, n) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] element = len(array) elif remove(choice.lower()) == "lsdradix": radix = 10 print("Unsorted array: ", array) LSDRadixsort(array, radix) print("Sorted array: ", array) print("\n") array = [423,5643,2345786,345,567,43,6,23,87,4,783,7] elif remove(choice.lower()) == "quit": run = False break else: print("That is not a choice\n") continue
# -*- coding: utf-8 -*- """ Dylan Sosa Numerical and Scientific Methods Day 11 Python 3 & Python 2.7 compatible """ from math import sin, cos, log, ceil, pi import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams rcParams['font.family'] = 'serif' rcParams['font.size'] = 16 # model parameters: a_r = 0.2 # birth rate per year of rabbits b_r = 0.001 # death rate per year of rabbits a_f = 0.001 # birth rate per year of foxes b_f = 0.5 # death rate per year of foxes # set initial conditions rabbits0 = 1000.0 # Initial number of rabbits foxes0 = 100.0 # Initial number of foxes T = 80 # total run time in years dt = 0.1 # time increment of 0.1 years N = int(T/dt) + 1 # number of time-steps t = np.linspace(0, T, N) # time discretization # initialize the array containing the solution for each time-step u = np.empty((N, 2)) u[0] = np.array([rabbits0, foxes0]) # fill 1st element with init. values def f(u): """Returns the right-hand side of the predator-prey system of equations (u_dot). Parameters ---------- u : array of float array containing the solution at time n. Returns ------- u_dot : array of float array containing the RHS given u. """ rabbits = u[0] foxes = u[1] u_dot = np.empty_like(u) # Update the values of u_dot to give the correct formula u_dot[0] = a_r*u[0] - b_r * u[0] * u[1] u_dot[1] = a_f * u[0] * u[1] - b_f * u[1] return u_dot def euler_step(u, f, dt): """Returns the solution at the next time-step using Euler's method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ return u + dt * f(u) # Note how we are able to call another function f(u) def runge_kutta4(u, f, dt): """Returns the solution at the next time-step using the fourth-order accurate Runge Kutta (RK4) method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ k1 = f(u) k2 = f(u+dt/2.0*k1) k3 = f(u+dt/2.0*k2) k4 = f(u+dt*k3) return u + dt/6.0 * (k1 + 2.0*k2 + 2.0*k3 + k4) # time loop - Runge Kutta (RK4) method for n in range(N-1): u[n+1] = runge_kutta4(u[n], f, dt) # visualization of the populations as a function of time plt.figure(figsize=(8, 6)) plt.grid(True) plt.xlabel(r'Time (years)', fontsize=18) plt.ylabel(r'Population', fontsize=18) plt.ylim([0, 3000]) plt.title('Population versus Time = %.2f' % T, fontsize=18) plt.plot(t, u[:, 0], '-', lw=2, label='rabbits') plt.plot(t, u[:, 1], '-', lw=2, label='foxes') plt.legend() # set initial conditions rabbits0_2 = 100.0 # Initial number of rabbits foxes0_2 = 1000.0 # Initial number of foxes T = 80 # total run time in years dt = 0.1 # time increment of 0.1 years N = int(T/dt) + 1 # number of time-steps t = np.linspace(0, T, N) # time discretization # initialize the array containing the solution for each time-step u = np.empty((N, 2)) u[0] = np.array([rabbits0_2, foxes0_2]) # fill 1st element with init. values def f2(u): """Returns the right-hand side of the predator-prey system of equations (u_dot). Parameters ---------- u : array of float array containing the solution at time n. Returns ------- u_dot : array of float array containing the RHS given u. """ rabbits = u[0] foxes = u[1] u_dot = np.empty_like(u) # Update the values of u_dot to give the correct formula u_dot[0] = a_r*u[0] - b_r * u[0] * u[1] u_dot[1] = a_f * u[0] * u[1] - b_f * u[1] return u_dot def euler_step(u, f, dt): """Returns the solution at the next time-step using Euler's method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f2(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ return u + dt * f2(u) # Note how we are able to call another function f2(u) def runge_kutte4_2(u, f, dt): """Returns the solution at the next time-step using the fourth-order accurate Runge Kutta (RK4) method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f2(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ k1 = f2(u) k2 = f2(u+dt/2.0*k1) k3 = f2(u+dt/2.0*k2) k4 = f2(u+dt*k3) return u + dt/6.0 * (k1 + 2.0*k2 + 2.0*k3 + k4) # time loop - Runge Kutta (RK4) method for n in range(N-1): u[n+1] = runge_kutte4_2(u[n], f2, dt) # visualization of the populations as a function of time plt.figure(figsize=(8, 6)) plt.grid(True) plt.xlabel(r'Time (years)', fontsize=18) plt.ylabel(r'Population', fontsize=18) plt.ylim([0, 3000]) plt.title('Population versus Time = %.2f' % T, fontsize=18) plt.plot(t, u[:, 0], '-', lw=2, label='rabbits') plt.plot(t, u[:, 1], '-', lw=2, label='foxes') plt.legend() # set initial conditions rabbits0_3 = 520.0 # Initial number of rabbits foxes0_3 = 180.0 # Initial number of foxes T = 80 # total run time in years dt = 0.1 # time increment of 0.1 years N = int(T/dt) + 1 # number of time-steps t = np.linspace(0, T, N) # time discretization # initialize the array containing the solution for each time-step u = np.empty((N, 2)) u[0] = np.array([rabbits0_3, foxes0_3]) # fill 1st element with init. values def f3(u): """Returns the right-hand side of the predator-prey system of equations (u_dot). Parameters ---------- u : array of float array containing the solution at time n. Returns ------- u_dot : array of float array containing the RHS given u. """ rabbits = u[0] foxes = u[1] u_dot = np.empty_like(u) # Update the values of u_dot to give the correct formula u_dot[0] = a_r*u[0] - b_r * u[0] * u[1] u_dot[1] = a_f * u[0] * u[1] - b_f * u[1] return u_dot def euler_step(u, f2, dt): """Returns the solution at the next time-step using Euler's method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f3(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ return u + dt * f3(u) # Note how we are able to call another function f3(u) def runge_kutte4_3(u, f3, dt): """Returns the solution at the next time-step using the fourth-order accurate Runge Kutta (RK4) method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f3(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ k1 = f3(u) k2 = f3(u+dt/2.0*k1) k3 = f3(u+dt/2.0*k2) k4 = f3(u+dt*k3) return u + dt/6.0 * (k1 + 2.0*k2 + 2.0*k3 + k4) # time loop - Runge Kutta (RK4) method for n in range(N-1): u[n+1] = runge_kutte4_3(u[n], f3, dt) # visualization of the populations as a function of time plt.figure(figsize=(8, 6)) plt.grid(True) plt.xlabel(r'Time (years)', fontsize=18) plt.ylabel(r'Population', fontsize=18) plt.ylim([0, 3000]) plt.title('Population versus Time = %.2f' % T, fontsize=18) plt.plot(t, u[:, 0], '-', lw=2, label='rabbits') plt.plot(t, u[:, 1], '-', lw=2, label='foxes') plt.legend() # set initial conditions rabbits0_4 = 520.0 # Initial number of rabbits foxes0_4 = 220.0 # Initial number of foxes T = 80 # total run time in years dt = 0.1 # time increment of 0.1 years N = int(T/dt) + 1 # number of time-steps t = np.linspace(0, T, N) # time discretization # initialize the array containing the solution for each time-step u = np.empty((N, 2)) u[0] = np.array([rabbits0_4, foxes0_4]) # fill 1st element with init. values def f4(u): """Returns the right-hand side of the predator-prey system of equations (u_dot). Parameters ---------- u : array of float array containing the solution at time n. Returns ------- u_dot : array of float array containing the RHS given u. """ rabbits = u[0] foxes = u[1] u_dot = np.empty_like(u) # Update the values of u_dot to give the correct formula u_dot[0] = a_r*u[0] - b_r * u[0] * u[1] u_dot[1] = a_f * u[0] * u[1] - b_f * u[1] return u_dot def euler_step(u, f2, dt): """Returns the solution at the next time-step using Euler's method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f4(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ return u + dt * f4(u) # Note how we are able to call another function f4(u) def runge_kutte4_4(u, f4, dt): """Returns the solution at the next time-step using the fourth-order accurate Runge Kutta (RK4) method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f4(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ k1 = f4(u) k2 = f4(u+dt/2.0*k1) k3 = f4(u+dt/2.0*k2) k4 = f4(u+dt*k3) return u + dt/6.0 * (k1 + 2.0*k2 + 2.0*k3 + k4) # time loop - Runge Kutta (RK4) method for n in range(N-1): u[n+1] = runge_kutte4_4(u[n], f4, dt) # visualization of the populations as a function of time plt.figure(figsize=(8, 6)) plt.grid(True) plt.xlabel(r'Time (years)', fontsize=18) plt.ylabel(r'Population', fontsize=18) plt.ylim([0, 3000]) plt.title('Population versus Time = %.2f' % T, fontsize=18) plt.plot(t, u[:, 0], '-', lw=2, label='rabbits') plt.plot(t, u[:, 1], '-', lw=2, label='foxes') plt.legend() # set initial conditions rabbits0_5 = 500.0 # Initial number of rabbits foxes0_5 = 200.0 # Initial number of foxes T = 80 # total run time in years dt = 0.1 # time increment of 0.1 years N = int(T/dt) + 1 # number of time-steps t = np.linspace(0, T, N) # time discretization # initialize the array containing the solution for each time-step u = np.empty((N, 2)) u[0] = np.array([rabbits0_5, foxes0_5]) # fill 1st element with init. values def f5(u): """Returns the right-hand side of the predator-prey system of equations (u_dot). Parameters ---------- u : array of float array containing the solution at time n. Returns ------- u_dot : array of float array containing the RHS given u. """ rabbits = u[0] foxes = u[1] u_dot = np.empty_like(u) # Update the values of u_dot to give the correct formula u_dot[0] = a_r*u[0] - b_r * u[0] * u[1] u_dot[1] = a_f * u[0] * u[1] - b_f * u[1] return u_dot def euler_step(u, f5, dt): """Returns the solution at the next time-step using Euler's method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f5(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ return u + dt * f5(u) # Note how we are able to call another function f5(u) def runge_kutte4_5(u, f5, dt): """Returns the solution at the next time-step using the fourth-order accurate Runge Kutta (RK4) method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equations. f5(u) = u_dot dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ k1 = f5(u) k2 = f5(u+dt/2.0*k1) k3 = f5(u+dt/2.0*k2) k4 = f5(u+dt*k3) return u + dt/6.0 * (k1 + 2.0*k2 + 2.0*k3 + k4) # time loop - Runge Kutta (RK4) method for n in range(N-1): u[n+1] = runge_kutte4_5(u[n], f5, dt) # visualization of the populations as a function of time plt.figure(figsize=(8, 6)) plt.grid(True) plt.xlabel(r'Time (years)', fontsize=18) plt.ylabel(r'Population', fontsize=18) plt.ylim([0, 3000]) plt.title('Population versus Time = %.2f' % T, fontsize=18) plt.plot(t, u[:, 0], '-', lw=2, label='rabbits') plt.plot(t, u[:, 1], '-', lw=2, label='foxes') plt.legend() plt.show()
#!/usr/bin/python import sys def doubleit(x): if not isinstance(x, (int, float)): raise TypeError var = x*2 return var def doublelines(filename): with open(filename) as fh: num_list = [ str(doubleit(int(val))) for val in fh] with open(filename, 'w') as fh: fh.write('\n'.join(num_list)) if __name__ == "__main__": input_val = sys.argv[1] doubled_val = doubleit(input_val) print "the value of {0} is {1}".format(input_val, doubled_val)
# class MaxSizeList(object): # def __init__(self, max): # self.max = max # self.list = [] # self.length = 0 # def push(self, val): # if(self.length >= self.max): # self.list.pop(0) # self.length -= 1 # self.list.append(val) # self.length += 1 # def get_list(self): # return self.list # def get_length(self): # return self.length class MaxSizeList(object): def __init__(self, max): self.max = max self.list = [] def push(self, val): if(len(self.list) >= self.max): self.list.pop(0) self.list.append(val) def get_list(self): return self.list def get_length(self): return len(self.list)
""" manual creation vs list comprehension """ import time def main(): timeStart = time.clock() theList1 = [i for i in range(10000000)] timeStop = time.clock() print('comprehension: ') print(timeStop - timeStart) timeStart = time.clock() theList2 = [] for i in range(10000000): theList2.append(i) timeStop = time.clock() print('loop: ') print(timeStop - timeStart) if __name__ == '__main__': main()
import Radix as r def processInput(alist): theList = [int(e) for e in alist[1:-1].split(',')] return theList def main(): theInput = input("Enter collection to be sorted: ") theInput = processInput(theInput) theInputUnsorted = theInput.copy() theInput.sort() numIterations = 0 while theInput != theInputUnsorted: numIterations += 1 theInputUnsorted = theInputUnsorted[5:] + r.radixSort(theInputUnsorted[:5]) print(theInputUnsorted) print('numIterations:', numIterations) if __name__ == "__main__": main()
import math import os import matplotlib.pyplot as plt from PIL import Image, ImageDraw # Подключим необходимые библиотеки. def sum3Tuple(a, b, c): y = [a[temp] + b[temp] + c[temp] for temp in range(0, min(len(a), len(b)))] return tuple(y) def sumTuple(a, b): y = [a[temp] + b[temp] for temp in range(0, min(len(a), len(b)))] return tuple(y) def sub3Tuple(a, b, c): y = [a[temp] - b[temp] - c[temp] for temp in range(0, min(len(a), len(b)))] return tuple(y) def subTuple(a, b): y = [a[temp] - b[temp] for temp in range(0, min(len(a), len(b)))] return tuple(y) def multTuple(a, b): y = [a[temp] * b[temp] for temp in range(0, min(len(a), len(b)))] return tuple(y) def sqrtTuple(a): y = [math.floor(math.sqrt(a[temp])) for temp in range(0, len(a))] return tuple(y) def maxTuple(a, b): y = [max(abs(a[temp]), abs(b[temp])) for temp in range(0, len(a))] return tuple(y) def validateTuple(a): y = [] for i in range(0, 3): if a[i] < 0: y.append(0) elif a[i] > 255: y.append(255) else: y.append(a[i]) return tuple(y) def toGrayScale(__input_name: str, __output_name: str): image = Image.open(__input_name) draw = ImageDraw.Draw(image) # Создаем инструмент для рисования. width = image.size[0] # Определяем ширину. height = image.size[1] # Определяем высоту. pix = image.load() # Выгружаем значения пикселей. for i in range(height): for j in range(width): a = pix[j, i][0] b = pix[j, i][1] c = pix[j, i][2] S = int(0.3 * a + 0.59 * b + 0.11 * c) draw.point((j, i), (S, S, S)) image.save(__output_name, "JPEG") del draw del image def preparationLess(__input_name: str, __output_name: str, F_MIN1: int, G_MIN1: int, G_MAX: int): image = Image.open(__input_name) draw = ImageDraw.Draw(image) # Создаем инструмент для рисования. width = image.size[0] # Определяем ширину. height = image.size[1] # Определяем высоту. pix = image.load() # Выгружаем значения пикселей. for i in range(height): for j in range(width): less = [] a = pix[j, i][0] b = pix[j, i][1] c = pix[j, i][2] original = [a, b, c] for pixel in original: if pixel <= F_MIN1: less.append(G_MIN1) else: less.append(pixel - G_MAX) draw.point((j, i), (less[0], less[1], less[2])) image.save(__output_name, "JPEG") del draw del image def preparationMore(__input_name: str, __output_name: str, F_MAX: int, G_MIN2: int, G_MAX2: int): image = Image.open(__input_name) draw = ImageDraw.Draw(image) # Создаем инструмент для рисования. width = image.size[0] # Определяем ширину. height = image.size[1] # Определяем высоту. pix = image.load() # Выгружаем значения пикселей. for i in range(height): for j in range(width): more = [] a = pix[j, i][0] b = pix[j, i][1] c = pix[j, i][2] original = [a, b, c] for pixel in original: if pixel <= F_MAX: more.append(pixel + G_MIN2) else: more.append(G_MAX2) draw.point((j, i), (more[0], more[1], more[2])) image.save(__output_name, "JPEG") del draw del image def previsFilter(__input_name: str, __output_name: str): image = Image.open(__input_name) # Открываем изображение. imageRes = Image.open(__input_name) # Открываем изображение. drawRes = ImageDraw.Draw(imageRes) # Создаем инструмент для рисования. width = image.size[0] # Определяем ширину. height = image.size[1] # Определяем высоту. pix = image.load() # Выгружаем значения пикселей. for i in range(height): for j in range(width): if (0 < i < height - 2) and (0 < j < width - 2): GX = subTuple(sum3Tuple(pix[j - 1, i + 1], pix[j, i + 1], pix[j + 1, i + 1]), sum3Tuple(pix[j - 1, i - 1], pix[j, i - 1], pix[j + 1, i - 1])) GY = subTuple(sum3Tuple(pix[j + 1, i - 1], pix[j + 1, i], pix[j + 1, i + 1]), sum3Tuple(pix[j - 1, i - 1], pix[j - 1, i], pix[j - 1, i + 1])) pos = maxTuple(GX, GY) pos = validateTuple(pos) drawRes.point((j, i), pos) imageRes.save(__output_name, "JPEG") del image del imageRes del drawRes def histogram(__input_name: str, __output_dir: str): if not os.path.exists(__output_dir): os.makedirs(__output_dir) image = Image.open(__input_name) width = image.size[0] # Определяем ширину. height = image.size[1] # Определяем высоту. pix = image.load() # Выгружаем значения пикселей. red = [] green = [] blue = [] for i in range(height): for j in range(width): a = pix[j, i][0] b = pix[j, i][1] c = pix[j, i][2] red.append(a) green.append(b) blue.append(c) plt.hist(red, bins=range(0, 255)) plt.savefig(__output_dir + "/histRed.png") plt.show() plt.hist(green, bins=range(0, 255)) plt.savefig(__output_dir + "/histGreen.png") plt.show() plt.hist(blue, bins=range(0, 255)) plt.savefig(__output_dir + "/histBlue.png") plt.show() del image if __name__ == "__main__": F_MAX = 175 G_MAX = 125 G_MIN1 = 0 F_MAX1 = 255 F_MIN1 = 255 - G_MAX G_MAX2 = 255 F_MIN2 = 0 G_MIN2 = 255 - F_MAX # print("origin hist ...") # histogram("./image1.jpg", "origin") # print("to gray ...") # toGrayScale("./image1.jpg", "ans.jpg") # print("preparation less ...") # preparationLess("./image1.jpg", "less.jpg", F_MIN1, G_MIN1, G_MAX) # print("preparation more ...") # preparationMore("./image1.jpg", "more.jpg", F_MAX, G_MIN2, G_MAX2) print("filter ...") previsFilter("./image1.jpg", "filt.jpg") # print("hist less ...") # histogram("./less.jpg", "less") # print("hist more ...") # histogram("./more.jpg", "more") # print("hist filt ...") # histogram("./filt.jpg", "filt")
""" Note: Although the skeleton below is in Python, you may use any programming language you want so long as the language supports object-oriented programming, and you make use of relevant object-oriented design principles. """ class Board(object): board = [['_','_','_'],['_','_','_'],['_','_','_']] def __init__(self): self.board = [['_','_','_'],['_','_','_'],['_','_','_']] def print_board(self): print (self.board[0][0] + " " + self.board[0][1] + " " + self.board[0][2]) print (self.board[1][0] + " " + self.board[1][1] + " " + self.board[1][2]) print (self.board[2][0] + " " + self.board[2][1] + " " + self.board[2][2]) return self.board def check_full(self): for i in range(0,2): for j in range(0,2): if self.board[i][j] == '_': return False return True def check_empty(self): for i in range(0,2): for j in range(0,2): if self.board[i][j] != '_': return False return True def mark_square(self, column, row, player): self.board[row][column] = player return self.board
# CTI-110 # P3LAB - Debugging # Jonathan Lopresto # 3/24/2020 #When score is equal to A_score display "Your grade is A." #When score is equal to B_score display "Your grade is B." #When score is equal to C_score display "Your grade is C." #When score is equal to D_score display "Your grade is D." #When score is not equal to any of the above display "Your grade is F." if score == A_score: print('Your grade is A.') else: if score == B_score: print('Your grade is B.') else: if score == C_score: print('Your grade is C.') else: if score == D_score: print('Your grade is D.') else: print('Your grade is F.')
import pandas as pd # Demo of a simplified Recommender System # # # First an introduction to some of the popular types of Recommender Systems: # Simple Recommender (based on item ratings only) # Recommends n top-rated movies to all users. # This approach requires only the movie ratings (item_id, rating). # Collaborative Filtering (also based on item ratings) # This approach requires only the triplets dataset # consisting of user_id, item_id, rating. # Similar Users # User A: likes movies M1, M2 and M3 # User B: likes movies M1, M2 and M3 # In this case, users A and B can be called similar, # and later when User B likes movie M4, # it will be recommended to User A. # Similar Items # User A: likes movies M1 and M2 # User B: likes movies M1 and M2 # User C: likes movies M1 and M2 # In this case, items M1 and M2 can be called similar, # and later when user D likes movie M2, # movie M1 will be recommended to user D. # Content-based Filtering (based on item meta-data) # This approach requires a vector for each user # consisting of the user's profile (user_id, genres liked, artists likes, directors liked, etc), # as well as a vector for each movie # consisting of the movie's meta-data (movie_id, directors, producers, artists, genres, etc). # We can use Cosine Similarity, Pearson's Correlation, TF-IDF, or a combination of these between # user's profile vector and movies' meta-data vectors. # Hybrid Systems # This approach produce the best recommendations, # however, they are the most complex to implement # as not only do they combine Collaborative and Content based filtering methods, # they also require more data for each user such as demographic information, pages visited, # interactions on social platforms, etc. # Hence, a hybrid recommender system needs to account for and meaningfully process all this # extra information to be able to provide truly personalized and useful recommendations. # # We shall build a rather simplistic item-item similarity # collaborative filtering method based on Pearson's correlation scores. # df = pd.read_csv('ml-latest-small/ratings.csv') movie_titles = pd.read_csv('ml-latest-small/movies.csv') df = pd.merge(df, movie_titles, on='movieId') ratings = pd.DataFrame(df.groupby('title')['rating'].mean()) ratings['number_of_ratings'] = df.groupby('title')['rating'].count() movie_matrix = df.pivot_table(index='userId', columns='title', values='rating') m1_user_rating = movie_matrix['Toy Story (1995)'] m2_user_rating = movie_matrix['Jumanji (1995)'] movies_similar_to_m1 = movie_matrix.corrwith(m1_user_rating) movies_similar_to_m2 = movie_matrix.corrwith(m2_user_rating) corr_m1 = pd.DataFrame(movies_similar_to_m1, columns=['correlation']) corr_m1.dropna(inplace=True) print('Movies similar to Toy Story (1995): ') print(corr_m1.head()) corr_m2 = pd.DataFrame(movies_similar_to_m2, columns=['correlation']) corr_m2.dropna(inplace=True) print('Movies similar to Jumanji (1995): ') print(corr_m2.head()) corr_m1 = corr_m1.join(ratings['number_of_ratings']) print('Movies similar to Toy Story (1995): ') print(corr_m1.head()) corr_m2 = corr_m2.join(ratings['number_of_ratings']) print('Movies similar to Jumanji (1995): ') print(corr_m2.head()) corr_m1 = corr_m1[corr_m1['number_of_ratings'] > 100].sort_values(by='correlation', ascending=False) print('Movies similar to Toy Story (1995): ') print(corr_m1.head()) corr_m2 = corr_m2[corr_m2['number_of_ratings'] > 100].sort_values(by='correlation', ascending=False) print('Movies similar to Jumanji (1995): ') print(corr_m2.head())
from pandas import DataFrame from sklearn.base import TransformerMixin class ModelTransformer(TransformerMixin): """ Wrapper to use a model as a feature transformer Taken from http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of-pipelines.html The pipeline treats these objects like any of the built-in transformers and fits them during the training phase, and transforms the data using each one when predicting. """ def __init__(self, model): self.model = model def fit(self, *args, **kwargs): self.model.fit(*args, **kwargs) return self def transform(self, X, **transform_params): return DataFrame(self.model.predict(X))
""" # My first app Here's our first attempt at using data to create a table: """ import numpy as np import pandas as pd import streamlit as st # Basic Display of Data st.markdown("## Displaying Data") st.write("Here's our first attempt at using data to create a table") df = pd.DataFrame({"first column": [1, 2, 3, 4], "second column": [10, 20, 30, 40]}) # st.write(200_00_0) st.dataframe(df) ## Display Styled Dataframe df2 = pd.DataFrame(np.random.randn(10, 20), columns=("col %d" % i for i in range(20))) st.dataframe(df2.style.highlight_max(axis=0)) ## Display Line Chart chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"]) st.line_chart(chart_data) ## Display Map Data map_data = pd.DataFrame( np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=["lat", "lon"] ) st.map(map_data) ## Slider Widget st.markdown("## Simple Widgets") x: int = st.slider("x") # 👈 this is a widget st.write(x, "squared is", x * x) ## Checkbox Widget if st.checkbox("Show dataframe"): chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"]) st.table(chart_data) ## Select box Widget df = pd.DataFrame({"first column": [1, 2, 3, 4], "second column": [10, 20, 30, 40]}) option = st.selectbox("Which number do you like best?", df["first column"]) st.write("You selected: ", option) ## Layout ## Add a selectbox to the sidebar: add_selectbox = st.sidebar.selectbox( "How would you like to be contacted?", ("Email", "Home phone", "Mobile phone") ) # Add a slider to the sidebar: add_slider = st.sidebar.slider("Select a range of values", 0.0, 100.0, (25.0, 75.0)) ## Columns left_column, right_column = st.columns(2) # You can use a column just like st.sidebar: left_column.button("Press me!") # Or even better, call Streamlit functions inside a "with" block: with right_column: chosen = st.radio( "Sorting hat", ("Gryffindor", "Ravenclaw", "Hufflepuff", "Slytherin") ) st.write(f"You are in {chosen} house!")
import itertools as it import math from collections import namedtuple from functools import cmp_to_key as ctk Point = namedtuple('Point', 'x y') def collect_asteroids_coordinates(data): asteroids = [] for idy, line in enumerate(data): for idx, point in enumerate(line): if point == '#': asteroids.append(Point(idx, idy)) return asteroids def find_best_location(asteroids): num_of_visible = int() for point in asteroids: num = sum(is_visible(point, p2) for p2 in asteroids) if num > num_of_visible: num_of_visible = num location = point return location, num_of_visible def is_visible(p1, p2): if (p1 == p2): return False vec = Point(p2.x - p1.x, p2.y - p1.y) if (abs(vec.x) < 2 and abs(vec.y) < 2): return True step = math.gcd(abs(vec.x), abs(vec.y)) if step == 1: return True step_vector = Point(vec.x // step, vec.y // step) intersecting_point = p1 while((intersecting_point := tuple(map(sum, zip(intersecting_point, step_vector)))) != p2): intersecting_point = Point(intersecting_point[0], intersecting_point[1]) if intersecting_point in asteroids: return False return True data = [i for i in open('input.txt', 'r').read().splitlines()] asteroids = collect_asteroids_coordinates(data) laser_pos, num_of_visible = find_best_location(asteroids) print("1:", num_of_visible) def compare_angle(p1, p2): dp1 = p1.x < 0 dp2 = p2.x < 0 if (dp1 != dp2): return cmp(dp1, dp2) if (p1.x == 0 and p2.x == 0): return cmp(sign(p1.y), sign(p2.y)) return sign(p1.x * p2.y - p1.y * p2.x) cmp = lambda a, b: (a > b) - (a < b) sign = lambda i: (i > 0) - (i < 0) viable_asteroids = [p for p in asteroids if is_visible(laser_pos, p)] relative_asteroids_pos = [Point(p.x - laser_pos.x, p.y - laser_pos.y) for p in viable_asteroids] asteroids_sorted = sorted(relative_asteroids_pos, key=ctk(compare_angle), reverse=True) point_at_twelve = asteroids_sorted.index(next(p for p in asteroids_sorted if p.x == 0 and p.y < 0)) asteroids_sorted = asteroids_sorted[point_at_twelve:] + asteroids_sorted[:point_at_twelve - 1] # temporary workaround XD print("2:", (asteroids_sorted[199].x + laser_pos.x) * 100 + asteroids_sorted[199].y + laser_pos.y)
""" This part of code is the Q learning brain, which is a brain of the agent. All decisions are made in here. View more on my tutorial page: https://morvanzhou.github.io/tutorials/ """ import numpy as np import pandas as pd class QLearningTable: def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9): self.actions = actions # a list self.lr = learning_rate self.gamma = reward_decay self.epsilon = e_greedy self.q_table = pd.DataFrame(columns=self.actions, dtype=np.float64) def choose_action(self, observation): self.check_state_exist(observation) if (np.random.random() < (1 - self.epsilon)): #choose random action return np.random.choice(self.actions) else: #choose one with highest q value cur_action = self.q_table.loc[observation,:] cur_action = cur_action.reindex(np.random.permutation(cur_action.index)) # print('cur action: ', cur_action) return np.argmax(cur_action) def learn(self, s, a, r, s_): self.check_state_exist(s_) old_reward = self.q_table.loc[s, a] if s_ != 'terminal': new_reward = r + self.gamma * self.q_table.loc[s_, :].max() # next state is not terminal else: new_reward = r # next state is terminal self.q_table.loc[s, a] += self.lr * (new_reward - old_reward) def check_state_exist(self, state): if (state not in self.q_table.index): print('actions: ', self.actions) print('columns: ', self.q_table.columns) to_add = pd.Series(data=[0] * len(self.actions), index=self.q_table.columns, name=state) # print('to_add: ', to_add) self.q_table = self.q_table.append( to_add )
def suffix(x): if(x==1): return "one"; elif( x==2): return "two"; elif( x==3): return "three"; elif(x==4): return "four"; elif(x==5): return "five"; elif( x==6): return "six"; elif(x==7): return "seven"; elif(x==8): return "eight"; elif( x==9): return "nine"; return ""; def prefix(x): if( x==2): return "twenty"; elif( x==3): return "thirty"; elif( x==4): return "forty"; elif( x==5): return "fifty"; elif( x==6): return "sixty"; elif( x==7): return "seventy"; elif( x==8): return "eighty"; elif(x==9): return "ninety"; def less20(x): if( x==0): return "zero"; elif( x==1): return "one"; elif( x== 2 ): return "two"; elif( x== 3 ): return "three"; elif( x== 4 ): return "four"; elif( x== 5 ): return "five"; elif( x== 6 ): return "six"; elif( x== 7 ): return "seven"; elif( x== 8 ): return "eight"; elif( x== 9 ): return "nine"; elif( x== 10 ): return "ten"; elif( x== 11 ): return "eleven"; elif( x== 12 ): return "twelve"; elif( x== 13 ): return "thirteen"; elif( x== 14 ): return "fourteen"; elif( x== 15 ): return "fifteen"; elif( x== 16 ): return "sixteen"; elif( x== 17 ): return "seventeen"; elif( x== 18 ): return "eighteen"; elif( x== 19 ): return "nineteen"; elif( x== 20 ): return "twenty"; st = str( input() ); it = int( st); if( it<=20): print( less20(it)); elif( st[1]=='0'): print( prefix( int(st[0]))); else: ans = prefix( int(st[0])); ans+="-"; ans+=suffix( int(st[1])); print(ans);
import sys import math import os import itertools import re from collections import defaultdict from operator import add from pyspark import SparkConf, SparkContext from itertools import combinations #This function is used to calculate the user user pairs of every book def getCombinations_User_Rating(userRating): #list of all the combinations is initialized list_of_combinations =[] #iterTools package is used to calculate combinations for x in itertools.combinations(userRating,2): #user rating of each user is appended to the combination list list_of_combinations.append(x) return list_of_combinations #function to group the similar users together def User_RatingPair(book,user_rating): #gets list of the combination of user ratings combination_of_user_Rating = getCombinations_User_Rating(user_rating) #groups the users that rated the book similar together for user1,user2 in combination_of_user_Rating: return (user1[0],user2[0]),(user1[1],user2[1]) return #function to calculate bookID and corressponding userID and rating score def Book_UserRating(data): #used regex to match the regular expression to the data ID = re.match(r'^"(.*?)";',data).group(1) #the obtained expression is splitted across the ; and the parts are stored in an array ID_Array = ID.split(";\"\"") userID = ID_Array[0] #used regex to match the regular expression to the data bookID = re.match(r'.*;"(.*?)";',data).group(1) rating_value = data.split("\"\"") rating_string = rating_value[3].strip() try: rating_score = float(rating_string) if(rating_score == 0.0): rating_score = 1.0 except ValueError: rating_score = 3.0 return bookID,(userID,rating_score) #The cosine similarity between two users is calculated and the ratings that they give to each book are used to get similarity def UserCosineSimilarity(user_pair, rating_list): total_score_of_A = 0.0 total_ratings_product_AB = 0.0 total_score_of_B = 0.0 number_of_Rating_Pairs = 0 for rating_pair in rating_list: a = float(rating_pair[0]) b = float(rating_pair[1]) total_score_of_A = total_score_of_A + a * a total_score_of_B = total_score_of_B + b * b total_ratings_product_AB += a * b number_of_Rating_Pairs = number_of_Rating_Pairs + 1 base = (math.sqrt(total_score_of_A) * math.sqrt(total_score_of_B)) if base == 0.0: return book_pair, (0.0,number_of_Rating_Pairs) else: cosine_similarity = total_ratings_product_AB / base #returns the user pair, cosine similarity and the number of rating pairs return user_pair, (cosine_similarity, number_of_Rating_Pairs) # Cosine similarity is assigned to the user pairs def CosineSimilarity_userPair(userPair_cosine_similarity_value_n): cosine_similarity_value_n = userPair_cosine_similarity_value_n[1] userPair = userPair_cosine_similarity_value_n[0] yield(userPair[0],(userPair[1],cosine_similarity_value_n)) yield(userPair[1],(userPair[0],cosine_similarity_value_n)) # calculate the user recommendations by calculating the nearest books using knn def UserRecommendations(book_ID,tuple_User_Rating,dictionary_of_similarity,number): total_similarity_with_rating = defaultdict(int) total_similarity = defaultdict(int) for (user,rating) in tuple_User_Rating: #The nearest neighbours of books in the dictionary are calculated nearest_neighbors = dictionary_of_similarity.get(user,None) if nearest_neighbors is not None: for (nearest_neighbor,(cosine_similarity, count)) in nearest_neighbors: if nearest_neighbor != user: # adds up the similarity of users total_similarity_with_rating[nearest_neighbor] = total_similarity_with_rating[nearest_neighbor] + float((str(cosine_similarity)).replace("\"","")) * float((str(rating)).replace("\"","")) total_similarity[nearest_neighbor] = total_similarity[nearest_neighbor] + float((str(cosine_similarity)).replace("\"","")) # create the normalized list of recommendation scores Recommendation_Scores_Of_User = [] for value in total_similarity.items(): if (value is not None) and (value[0] is not None) and (value[1] is not None): user = str(value[0]) total_score = float(value[1]) if total_score == 0.0: Recommendation_Scores_Of_User.append((0.0, user)) else: Recommendation_Scores_Of_User.append((total_similarity_with_rating[user]/total_score, user)) # Here we sort the Recommendation Scores in descending order Recommendation_Scores_Of_User.sort(reverse=True) #returns the book id with the list of recommendation scores return book_ID,Recommendation_Scores_Of_User[:number] # Book specific user recommendations scores are generated using this function. def generateBookRecommendations (bookID_user_recommendation_scores): book_ID = bookID_user_recommendation_scores[0] user_recommendation_scores = bookID_user_recommendation_scores[1] Book_Recommendation_scores_for_each_user = [] if (user_recommendation_scores is not None) and (len(user_recommendation_scores) > 0): for user_recommendation_score in user_recommendation_scores: try: user_ID = user_recommendation_score[1] rating = user_recommendation_score[0] Book_Recommendation_scores_for_each_user.append((user_ID, (rating, book_ID))) except ValueError: a = 1 return Book_Recommendation_scores_for_each_user #Used to calculate the book recommendation lists def UserBookRecommendationLists(book_user_recommendation): user_Book_recommendation_scores = [] book_ID = book_user_recommendation[0] user_recommendation_scores = book_user_recommendation[1] if (user_recommendation_scores is not None) and (len(user_recommendation_scores) > 0): for user_recommendation_score in user_recommendation_scores: if (user_recommendation_score is not None) and (len(user_recommendation_score) > 0): for user_recommendation_score_tuple in user_recommendation_score: try: rating = user_recommendation_score_tuple[0] user_ID = user_recommendation_score_tuple[1] user_Book_recommendation_scores.append((user_ID, (rating, book_ID))) except ValueError: a = 1 return(1,user_Book_recommendation_scores) #creates the user recommendations dictionary def UserBookRecommendationDict(user_book_recommendations_List_Of_Lists): user_book_recommendations_MainList = [] dictionary_User_Book_Recommendation = {} tupleList_User_Book_Recommendation = [] for user_book_recommendations_Lists in user_book_recommendations_List_Of_Lists[1]: user_book_recommendations_MainList += user_book_recommendations_Lists for (user, book_rating) in user_book_recommendations_MainList: if user in dictionary_User_Book_Recommendation: dictionary_User_Book_Recommendation[user].append(book_rating) else: dictionary_User_Book_Recommendation[user] = [book_rating] for key , value in dictionary_User_Book_Recommendation.items(): tupleList_User_Book_Recommendation.append((key,value)) return tupleList_User_Book_Recommendation if __name__ == "__main__": if len(sys.argv) != 3: print >> sys.stderr, "Usage: program_file <Book-Rating_file> <output_path>" exit(-1) # reading input from the path mentioned configuration= (SparkConf() .setMaster("local") .setAppName("user-user-collaboration") .set("spark.executor.memory", "16g") .set("spark.driver.memory", "16g") .set('spark.kryoserializer.buffer.max', '1g')) sc = SparkContext(conf = configuration) # The book ratings contain the data file bookRatings = sc.textFile(sys.argv[1], 1) train_Data, test_Data = bookRatings.randomSplit([0.80, 0.20], seed = 11L) # the book user ratingis calculated by calling Book_User rating function Book_UserRating = train_Data.map(lambda x : Book_UserRating(x)).filter(lambda p: len(p[1]) > 1).groupByKey().cache() # the possible pairs for user-user pair for given book and the ratings of the corresponding booksare stored User_RatingPair = Book_UserRating.map(lambda x: User_RatingPair(x[0],x[1])).filter(lambda x: x is not None).groupByKey().cache() #the cosine similarity between two users is calculated userCosineSimilarity = User_RatingPair.map(lambda x: UserCosineSimilarity(x[0],x[1])).filter(lambda x: x[1][0] >= 0) # values that contain user Id as key and the value is a list of tuples that has other user ids and their cosine similarity with the key user cosineSimilarity_userPair = userCosineSimilarity.flatMap(lambda x : CosineSimilarity_userPair(x)).collect() #creates a dictionary for the cosine similarity CosineDict = {} for (user, data) in cosineSimilarity_userPair: if user in CosineDict: CosineDict[user].append(data) else: CosineDict[user] = [data] #no of books to recommended BooksRecommended = 50 # list of users with their recomendation score for each book is calculated book_user_recommendations = Book_UserRating.map(lambda x: UserRecommendations(x[0], x[1], CosineDict, BooksRecommended)).filter(lambda x: x is not None).groupByKey().cache() user_book_recommendations_Lists = book_user_recommendations.map(lambda x: UserBookRecommendationLists(x)).groupByKey() user_bookRecomendations_List = user_book_recommendations_Lists.map(lambda x: UserBookRecommendationDict(x)).filter(lambda x: x is not None) #output path is specified outputPath = sys.argv[2]+"/BookRecomendations" user_bookRecomendations_List.saveAsTextFile(outputPath) #context is stopped sc.stop()
#Print Even numbers in a list using Lambda function n = [3,5,2,11,6,8] print (list(filter(lambda varX: varX % 2 == 0,n))
import time class BinarySearchTree: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): if value < self.value: # check left add left if none if less than self.value if not self.left: self.left = BinarySearchTree(value) else: self.left.insert(value) else: # check right go right if none if not self.right: self.right = BinarySearchTree(value) else: self.right.insert(value) def contains(self, target): if self.value == target: return True if target < self.value: if not self.left: return False else: return self.left.contains(target) else: if not self.right: return False else: return self.right.contains(target) start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() # kind of suprised hash is working. I think there are downsides for a real application. # Creating a bst hashing each name and inserting the hash value into tree # Hashing names in set 2 and searching with contains for duplicates # Appending duplicates to duplicates if contains check passes # runtime: 0.08380603790283203 seconds duplicates = [] bst = BinarySearchTree(0) for name_1 in names_1: hash_name = hash(name_1) # num_name = int(name_1) bst.insert(hash_name) for name_2 in names_2: hash_name = hash(name_2) if bst.contains(hash_name): # num_name = int(name_2) duplicates.append(name_2) # runtime: 5.326942205429077 seconds # for name_1 in names_1: # for name_2 in names_2: # if name_1 == name_2: # duplicates.append(name_1) end_time = time.time() print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n") print(f"runtime: {end_time - start_time} seconds")
import zipfile from os import path from tqdm import tqdm while(1): wordlist = input("wordlist file : ") if (path.exists(wordlist) ) : break print("[-] File does not exist") while(1): zip_file = input("Zipfile : ") if (path.exists(zip_file) ) : break print("[-] File does not exist") zip_file = zipfile.ZipFile(zip_file) n_words = len(list(open(wordlist, "rb"))) print("Total passwords to test:", n_words) with open(wordlist, "rb") as wordlist: for word in tqdm(wordlist, total=n_words, unit="word"): try: zip_file.extractall(pwd=word.strip()) except: continue else: print("[+] Password found:", word.decode().strip()) exit(0) print("[!] Password not found, try other wordlist.")
""" The world_values data set is available online at http://54.227.246.164/dataset/. In the data, residents of almost all countries were asked to rank their top 6 'priorities'. Specifically, they were asked "Which of these are most important for you and your family?" This code and world-values.tex guides the student through the process of training several models to predict the HDI (Human Development Index) rating of a country from the responses of its citizens to the world values data. The new model they will try is k Nearest Neighbors (kNN). The students should also try to understand *why* the kNN works well. """ from math import sqrt import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.model_selection import GridSearchCV from world_values_utils import import_world_values_data from world_values_utils import hdi_classification from world_values_utils import calculate_correlations from world_values_utils import plot_pca from world_values_pipelines import ridge_regression_pipeline from world_values_pipelines import lasso_regression_pipeline from world_values_pipelines import k_nearest_neighbors_regression_pipeline from world_values_pipelines import svm_classification_pipeline from world_values_pipelines import k_nearest_neighbors_classification_pipeline from world_values_parameters import regression_ridge_parameters from world_values_parameters import regression_lasso_parameters from world_values_parameters import regression_knn_parameters from world_values_parameters import classification_svm_parameters from world_values_parameters import classification_knn_parameters from sklearn.neighbors import NearestNeighbors from sklearn.neighbors import KNeighborsRegressor def main(): print("Predicting HDI from World Values Survey") print() # Import Data # print("Importing Training and Testing Data") values_train, hdi_train, values_test = import_world_values_data() # Center the HDI Values # hdi_scaler = StandardScaler(with_std=False) hdi_shifted_train = hdi_scaler.fit_transform(hdi_train) # Classification Data # hdi_class_train = hdi_train['2015'].apply(hdi_classification) # Data Information # print('Training Data Count:', values_train.shape[0]) print('Test Data Count:', values_test.shape[0]) print() # Calculate Correlations # # calculate_correlations(values_train, hdi_train) # PCA # # plot_pca(values_train, hdi_train, hdi_class_train) # Regression Grid Searches # #regression_grid_searches(training_features=values_train, # training_labels=hdi_shifted_train) # find_countries(training_features = values_train, k = 7, scale = False) # HDI_test(values_train, hdi_shifted_train, values_test, 3) #find_countries(values_train, 7, True) # Classification Grid Searches # classification_grid_searches(training_features=values_train, training_classes=hdi_class_train) def find_countries(training_features, k, scale = True): neighbors = NearestNeighbors(n_neighbors = k+1) neighbors.fit(training_features) # prepare for usa feature if scale : scaler = StandardScaler() training_features = scaler.fit_transform(training_features.copy()) usa_feature = training_features[45,] else : usa_feature = training_features.iloc[45] ind = neighbors.kneighbors(usa_feature, return_distance = False)[0][1:k+1] NN_countries = pd.read_csv('world-values-train2.csv') print(NN_countries['Country'].loc[ind]) def _rmse_grid_search(training_features, training_labels, pipeline, parameters, technique): """ Input: training_features: world_values responses on the training set training_labels: HDI (human development index) on the training set pipeline: regression model specific pipeline parameters: regression model specific parameters technique: regression model's name Output: Prints best RMSE and best estimator Prints feature weights for Ridge and Lasso Regression Plots RMSE vs k for k Nearest Neighbors Regression """ grid = GridSearchCV(estimator=pipeline, param_grid=parameters, scoring='neg_mean_squared_error') grid.fit(training_features, training_labels) print("RMSE:", sqrt(-grid.best_score_)) print(grid.best_estimator_) # Check Ridge or Lasso Regression if hasattr(grid.best_estimator_.named_steps[technique], 'coef_'): print(grid.best_estimator_.named_steps[technique].coef_) else: # Plot RMSE vs k for k Nearest Neighbors Regression plt.plot(grid.cv_results_['param_knn__n_neighbors'], (-grid.cv_results_['mean_test_score'])**0.5) plt.xlabel('k') plt.ylabel('RMSE') plt.title('RMSE versus k in kNN') plt.show() print() def HDI_test(training_features, hdi_train, test_features, k, scale = True) : if scale: scaler = StandardScaler() training_features = scaler.fit_transform(training_features.copy()) test_features = scaler.fit_transform(test_features.copy()) knnRegressor = KNeighborsRegressor(n_neighbors = 3, weights='distance') knnRegressor.fit(training_features, hdi_train) print(knnRegressor.predict(test_features)) def regression_grid_searches(training_features, training_labels): """ Input: training_features: world_values responses on the training set training_labels: HDI (human development index) on the training set Output: Prints best RMSE, best estimator, feature weights for Ridge and Lasso Regression Prints best RMSE, best estimator, and plots RMSE vs k for k Nearest Neighbors Regression """ print("Ridge Regression") _rmse_grid_search(training_features, training_labels, ridge_regression_pipeline, regression_ridge_parameters, 'ridge') print("Lasso Regression") _rmse_grid_search(training_features, training_labels, lasso_regression_pipeline, regression_lasso_parameters, 'lasso') print("k Nearest Neighbors Regression") _rmse_grid_search(training_features, training_labels, k_nearest_neighbors_regression_pipeline, regression_knn_parameters, 'knn') def _accuracy_grid_search(training_features, training_classes, pipeline, parameters): """ Input: training_features: world_values responses on the training set training_labels: HDI (human development index) on the training set pipeline: classification model specific pipeline parameters: classification model specific parameters Output: Prints best accuracy and best estimator of classification model """ grid = GridSearchCV(estimator=pipeline, param_grid=parameters, scoring='accuracy') grid.fit(training_features, training_classes) print("Accuracy:", grid.best_score_) print(grid.best_estimator_) print() def classification_grid_searches(training_features, training_classes): """ Input: training_features: world_values responses on the training set training_labels: HDI (human development index) on the training set Output: Prints best accuracy and best estimator for SVM and k Nearest Neighbors Classification """ print("SVM Classification") _accuracy_grid_search(training_features, training_classes, svm_classification_pipeline, classification_svm_parameters) print("k Nearest Neighbors Classification") _accuracy_grid_search(training_features, training_classes, k_nearest_neighbors_classification_pipeline, classification_knn_parameters) if __name__ == '__main__': main()
n = int(input("Times table:")) x = 1 while x <= 10: print("%d x %d = %d" % (n, x, n*x) ) x = x + 1
#Given a number count the total number of digits in a number num = input ("Digite um número extenso qualquer: ") num = int (num) count = 0 while num != 0: num //= 10 count+= 1 print("O total de dígitos neste número é: ", count)
#primeiro exemplo da função for for x in ( 1, 7, -2, 4.8 ) : print ( "Número : " , x ) print ( "Tenha um bom dia ! " )
grade = input ("Enter grade value:") grade = float (grade) if grade >= 5.0: print ("Congratulations! You are approved!") if grade < 5.0: print ("Recovery!") print ("Need to study more!") print ("And try hard!") print ("Have a nice day!")
a = int(input('Square side size: ')) print(a) print ('The perimeter of this square is: ', 4*a)
from unittest import TestCase from MinHeap import MinHeap class TestMinHeap(TestCase): def test_minHeap(self): l = [5, 3, 4, 2, 6, 1] h = MinHeap() for item in l: h.push(item) last_element = 0 while h.peak() is not None: if h.peak() < last_element: return self.fail('1 MinHeap return {} last time and {} this time'.format(last_element, h.peak())) last_element = h.pop() h = MinHeap(l) last_element = 0 while h.peak() is not None: if h.peak() < last_element: return self.fail('2 MinHeap return {} last time and {} this time'.format(last_element, h.peak())) last_element = h.pop() h = MinHeap(l) h.pop() h.pop() h.push(0) h.push(7) if h.pop() != 0: return self.fail('MinHeap did not re-heapify')
a = int(input()) #Входное значение а b = int(input()) #Входное значение b while b != 0: #Цикл пока b не равен 0 a, b = b, a % b #переменной 'a' присваивается значение переменной 'b', переменной 'b' присваивается остаток от ('a' / 'b') print('НОД', a) #Наибольший общий делитель
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ # Runtime: 60 ms, faster than 85.59% of Python3 online submissions for Two Sum II - Input array is sorted. # Memory Usage: 14.8 MB, less than 32.26% of Python3 online submissions for Two Sum II - Input array is sorted. def twoSum2(nums: [int], target: int) -> [int]: left = 0 right = len(nums) - 1 while left < right: if nums[left]+nums[right] > target: right -= 1 elif nums[left]+nums[right] < target: left += 1 else: return [left+1, right+1] return print(twoSum2([2,7,11,15], 9)) print(twoSum2([1,2,7,11,15], 9)) print(twoSum2([1,2,3,7,11,15], 10))
from my_timer import timed from prime_numbers import count_factors_with_primes, sieve # A dict of triangular numbers tnum = {1: 1, 2: 3, 3: 6} def find_tnum(x): """Find the x'th triangular number. A triangular number is generated by adding the natural numbers. :param x: The triangular number to get :return: The x'th triangular number """ if x not in tnum: tnum[x] = find_tnum(x-1) + x return tnum[x] @timed def pe_prob_012(x): """Find the first triangle number to have over x divisors :return: The first triangular number to have over x divisors """ i = 1 primes = sieve(2000000) while not count_factors_with_primes(find_tnum(i), primes) > x: i += 1 return tnum[i] if __name__ == '__main__': print pe_prob_012(500)
"""@author: Ramkishan K Pawar program to convert a given nameslist into usernames""" names = ["Ramkishan Pawar", "Madhuri Jaju", "Sonal Patwari", "Yashika Lalwani", "Arjun Londhe", "Payal Roul"] usernames = [] for name in names: usernames.append(name.lower().replace(" ", "_")) print(usernames)
"""@author: Ramkishan K Pawar program to create html list using python.""" items = ["first string", "second string"] html_str = "<ul>\n" for each_item in items: html_str += "<li>{}</li>\n".format(each_item) html_str += "</ul>" print(html_str)
import numpy as np from global_utils import * class DirectMappingNN: """ No hidden layer, only input -> output. Asssuming, sigmoid activation on the output layer, although the sigmoid activation function for the output layer is not called inside of this network but instead inside of the memory network since the memory network computes the sigmoid of the sum of the net output of this network and alcove plus its bias vector. Author: Jason Yim, Jay Miller """ def __init__(self, input_size, output_size=0, l_rate=0.05): """ args: input_size - size of input output_size - size of output l_rate - learning rate of network """ if (output_size == 0): output_size = input_size self.l_rate = l_rate # making sure the layers are column vectors self.input = np.matrix(np.zeros(input_size)).T self.output = np.matrix(np.zeros(output_size)).T # weight matrices self.W_oi = np.random.normal(loc=0, scale=.5, size=(output_size, input_size)) # no bias vector on output because it's in the memory_network def forward_pass(self, input): """ Perform a forward pass on the network given an input vector. Don't perform activation function on output, since the memory network does this itself on the sum of the two individual networks. """ if (input.shape != self.input.shape): print "Input dimension does not match" self.input = input self.output = np.dot(self.W_oi, self.input) def backward_pass(self, dE_dOut): """ Perform a backward pass on the network given the negative of the derivative of the error with respect to the output. """ if (dE_dOut.shape != self.output.shape): print "Target/output dimensions do not match" error = dE_dOut # calculate deltas delta_o = np.multiply(np.multiply(error, self.output), 1-self.output) # deltas for weights W_oi_delta = np.dot(np.multiply(self.l_rate, delta_o), self.input.T) self.W_oi = self.W_oi + W_oi_delta class FeedForwardNN: """ A single hidden layer, neural network implementation To be used as the I -> H -> O route in the memory network. Sigmoid activation on the hidden layer is assumed as is sigmoid activation on the output layer although the sigmoid activation function for the output layer is not called inside of this network but instead inside of the memory network since the memory network computes the sigmoid of the sum of the net output of this network and alcove plus its bias vector. Author: Jason Yim, Jay Miller """ def __init__(self, input_size, hidden_size, output_size=0, l_rate=0.05): """ args: input_size - size of input output_size - size of output hidden_size - size of hidden_layers for now each hidden layer has the same size hidden_layers - number of hidden layers currently only working with 1 l_rate - learning rate of network """ if (output_size == 0): output_size = input_size self.l_rate = l_rate # making sure the layers are column vectors self.input = np.matrix(np.zeros(input_size)).T self.output = np.matrix(np.zeros(output_size)).T self.hidden = np.matrix(np.zeros(hidden_size)).T self.activ_func = sigmoid # weight matrices self.W_hi = np.random.normal(loc=0, scale=.5, size=(hidden_size, input_size)) self.B_h = np.random.normal(loc=0, scale=1, size=(hidden_size, 1)) self.W_oh = np.random.normal(loc=0, scale=.5, size=(output_size, hidden_size)) # no bias vector on output because it's in the memory_network def forward_pass(self, input): """ Perform a forward pass on the network given an input vector. Don't perform activation function on output, since the memory network does this itself on the sum of the two individual networks. """ if (input.shape != self.input.shape): print "Input dimension does not match" self.input = input self.hidden = self.activ_func(np.dot(self.W_hi, self.input) + self.B_h) self.output = np.dot(self.W_oh, self.hidden) def backward_pass(self, dE_dOut): """ Perform a backward pass on the network given the negative of the derivative of the error with respect to the output. """ if (dE_dOut.shape != self.output.shape): print "Target/output dimensions do not match" error = dE_dOut # calculate deltas delta_o = np.multiply(np.multiply(error, self.output), 1-self.output) delta_h = np.multiply(np.multiply(np.dot(self.W_oh.T, delta_o), self.hidden), 1-self.hidden) # deltas for weights W_oh_delta = np.dot(np.multiply(self.l_rate, delta_o), self.hidden.T) W_hi_delta = np.dot(np.multiply(self.l_rate, delta_h), self.input.T) # update weights and bias self.W_hi = self.W_hi + W_hi_delta self.W_oh = self.W_oh + W_oh_delta self.B_h = self.B_h + self.l_rate*delta_h
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 22 17:10:37 2018 @author: chuxuan """ """ 利用字典,每次减去已经表达的数字 """ def solution(num): results = "" left = num roms_list = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] roms = {5: "V", 1: "I", 10:"X", 50: "L", 100: "C", 500:"D", 1000: "M", 4:"IV", 9:"IX", 90:"XC", 400:"CD", 900:"CM", 40:"XL"} for k in roms_list: while left >= k: results += roms[k] left = left - k return results print(solution(58))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 24 22:18:53 2018 @author: chuxuan """ def gengeratePar(n): res =[] generate(n,n,"",res) return res def generate(left,right,str,res): if left == 0 and right == 0: res.append(str) return if left > 0: generate(left-1,right,str +'(',res) if right > left: generate(left,right-1,str+')',res) print(generateParenthesis(3))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 23 21:35:01 2018 @author: chuxuan """ # Utlize the Dynamic programming def findTargetSumWays(nums, S): """ :type nums: List[int] :type S: int :rtype: int """ sum_num = sum(nums) if (S > sum_num) or ((S+sum_num)%2==1): return 1 else: target = int(.5*(S+sum_num)) dp = [0]*(target+1) dp[0]=1 for n in nums: i = target while (i>=n): dp[i] = dp[i] + dp[i-n] i -=1 return dp[-1] print(findTargetSumWays([1,1,1,1,1],3))
''' Construir um algoritmo que contenha 3 listas: • Nomes de produtos • Preços de cada produto • Quantidades de cada produto • Construir uma função para imprimir um dos produtos da lista e uma função para retirar um dos produtos das listas Criar um repositório GIT remoto (Github, Gitlab ou Bitbucket), fazer commit do trabalho para este repositório e postar aqui apenas o link do repositório. ''' nome_produto = ['a', 'b', 'c', 'd', 'e'] preco_produto = [1,2,3,4,5] qt_produto = [5,4,3,2,1] menu = ''' [1] - Escolher produto [2] - Deletar produto ''' def lista_produtos(): for i in range (len(nome_produto)): print(f'{i} - Produto: {nome_produto[i]}') def escolhe_produto(): i = int(input('Informe o índice do produto que deseja listar: ')) input(f'Produto: {nome_produto[i]} - Preço: {preco_produto[i]} - Quantidade: {qt_produto[i]}') def deleta_produto(): d = int(input('Informe o índice do produto que deseja deletar: ')) del nome_produto[d] del preco_produto[d] del qt_produto[d] return nome_produto while True: print(menu) escolha = int(input('Escolha: ')) if escolha == 1: lista_produtos() escolhe_produto() elif escolha == 2: lista_produtos() deleta_produto() lista_produtos() else: input('Opção inválida')
import random import tkinter as tk import os class Game(tk.Frame): """GUI for Monty Hall show""" doors = ('a', 'b', 'c') def __init__(self, parent): super(Game, self).__init__(parent) self.parent = parent self.img_file = 'all_closed.png' self.choice = '' self.winner = '' self.reveal = '' self.first_choice_wins = 0 self.change_doors_wins = 0 self.create_widgets() def create_widgets(self): """Create label, button, and text widgets.""" # add labels to image of doors img = tk.PhotoImage(file = 'all_closed.png') self.photo_lbl = tk.Label(self.parent, image = img, text = '', borderwidth = 0) self.photo_lbl.grid(row = 0, column = 0, columnspan = 10, sticky = 'W') self.photo_lbl.image = img # add instructions instr_input = [ ('Behind one door is the prize,', 1, 0, 5, 'W'), ('Behind the others are goats.', 2, 0, 5, 'W'), ('Pick a door:', 1, 3, 1, 'E') ] for text, row, column, columnspan, sticky in instr_input: instr_lbl = tk.Label(self.parent, text = text) instr_lbl.grid(row = row, column = column, columnspan = columnspan, sticky = sticky, ipadx = 30) # create radio buttons for user input self.door_choice = tk.StringVar() self.door_choice.set(None) a = tk.Radiobutton(self.parent, text = 'A', variable = self.door_choice, value = 'a', command = self.win_reveal) b = tk.Radiobutton(self.parent, text = 'B', variable = self.door_choice, value = 'b', command = self.win_reveal) c = tk.Radiobutton(self.parent, text = 'C', variable = self.door_choice, value = 'c', command = self.win_reveal) # create widgets for changing door choice self.change_door = tk.StringVar() self.change_door = set(None) instr_lbl = tk.Label(self.parent, text = 'Change door?') instr_lbl.grid(row = 2, column = 3, columnspan = 1, sticky = 'E') self.yes = tk.Radiobutton(self.parent, state = 'disabled', text = 'Y', variable = self.change_door, value = 'y', command = self.show_final) self.no = tk.Radiobutton(self.parent, state = 'disabled', text = 'N', variable = self.change_door, value = 'n', command = self.show_final) # create text widgets for win stats defaultbg = self.parent.cget('bg') self.unchanged_wins_txt = tk.Text(self.parent, width = 20, height = 1, wrap = tk.WORD, bg = defaultbg, fg = 'black', borderwidth = 0) self.changed_wins_txt = tk.Text(self.parent, width = 20, height = 1, wrap = tk.WORD, bg = defaultbg, fg = 'black', borderwidth = 0) # place the widgets in the frame a.grid(row = 1, column = 4, stick = 'W', padx = 20) b.grid(row = 1, column = 4, stick = 'N', padx = 20) c.grid(row = 1, column = 4, stick = 'E', padx = 20) self.yes.grid(row = 2, column = 4, sticky = 'W', padx = 20) self.no.grid(row = 2, column = 4, sticky = 'W', padx = 20) self.unchanged_wins_txt.grid(row = 1, column = 5, columnspan = 5) self.changed_wins_txt.grid(row = 2, column = 5, columnspan = 5) def update_image(self): """Update current doors image.""" img = tkPhotoImage(file = self.img_file) self.photo_lbl.configure(image = img) self.photo_lbl.image = img def win_reveal(self): """Randomly pick winner and reveal unchosen door.""" door_list = list(self.doors) self.choice = self.door_choice.get() self.winner = random.choice(door_list) door_list.remove(self.winner) if self.choice in door_list: door_list.remove(self.choice) self.reveal = door_list[0] else: self.reveal = random.choice(door_list) self.img_file = ('reveal_{}.png'.format(self.reveal)) self.update_image() # turn on and clear yes/no buttons self.yes.config(state = 'normal') self.no.config(state = 'normal') self.change_door.set(None) # close doors after opening self.img_file = 'all_closed.png' self.parent.after(2000, self.update_image) def show_final(self): """Reveal image behind user's final door choice & count wins.""" door_list = list(self.doors) switch_doors = self.change_door.get() if switch_doors == 'y': door_list.remove(self.choice) door_list.remove(self.reveal) new_pick = door_list[0] if new_pick == self.winner: self.img_file = 'money_{}.png'.format(new_pick) self.change_doors_wins += 1 else: self.img_file = 'goat_{}.png'.format(self.choice) self.first_choice_wins += 1 elif switch_doors == 'n': if new_pick == self.winner: self.img_file = 'goat_{}.png'.format(self.choice) self.first_choice_wins += 1 else: self.img_file = 'money_{}.png'.format(new_pick) self.change_doors_wins += 1 # update door image self.update_image() # update displayed statistics self.unchaged_wins_txt.delete(1.0, 'end') self.unchaged_wins_txt.insert(1.0, 'Unchanged wins = {:d}'.format(self.first_choice_wins)) self.changed_wins_txt.delete(1.0, 'end') self.changed_wins_txt.insert(1.0, 'Changed wins = {:d}'.format(self.change_doors_wins)) # turn off yes/no buttons and clear door choice buttons self.yes.config(state = 'disabled') self.no.config(state = 'disabled') self.door_choice.set(None) # close doors after opening self.img_file = 'all_closed.png' self.parent.after(2000, self.update_image) # set up root window and run event loop root = tk.Tk() root.title('Monty Hall Problem') root.geometry('1280x820') game = Game(root) root.mainloop()
# Python code to create the two tables and insert data import sqlite3 conn = sqlite3.connect('data.db') c = conn.cursor() c.execute('''CREATE TABLE person ( id INTEGER PRIMARY KEY ASC, name varchar(250) NOT NULL)''') c.execute('''CREATE TABLE address ( id INTEGER PRIMARY KEY ASC, street_name varchar(250), street_number varchar(250), post_code varchar(250) NOT NULL, person_id INTEGER NOT NULL, FOREIGN KEY(person_id) REFERENCES person(id))''') c.execute(''' INSERT INTO person VALUES(1, 'Mary Poppins') ''') c.execute( ''' INSERT INTO address VALUES(1, 'Magic Lane', '22', '12000', 1) ''') conn.commit() conn.close()
#!/usr/bin/env python3 #Input string that use different characters as delimiters s1 = "Donald, Victoria, Andrew, Sarah" s2 = "Donald Victotia Andrew Sarah" s3 = "Donald@Victoria@Andrew@Sarah" #print out the initial strings print("s1: ", s1) print ("s2: ", s2) print ("s3: ", s3) #Split the string, creae a list using a comma-separator list1 = s1.split(',') print("list1: ", list1) #Split the string, create a list using the default space list2 = s2.split() print("list2: ", list2) #Split the string create a list using the @ charachet as a delimiter list3 = s3.split ('@') print("liat3: ", list3)
#!/usr/bin/env python3 s1 = "%to, two, too!" print(s1) #This illustrates more string slicing #This shows the first character in the string print(s1[0]) #This shows the last characher in the string print(s1[-1]) #This gets he frist three characters in the string #This includes indexes 0 to 2. It does not include index 3 print(s1[:3]) #This starts at index 7 and goes to the end of the string print(s1[7:]) #This should print out the string ',too!' #This start at index 3 and goes to index y (does NOT include index 8) print(s1[3:8]) #Thisa should print out the string ',two.'
#!//usr/bin/env python3 my_num = 1234.56789 my_pi = 3.1415926535 print("My number is:",my_num) print("The value of pi: ",my_pi) ####################################################################### # Format to 2 decimal places # NOTE that you don't need the 0 before.2f ####################################################################### print(format(my_num,'0.2f'),"prints using 2 decimal places") print(format(my_num,'.2f'), "Also prints using 2 decimal places") print("NOTE that it rounded my result!!!") print() # Format to only 1 decimal place print(format(my_num, '.1f'), "Also printing using 1 decimal places") print("NOTE that it rounded my result!!!") # Format PI from 10 decimal places to 6 decimal places print(format(my_pi, '6f'), "Also prints using 6 decimal places") print("NOTE that it rounded my resoult!!!")
#!/usr/env python3 #Import the operating system module import os #Open the input file for reading in_file = open('infile_002.txt', 'r') line_count = 0 total_glucose = 0 total_insulin_dose = 0 ############################################################# #Read the imput file...it is stored in a list ############################################################ sugar_levels_list = in_file.readlines() print("====SUGAR LEVELS LIST below=======") print(sugar_levels_list) print() print("----First element int he SUGAR LEVELS LIST----") print(sugar_levels_list[0]) print() ############################################################## #Loop through each line oin the input file...print out the file ############################################################### for a_line in sugar_levels_list: print(a_line, end ="") #Using the end paracmeter, extra line feeds not added #Save the glucose value at the end of this string, locate at index 2 #The format is: DATE, TIME, GLOCOSE-VALUE, INSULIN_DOSE tmp_list = a_line.split(',') glucose_value = tmp_list[2] insulin_dose = tmp_list[3] print("...glucose value=",glucose_value) total_glucose +=int(glucose_value) total_insulin_dose +=int(insulin_dose) line_count +=1 print() print("DONE READING THE FILE...") print("....Total Glucose=",total_glucose) print("...Total Count = ",line_count) print("...Average Glocuse= ",total_glucose/line_count) print("...Average Insulin Dose = ",total_insulin_dose/line_count) in_file.close() #IMPORTANT! Don't forget to Close the file
from math import gcd; def nth_root(n, index): return n ** (1 / index); class Number(): """ Object for representing numerical values in an expression """ def __init__(self, value=0): if isinstance(value, (int, float)): self.numerator, self.denominator = float(value).as_integer_ratio(); elif isinstance(value, tuple): if len(value) == 2 and value[1] != 0: self.numerator, self.denominator = map(int, value); else: raise ValueError("tuple must be of length 2 and the denominator cannot be 0."); else: raise TypeError("value must be a float, int, or 2-tuple of ints."); self.reduce(); def __repr__(self): return "Number( {} / {} )".format(self.numerator, self.denominator); def __neg__(self): return Number(-1) * self; def __add__(self, other): numerator = self.numerator * other.denominator + self.denominator * other.numerator; denominator = self.denominator * other.denominator return Number((numerator, denominator)); def __sub__(self, other): return self + (-other); def __mul__(self, other): numerator = self.numerator * other.numerator; denominator = self.denominator * other.denominator; return Number((numerator, denominator)); def __truediv__(self, other): numerator = self.numerator * other.denominator; denominator = self.denominator * other.numerator; return Number((numerator, denominator)); def __pow__(self, other): return Number((nth_root(self.numerator, other.denominator) ** other.numerator, nth_root(self.denominator, other.denominator) ** other.numerator)); def __eq__(self, other): return (self.numerator, self.denominator) == (other.numerator, other.denominator); def __lt__(self, other): return self.as_decimal() < other.as_decimal(); def __gt__(self, other): return self.as_decimal() > other.as_decimal(); def as_decimal(self): """ return the value in decimal form. """ return self.numerator / self.denominator; def reduce(self): """ Simplify the fraction """ common_divisor = gcd(self.numerator, self.denominator); self.numerator //= common_divisor; self.denominator //= common_divisor;
""" x^3 + 4x^2 - 10 = 0 en [1,2] """ ###Funciones auxiliares #funcion a resolver def func(x): value = x**3 + 4*x**2-10 return value def sign(x): if x > 0: return 1 elif x < 0: return -1 else: return 0 ###Metodo #longitud intervalo ai = 1.0 bi = 2.0 #Tolerancia Tol = 1.0e-4 #Error inicial error = 1.0 #Nmax de interaciones Nmax = 1000 iteracion = 0 #Verificacion del valor medio if (sign(func(ai))* sign(func(bi))<0): while(error > Tol): pi = 0.5*(ai+bi) pi_previo = pi #redefinimos los limites del intervalo #if(abs(func(pi)) < Tol): # print("La raiz del polinomio es %.5f"%(pi)) #else: if(sign(func(pi)) == sign(func(ai))): ai = pi bi = bi elif(sign(func(pi)) == sign(func(bi))): ai = ai bi = pi pi = 0.5*(ai+bi) error = abs(pi - pi_previo) iteracion = iteracion+1 print("pi=%f\t ai=%f\t f(pi)=% f\t error=%f"%(pi,ai,func(pi),error)) if(iteracion > Nmax): print("Numero de iteraciones excedido") break else: print("Intervalo inadecuado") print("Cero de F(x) = %f , F(pi)= %.5f"%(pi, func(pi)))
#!/usr/bin/env python # coding: utf-8 # **Linear Regression project using PySpark** # # Data has been taken from UC Irvine Machine Learning repository. It is a description of Ship carriers and the related parameters which includes: # * Ship Name # * Cruise Line # * Age of the ship # * Tonnage # * Passanger Capacity # * Length # * Number of Cabins # * Passenger Density # * Crew (Target Variable) # # I would be using PySpark and Machine Learning to predict our target variable, Crew. # # In[ ]: #Start a new Spark Session import findspark findspark.init('/home/ubuntu/spark-2.1.1-bin-hadoop2.7') from pyspark.sql import SparkSession # App named 'Cruise' spark = SparkSession.builder.appName('cruise').getOrCreate() # In[6]: #Read the csv file in a dataframe df = spark.read.csv('cruise_ship_info.csv',inferSchema=True,header=True) # In[7]: #Check the structure of schema df.printSchema() # In[8]: df.show() # In[9]: df.describe().show() # In[10]: df.groupBy('Cruise_line').count().show() # In[23]: #Convert string categorical values to integer categorical values from pyspark.ml.feature import StringIndexer indexer = StringIndexer(inputCol="Cruise_line", outputCol = "cruise_cat") indexed = indexer.fit(df).transform(df) indexed.head(5) # In[24]: from pyspark.ml.linalg import Vectors # In[25]: from pyspark.ml.feature import VectorAssembler # In[26]: indexed.columns # In[28]: # Create assembler object to include only relevant columns assembler = VectorAssembler( inputCols=['Age', 'Tonnage', 'passengers', 'length', 'cabins', 'passenger_density', 'crew', 'cruise_cat'], outputCol="Features") # In[29]: output = assembler.transform(indexed) # In[30]: output.select("features","crew").show() # In[31]: final_data = output.select("features","crew") # In[32]: #Split the train and test data into 70/30 ratio train_data,test_data = final_data.randomSplit([0.7,0.3]) # In[33]: from pyspark.ml.regression import LinearRegression # In[34]: #Training the linear model lr = LinearRegression(labelCol='crew') # In[35]: lrModel = lr.fit(train_data) # In[39]: print("Coefficients: {} Intercept: {}".format(lrModel.coefficients,lrModel.intercept)) # In[40]: #Evaluate the results with the test data test_results = lrModel.evaluate(test_data) # In[41]: print("RMSE: {}".format(test_results.rootMeanSquaredError)) print("MSE: {}".format(test_results.meanSquaredError)) print("R2: {}".format(test_results.r2)) # In[42]: from pyspark.sql.functions import corr # In[43]: #Checking for correlations to explain high R2 values df.select(corr('crew','passengers')).show() # In[44]: df.select(corr('crew','cabins')).show()
#!/usr/bin/python3 def ChangeInt(a): a = 10 b = 2 ChangeInt(b) print(b) # 结果是 2 # !/usr/bin/python3 # 可写函数说明 def printme(str): "打印任何传入的字符串" print(str); return; # 调用printme函数 printme();
# -*- coding: UTF-8 -*- import os; # document = open("testfile.txt", "w+"); # print ("文件名: ", document.name); # document.write("这是我创建的第一个测试文件!\nwelcome!"); # print (document.tell()); # #输出当前指针位置 # document.seek(os.SEEK_SET); # #设置指针回到文件最初 # context = document.read(); # print (context); # document.close(); doc=open("2017.txt","w+"); print("filename",doc.name) doc.write("this is my first file\nwelcome!"); print(doc.tell()); doc.seek(os.SEEK_SET); context=doc.read(); print(context); doc.close();
from random import randint def calc_monster_attack(attack_min, attack_max): return randint(attack_min, attack_max) def game_ends(winner_name): print(winner_name + " won!") def main(): game_running = True game_results = [] while game_running: counter = 0 new_round = True player = {"name": "Player", "attack": 13, "heal": 16, "health": 100} monster = {"name": "Enemy", "attack_min": 12, "attack_max": 17, "health": 80} print("---" * 7) player["name"] = input("Enter your name : ") if player["name"] == "": player["name"] = "Player" print("Welcome, " + player["name"] + "\n") while new_round: counter += 1 player_won = False monster_won = False print("---" * 7) print("Please an select action: ") print("1. Attack ") print("2. Heal ") print("3. Exit Game") player_choice = input(" >>> ") print("---" * 7) if player_choice == "1": monster["health"] -= player["attack"] if monster["health"] <= 0: monster["health"] = 0 player_won = True else: player["health"] -= calc_monster_attack(monster["attack_min"], monster["attack_max"]) if player["health"] <= 0: player["health"] = 0 monster_won = True print(f"\nAttacking {monster['name']}!") print(f"{monster['name']} now has {monster['health']} health left") print(f"Attacking {player['name']}!") print(f"{player['name']} now has {player['health']} health left\n") elif player_choice == "2": player["health"] += player["heal"] print(f"Healing {player['name']}!") print(f"{player['name']} now has {player['health']} health") elif player_choice == "3": print("Ending game...") game_running = False new_round = False else: print("Invalid Input. Please choose from the options above!") if player_won and monster_won: print(player["name"] + " has " + player["health"] + " left") print(monster["name"] + " has " + monster["health"] + " left") elif player_won: game_ends(player["name"]) round_result = print("Name :", player["name"] + "\n" + "Health :", str(player["health"]) + "\n" + "Rounds :", counter) game_results.append(round_result) print("The round has now ended...") new_round = False elif monster_won: game_ends(monster["name"]) round_result = print("Name :", player["name"] + "\n" + "Health :", str(player["health"]) + "\n" + "Rounds :", counter) game_results.append(round_result) print("The round has now ended...") new_round = False main()
# PdfText.py """ Classes for managing the production of formatted text, i.e. a chapter. PdfChapter() PdfParagraph() PdfString() """ from PdfDoc import PdfDocument from PdfFontMetrics import PdfFontMetrics import math # global metrics = PdfFontMetrics() FNfontkey = 'F3' FNfontsize = 5 FONTMarker = '^' # function copied from stackoverflow # https://stackoverflow.com/questions/28777219/basic-program-to-convert-integer-to-roman-numerals from collections import OrderedDict def write_roman(num): roman = OrderedDict() roman[1000] = "M" roman[900] = "CM" roman[500] = "D" roman[400] = "CD" roman[100] = "C" roman[90] = "XC" roman[50] = "L" roman[40] = "XL" roman[10] = "X" roman[9] = "IX" roman[5] = "V" roman[4] = "IV" roman[1] = "I" def roman_num(num): for r in roman.keys(): x, y = divmod(num, r) yield roman[r] * x num -= (r * x) if num <= 0: break return "".join([a for a in roman_num(num)]).lower() class TextFont( object ): """ Simple data structure to hold font name and size Fonts are the standard pdf fonts F1, F2, F3, with I and B varians, Times Roman F3 Italic F3I Bold F3B F1: Courier] [F2: Helvetica] [F3: Times-Roman] """ def __init__(self, pname, psize): """ Example: f = TextFont('F3',10) """ self.name = pname self.size = psize def __str__( self): return 'TextFont("' + self.name+'",'+str(self.size)+')' def asItalic( self): """ Return a new TextFont, which is a italic version of self """ return TextFont( self.name[0:2]+'I', self.size) def asBold(self): """ Return a copy of self as a bold font """ return TextFont( self.name[0:2]+'I', self.size) def asNormal(self): """ Return a copy of self as a plain font, not italic or bold """ return TextFont( self.name[0:2], self.size) class PdfChapter( object ): """ PdfChapter is the container for stand-alone amount of formatted text, such as a chapter of text. It may have headings, multiple paragraphs, and changes of font within a section of text such as a paragraph. It begins with a new page and terminates with an end page. PdfParagraphs are added to self.paragraphs list PdfPages are later constructed from the list of PdfParagraphs A chapter may have a standard header, stored as a paragraph in self.header A chapter may have a footer, set via a very limited method, and later converted into a paragraph. instance variables: """ def __init__( self, doc ): """ Initializer for PdfChapter The PDFDoc instance passed as <doc> should be already initialized. chapter printing starts at a new page """ self.pdf = doc self.paragraphs = [] self.pages = [] self.initialPageNumber = 0 # modify this to start with something other than 1 self.runningPageNumber = 0 # this increments as pages are produced # printed page number is initialPageNumber + runningPageNumber self.header = None # a header is a PdfParagraph() self.headerSkip = None # flag to skip the first page when printing a header self.footerStyle = None self.footerFont = None self.footer = None self.footnotes = [] # self.footnoteFont = TextFont('F3',7) self.superscriptFont = TextFont('F3',5) # dimensional info extracted from PdfDocument, may be overridden self.lineHeightFactor = doc.lineHeightFactor self.leftMargin = doc.getLeftMargin('p') self.rightMargin = doc.getRightMargin('p') self.lineWidth = doc.getLineWidth('p') self.topRow = doc.getTopMargin('p') self.bottomRow = self.getBottomMargin('p') def nxtFootnoteNbr( self ): """ Return the next available footnote number. """ return len(self.footnotes) + 1 def addFootnote(self, fnote): """ Add a PdfFoontnote() to the chapter list """ assert fnote is PdfFootnote self.footnotes.append( fnote ) def getFootnote(self, nbr): """ Get the <nbr>th footnote. Footnote 2 is expected to be in self.footnotes[1] """ assert len(self.footnotes) >= nbr - 1 assert self.footnotes[ ngr - 1].fnNum == nbr return self.footnotes[nbr - 1] def footnoteParagraph(self, fnNbr): """ Construct a paragraph from the chapter's <fnNbr>th footnote. generate an exception if it does not exist """ fn = self.getFootnote( nbr) para = PdfParagraph( self ) para.indent = 0 para.lead = 0 para.tail = 0 def footerParagraph(self, pageNumber): """ Construct a paragraph that will print the footer Return None is there is no footer. Since page number may be printed, it must be called for each page. """ ret = None if self.footerStyle is not None: para = PdfParagraph() para.tail = 0 para.indent = 0 if self.footerType == 'RomanRight': para.alignment = 'r' para.addString( self.footerFont, write_roman( page_number)) para.buildLines(self) return para def setFooterStyle(self, pStyle, font): """ define the chapter footer, such as setFooterStyle( 'RomanRight', TextFont('F3',9)) """ assert pStyle in [ 'RomanRight','None'], "Unknown footer style: "+pStyle assert font is TextFont self.footerStyle = pStyle self.footerFont = font def footerDepth( self ): """ Return the depth, in points, of the footer. """ ret = 0 if self.footerStyle is not None: ret = 2 * self.footerFont.size * self.lineHeightFactor return ret def addParagraph( self, para): """ Add <para> to the list of paragraphs """ assert para is PdfParagraph self.paragraphs.append( para ) def setHeader( self, pheader, pskipFirst ): """ add the header - it is a paragraph repeated on each page, except maybe the first """ assert header is PdfParagrah self.header = pheader self.headerSkip = pskipFirst def headerDepth(self): """ return the number of points required for the optional header. A header is just a paragraph so is """ if self.header is None: return 0 else: self.header.depth() def lineWidth(self): """ return the width of a line (without paragraph-specific modifications) for a chapter """ ret = self.pdf.getLineWidth('p') def buildPages(): """ construct a list of PdfPage() """ self.pages = [] self.runningPageNumber = 0 done = False paraCtr = -1 page = None r = self.topRow # end row should be constant other than for footnotes er = self.bottomRow - self.footerDepth() for para in self.paragraphs: if page is None: # we need a new page self.runningPageNumber++ fnDepth = 0 page = PdfPage( self, self.runningPageNumber + self.initialPageNumber) # add the header for ln in while not done: self.runningPageNumber++ page = PdfPage( self, self.runningPageNumber + self.initialPageNumber) fnDepth = 0 # track footnote depth as footnotes are added to the page # the page hdrLines and ftrLines are populated # the first addressable body line is the bottom hdrline + header.tail # now start to consume paragraphs r = self.topRow + self.headerDepth() # end row is the start of the footer, adjusted for optional footnotes # (when implemented) er = chapter.bottomRow - self.footerDepth() def print(self): """ A paragraphs have been added. header and footer defined. Perform the sequence of steps to print. for each paragraph execute para.buildLines(), i.e. self.buildLines execute self.buildPages() for each page execute page.print() """ for para in self.paragrahs: para.buildLines(self) self.header.buildLines() self.buildLines() self.buildPages() self.printPages() # ****** def prepare( self ): # calculate the total length, in points, of all strings in all paragraphs. linewidth = self.pdf.getLineWidth('p') # print(' Building lines of length '+ str( linewidth )) for para in self.paragraphs: # length of each string. Probably redundant. for s in para.strings: s.length = metrics.strLength( s.fontkey, s.fontsize, s.string ) # now within each paragragh, build lines - which may be multiple strings or # more often may be subsections of strings. para.buildLines( linewidth ) def newPage(self ): """ uses Chapter().pdf to invoke a new page in the pdf document. Increments pagenumber sets chapter prow and pcol to 0 """ self.pdf.newPage() # is there a header string? self.pageNumber += 1 self.prow = 0 self.pcol = 0 def endPage(self, footNotesCtr = 0, fnOrd = 1): if footNotesCtr > 0: print('printing footnotes') self.footnotes.printFootNotes( footNotesCtr, fnOrd, self.prow ) # ef printFootNotes( self, qty, firstNum, pRow): if self.footerStyle is None: pass elif self.footerStyle == 'RomanRight': s = write_roman(self.pageNumber) br = self.pdf.getBottomRow('p') rc = self.pdf.getLineWidth('p') self.pdf.write( rc,br, s,'r','p') self.pdf.endPage() def process(self ): """ PdfChapter.process( PdfDoc ) Print the chapter. Start a new page at the beginning. End whatever page is current at the end """ # self.newPage( ) self.pdf.setTextState() # go paragraph by paragraph, lines by lines. initial = True self.lineIncrement = self.pdf.lineHeight * self.pdf.lineHeightFactor for para in self.paragraphs: para.printParagraph( self ) self.endPage( ) def stretch(self, lns, amt): """ insert spaces until the length of the set to strings has been increased by <amt> points. """ ret = [] amtToAdd = amt while amtToAdd > 2: for l in lns: ol = l.length l.stretch( amtToAdd ) # retuce amtToAdd by the increase in length of the string amtToAdd = amtToAdd - ( l.length - ol ) if amtToAdd <= 2 : break; return lns class PdfParagraph( object ): """ PdfParagraph represents a body of text. It may be one-line, such as a chapter (or section) header, it may be a long paragraph. It contains of a list of PdfString objects- it may contain one string, it may contain many. For all of its components, they are produced sequentially and share the same justification: left, center, right, full l c r f A chapter heading would often be one short line of text, in a larger or more distinct font, and centered. Properties: alignment [ 'l','c','r','j'] indent points tail points lead points strings = [] lines = None or [] """ def __init__( self, chapter, lineHeightFactor = 1.2, alignment = 'l', indent = 0, tail = 10 ): """ all elements in a PdfParagraph share the same justification. <indent> is used for the first line of text. It is in points. <tail> moves the chapter row counter down tail points """ assert alignment in [ 'l','c','r','j'] assert chapter is PdfChapter self.chapter = chapter self.lineHeightFactor = lineHeightFactor self.alignment = alignment self.indent = indent self.tail = tail self.lead = 0 self.strings = [] self.lines = None def setIndent(self, pIndent): self.indent = pIndent def setAlignment(self, pAlignment): self.alignment = pAlignment def setJustification( self, pJustification): self.justification = pJustification def setLineHeightFactor( self, pLineHeightFactor ): self.lineHeightFactor = pLineHeightFactor def setTail(self, pTail): self.tail = pTail def setLead(self, pLead): self.lead = plead def depth( self): if self.lines is None: self.buildLines() ret = 0 for ln in self.lines: ret += ln.depth() * self.lineHeightFactor ret += (self.tail + self.lead) return ret def addString(self, pfont, pstring, pfootnotes = None): """ Construct a PdfString from the parameters and add to the strings list <pfootnotes> may be None (the dault) or a list of strings. Uses chapter.nxtFootnoteNbr() """ assert pfont is TextFont if pfootnotes is None: self.strings.append( PdfString( pfont, pstring ) else: # split the string on the ^ charactert txt = pstring.split('^') # the string should be in a list with 1 more element than there are footnotes assert len(txt) = len(pfootnotes) + 1 i = None for i in range(0,len(pstring)) # the first string is split self.strings.append( PdfString(pfont, txt[i])) num = self.chapter.nxtFootnoteNbr() # add the superscript self.strings.append( PdfStringFN( chapter.superscriptFont, str(num))) fn = PdfFootnote( num, pstring[i] # add the ending string is it exists if len(txt[-1]) > 0: self.strings.append( PdfString( pfont, txt[-1])) def buildLines( self, chapter ): """ This method takes all of the strings and breaks them up fit within individual lines. The end result is an array of PdfLine() lines that each fit on a single line regardless of font changes (within reason). It does this by splitting PdfStrings that overflow a line into multiple shorter PdfStrings. And combing short strings. Each PdfLine contains one or more PdfStrings, so be printed on the same line. The lines[] attribute contains a list of PdfLines. These will have the col value set, the row will be None while owned by a PdfParagraph. Within a paragraph the first line may have an indent, and therefore e shorter If the next string is a PdfStringFN then it is added no matter what. """ workingLine = PdfLine(None, chapter.leftMargin - self.indent) self.lines = [] linewidth = chapter.lineWidth workingLen = 0 # spaceLen = metrics.strLength(self.fontkey, self.fontsize, ' ') ctr = 0 ps = None # the first line of a paragraph may have an indent. targetlen = linewidth - self.indent worklingLine.col = lm for s in self.strings: ps = s.split2( targetlen ) workingLine.addString(ps) targetlen = targetlen - ps.length # print('added '+ps.string+' new targetlen is '+str(targetlen)) # we are at the end if a line when s.length > 0 # is s.length == 0 then the current line may not be full while s.length > 0: self.lines.append( workingLine ) lm = chapter.leftMargin workingLine = PdfLine( None, chapter.lm) targetlen = chapter.lineWidth ps = s.split2( targetlen ) targetlen = targetlen - ps.length workingLine.addString( ps ) # at this point s is consumed. targetlen is reduced as necessary, The # next string - perhaps in a different font - may fit, in full or in part # on the same line if targetlen < 10: self.lines.append( pdfLine ) workingLine = PdfLine( None, chapter.leftMargin) targetlen = chapter.lineWidth if len(workingLine.strings) > 0: self.lines.append( workingLine ) # now fully populated para.lines with PdfLine() instances def documentLines(self): """ print out the complete lines with total length for each """ for ln in self.lines: s = '' x = 0 for l in ln.strings: s += l.string x += l.length print( "{:4.0f}".format(x)+": "+s) def printParagraph(self, chapter): """ <chapter> is a PdfChapter. It is needed because it has access to endPage() and newPage() methods. And it tracks the chapter page number. chapter().pdf is a pdfDoc which is used for the printing. This method prints the paragraphs, beginning at the current row and at column 0. If there is insufficient room for one or more rows then the chapter.endPage() and chapter.newPage() methods are invoked. """ # self.documentLines() if self.lines is None: self.buildLines(doc.getLineWidth('p')) self.pcol = self.indent firstLine = True lineCount = len( self.lines ) lineCtr = 0 fnCtr = 0 # footnote counter for ln in self.lines: lineCtr += 1 if chapter.prow >= chapter.pdf.getBottomRow('p') - (chapter.footerLines() * (chapter.lineIncrement)) - chapter.footnotes.height(fnCtr): chapter.endPage( fnCtr ) fnCtr = 0 chapter.newPage( ) if firstLine: chapter.pcol = self.indent firstLine = False else: chapter.prow += chapter.lineIncrement if firstLine: chapter.pcol = self.indent firstLine = False else: chapter.pcol = 0 # how many point in this line lnlen = 0 # calculate the length of the line, after removing any trailing spaces # from the end of the ln ln[-1].setString( ln[-1].string.rstrip()) for l in ln: lnlen += l.length gap = chapter.pdf.getLineWidth('p') - lnlen if lineCtr == 1: gap = gap - self.indent if self.alignment == 'c': # bump pcol by half the difference between string length and line length chapter.pcol = gap / 2 elif self.alignment == 'r': chapter.pcol = gap elif self.alignment == 'j': # need to allocate gap among Strings # unless it is the last line if lineCtr < lineCount: ln = chapter.stretch( ln, gap) for l in ln: # each line [ ln ] in self.lines is a list of 1 or more print statements, all to # be on the same line. If there are multiple print statements they probably # use different fonts # set position to next Line f = l.string.count('^') if f > 0: print('footnote found in '+l.string) chapter.pdf.setFont( l.fontkey, l.fontsize ) chapter.pdf.write(chapter.pcol, chapter.prow , l.string, 'l','p') chapter.pcol += l.length if self.tail > 0: chapter.prow += self.tail * chapter.lineIncrement class PdfString( object ): """ PDFString is a continuous bit of text in a common font. It may end with a footnote. """ def __init__( self, pfont, pstring): """ Initialize a new string, invoke setLength() """ assert pfont is TextFont self.fontkey = pfont.name self.fontsize = pfont.size self.string = string self.setLength() def setLength(self): """ set the length property based on metrics.strLenth """ self.length = metrics.strLength( self.fontkey, self.fontsize, self.string) def depth(self): """ the depth of a string - not very useful - is simply the fontize """ return self.fontsize def setString(self, t): """ reset the string property with <t> and invoke self.setLength() """ self.string = t self.setLength() def split2(self, strLen): """ Splits a string. Returns a new PdfString that has a string <= strLen Modifes self, removing that portion of the string. 1. if the length of the string is 0 then it returns None 2. If the length is < <strLen> then it returns a clone of itself, and sets itself to an empty string of length 0 3. If there is no space in self.string then the same as #2 above 4. If the very first word in self.string is longer than strLen then it returns a PdfString with that first word. So if self.string is not empty then it returns a string of some length that may be greater than strLen """ ret = None if len(self.string) == 0: return None elif self.length <= strLen: ret = PdfString( TextFont(self.fontkey, self.fontsize), self.string) self.setString('') elif self.string.find(' ') < 0: ret = PdfString( TextFont(self.fontkey, self.fontsize), self.string) self.setString('') else: # build a new string. wrkStr = self.string newStr = '' newLen = 0 # if there is some content and at least 1 space return the characters # up to and including the first space no matter now long newStr = wrkStr[ 0: wrkStr.find(' ')+ 1] wrkStr = wrkStr[ wrkStr.find(' ')+ 1 :] newLen = metrics.strLength( self.fontkey, self.fontsize, newStr) while newLen < strLen and len(wrkStr) > 0: nxtStr = wrkStr[ 0: wrkStr.find(' ')+1] nxtLen = metrics.strLength(self.fontkey,self.fontsize, nxtStr) if newLen + nxtLen <= strLen: newStr += nxtStr newLen += nxtLen wrkStr = wrkStr[ wrkStr.find(' ')+1 :] else: # print('Could not fit in' + str(nxtLen)) break ret = PdfString( TextFont( self.fontkey, self.fontsize ) , newStr) ret.setLength() self.setString( wrkStr) self.setLength() return ret class PdfStringFN( PdfString ): """ Inherits from PdfString. Font is set """ def __init__( self, pfont, pstring): """ passes through to super class """ PfdString.__init__(self, pfont,pstring) class PdfLine( object): """ # a PdfLine is a collection of strings that are to be output on the same row. Methods: footnoteCount() getFootNote(<nPos>) setPos(r,c) addString( pdfString ) height() print() Properties row col strings [] length """ def __init__(self, prow = None, pcol = none): """ properties self.row self.col self.strings = [] self.length = 0 """ self.row = pRow self.col = pCol self.strings = [] self.length = 0 def footnoteCount(self): """ Return the count of footnotes present in the line. Footnotes are identified by being a PdfStringFN type """ ret = 0 for s in self.strings: if s is PdfStringFN: ret++ return ret def getFootnote( nPos ): """ Returns an int, or None Return the footnote number of the footnote in the <nPos> position. The first footnote by position in a string might be footnote number 7, if it is the 7th footnote registered in the chapter. The value is returned as an int. """ ret = None ctr = 0 for s in self.strings: if s is PdfStringFN: ctr++ if ctr == nPos: ret = int(s.string) break return ret def setPos( self, r, c): """ Set self.row and self.col """ self.row = r self.col = c def addString(self, pdfString): """ add a PdfString to self.strings, and reset self.length """ assert pdfString is PdfString self.strings.append( pdfString) self.length += pdfString.length def height(self): """ height is the maximum height found in strings """ ret = 0 for s in self.strings: ret = max(ret, s.fontsize) return ret def print(self, doc): """ print the line of text using the <doc> PdfDocument methods """ r = self.row c - self.col for s in self.strings doc.write( c, r, s.string,'l','p') c += s.length # ##### def findChars(self, c ): """ return a list of the indexes of all occurrences of <c> in self.string. May be useful for full justification """ ret = [] for i in range(0, len(self.string)): if self.string[i] == c: ret.append(i) return ret def stretch(self, amt): """ loop though self.string once, adding spaces to existing spaces, until the string has been traversed or each space has been padded once. So will not necessarily stretch the string to the full amount. The <amt> to be added may be spread among multiple strings. """ spaceLen = metrics.strLength( self.fontkey, self.fontsize, ' ') added = 0 newStr = '' if amt < 2: return self elif self.length < 10: return self for c in self.string: if c == ' ' and added < amt : newStr += c + ' ' added += spaceLen else: newStr += c self.setString( newStr ) class PdfPage(object): """ a single printable page """ def __init__(self, chapter, pageNumber): """ Initializes a new pasge. writes out hdrlines to self.hdrLines, starting at chapter.topRow writes out foot lines at chapter.bottomRow bdyLines is an empty list. <pageNUmber> is the number to print. """ self.footnoteCount = 0 self.pageNumber = pageNumber self.bdyLines = [] self.hdrLines = [] self.ftrLines = [] # add the header lines. Starting point is chapter.topRow lctr = 0 for ln in self.header.lines: lctr++ ln.row = chapter.topRow + lctr - 1 self.hdrLines.append( ln ) # create a footer paragraph if self.footerStyle is not None: para = chapter.footerParagraph( self.pageNumber ) for ln in para.lines: ln.row = chapter.bottomRow self.ftrLines.append( ln) class PdfFootNote( PdfParagraph): """ Inherits from PdfParagraph(), but hard-codes most spacing properties """ def __init__(self, chapter, fnNum): """ fnNum is the footnote number That is created in chapter.superscriptFont as the first string in the paragraph. """ self.chapter = chapter self.fnNum = fnNum self.lead = 0 self.tail = 0 self.indent = 0 self.alignment = 'l' self.strings = [] self.lines = [] self.strings.append ( PdfString( self.chapter.superscriptFont, str(fnNum)) ) def addString(self, pString): """ Add a string to a footnote """ self.strings.append( PdfString(self.chapter.footnoteFont, pString)) def addItalic( self, pString): """ Add an italic string to a footnote """ self.strings.append( PdfString(self.chapter.footnoteFont.asItalic(), pString)) def addBold( self, pString): """ Add a bold font string to a footnote """ self.strings.append( PdfString(self.chapter.footnoteFont.asBold(), pString))
import unittest import sys sys.path.insert(0, '../') from Graph import Graph from Metro import Metro from Route import Route class TestGraph(unittest.TestCase): ''' A unit test suite for the Graph class. ''' def setUp(self): ''' Sets up the test suite by creating a new graph before every test is ran ''' city_pair = ['CHI', 'TOR'] metro_pair = ['SHA', 'NYC'] shorter_route_a = ['CHI', 'TES'] shorter_route_b = ['TES', 'TOR'] routes = [Route(city_pair, 1337), Route(metro_pair, 9001), Route(shorter_route_a, 50), Route(shorter_route_b, 100)] metros = [Metro('cityCode1', 'cityName1', 'c', 'd', 'e', 'f', 'g', 'h'), Metro('cityCode2', 'cityName2', 'c', 'd', 'e', 'f', 'g', 'h')] chi = Metro('CHI', 'Chicago') tor = Metro('TOR', 'Toronto') tes = Metro('TES', 'Test City') chi.outgoing.append(tor) chi.outgoing.append(tes) tor.incoming.append(chi) tor.incoming.append(tes) tes.outgoing.append(tor) tes.incoming.append(chi) metros.append(chi) metros.append(tor) metros.append(tes) self.graph = Graph(metros, routes) def test_constructor(self): ''' Tests the constructor of the Graph class by checking if all the values passed into the constructor match all of the object's instance variables ''' self.assertEqual('CHI', self.graph.edges[0].ports[0]) self.assertEqual('TOR', self.graph.edges[0].ports[1]) self.assertEqual(1337, self.graph.edges[0].distance) self.assertEqual('SHA', self.graph.edges[1].ports[0]) self.assertEqual('NYC', self.graph.edges[1].ports[1]) self.assertEqual(9001, self.graph.edges[1].distance) self.assertEqual(self.graph.vertices[0].code, 'cityCode1') self.assertEqual(self.graph.vertices[0].name, 'cityName1') self.assertEqual(self.graph.vertices[0].country, 'c') self.assertEqual(self.graph.vertices[0].continent, 'd') self.assertEqual(self.graph.vertices[0].timezone, 'e') self.assertEqual(self.graph.vertices[0].coordinates, 'f') self.assertEqual(self.graph.vertices[0].population, 'g') self.assertEqual(self.graph.vertices[0].region, 'h') self.assertEqual(self.graph.vertices[1].code, 'cityCode2') self.assertEqual(self.graph.vertices[1].name, 'cityName2') self.assertEqual(self.graph.vertices[1].country, 'c') self.assertEqual(self.graph.vertices[1].continent, 'd') self.assertEqual(self.graph.vertices[1].timezone, 'e') self.assertEqual(self.graph.vertices[1].coordinates, 'f') self.assertEqual(self.graph.vertices[1].population, 'g') self.assertEqual(self.graph.vertices[1].region, 'h') def test_add_vertex(self): ''' Tests the add_vertex() function by adding metros to the vertices list with add_vertex() and checking if those metros have been added to the vertices list instance variable. ''' self.graph.add_vertex(Metro('cityCode3', 'cityName3', 'c', 'd', 'e', 'f', 'g', 'h')) new_city = self.graph.get_vertex_from_code('cityCode3') self.assertEqual(new_city.code, 'cityCode3') self.assertEqual(new_city.name, 'cityName3') self.assertEqual(new_city.country, 'c') self.assertEqual(new_city.continent, 'd') self.assertEqual(new_city.timezone, 'e') self.assertEqual(new_city.coordinates, 'f') self.assertEqual(new_city.population, 'g') self.assertEqual(new_city.region, 'h') def test_set_vertices(self): ''' Tests the set_vertices() function by initializing a list of metros and setting the vertices list instance variable of the Graph object equal to the list we've initialized by calling set_vertices(). Then we iterate through the list and checking if the list consists of the elements of the original vertices list we've initialized. ''' metros = [Metro('cityCode3', 'cityName3', 'c', 'd', 'e', 'f', 'g', 'h'), Metro('cityCode4', 'cityName4', 'c', 'd', 'e', 'f', 'g', 'h')] self.graph.set_vertices(metros) self.assertEqual(self.graph.vertices[0].code, 'cityCode3') self.assertEqual(self.graph.vertices[0].name, 'cityName3') self.assertEqual(self.graph.vertices[0].country, 'c') self.assertEqual(self.graph.vertices[0].continent, 'd') self.assertEqual(self.graph.vertices[0].timezone, 'e') self.assertEqual(self.graph.vertices[0].coordinates, 'f') self.assertEqual(self.graph.vertices[0].population, 'g') self.assertEqual(self.graph.vertices[0].region, 'h') self.assertEqual(self.graph.vertices[1].code, 'cityCode4') self.assertEqual(self.graph.vertices[1].name, 'cityName4') self.assertEqual(self.graph.vertices[1].country, 'c') self.assertEqual(self.graph.vertices[1].continent, 'd') self.assertEqual(self.graph.vertices[1].timezone, 'e') self.assertEqual(self.graph.vertices[1].coordinates, 'f') self.assertEqual(self.graph.vertices[1].population, 'g') self.assertEqual(self.graph.vertices[1].region, 'h') def test_add_edge(self): ''' Tests the add_edge() function by adding routes to the edges list with add_edge() and checking if those routes have been added to the edges list instance variable. ''' self.graph.add_edge('YOL', 'SWA', 420) self.assertEqual('YOL', self.graph.edges[4].ports[0]) self.assertEqual('SWA', self.graph.edges[4].ports[1]) self.assertEqual(420, self.graph.edges[4].distance) def test_set_edges(self): ''' Tests the set_edges() function by initializing a list of edges and setting the edges list instance variable of the Route object equal to the list we've initialized by calling set_edges(). Then we iterate through the list and checking if the list consists of the elements of the original edges list we've initialized. ''' flightPair = ['TES', 'TIN'] pair = ['GRA', 'PHS'] routes = [Route(flightPair, 12345), Route(pair, 98765)] self.graph.set_edges(routes) self.assertEqual('TES', self.graph.edges[0].ports[0]) self.assertEqual('TIN', self.graph.edges[0].ports[1]) self.assertEqual(12345, self.graph.edges[0].distance) self.assertEqual('GRA', self.graph.edges[1].ports[0]) self.assertEqual('PHS', self.graph.edges[1].ports[1]) self.assertEqual(98765, self.graph.edges[1].distance) def test_get_vertex_from_code(self): ''' Tests the get_vertex_from_code() function by calling the function with known codes and checking if the retrieved metros are equal to their position in the vertices list in the graph. ''' metro = self.graph.get_vertex_from_code('cityCode1') city = self.graph.get_vertex_from_code('cityCode2') self.assertEqual(metro, self.graph.vertices[0]) self.assertEqual(city, self.graph.vertices[1]) def test_get_vertex_from_name(self): ''' Tests the get_vertex_from_name() function by calling the function with known names and checking if the retrieved metros are equal to their position in the vertices list in the graph. ''' metro = self.graph.get_vertex_from_name('cityName1') city = self.graph.get_vertex_from_name('cityName2') self.assertEqual(metro, self.graph.vertices[0]) self.assertEqual(city, self.graph.vertices[1]) def test_get_edge(self): ''' Tests the get_edge() function by adding test vertices and edges to the graph, then calling the function and checking if the edge that is returned is the same as the one made in the beginning. Invalid inputs are tested by checking if None is returned when invalid codes are inputed. ''' pyt = Metro('PYT', 'Pyt') hon = Metro('HON', 'Hon') self.graph.add_vertex(pyt) self.graph.add_vertex(hon) self.graph.add_edge('PYT', 'HON', 510) result = self.graph.get_edge(pyt.code, hon.code) self.assertEqual(pyt.code, result.ports[0]) self.assertEqual(hon.code, result.ports[1]) false_result = self.graph.get_edge('aaa', 'bbb') self.assertEqual(false_result, None) def test_shortest_path(self): ''' Tests the shortest_path() function getting existing nodes, and checking if the shortest path outputed by the function calling is the same as the shortest path of the graph. It also tests for invalid inputs. ''' chi = self.graph.get_vertex_from_name('Chicago') tor = self.graph.get_vertex_from_name('Toronto') tes = self.graph.get_vertex_from_name('Test City') shortest_path_sol = [chi, tes, tor] short_path = self.graph.shortest_path(chi, tor) self.assertEqual(shortest_path_sol, short_path) # invalid_inputs = self.graph.shortest_path(Metro(). Metro('a', 'b')) # self.assertEqual(invalid_inputs, []) # runs the test suite suite = unittest.TestLoader().loadTestsFromTestCase(TestGraph) unittest.TextTestRunner(verbosity=2).run(suite)
import unittest from src.pub import Pub #capital P because class names always begin with capital letter from src.drink import Drink from src.customer import Customer class TestPub(unittest.TestCase):#these parameters tell python this is a test, and not a normal class def setUp(self): self.pub = Pub("The Prancing Pony", 100.00) self.drink = Drink("Mojito", 8.00, 6) self.customer_1 = Customer("Skye", 50.00, 19) self.customer_2 = Customer("David", 25.00, 17) self.customer_3 = Customer("John", 75.00, 27) def test_pub_has_name(self): self.assertEqual("The Prancing Pony", self.pub.name) def test_pub_has_till(self): self.assertEqual(100.00, self.pub.till) def test_pub_has_drinks(self): self.assertEqual([], self.pub.drink) def test_till_updated(self): self.assertEqual(108, self.pub.add_to_till(self.drink)) def test_pub_checks_age(self): self.assertEqual(True, self.pub.check_age(self.customer_1)) self.assertEqual(False, self.pub.check_age(self.customer_2)) def test_assess_drunkenness(self): self.customer_1.increase_drunkenness(self.drink) self.customer_1.increase_drunkenness(self.drink) self.customer_1.increase_drunkenness(self.drink) self.assertEqual("Sorry, you're too drunk", self.pub.assess_drunkenness(self.customer_1)) self.assertEqual("You're boring and sober", self.pub.assess_drunkenness(self.customer_2))
#Rotate array k times #Method1 # O(N*K) - may take much time when k and n is large def rotate_m1(arr, k): s = len(arr) if s < 1 or s == k: return A k = k % s for x in range(k): tmp = arr[s - 1] for i in range(s - 1, 0, -1): arr[i] = arr[i - 1] arr[0] = tmp return arr def reverse(arr, i, j): for idx in range((j - i + 1) // 2): arr[i+idx], arr[j-idx] = arr[j-idx], arr[i+idx] #Method2 #O(N) # the base case with K < N, the idea in this case is to split the array in two parts A and B, # A is the first N-K elements array and B the last K elements. # the algorithm reverse A and B separately and finally reverse the full # array (with the two part reversed separately). # To manage the case with K > N, think that every time you reverse the array N times you # obtain the original array again so we can just use the module operator to find where # to split the array (reversing only the really useful times avoiding useless shifting) def rotate_m2(arr, k): s = len(arr) if s == 0: return [] k = k%s reverse(arr, s - k, s -1) reverse(arr, 0, s - k -1) reverse(arr, 0, s - 1) return arr if __name__== "__main__": arr1=[1,2,3,4,5,6,7,8,9] arr2=[1,2,3,4,5,6,7,8,9] print(rotate_m1(arr1,2)) print(rotate_m2(arr2,2))
class BST: def __init__(self, value): self.value=value self.left=None self.right=None #iterative def insert(self,value): curr=self while True: if curr.value>value: if curr.left is None: curr.left= BST(value) break else: curr = curr.left else: if curr.right is None: curr.right = BST(value) break else: curr=curr.right return self #iterative def search(self, value): curr=self while curr is not None: if curr.value>value: curr = curr.left elif curr.value<value: curr = curr.right else: return True return False #recursive def PrintTree(self): if self.left: self.left.PrintTree() print( self.value), if self.right: self.right.PrintTree() #TODO #remove if __name__ == '__main__': node= BST(2) node.insert(5) node.insert(3) node.PrintTree()
#To solve Rat in a maze problem using backtracking #initializing the size of the maze and soution matrix N = 4 solution_maze = [ [ 0 for j in range(N) ] for i in range(N) ] def is_safe(maze, x, y ): '''A utility function to check if x, y is valid return true if it is valid move, return false otherwise ''' if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: return True return False def check_if_solution_exists(maze): if solve_maze(maze) == False: print("Solution doesn't exist"); return False # recursive function to solve rat in a maze problem def solve_maze(maze, x=0,y=0): ''' This function will make several recursive calls until we reach to some finding, if we reach to destination following asafe path, then it prints the solution and return true, will return false otherwise. ''' # if (x, y is goal) return True if x == N - 1 and y == N - 1: solution_maze[x][y] = 1 print("solution:", solution_maze) return True # check if the move is valid if is_safe(maze, x, y) == True: # mark x, y as part of solution path # for(0,0) it sets up 1 in solution maze solution_maze[x][y] = 1 # Move forward in x direction (recursive call) if solve_maze(maze, x + 1, y) == True: return True # Move down in y direction if moving in x direction is not fruitful #(recursive call) if solve_maze(maze, x, y + 1) == True: return True #no option for rat to move, backtrack solution_maze[x][y] = 0 return False # Driver program to test above function if __name__ == "__main__": maze = [ [1, 0, 0, 0], [1, 1, 0, 1], [1, 0, 0, 0], [1, 1, 1, 1] ] check_if_solution_exists(maze)