text
stringlengths
37
1.41M
def quick_sort(list, start, end): # repeat until sublist has one item # because the algorithm is using in-place space, we can not use len(list) instead we use start, end for sublist if start < end: # get pivot using partition method pivot = partition(list, start, end) # recurse quick sort left side from pivot quick_sort(list, start, pivot-1) # recurse quick sort right side from pivot quick_sort(list,pivot+1, end) return list def partition(list, start, end): # use end item as initial pivot pivot = end # use start as initial wall index wall = start left = start # repeat until left item hit the end of list while left < pivot: # if left item is smaller than pivot, swap left item with wall and move wall to right # this will ensure items smaller than pivot stay left side from the wall and # the items greater than pivot stay right side from the wall if list[left] < list[pivot]: list[wall], list[left] = list[left], list[wall] wall = wall + 1 left = left + 1 # when left hit the end of list, swap pivot with wall list[wall], list[pivot] = list[pivot], list[wall] # now left side of wall are the items smaller than wall # now right side of pivot are the items greater than wall # wall is the new pivot pivot = wall return pivot list = [1,2,69,47,10,8] new_list = quick_sort(list,0,len(list)-1) print(new_list)
""" Lab 07: Generators, Linked Lists, and Trees """ # Generators def naturals(): """A generator function that yields the infinite sequence of natural numbers, starting at 1. >>> m = naturals() >>> type(m) <class 'generator'> >>> [next(m) for _ in range(10)] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ i = 1 while True: yield i i += 1 def scale(s, k): """Yield elements of the iterable s scaled by a number k. >>> s = scale([1, 5, 2], 5) >>> type(s) <class 'generator'> >>> list(s) [5, 25, 10] >>> m = scale(naturals(), 2) >>> [next(m) for _ in range(5)] [2, 4, 6, 8, 10] """ for i in s: result = i * k yield result # Linked Lists def link_to_list(link): """Takes a linked list and returns a Python list with the same elements. >>> link = Link(1, Link(2, Link(3, Link(4)))) >>> link_to_list(link) [1, 2, 3, 4] >>> link_to_list(Link.empty) [] """ # iterative solution list = [] while link != Link.empty: list.append(link.first) link = link.rest return list + [] # recursive solution if link == Link.empty: return [] else: return [link.first] + link_to_list(link.rest) # Trees def cumulative_sum(t): """Mutates t so that each node's label becomes the sum of all labels in the corresponding subtree rooted at t. >>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)]) >>> cumulative_sum(t) >>> t Tree(16, [Tree(8, [Tree(5)]), Tree(7)]) """ for b in t.branches: cumulative_sum(b) t.label = sum([leaf.label for leaf in t.branches]) + t.label def is_bst(t): """Returns True if the Tree t has the structure of a valid BST. >>> t1 = Tree(6, [Tree(2, [Tree(1), Tree(4)]), Tree(7, [Tree(7), Tree(8)])]) >>> is_bst(t1) True >>> t2 = Tree(8, [Tree(2, [Tree(9), Tree(1)]), Tree(3, [Tree(6)]), Tree(5)]) >>> is_bst(t2) False >>> t3 = Tree(6, [Tree(2, [Tree(4), Tree(1)]), Tree(7, [Tree(7), Tree(8)])]) >>> is_bst(t3) False >>> t4 = Tree(1, [Tree(2, [Tree(3, [Tree(4)])])]) >>> is_bst(t4) True >>> t5 = Tree(1, [Tree(0, [Tree(-1, [Tree(-2)])])]) >>> is_bst(t5) True >>> t6 = Tree(1, [Tree(4, [Tree(2, [Tree(3)])])]) >>> is_bst(t6) True >>> t7 = Tree(2, [Tree(1, [Tree(5)]), Tree(4)]) >>> is_bst(t7) False """ list = [] if t.is_leaf(): list.append(True) if len(t.branches) == 2: list.append('has_more_than_one_child') for b in t.branches: if b.is_leaf(): list.append(True) elif len(b.branches) == 1: if 'has_more_than_one_child' in list: if b.label >= b.branches[0].label: list.append(True) else: list.append(False) else: list.append(True) elif len(b.branches) == 2: list.append('has_more_than_one_child') if b.label >= b.branches[0].label: list.append(True) else: list.append(False) if b.label < b.branches[1].label: list.append(True) else: list.append(False) elif len(branches) > 2: list.append(False) if False in list : return False else: return True # Link List Class class Link: """A linked list. >>> s = Link(1) >>> s.first 1 >>> s.rest is Link.empty True >>> s = Link(2, Link(3, Link(4))) >>> s.first = 5 >>> s.rest.first = 6 >>> s.rest.rest = Link.empty >>> s # Displays the contents of repr(s) Link(5, Link(6)) >>> s.rest = Link(7, Link(Link(8, Link(9)))) >>> s Link(5, Link(7, Link(Link(8, Link(9))))) >>> print(s) # Prints str(s) <5 7 <8 9>> """ empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest def __repr__(self): if self.rest is not Link.empty: rest_repr = ', ' + repr(self.rest) else: rest_repr = '' return 'Link(' + repr(self.first) + rest_repr + ')' def __str__(self): string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>' # Tree ADT class Tree: """ >>> t = Tree(3, [Tree(2, [Tree(5)]), Tree(4)]) >>> t.label 3 >>> t.branches[0].label 2 >>> t.branches[1].is_leaf() True """ def __init__(self, label, branches=[]): for b in branches: assert isinstance(b, Tree) self.label = label self.branches = list(branches) def is_leaf(self): return not self.branches def __repr__(self): if self.branches: branch_str = ', ' + repr(self.branches) else: branch_str = '' return 'Tree({0}{1})'.format(self.label, branch_str) def __str__(self): def print_tree(t, indent=0): tree_str = ' ' * indent + str(t.label) + "\n" for b in t.branches: tree_str += print_tree(b, indent + 1) return tree_str return print_tree(self).rstrip() def is_palindrome(seq): """ Returns True if the sequence is a palindrome. A palindrome is a sequence that reads the same forwards as backwards >>> is_palindrome(Link("l", Link("i", Link("n", Link("k"))))) False >>> is_palindrome(["l", "i", "n", "k"]) False >>> is_palindrome("link") False >>> is_palindrome(Link.empty) True >>> is_palindrome([]) True >>> is_palindrome("") True >>> is_palindrome(Link("a", Link("v", Link("a")))) True >>> is_palindrome(["a", "v", "a"]) True >>> is_palindrome("ava") True """ n = 1 last_seq = len(seq) - n for i in range(len(seq)): if seq[0] != seq[last_seq]: return False n = n + 1 return True def sum_nums(lnk): """ >>> a = Link(1, Link(6, Link(7))) >>> sum_nums(a) 14 """ if lnk.rest is Link.empty: return lnk.first else: print(lnk) return lnk.first + sum_nums(lnk.rest) def multiply_lnks(lst_of_lnks): """ >>> a = Link(2, Link(3, Link(5))) >>> b = Link(6, Link(4, Link(2))) >>> c = Link(4, Link(1, Link(0, Link(2)))) >>> p = multiply_lnks([a, b, c]) >>> p.first 48 >>> p.rest.first 12 >>> p.rest.rest.rest is Link.empty True """ product = 1 for link in lst_of_lnks: if link is Link.empty: return Link.empty else: product *= link.first lst_of_lnks_rests = [lnk.rest for lnk in lst_of_lnks] return Link(product, multiply_lnks(lst_of_lnks_rests)) def filter_link(link, f): """ >>> link = Link(1, Link(2, Link(3))) >>> g = filter_link(link, lambda x: x % 2 == 0) >>> next(g) 2 >>> next(g) StopIteration >>> list(filter_link(link, lambda x: x % 2 != 0)) [1, 3] """ while link is not Link.empty: if f(link.first): yield link.first link = link.rest def filter_no_iter(link, f): """ >>> link = Link(1, Link(2, Link(3))) >>> list(filter_no_iter(link, lambda x: x % 2 != 0)) [1, 3] """ if link is Link.empty: return if f(link.first): yield link.first yield from filter_no_iter(link.rest, f) def sum_paths_gen(t): """ >>> t1 = Tree(5) >>> next(sum_paths_gen(t1)) 5 >>> t2 = Tree(1, [Tree(2, [Tree(3), Tree(4)]), Tree(9)]) >>> sorted(sum_paths_gen(t2)) [6, 7, 10] """ # official answer if t.is_leaf(): yield t.label for b in t.branches: for s in sum_paths_gen(b): yield s + t.label # my answer i = 0 if t.is_leaf(): yield t.label for child in t.branches: n = 0 n += child.label if child.is_leaf(): yield child.label + t.label for ancestor in child.branches: n -= i i = ancestor.label n += i yield n + t.label def make_even(t): """ >>> t = Tree(1, [Tree(2, [Tree(3)]), Tree(4), Tree(5)]) >>> make_even(t) >>> t.label 2 >>> t.branches[0].branches[0].label """ for b in t.branches: make_even(b) if t.label % 2 != 0: t.label += 1 def fill_tree(t, n): """ >>> t0 = Tree(0, [Tree(1), Tree(2)]) >>> t1 = fill_tree(t0, 5) >>> t1 Tree(5, [Tree(5), Tree(5)]) """ if t.is_leaf(): return Tree(n) else: return Tree(n, [fill_tree(b, n)for b in t.branches]) def combine_tree(t1, t2, combiner): """ >>> a = Tree(1, [Tree(2, [Tree(3)])]) >>> b = Tree(4, [Tree(5, [Tree(6)])]) >>> combined = combine_tree(a, b, mul) >>> combined.label 4 >>> combined.branches[0].label 10 """ return Tree(combiner(t1.label, t2.label),[combine_tree(b1, b2, combiner)for b1, b2 in zip(t1.branches, t2.branches)]) def average(t): """ Returns the average value of all the labels in t. >>> t0 = Tree(0, [Tree(1), Tree(2, [Tree(3)])]) >>> average(t0) 1.5 >>> t1 = Tree(8, [t0, Tree(4)]) >>> average(t1) 3.0 """ def helper(t, count): list = [t.label] for b in t.branches: print(list) print([]) list.extend(helper(b, count + 1)) return list return helper(t, 1) def alt_tree_map(t, map_fn): """ >>> t = Tree(1, [Tree(2, [Tree(3)]), Tree(4)]) >>> negate = lambda x: -x >>> alt_tree_map(t, negate) Tree(-1, [Tree(2, [Tree(-3)]), Tree(4)]) """ count = 1 for b in t.branches: for leaf in alt_tree_map(b, map_fn): count += leaf print(count) return count def is_min_heap(t): # one way x = [is_min_heap(b) if b.label > t.label else False for b in t.branches] if False in x: return False else: return True # second way for b in t.branches: list = [] if b.label > t.label: list.append(is_min_heap(b)) else: list.append(False) if False in list: return False return True def largest_product_path(t): """ >>> largest_product_path(None) 0 >>> largest_product_path(Tree(3)) 3 >>> t = Tree(3, [Tree(7, [Tree(2)]), Tree(8, [Tree(1)]), Tree(4)]) >>> largest_product_path(t) 42 """ tree = t def helper(t): if not t: return 0 result = t.label count = t.label list = [] for b in t.branches: result = count * helper(b) list.append(result) print(list) if t == tree: if len(list) > 0: return max(list) else: return t.label else: return result return helper(t) def largest_product_path_2(t): """ >>> largest_product_path(None) 0 >>> largest_product_path(Tree(3)) 3 >>> t = Tree(3, [Tree(7, [Tree(2)]), Tree(8, [Tree(1)]), Tree(4)]) >>> largest_product_path_2(t) 42 """ if not t: return 0 elif t.is_leaf(): return t.label else: paths = [largest_product_path_2(b) for b in t.branches] print(paths) return t.label * max(paths) def largest_product_path_3(t): """ >>> largest_product_path(None) 0 >>> largest_product_path(Tree(3)) 3 >>> t = Tree(3, [Tree(7, [Tree(2)]), Tree(8, [Tree(1)]), Tree(4)]) >>> largest_product_path_3(t) 42 """ paths = [] print([]) if t.is_leaf(): return t.label for b in t.branches: paths.append(largest_product_path_3(b)) print(paths) if len(paths) > 0: return t.label * min(paths) else: return t.label def contains(t, e): if t.label == e: return True for b in t.branches: if contains(b, e) == True: return True print(contains(b, e)) return 2 def max_tree(t): """ >>> max_tree(Tree(1, [Tree(5, [Tree(7)]),Tree(3,[Tree(9),Tree(4)]),Tree(6)])) Tree(9, [Tree(7, [Tree(7)]),Tree(9,[Tree(9),Tree(4)]),Tree(6)]) """ if t.is_leaf(): return Tree(t.label) new_branches = [max_tree(b)for b in t.branches] new_label = max([t.label] + [leaf.label for leaf in new_branches]) return Tree(new_label, new_branches) def tree(t): list = [] for b in t.branches: list.append(b.label) tree(b) print(list) return list def level_order(t): def helper(t, count): if count == 1: list = [t.label] else: list = [] for b in t.branches: list.append(b.label) for b in t.branches: list.extend(helper(b, count + 1)) return list return helper(t, 1) def all_paths(t): if t.is_leaf(): return [[t.label]] list = [] print(list) for b in t.branches: for s in all_paths(b): list.append([t.label] + s) print(list) return list def all_paths_6(t): if t.is_leaf(): return [t.label] list = [] print(list) for b in t.branches: list.append([t.label] + all_paths_6(b)) print(list) return list def filter_tree(t, fn): """ >>> t = Tree(1, [Tree(2), Tree(3, [Tree(4)]), Tree(6, [Tree(7)])]) >>> filter_tree(t, lambda x: x % 2 != 0) >>> t tree(1, [Tree(3)]) >>> t2 = Tree(2, [Tree(3), Tree(4), Tree(5)]) >>> filter_tree(t2, lambda x: x != 2) >>> t2 Tree(2) """ if t.is_leaf(): t.label = 0 if not fn(t.label): t.label = 0 for b in t.branches: filter_tree(b, fn) def filter_tree_2(t, fn): if not fn(t.label): t.branches = [] else: for b in t.branches[:]: print(b) print([]) if not fn(b.label): t.branches.remove(b) elif b.is_leaf(): t.branches.remove(b) else: filter_tree(b, fn) def nth_level_tree_map(fn, tree, n): """Mutates a tree by mapping a function all the elements of a tree. >>> tree = Tree(1, [Tree(7, [Tree(3), Tree(4), Tree(5)]), Tree(2, [Tree(6), Tree(4)])]) >>> nth_level_tree_map(lambda x: x + 1, tree, 2) >>> tree Tree(2, [Tree(7, [Tree(4), Tree(5), Tree(6)]), Tree(2, [Tree(7), Tree(5)])]) """ #tree.label = fn(tree.label) #def helper(tree, count): #print(count) #print([]) #for b in tree.branches: #if count % n == 0: #b.label = fn(b.label) #helper(b, count + 1) #return helper(tree, 1) def helper(tree, level): if level % n == 0: print('label') print(tree.label) print('level') print(level) tree.label = fn(tree.label) for b in tree.branches: helper(b, level + 1) helper(tree, 0) #def map_mut(f, L): """ >>> L = [1, 2, 3, 4] >>> map_mut(lambda x: x**2, L) >>> L [1, 4, 9, 16] """ #list = [] #for i in L: #list.append(f(i)) #return list #for i in L: #L[i] = f[L[i]) def make_max_finder(): """ >>> m = make_max_finder() >>> m([5, 6, 7]) 7 >>> m([1, 2, 3]) 7 >>> m([9]) 9 >>> m2 = make_max_finder() >>> m2([1]) 1 """ counter = 0 def helper(list): nonlocal counter max_num = max(list) if max_num > counter: counter = max_num return max_num else: return counter return helper def has_cycle(link): """Return whether link contains a cycle. >>> s = Link(1, Link(2, Link(3))) >>> s.rest.rest.rest = s >>> has_cycle(s) True >>> t = Link(1, Link(2, Link(3))) >>> has_cycle(t) False >>> u = Link(2, Link(2, Link(2))) >>> has_cycle(u) False """ def helper(link, sub_link): if sub_link is Link.empty: return False elif sub_link is link: return True else: return helper(link, sub_link.rest) return helper(link, link.rest) def has_cycle_iteratively(link): original_link = link new_link = link.rest while new_link is not Link.empty: if new_link is original_link: return True new_link = new_link.rest return False def seq_in_link(link, sub_link): """ >>> lnk1 = Link(1, Link(2, Link(3, Link(4)))) >>> lnk2 = Link(1, Link(4)) >>> lnk3 = Link(4, Link(3, Link(2, Link(1)))) >>> seq_in_link(lnk1, lnk2) True >>> seq_in_link(lnk1, lnk3) False """ if sub_link is Link.empty: return True elif link is Link.empty: return False elif link.first != sub_link.first: return seq_in_link(link.rest, sub_link) elif link.first == sub_link.first: return seq_in_link(link.rest, sub_link.rest) def infinity1(start): while True: start = start + 1 return start def infinity2(start): while True: start = start + 1 yield start def generate_constant(x): """A generator function that repeats the same value x forever. >>> area = generate_constant(51) >>> next(area) 51 >>> next(area) 51 >>> sum([next(area) for _ in range(100)]) 5100 """ while True: yield x def black_hole(seq, trap): """A generator that yields items in SEQ until one of them matches TRAP, in which case that value should be repeatedly yielded forever. >>> trapped = black_hole([1, 2, 3], 2) >>> [next(trapped) for _ in range(6)] [1, 2, 2, 2, 2, 2] >>> list(black_hole(range(5), 7)) [0, 1, 2, 3, 4] """ for i in seq: if i == trap: x = generate_constant(i) return x else: yield i def weird_gen(x): if x % 2 == 0: yield x * 2 def greeter(x): while x % 2 != 0: print('hi') yield x print('bye') def gen_inf(lst): while True: return lst def filter(iterable, fn): """ >>> is_even = lambda x: x % 2 == 0 >>> list(filter(range(5), is_even)) [0 , 2 , 4] >>> all_odd = (2*y-1 for y in range (5)) >>> list(filter(all_odd, is_even)) [] >>> s = filter(naturals(), is_even) >>> next(s) 2 >>> next(s) 4 """ for i in iterable: if fn(i): yield i def tree_sequence(t): """ >>> t = Tree(1, [Tree(2, [Tree(5)]), Tree(3, [Tree(4)])]) >>> print(list(tree_sequence(t))) [1, 2, 5, 3, 4] """ yield t.label for b in t.branches: yield from tree_sequence(b) def make_digit_getter(n): """ Returns a function that returns the next digit in n each time it is called, and the total value of all the integers once all the digits have been returned. >>> year = 8102 >>> get_year_digit = make_digit_getter(year) >>> for _ in range(4): ... print(get_year_digit()) 2 0 1 8 >>> get_year_digit() 11 """ sum = 0 def function(): nonlocal n p = n n = n // 10 x = p % 10 sum += x if n > 0: return x else: return sum return function def max_leaf(t): """Create a new Tree with every node being the maximum distance away that node is from a leaf node. >>>t = Tree(3, [Tree(4), Tree(4, [Tree(1)])]) >>>new_t = max_leaf(t) >>>new_t.entry 2 # The 3 node was 2 away from the 1 node >>>[b.entry for b in new_t.branches] [0 1] """ if t.is_leaf(): return Tree(0) else: b = [] for branch in t.branches: b.append(max_leaf(branch)) print(b) return Tree(max(branch.label for branch in b ) + 1, b) def contains(t, elm): """Return True if tree contains element, false otherwise. >>>t = Tree(4, [Tree(5), Tree(5, [Tree(6)])]) >>>t = Tree(3, [Tree(4), Tree(4, [Tree(1)])]) >>>contains(t, 6) == True True >>>contains(t, 1) == False True """ if t.label == elm: return True list = [] for b in t.branches: if contains(b, elm): return True return False def all_paths(t): """ >>>t = Tree(4, [Tree(5), Tree(5, [Tree(6)])]) >>>t2 = Tree(3, [Tree(4), Tree(4, [t])]) """ if t.is_leaf(): return [[t.label]] list = [] for b in t.branches: for leaf in all_paths(b): list.append(leaf) print(list) print('w') return [t.label] + list def count_nodes(t): return 1 + min([count_nodes(b)for b in t.branches]) def list_leaves(t): if t.is_leaf(): return [t.label] list= [] for b in t.branches: list.extend(list_leaves(b)) return list def print_tree(t, indent = 0 ): print(' ' * indent + str(t.label)) for b in t.branches: print_tree(b, indent + 1) def sum_of_nodes(t): """ >>> t = tree(...) # Tree from question 2. >>> sum_of_nodes(t) # 9 + 2 + 4 + 4 + 1 + 7 + 3 = 30 30 """ sum = t.label for b in t.branches: sum += sum_of_nodes(b) return sum def replace_x(t, x): branches = [] for b in t.branches: branches += [replace_x(b, x)] if t.label == x: return Tree(0, branches) else: return Tree(t.label, branches) def replace_leaves_sum(t): """ >>> t = Tree(1, [Tree(3, [Tree(2), Tree(8)]), Tree(5)]) >>> replace_leaves_sum(t) >>> t Tree(1, [Tree(3, [Tree(6), Tree(12)]), Tree(6)]) """ def helper(t, list ): if t.is_leaf(): t.label = sum(list) + t.label else: for b in t.branches: helper(b, list.append(t.label)) return helper(t, []) def prune_min(t): """Prune the tree mutatively from the bottom up. >>> t1 = Tree(6) >>> prune_min(t1) >>> t1 Tree(6) >>> t2 = Tree(6, [Tree(3), Tree(4)]) >>> prune_min(t2) >>> t2 Tree(6, [Tree(3)]) >>> t3 = Tree(6, [Tree(3, [Tree(1), Tree(2)]), Tree(5, [Tree(3), Tree(4)])]) >>> prune_min(t3) >>> t3 Tree(6, [Tree(3, [Tree(1)])]) """ if not t.is_leaf(): if t.branches[0].label > t.branches[1].label: t.branches = [t.branches[1]] else: t.branches = [t.branches[0]] for b in t.branches: prune_min(b)
import numpy as np # --Description-- # NxN Board # Initial state is random # Winning -> all white (ones) class Board(): def __init__(self, size): self.rows = size self.cols = size self.board = None self.boardZeros = None self.boardOnes = None def getRows(self): return self.rows def getCols(self): return self.cols def getBoard(self): return self.board def getFlatBoard(self): return self.board.flatten() # def buildBoard(self, board, size): # np. def setBoard(self, board): self.board = board def initializeBoardRandom(self): board = np.random.randint(2, size=(self.rows, self.cols)) self.board = board def initializeBoardZeros(self): board = np.zeros(shape=(self.rows, self.cols)) self.boardZeros = board def initializeBoardOnes(self): board = np.ones(shape=(self.rows, self.cols)) self.boardOnes = board def draw(self): print(self.board) def verify(self): result = np.array_equal(self.board, self.boardZeros) return result def move(self, i, j): if i > (self.rows - 1) or i < 0 or j > (self.cols - 1) or j < 0: # Illegal move print("Illegal move.") else: # Legal move # print("Legal move.") # Corners if i == 0 and j == 0: # print("Top left") self.board[0][0] = (self.board[0][0] + 1) % 2 self.board[0][1] = (self.board[0][1] + 1) % 2 self.board[1][0] = (self.board[1][0] + 1) % 2 elif i == 0 and j == (self.cols - 1): # print("Top right") self.board[0][self.cols - 1] = (self.board[0][self.cols - 1] + 1) % 2 self.board[0][self.cols - 2] = (self.board[0][self.cols - 2] + 1) % 2 self.board[1][self.cols - 1] = (self.board[1][self.cols - 1] + 1) % 2 elif i == (self.rows - 1) and j == 0: # print("Botton left") self.board[self.rows - 1][0] = (self.board[self.rows - 1][0] + 1) % 2 self.board[self.rows - 1][1] = (self.board[self.rows - 1][1] + 1) % 2 self.board[self.rows - 2][0] = (self.board[self.rows - 2][0] + 1) % 2 elif i == (self.rows - 1) and j == (self.cols - 1): # print("Botton right") self.board[self.rows - 1][self.cols - 1] = (self.board[self.rows - 1][self.cols - 1] + 1) % 2 self.board[self.rows - 1][self.cols - 2] = (self.board[self.rows - 1][self.cols - 2] + 1) % 2 self.board[self.rows - 2][self.cols - 1] = (self.board[self.rows - 2][self.cols - 1] + 1) % 2 else: # print("Not corner") if i == 0: # print("Top row") self.board[i][j] = (self.board[i][j] + 1) % 2 self.board[i][j + 1] = (self.board[i][j + 1] + 1) % 2 self.board[i][j - 1] = (self.board[i][j - 1] + 1) % 2 self.board[i + 1][j] = (self.board[i + 1][j] + 1) % 2 elif i == (self.rows - 1): # print("Bottom row") self.board[i][j] = (self.board[i][j] + 1) % 2 self.board[i][j + 1] = (self.board[i][j + 1] + 1) % 2 self.board[i][j - 1] = (self.board[i][j - 1] + 1) % 2 self.board[i - 1][j] = (self.board[i - 1][j] + 1) % 2 elif j == 0: # print("Left col") self.board[i][j] = (self.board[i][j] + 1) % 2 self.board[i + 1][j] = (self.board[i + 1][j] + 1) % 2 self.board[i - 1][j] = (self.board[i - 1][j] + 1) % 2 self.board[i][j + 1] = (self.board[i][j + 1] + 1) % 2 elif j == (self.cols - 1): # print("Right col") self.board[i][j] = (self.board[i][j] + 1) % 2 self.board[i + 1][j] = (self.board[i + 1][j] + 1) % 2 self.board[i - 1][j] = (self.board[i - 1][j] + 1) % 2 self.board[i][j - 1] = (self.board[i][j - 1] + 1) % 2 else: # print("Inside") self.board[i][j] = (self.board[i][j] + 1) % 2 self.board[i + 1][j] = (self.board[i + 1][j] + 1) % 2 self.board[i - 1][j] = (self.board[i - 1][j] + 1) % 2 self.board[i][j + 1] = (self.board[i][j + 1] + 1) % 2 self.board[i][j - 1] = (self.board[i][j - 1] + 1) % 2 def main(): print("Board class") if __name__ == '__main__': main()
import threading # 이건 모듈이다. n = 1000 offset = n//4 def thread_main(li, i): for idx in range(offset * i, offset * (i+1)): li[idx] *=2 li=[i+1 for i in range(1000)] threads=[] # 스레드를 생성 # 실행 흐름을 담당할 변수를 for i in range(4): # Thread는 모듈에 있는 함수이다. th=threading.Thread( # thread_main에 들어가는 매개변수 li, i target=thread_main, args = (li, i)) threads.append(th) # 멀티 스레딩 for th in threads: th.start() # 메인 스레드에서 나머지 스레들 들이 모든 실행을 끝날 때까지 기다린다. for th in threads: th.join() print(li)
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum. A leaf is a node with no children. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __init__(self): self.res = [] def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: def dfs(node, targetSum, tmp_res = []): if node: if not node.left and not node.right and targetSum - node.val == 0: self.res.append(tmp_res + [node.val]) if node.left: dfs(node.left, targetSum - node.val, tmp_res + [node.val]) if node.right: dfs(node.right, targetSum - node.val, tmp_res + [node.val]) dfs(root, targetSum, []) return(self.res)
# O(k+(n-k)lgk) time, min-heap def findKthLargest4(self, nums, k): heap = [] for num in nums: heapq.heappush(heap, num) for _ in xrange(len(nums)-k): heapq.heappop(heap) return heapq.heappop(heap) def findKthLargest(self, nums, k): heap = nums[:k] heapify(heap) for n in nums[k:]: heappushpop(heap, n) return heap[0] # https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/60306/Python-different-solutions-with-comments-(bubble-sort-selection-sort-heap-sort-and-quick-sort). # O(k) is the time to build min-heap, after this process you have (n-k) elements left, every element needs to be inserted into the min-heap which costs log(k) time for each element, so the total time is O(k+(n-k)log(k)). # python heap is a min-heap # The interesting property of a heap is that its smallest element is always the root, heap[0]. # 1, 2, K, import heapq class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: # check if not nums or not k: return False # init heap = [] # main function for i in nums[:k]: heapq.heappush(heap, i) for i in nums[k:]: heappushpop(heap, i) return heap[0]
# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. # If target is not found in the array, return [-1, -1]. # Follow up: Could you write an algorithm with O(log n) runtime complexity? # Example 1: # Input: nums = [5,7,7,8,8,10], target = 8 # Output: [3,4] # Example 2: # Input: nums = [5,7,7,8,8,10], target = 6 # Output: [-1,-1] # Example 3: # Input: nums = [], target = 0 # Output: [-1,-1] # Constraints: # 0 <= nums.length <= 105 # -109 <= nums[i] <= 109 # nums is a non-decreasing array. # -109 <= target <= 109 class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: # check the input if not nums or len(nums) == 0: return [-1,-1] # init start, end = 0, len(nums) - 1 # main function while start + 1 < end: mid = (start + end ) // 2 v_mid = nums[mid] # check v_mid if v_mid < target: start = mid elif v_mid > target: end = mid elif v_mid == target: if nums[start] < target: start += 1 if nums[end] > target: end -= 1 if nums[start] == nums[end] == target: break # check the value if nums[start] == target and nums[end] == target: return [start, end] if nums[start] == target: return [start, start] if nums[end] == target: return [end, end] else: return [-1, -1]
""" # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ # DFS class Solution: def cloneGraph(self, node): # DFS recursively if not node: return node m = {node: Node(node.val)} self.dfs(node, m) return m[node] def dfs(self, node, m): for neigh in node.neighbors: if neigh not in m: m[neigh] = Node(neigh.val) self.dfs(neigh, m) m[node].neighbors.append(m[neigh]) # BFS class Solution: def cloneGraph(self, node): # BFS recursively if not node: return node m = {node: Node(node.val)} self.bfs(node, m) #print(m.items()) return m[node] def bfs(self, node, m): queue = collections.deque([node]) level = [node] while queue: size = len(level) level = [] for i in range(size): tmp_node = queue.popleft() print(tmp_node.val) for neigh in tmp_node.neighbors: if neigh not in m: m[neigh] = Node(neigh.val) level.append(neigh) queue.append(neigh) m[tmp_node].neighbors.append(m[neigh])
# DFS class Solution: def combine(self, n: int, k: int) -> List[List[int]]: res = [] tmp_list = [] pos = 0 nums = list(range(1, n + 1)) self.get_combination(res, nums, tmp_list, k, pos) return(res) def get_combination(self, res, nums, tmp_list, k, pos): if len(tmp_list) == k: res.append(tmp_list[:]) else: for i in range(pos, len(nums)): tmp_list.append(nums[i]) left_nums = nums[:i] + nums[i + 1:] self.get_combination(res, left_nums, tmp_list, k, i) tmp_list.pop() # cheating from itertools import combinations class Solution: def combine(self, n, k): res = list(combinations(list(range(1, n+1)), k)) return(res) # recursive II class Solution: def combine(self, n, k): res = [] if k == 0: return [[]] for i in range(k, n+1): for pre in self.combine(i-1, k-1): res.append(pre + [i]) return(res) if __name__ == "__main__": s = Solution() print(s.combine(3, 2))
from collections import Counter from itertools import cycle def calculate(input_): """ Given a string with numbers separated by comma like "+1, -2" calculate the sum of the numbers """ return sum([int(x.strip()) for x in input_.split(",") if x]) def find_reached_twice(input_): """ Given a string with numbers separated by comma like "+1, -2" calculate the frequency reached twice """ counter = Counter() values = cycle([int(x.strip()) for x in input_.split(",") if x]) frequency = 0 counter[frequency] += 1 for value in values: frequency += value counter[frequency] += 1 if counter[frequency] == 2: break return frequency def run(): with open("../inputs/day01.txt") as f: raw = f.read().replace("\n", ",") print(f"The reached frequency is {calculate(raw)}") print(f"The first frequency reached twice is {find_reached_twice(raw)}")
from sys import stdin, stdout from math import sqrt class Rectangle(): def __init__(self, x1, x2, y1, y2): self.__x1 = x1 self.__x2 = x2 self.__y1 = y1 self.__y2 = y2 def point_in_figure(self, x, y): return((x > min(self.__x1,self.__x2)) and (x < max(self.__x1,self.__x2)) and (y > min(self.__y1,self.__y2)) and (y < max(self.__y1,self.__y2))) class Circle(): def __init__(self, x, y, r): self.__x = x self.__y = y self.__r = r def point_in_figure(self, x, y): dist = sqrt((x-self.__x)**2 + (y-self.__y)**2) return (dist < self.__r) class Triangle(): def __init__(self, x1, y1, x2, y2, x3, y3): self.__x1 = x1 self.__y1 = y1 self.__x2 = x2 self.__y2 = y2 self.__x3 = x3 self.__y3 = y3 def point_in_figure(self, x, y): a = (self.__x2-self.__x1)*(y-self.__y1) - (x-self.__x1)*(self.__y2-self.__y1) b = (self.__x3-self.__x2)*(y-self.__y2) - (x-self.__x2)*(self.__y3-self.__y2) c = (self.__x1-self.__x3)*(y-self.__y3) - (x-self.__x3)*(self.__y1-self.__y3) return((a < 0 and b < 0 and c < 0) or (a > 0 and b > 0 and c > 0)) f = stdin.readline() figures = [] while (f != '*\n'): f = f.strip().split() if (f[0] == 'r'): r = Rectangle(float(f[1]), float(f[3]), float(f[2]), float(f[4])) figures.append(r) elif (f[0] == 'c'): c = Circle(float(f[1]), float(f[2]), float(f[3])) figures.append(c) else: t = Triangle(float(f[1]), float(f[2]), float(f[3]), float(f[4]), float(f[5]), float(f[6])) figures.append(t) f = stdin.readline() p = stdin.readline().strip().split() count = 1 while (p[0] != p[1]) or (p[0] != '9999.9'): ok = True for f in figures: if (f.point_in_figure(float(p[0]), float(p[1]))): stdout.write('Point {} is contained in figure {}\n'.format(count, (figures.index(f)+1))) ok = False if ok: stdout.write('Point {} is not contained in any figure\n'.format(count)) count = count + 1 p = stdin.readline().strip().split()
str="wecjdifhvgsjfudhscgj" list1=list(set(str)) dict1=dict() for i in list1: num=str.count(i) dict1.setdefault(i,num) items=list(dict1.items()) items.sort(key=lambda x:x[1],reverse=True) for i in items: print("{}:{}".format(i[0],i[1]))
class College: college_name="Atria" principal="Ram" college_code="1At01" annual_fees=10 @classmethod def modcoll(cls): a=int(input("enter choice 1.collname,2.pricipal,3.code")) if a==1: cls.college_name=input("Enter the coll name to be updated") elif a==2: cls.principal=input("Enter principal name to be updated") elif a==3: cls.college_code=input("Enter code to be updated") else: cls.college_name=input("Enter the coll name to be updated") cls.principal=input("Enter principal name to be updated") cls.college_code=input("Enter code to be updated") def __init__(self,name,usn,branch,phno,exam_fee):#hod: self.name=name self.usn=usn self.branch=branch self.phno=phno self.exam_fee=exam_fee #self.hod=hod def disp(self): print("Name of college: ",self.college_name) print("Name of principal: ",self.principal) print("College code: ",self.college_code) print("Name of student: ",self.name) print("Usn of student: ",self.usn) print("Branch of student: ",self.branch) print("Ph no of student: ",self.phno) @staticmethod def fees(): total_fee=student1.exam_fee+College.annual_fees print("total fees: " ,total_fee) student1=College("nav","1at11","mech",1234,500) student2=College("ravi","1at12","civil",12345,600) student3=College("rao","1at13","e&c",1345,1000) student1.disp() student1.fees()
from enum import Enum class IntermediateType(Enum): BOOL = 'bool' CHAR = 'char' STRING = 'string' DOUBLE = 'double' INT = 'int' LONG = 'long' ARRAY = 'array' LIST = 'list' SET = 'set' MAP = 'map' LINKED_LIST_NODE = 'LinkedListNode' BINARY_TREE_NODE = 'BinaryTreeNode' def __str__(self): return str(self.value)
class LinkedListNode: def __init__(self, value=None, next=None): self.value = value self.next = next def __eq__(self, other): if not isinstance(other, self.__class__): return False p = self q = other while p is not None and q is not None: if p.value is None and q.value is None: return True if p.value is None or q.value is None: return False if p.value != q.value: return False p = p.next q = q.next return p is None and q is None def __ne__(self, other): return not self.__eq__(other) # just for debug def __str__(self): result = '[' result += str(self.value) if self.value is not None else 'null' cur = self.next while cur is not None: result += ', ' result += str(cur.value) if cur.value is not None else 'null' cur = cur.next result += ']' return result def __hash__(self): hash_code = 1 p = self while p is not None: hash_code = 31 * hash_code + (0 if p.value is None else hash(p.value)) p = p.next return hash_code
from typing import List from colors import blue, yellow import re def char_to_num(char: str) -> int: """Переводит заголовки строк (a,b,c) в числа для дальнейших операций с матрицей""" return ord(char) - 97 def num_to_char(num: int) -> str: """Переводит числа в заголовки строк для вывода доски""" return str(chr(97 + num)) def get_board_size() -> int: """Получает от пользователя размер доски и обрабатывает ввод""" print('Привет! Это крестики-нолики, давайте играть :) \n') while True: input_value = input('-- Введите размер квадратного поля (целое число от 3 до 5): \n') try: board_size = int(input_value) if board_size in range(3, 6): return board_size else: print('Введенное число должно быть от 3 до 5 включительно') except ValueError: print('Это не целое число, попробуйте еще раз') def color_mark(mark: str) -> str: """Разукрашивает метки для вывода на доску""" if mark == 'x': return blue(mark) elif mark == 'o': return yellow(mark) else: return ' ' def show_board(board_matrix: List): """Выводит в консоль доску с игрой""" size = len(board_matrix) print('\n | ' + ' | '.join([str(x + 1) for x in range(size)]) + ' |') print('-' * (3 + 4 * size)) for i, row in enumerate(board_matrix): print(f'{num_to_char(i)} | ' + ' | '.join([color_mark(x) for x in row]) + ' |') print('-' * (3 + 4 * size)) def get_player_mark(player_id: int) -> str: """Получает по id игрока метку, которую игрок использует в игре""" switcher = { 1: 'x', 2: 'o' } return switcher.get(player_id, 'Несуществуюший игрок') def make_move(board_matrix: List, player_id: int): """Предлагает игроку сделать ввод хода в консоли и обрабатывает полученное значение""" while True: input_move = str(input(f'-- Ваш ход (игрок {player_id}): \n')) try: move = re.search(r'^([a-z])(\d+)$', input_move) row = char_to_num(move.group(1)) column = int(move.group(2)) - 1 if row < 0 or column < 0: raise Exception if board_matrix[row][column] is None: board_matrix[row][column] = get_player_mark(player_id) break else: print('Клетка уже занята, попробуйте снова') except Exception: print('Неверный ввод хода, попробуйте еще раз') def check_win_rows(board_matrix: List) -> bool: """ Проверяет, заполнил ли хотя бы один игрок хотя бы одну строку своими метками полностью. Если да, то этот игрок и будет победителем. """ for row in board_matrix: if len(set(row)) == 1: if row[0] is not None: return True def check_win_columns(board_matrix: List) -> bool: """ Проверяет, заполнил ли хотя бы один игрок хотя бы один столбец своими метками полностью. Если да, то этот игрок и будет победителем. """ transposed_matrix = list(map(list, zip(*board_matrix))) return check_win_rows(transposed_matrix) def check_win_diag(board_matrix: List) -> bool: """ Проверяет, заполнил ли хотя бы один игрок хотя бы одну диагональ своими метками полностью. Если да, то этот игрок и будет победителем. """ if len(set([board_matrix[i][i] for i in range(len(board_matrix))])) == 1: if board_matrix[0][0] is not None: return True if len(set([board_matrix[i][len(board_matrix) - i - 1] for i in range(len(board_matrix))])) == 1: if board_matrix[0][len(board_matrix) - 1] is not None: return True def check_draw(move_count: int, board_size: int) -> bool: """Проверяет, заполнены ли все клетки на доске. Если да, то это ничья""" if move_count == board_size ** 2: return True def game(): """Содержит логику игры крестики-нолики""" board_size = get_board_size() matrix = [[None] * board_size for _ in range(board_size)] show_board(matrix) move_count = 0 while True: player_id = (move_count % 2) + 1 make_move(matrix, player_id) show_board(matrix) if check_win_rows(matrix) or check_win_columns(matrix) or check_win_diag(matrix): print(f'Игрок {player_id} победил 🎉') break elif check_draw(move_count, board_size): print('Поле полностью заполнено - это ничья') break move_count += 1 if __name__ == '__main__': game()
import os print("""Choose from the options below ...... 1. Create a new VG 2. View VGs 3. Exit""") while True: c = input("Enter your choice: ") if int(c) == 1 : pv = input("Enter names of the drivers: ") vg = input("Enter the name to be allocated to the created Volume Group: ") os.system("pvcreate " + pv) os.system("vgcreate --name " + vg + " " + pv) os.system("vgdisplay") elif int(c) == 2: os.system("vgdisplay") elif int(c) == 3 : exit() else: print("Choice not supported")
''' READ ME: Unfortunately, the remaining projects in this course require a library accessed only through the course website sandbox. If you would like to play this game you can view it here: http://www.codeskulptor.org/#user47_WrxHGCVrsK_6.py If this link has been removed in the backend, you can always play the game by coming here: http://www.codeskulptor.org/, removing the code and replacing it with my code below: Side Note: The instructors said to use global variables in this case. Thanks for understanding :) ''' # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math def new_game(): global secret_number secret_number = random.randrange(0, 100) # define event handlers for control panel def calculate_attempts(number): '''Calculates the number of attempts so you only have the maximum amount of guesses to win using binary search''' global attempts attempts = math.ceil(math.log(number, 2)) print "You have", int(attempts), "attempt to win." print "Please only guess whole numbers. Good Luck!" print def range100(): global secret_number secret_number = random.randrange(0, 100) calculate_attempts(100) print "guess the number between 1 and 100" def range1000(): global secret_number secret_number = random.randrange(0, 1000) calculate_attempts(1000) print "guess the number between 1 and 1000" def decrement_attempts(): global attempts attempts -= 1 def input_attempts(): global attempts decrement_attempts() print "Attempts remaining", int(attempts) def input_guess(guess): input_attempts() guess = int(guess) if(attempts <= 0): print print "Game Over! You Lose." print print elif(guess > secret_number): print "Lower" elif(guess < secret_number): print "Higher" else: print "Correct" # create frame frame = simplegui.create_frame('Guess The Number', 200, 200, 300) # register event handlers for control elements and start frame guess = frame.add_input('Guess The Number', input_guess, 200) start100 = frame.add_button('Range is [0,100)', range100, 75) start1000 = frame.add_button('Range is [0,1000)', range1000, 75) frame.start() # call new_game new_game()
#Bubble Sort l1=eval(input("Enter list here")) count=0 for i in range(len(l1)): for j in range(len(l1)-i-1): if l1[j]<=l1[j+1]: count+=1 continue elif l1[j]>l1[j+1]: l1[j], l1[j+1]=l1[j+1], l1[j] count+=1 print(l1, "operations took place", count,"number of times")
import csv with open('Dataset.csv', newline = '') as f: reader = csv.reader(f) fileData = list(reader) # Remove header while reading data fileData.pop(0) newData = [] ### HEIGHT # FOR I IN RANGE => for each # len => length for i in range(len(fileData)): n_num = fileData[i][1] newData.append(float(n_num)) # # ### WEIGHT # # FOR I IN RANGE => for each # # len => length # for i in range(len(fileData)): # n_num = fileData[i][2] # newData.append(float(n_num)) # MEAN n = len(newData) total = 0 for x in newData: total = total + x mean = total/n print("The mean/average is " + str(mean))
import requests import json import pandas as pd import matplotlib.pyplot as plt # POST to API payload = {'country': 'Italy'} URL = 'https://api.statworx.com/covid' response = requests.request("POST", url=URL, data=json.dumps(payload)) # Convert to data frame df = pd.DataFrame.from_dict(json.loads(response.text)) # print(df.info()) # print(df.head()) # print(df["cases_cum"]) fig = plt.figure(figsize= (8, 6)) plt.plot(df["cases_cum"], 'bo') fig.suptitle("Country: Italy") plt.xlabel("Number of days since 1/1/2020") plt.ylabel("Number of cases") plt.show() # url = "https://coronavirus-monitor.p.rapidapi.com/coronavirus/cases_by_country.php" # # headers = { # 'x-rapidapi-host': "coronavirus-monitor.p.rapidapi.com", # 'x-rapidapi-key': "b6096bb964msh0f75e8faa61784cp10b2d6jsn0f3e403692d3" # } # # response = requests.request("GET", url, headers=headers) # # df = pd.DataFrame.from_dict(json.loads(response.text)) # print(df.info()) # # print(df['countries_stat']) # filter_by_country = {} # for dict in df['countries_stat']: # if dict['country_name'] not in filter_by_country: # filter_by_country[dict['country_name']] = dict # # print(filter_by_country['Egypt'])
def prompt_input(prompt, errormsg): """ Prompts the user for an integer using the prompt parameter. If an invalid input is given, an error message is shown using the error message parameter. A valid input is returned as an integer. Only accepts integers that are bigger than 1. """ is_int = False while is_int == False: try: input_number = int(input(prompt)) except ValueError: print(errormsg) else: is_int = True if input_number <= 1 and is_int == True: print(errormsg) is_int = False return input_number def check_prime(number): """ Checks whether an integer is a prime number. Returns False if the number isn't a prime; if it is a prime, returns True """ prime = True for i in range(2, number): if (number % i) == 0: prime = False return prime prime_number = prompt_input("Give an integer that's bigger than 1:", "You had one job") if check_prime(prime_number) == True: print("This is a prime") else: print("This is not a prime")
import matplotlib.pyplot as plt from scipy.interpolate import interp1d import numpy as np ### 1d example of interpolation ### in_data_x = np.array([1., 2., 3., 4., 5., 6.]) in_data_y = np.array([1.5, 2., 2.5, 3., 3.5, 4.]) # y = .5 x - 1 f = interp1d(in_data_x, in_data_y, kind='linear') print(f) # f in all of the points of the grid (in_data_x): output coincides with in_data_y print( f(1), f(1.), f(1.5), f(2.), f(2.5), f(3.)) # f in a point outside the grid: print( f(1.8)) # this is equal to y = .5 x - 1 for x = 1.8, up to some point. assert( np.round(0.5 * 1.8 + 1, decimals=10) == np.round(f(1.8), decimals=10)) # plot up to this point xnew = np.arange(1, 6, 0.1) ynew = f(xnew) plt.plot(in_data_x, in_data_y, 'o', xnew, ynew, '-') # close the image to move forward. #plt.show() ### another 1d example of interpolation ### in_data_x = np.array([1., 2., 3., 4., 5., 6.]) in_data_y = np.array([-1.8, -1.2, -0.2, 1.2, 3., 5.2]) # y = .2 x**2 - 2 f = interp1d(in_data_x, in_data_y, kind='cubic') print (f) # f in all of the points of the grid (in_data_x): output coincides with in_data_y print (f(1), f(1.), f(1.5), f(2.), f(2.5), f(3.)) # f in a point outside the grid: print( f(1.8)) # this is equal to y = .2 x**2 - 2 for x = 1.8, up to some precision. assert(np.round(0.2 * 1.8 ** 2 - 2, decimals=10) == np.round(f(1.8), decimals=10)) # plot up to this point xnew = np.arange(1, 6, 0.1) ynew = f(xnew) plt.plot(in_data_x, in_data_y, 'o', xnew, ynew, '-') #plt.show() from scipy.ndimage.interpolation import map_coordinates import numpy as np in_data = np.array([[0., -1., 2.], [2., 1., 0.], [4., 3., 2.]]) # z = 2.*x - 1.*y # want the second argument as a column vector (or a transposed row) # see on some points of the grid: print( 'at the point 0, 0 of the grid the function z is: ') print( map_coordinates(in_data, np.array([[0., 0.]]).T, order=1)) print( 'at the point 0, 1 of the grid the function z is: ') print( map_coordinates(in_data, np.array([[0., 1.]]).T, order=1)) print( 'at the point 0, 2 of the grid the function z is: ') print( map_coordinates(in_data, np.array([[0., 2.]]).T, order=1)) # see some points outside the grid print() print( 'at the point 0.2, 0.2 of the grid, with linear interpolation z is:') print( map_coordinates(in_data, np.array([[.2, .2]]).T, order=1)) print( 'and it coincides with 2.*.2 - .2') print() print( 'at the point 0.2, 0.2 of the grid, with cubic interpolation z is:') print( map_coordinates(in_data, np.array([[0.2, .2]]).T, order=3))
a = 33 b = 200 if b > a: print("b is greater than a") a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") a = 33 b = 200 if b > a: pass
set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set1.update(set2) print(set1) x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.intersection_update(y) print(x) x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.intersection(y) print(z) x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.symmetric_difference_update(y) print(x) x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.symmetric_difference(y) print(z)
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split """" Implementing a model a described in the link below would probably work well for this type of data https://nbviewer.jupyter.org/github/srnghn/ml_example_notebooks/blob/master/Predicting%20Yacht%20Resistance%20with%20K%20Nearest%20Neighbors.ipynb For this model to work we would probably need to clean some of the data such as turning Stevedorenames into integers. We could then try and fit the model, and play around with the type of input we provide the model. Most likely not all data is useful some we might find a better solution with less input columns. """ predictionTypes = ["discharge1", "load1", "discharge2", "load2", "discharge3", "load3", "discharge4", "load4",] vesselData = pd.read_csv('VesselData.csv') print(vesselData)
from pprint import pprint def prepare_dict(file_name: str) -> dict: result: dict = dict() with open(file_name, encoding='utf-8') as file: for line in file: name_dish = line.strip() records_ingredients = int(file.readline()) ingridient_list = [] for ingridients in range(records_ingredients): ingridient_name, quantity, measure = file.readline().split('|') ingridient_list.append({'ingridient_name': ingridient_name.strip(), 'quantity': int(quantity.strip()), 'measure': measure.strip()}) result[name_dish] = ingridient_list file.readline() return result cook_book = prepare_dict("homework.txt") pprint(cook_book, sort_dicts=False) def get_shop_list_by_dishes(dishes, person): my_list = {} for dish in dishes: for ingr in (cook_book[dish]): itm_list = dict([(ingr['ingridient_name'], \ {'measure': ingr['measure'], \ 'quantity': int(ingr['quantity']) * person})]) if my_list.get(ingr['ingridient_name']): item = (int(my_list[ingr['ingridient_name']]['quantity']) + int(itm_list[ingr['ingridient_name']]['quantity'])) my_list[ingr['ingridient_name']]['quantity'] = item else: my_list.update(itm_list) return my_list print() pprint(get_shop_list_by_dishes(['Запеченный картофель', 'Омлет'], 2))
#Zad.9 Napisz skrypt, w którym zadeklarujesz zmienne typu: string, float i szestnastkowe. # Następnie wyświetl je wykorzystując odpowiednie formatowanie. string = 'Hello World!' float = float(10) szesznastka = hex(156) print(string) print(float) print(szesznastka)
# Zad3. Napisz skrypt, w którym stworzysz operatory przyrostkowe dla operacji: +, -, *, /, **, % a, b, c, d, e, f = 10, 10, 10, 10, 10, 10 a += 2 print(a) b -= 2 print(b) c *= 2 print(c) d /= 2 print(d) e **= 2 print(e) f %= 2 print(f)
def convert_tulpe_to_str(tpl): result = "" if len(tpl) > 0: for word in tpl: result += str(word) + " " result.rstrip() return result
# 猜数字游戏,1到100之间的随机数字 import random r = random.randint(1,100) count = 0 while True: count = count + 1 num = int(input('请输入数字:')) if num == r: print('恭喜你,你猜对了') break elif num > r: print('比', num, '小,再猜') elif num < r: print('比', num, '大,接着猜') print('这是第', count, '次')
#NAME :PRANJAL SARODE #DIV :D ROLL NO :9 from matplotlib import pyplot as plt # python lib for plotting graph import numpy as np # python lib for using 2d array import math # python lib for using mathematical aretmetics print("Given Stress Tensor") print( ) A = np.array([[120, -55, -75], [-55, 55, 33], [-75, 33, -85]]) print(A) print( ) print("The values of Stress Invariants on solving their respective derived formulae") print( ) I1 = A[0][0] + A[1][1] + A[2][2] print("I1 = ",I1) I2 = A[0][0]*A[1][1] + A[0][0]*A[2][2] + A[1][1]*A[2][2] - A[1][0]*A[1][0] - A[1][2]*A[1][2] - A[2][0]*A[2][0] print("I2 = ",I2) I3 = np.linalg.det(A) print("I3 = ",I3) print( ) print("On substituting the value of I1 I2 I3 in equation :") print("sigma^3 -I1*sigma^2 + I2*sigma - I3 = 0") print() print("We get three values of sigma as:") I =np.roots([1, -I1, I2, -I3]) print("sigma1 = ",I[0]) print("sigma2 = ",I[1]) print("sigma3 = ",I[2]) print() print("Now choosing the most +ve value from above values of sigma and using below") print("Equilibrium equations for element aligned with principle direction") X = np.array([[A[0][0] - I[0], A[0][1], A[0][2]], [A[1][0], A[1][1] - I[0], A[1][2]], [A[2][0], A[2][1], A[2][2] - I[0]]]) print(X) print() print("Replacing the last equation with l^2 + m^2 + n^2 = 1") print("Thereby replacing n with value 1, Hence A = ") d = np.array([[X[0][0], X[0][1], X[0][2]], [X[1][0], X[1][1], X[1][2]], [0, 0, 1]]) print(d) print() b = np.array([[0], [0], [1]]) print("The value of B = ") print(b) print() DC = np.linalg.solve(d, b) print("On solving the above linear equations AX = B , We get") print(DC) len = math.sqrt(DC[0]*DC[0] + DC[1]*DC[1] + 1) print(len) print(DC/(len))
def math(number): square = number * number third = number * number * number print("The square of your number is {a} and to the third power is {b}.".format(a=square, b=third) while True: while True: number = int(input("Tell me a number")) math(number)
# # 异或 # class Solution: # def hammingDistance(self, x: int, y: int) -> int: # res = 0 # t = x ^ y # while t: # t &= (t - 1) # # 每经过一次t &= t - 1,都会消除t对应的二进制的最右边的“1” # res += 1 # # return res # 使用移位的方式,检查最右侧或最左侧的元素是否为1 class Solution: def hammingDistance(self, x: int, y: int) -> int: xor = x ^ y res = 0 while xor: if xor & 1: res += 1 xor >>= 1 return res a, b = 1, 2 print(Solution().hammingDistance(a, b))
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here if n == 0: return 0 if n == 1 or n == 2: return 1 # 辅助数组空间 # dp = [0] * (n + 1) # dp[1] = 1 # # for i in range(2, n + 1): # dp[i] = dp[i - 1] + dp[i - 2] # # return dp[n] # 辅助变量 pre1, pre2 = 0, 1 c = 0 for i in range(2, n+1): c = pre1 + pre2 pre1 = pre2 pre2 = c return c k = 39 print(Solution().Fibonacci(k))
""" 现在有一幅扑克牌,去掉大小王52张牌。随机选出4张牌,可以任意改变扑克牌的顺序, 并填入 + - * / 四个运算符,不用考虑括号,除法按整数操作,计算过程中没有浮点数,问是否能够求值得到给定的数m。 输入描述: 一行四个数字 (JQK 分别被替换成11,12,13)单空格分割,另一行输入 m 输出描述: 可以输出1, 否则输出0 """ def fun(nums, m): def dfs(exp, s, i): if i == 4: if str(s) == m: # print(exp[:-1]) return True return False exp = exp + str(nums[i]) s = eval(exp) return dfs(exp + '+', s, i + 1) or dfs(exp + '-', s, i + 1) \ or dfs(exp + '*', s, i + 1) or dfs(exp + '//', s, i + 1) return dfs('', 0, 0) if __name__ == '__main__': numbers = input().strip().split() tar = input().strip() res = '1' if fun(numbers, tar) else '0' print(res)
from typing import List # 超时 # class Solution: # def findAnagrams(self, s: str, p: str) -> List[int]: # if not s or not p: # return [] # ns, np = len(s), len(p) # res = [] # hashp = {} # for i in range(np): # ch = p[i] # hashp[ch] = hashp.get(ch, 0) + 1 # # for i in range(ns - np + 1): # hashs = {} # for j in range(np): # ch = s[i + j] # hashs[ch] = hashs.get(ch, 0) + 1 # if hashs == hashp: # res.append(i) # # return res # 滑动窗口 class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: if not s or not p: return [] ns, np = len(s), len(p) left, right = 0, np window = {} while right < ns: ch = s[left] window[ch] = window.get(ch, 0) + 1 # S = "cbaebabacd" # P = "abc" S = "abab" P = "ab" print(Solution().findAnagrams(S, P))
# -*- coding:utf-8 -*- class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # 返回 RandomListNode def Clone(self, pHead): # write code here # 1. 先复制普通节点,再复制随机节点 if not pHead: return p = pHead while p: node = RandomListNode(p.label) node.next = p.next p # 2. 使用字典降低查找的复杂度 # if not pHead: # return # hashmap = dict() # p = pHead # # while p: # node = RandomListNode(p.label) # hashmap[p] = node # p = p.next # # p = pHead # while p: # node = hashmap[p] # if p.next: # node.next = hashmap[p.next] # if p.random: # node.random = hashmap[p.random] # # p = p.next # return hashmap[pHead]
class Solution: """ @param A: A string @param B: A string @return: the length of the longest common substring. """ # 1.暴力解法 # def longestCommonSubstring(self, A, B): # # write your code here # m, n = len(A), len(B) # maxlen = 0 # # for i in range(m): # k = i # for j in range(n): # cnt = 0 # # if A[i: i + 3] == 'dnf' and B[j: j + 2] == 'dn': # while i < m and j < n and A[i] == B[j]: # i += 1 # j += 1 # cnt += 1 # i = k # maxlen = max(maxlen, cnt) # # return maxlen # 2. 动态规划 def longestCommonSubstring(self, A, B): m, n = len(A), len(B) dp = [[0] * (n + 1) for _ in range(m + 1)] maxlen = 0 for i in range(1, m + 1): for j in range(1, n + 1): if A[i - 1] == B[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = 0 maxlen = max(dp[i][j], maxlen) return maxlen # s1 = "ABCD" # s2 = "CBCE" # s1, s2 = "ABCD", "EACB" s1, s2 = "adfanadsnf;andvadsjfafjdlsfnaldjfi*odiasjfasdlnfasldgao;inadfjnals;dfjasdl;jfa;dsjfa;sdnfsd;afhwery894yra7f78asfas8fy43rhaisuey34hiuy^%(9afysdfhaksdhfsdkjfhsdhfakldhfsdkf*h", "dafdnf**" print(Solution().longestCommonSubstring(s1, s2))
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: # 方法:排序 & 合并。时间和空间复杂度取决于排序的复杂度,即O(NlogN),空间O(logN), # 对每个区间的左端点进行排序 intervals.sort(key=lambda x: x[0]) merged = [] for int in intervals: # 如果列表为空,或当前区间与上一个区间不重合,则直接添加 if not merged or merged[-1][1] < int[0]: merged.append(int) else: # 否则,可以对区间进行合并 merged[-1][1] = max(merged[-1][1], int[1]) return merged
def insertSort(nums): n = len(nums) for i in range(n): tmp = nums[i] j = i - 1 while j >= 0 and nums[j] > tmp: nums[j + 1] = nums[j] j -= 1 print(nums) nums[j + 1] = tmp # print(nums) return nums numbers = [-5, 5, 11, 2, 4, -3] insertSort(numbers)
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # 方法1。迭代法。时间复杂度为O(L1+L2),空间复杂度O(1) class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 pHead = ListNode() p = pHead while l1 and l2: if l1.val <= l2.val: p.next = l1 l1 = l1.next else: p.next = l2 l2 = l2.next p = p.next # 将l1或l2链表中剩余的元素加入链表 p.next = l1 if l1 else l2 return pHead.next # # 方法2.递归。时间复杂度O(L1+L2),空间复杂度O(L1+L2) class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 if l1.val <= l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 L1, L2 = 3, 3 p1, p2 = ListNode(), ListNode() pt1, pt2 = p1, p2 print("第一个链表") for i in range(L1): x = int(input()) pt1.next = ListNode(x) pt1 = pt1.next print("第二个链表") for i in range(L2): x = int(input()) pt2.next = ListNode(x) pt2 = pt2.next print("输出结果") res = Solution().mergeTwoLists(p1.next, p2.next) while res: print(res.val) res = res.next
class Solution: def climbStairs(self, n: int) -> int: # 方法:动态规划 # if n < 3: return n # dp = [0] * (n + 1) # dp[0], dp[1] = 1, 1 # for i in range(2, n + 1): # dp[i] = dp[i - 1] + dp[i - 2] # return dp[-1] # 空间优化 if n < 3: return n a, b = 1, 2 for i in range(3, n + 1): c = a + b a, b = b, c return c N = 3 print(Solution().climbStairs(N))
# -*- coding:utf-8 -*- class Solution: def MoreThanHalfNum_Solution(self, numbers): # write code here if not numbers: return n = len(numbers) arr = [0] * n for num in numbers: arr[num - 1] += 1 for i, a in enumerate(arr): if a > n // 2: return i + 1 return 0 nums = [1, 2, 2, 3, 3, 2, 3, 3, 2] print(Solution().MoreThanHalfNum_Solution(nums))
#-*- coding: utf-8 -*- import threading,multiprocessing def loop(): x = 10 while True: x = x+1 print(x) for i in range(multiprocessing.cpu_count()): t = threading.Thread(target=loop) t.start()
#-*- coding: utf-8 -*- #python 关于map与reduce的应用 from functools import reduce #编写数字字典 def char2num(ch): return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[ch] def f(x,y): return x*10 + y #将字符串转换成浮点数 def str2float(s): a = s.index('.') s1 = s[:a] s2 = s[a+1:] n = len(s2) return reduce(f,map(char2num,s1)) + reduce(f,map(char2num,s2))*(0.1**n) print('str2float(\'123.456\') =',str2float('123.456')) print('asdasd')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #python关于filter()也就是筛选函数的应用 求素数 def main(): for n in primes(): if n<1000: print(n) else: break #生成间隔为2的自然数 def _odd_iter(): n = 1 while True: n +=2 yield n def _not_dicisible(n): return lambda x:x%n>0 def primes(): yield 2 it = _odd_iter while True: n = next(it) yield n it = filter(_not_dicisible(n),it) if _name_ == '_main_': main()
# -*- coding: utf-8 -*- import hashlib db = { 'michael': 'e10adc3949ba59abbe56e057f20f883e', 'bob': '878ef96e86145580c38c87f0410ad153', 'alice': '99b1c2188db85afee403b1536010c2c9' } #返回密码的md5码 def calc_md5(password): md5 = hashlib.md5() md5.update(password.encode('utf-8')) return md5.hexdigest() #登录方法 def login(user,password): try: db_pwd = db[user] if db_pwd ==calc_md5(password): print('login sucess') else: print('wrong password') except KeyError: print ('don\'t hava that user') login('zbf','123456') login('michael','123456')
# roman number to integer nums = [] def romanToInt(roman): sum = 0 for letter in roman: if letter is '': nums.append(0) elif letter is 'I' or letter is 'i': nums.append(1) elif letter is 'V' or letter is 'v': nums.append(5) elif letter is 'X' or letter is 'x': nums.append(10) elif letter is 'L' or letter is'l': nums.append(50) elif letter is 'C' or letter is 'c': nums.append(100) elif letter is 'D' or letter is 'd': nums.append(500) elif letter is 'M' or letter is 'm': nums.append(1000) else: print('Please input a correct roman number!') raise TypeError ''' 倒序查看,指针从倒数第二个数字开始查找 如果当前数字小于后一个数字 则当前数字取负 ''' for i in range(len(nums)-2, -1, -1): if nums[i] < nums[i+1]: nums[i] = nums[i]*(-1) for i in nums: sum = sum + i return sum print(romanToInt('CMXCIX')) # integer to roman number # def integerToList(integer): # 代码优化 # '''将数字转换为列表形式 # ''' # numList = [] # list_number_one = integer // 1000 # numList.append(list_number_one) # list_number_two = (integer % 1000) // 100 # numList.append(list_number_two) # list_number_three = ((integer % 1000) % 100) // 10 # numList.append(list_number_three) # list_number_four = ((integer % 1000) % 100) % 10 # numList.append(list_number_four) # return numList def integerToRoman(integer): ''' 将数字列表转换为罗马数字 ''' numList = [integer // 1000, (integer % 1000) // 100, ((integer % 1000) % 100) // 10, ((integer % 1000) % 100) % 10] roman = '' # numList = integerToList(integer) one = 'M' * numList[0] two = 'CM' * (numList[1] // 9) + 'D' * ((numList[1] % 9) // 5) + 'CD' * (((numList[1] % 9) % 5) // 4) + 'C' * (((numList[1] % 9) % 5) % 4) three = 'XC' * (numList[2] // 9) + 'L' * ((numList[2] % 9) // 5) + 'XL' * (((numList[2] % 9) % 5) // 4) + 'X' * (((numList[2] % 9) % 5) % 4) four = 'IX' * (numList[3] // 9) + 'V' * ((numList[3] % 9) // 5) + 'IV' * (((numList[3] % 9) % 5) // 4) + 'I' * (((numList[3] % 9) % 5) % 4) roman = roman.join(one + two + three + four) return roman print(integerToRoman(99))
class Board: def __init__(self, WIDTH, HEIGHT, SPACING): """constructor of Board object""" self.WIDTH = WIDTH self.HEIGHT = HEIGHT self.SPACING = SPACING def board_display(self): """draw lines of board""" # draw the horizontal line strokeWeight(2) for i in range(1, self.HEIGHT//self.SPACING + 1): line(0, self.SPACING*i, self.WIDTH, self.SPACING*i) # draw the vertical line for i in range(1, self.WIDTH//self.SPACING + 1): line(self.SPACING*i, 0, self.SPACING*i, self.HEIGHT)
from stack import Stack stack=Stack() stack.push("a") stack.push("b") stack.push("c") temp=stack.__str__() print(temp) for letter in range(97,123): print(chr(letter))
from dot import Dot class Dots: """A collection of dots.""" def __init__(self, WIDTH, HEIGHT, LEFT_VERT, RIGHT_VERT, TOP_HORIZ, BOTTOM_HORIZ): self.WIDTH = WIDTH self.HEIGHT = HEIGHT self.TH = TOP_HORIZ self.BH = BOTTOM_HORIZ self.LV = LEFT_VERT self.RV = RIGHT_VERT self.SPACING = 75 self.EAT_DIST = 50 # Initialize four rows of dots, based on spacing and width of the maze self.top_row = [Dot(self.SPACING * i, self.TH) for i in range(self.WIDTH//self.SPACING + 1)] self.bottom_row = [Dot(self.SPACING * i, self.BH) for i in range(self.WIDTH//self.SPACING + 1)] self.left_col = [Dot(self.LV, self.SPACING * i) for i in range(self.HEIGHT//self.SPACING + 1)] self.right_col = [Dot(self.RV, self.SPACING * i) for i in range(self.HEIGHT//self.SPACING + 1)] def display(self): """Calls each dot's display method""" for i in range(0, len(self.top_row)): self.top_row[i].display() for i in range(0, len(self.bottom_row)): self.bottom_row[i].display() for i in range(0, len(self.left_col)): self.left_col[i].display() for i in range(0, len(self.right_col)): self.right_col[i].display() # TODO: # PROBLEM 3: implement dot eating # # BEGIN CODE CHANGES # Modify the dots so a dot is being eaten (removed). # x: x coordinate in pacman game, not the pixel coordinate. # y: y coordinate in pacman game, not the pixel coordinate. def eat(self, x, y): """Given the location of pacman, remove the dot which has been eaten""" for dot in self.top_row: if (dot.x in range(x-self.EAT_DIST, x+self.EAT_DIST) and dot.y in range(y-self.EAT_DIST, y+self.EAT_DIST)): self.top_row.remove(dot) for dot in self.left_col: if (dot.x in range(x-self.EAT_DIST, x+self.EAT_DIST) and dot.y in range(y-self.EAT_DIST, y+self.EAT_DIST)): self.left_col.remove(dot) for dot in self.bottom_row: if (dot.x in range(x-self.EAT_DIST, x+self.EAT_DIST) and dot.y in range(y-self.EAT_DIST, y+self.EAT_DIST)): self.bottom_row.remove(dot) for dot in self.right_col: if (dot.x in range(x-self.EAT_DIST, x+self.EAT_DIST) and dot.y in range(y-self.EAT_DIST, y+self.EAT_DIST)): self.right_col.remove(dot) # # END CODE CHANGES # Check if there is any non-zero dot exists in the four arrays of dots. def dots_left(self): """Returns the number of remaing dots in the collection""" return (len(self.top_row) + len(self.bottom_row) + len(self.left_col) + len(self.right_col))
import glob import pathlib from PIL import Image mainfolder = input("Input folder: ") p = pathlib.Path("{}/".format(mainfolder)) def compress(img_file): print(img_file) basewidth = 1920 img = Image.open(img_file) wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) img = img.resize((basewidth,hsize), Image.ANTIALIAS) img.save(img_file) for img_file in p.rglob("*.png"): compress(img_file) for img_file in p.rglob("*.jpg"): compress(img_file) for img_file in p.rglob("*.jpeg"): compress(img_file)
#Lab 7 Seat Class with respective sub classes #Logan Kilpatrick #Implimented by lab7.py #imported by chart class class Seat: ''' The Seat class has: instance variables price and taken (a boolean).(parent class) a constructor that initializes the taken attribute to False and ... has a default argument price which you should provide a default value. an abstract method getExtra that requires all subclasses to implement it.#read abstract class notes!!! ''' def __init__(self, price = 0, taken = False,): '''constructor. takes in 2 paremeters if the user provides them, otherwise, sets them to said default values. ''' self._price = price self._taken = taken def getExtra(self):#abstract class, look up implimentation. forces the child class to have zero parameters raise NotImplementedError def isTaken(self): '''isTaken: return True if the seat is taken, False if the seat is still available ''' return (self._taken == True) def setTaken(self, nowTaken): '''sets the origional with true or false. takes in the value to set it with as a parameter ''' self._taken = nowTaken return (self._taken) def getPrice(self): '''getPrice: return the value in the instance variable price''' return(self._price) def setPrice(self, price): '''Sets the origional price. Takes in a parameter and sets the prcie to that number.''' self._price = price def __repr__(self): #print statement that shows the info about the objects return self._price class Premium(Seat): def __init__(self, price): '''takes in a price and then passes the price to the superclasses(parents) constructor ''' super().__init__(price) def getExtra(self): '''prints the extra info about the Premium ticket''' return(" : your swag bag, drink, and ticket are at will call") class Choice(Seat): def __init__(self, price): '''takes in a price and then passes the price to the superclasses(parents) constructor ''' super().__init__(price) def getExtra(self): '''prints the extra info about the Choice ticket''' return(" : your drink ticket and ticket are at will call") class Regular(Seat): def __init__(self, price): '''takes in a price and then passes the price to the superclasses(parents) constructor ''' super().__init__(price) def getExtra(self): '''prints the extra info about the Regular ticket''' return(" : your ticket is at will call")
import math from datetime import datetime la1 = float(raw_input("Enter the starting latitude: ")) lo1 = float(raw_input("Enter the starting longitude: ")) la2 = float(raw_input("Enter the ending latitude: ")) lo2 = float(raw_input("Enter the ending longitude: ")) ts1 = "2016-01-15 10:00:00" ts2 = "2016-01-15 10:30:00" def distance(lat1, lon1, lat2, lon2): R = 6371000 l1r = math.radians(lat1) l2r = math.radians(lat2) latDr = math.radians(lat2 - lat1) lonDr = math.radians(lon2 - lon1) a = math.sin(latDr / 2) * math.sin(latDr / 2) + math.cos(l1r) * math.cos(l2r) * math.sin(lonDr / 2) * math.sin(lonDr / 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) d = (R * c) / 1000 return d # distance is in kilometers def timeDiff(t1, t2): t1obj = datetime.strptime(t1, "%Y-%m-%d %H:%M:%S") t2obj = datetime.strptime(t2, "%Y-%m-%d %H:%M:%S") tDiff = t2obj - t1obj return tDiff.seconds # time is in seconds def speed(distance, time): # distance is in km # time is in seconds vehSpeed = ( float(distance) / time ) * 60 * 60 return vehSpeed distanceTraveled = distance(la1, lo1, la2, lo2) timeTaken = timeDiff(ts1, ts2) velocity = speed(distanceTraveled, timeTaken) print "Speed is: {0} km/h".format(velocity)
TELEPHONES = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"] NAMES = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] numero = input("Quel est le numéro?") findIt = False for i in range(0, 9): if TELEPHONES[i] == numero: print(NAMES[i]) findIt = True if not findIt: print("non attribué")
print("entrez votre prénom et votre nom séparés d'un espace") fullName = input() sep = " " nom = "" prenom = "" inPrenom = True for i in range(0, len(fullName)): if fullName[i] == sep: inPrenom = False elif inPrenom: prenom = prenom + fullName[i] else: nom = nom + fullName[i] print(prenom[0].upper() + ". " + nom[0].upper())
c = input('請輸入攝氏: ') c = float(c) #溫度可能有小數點 f = (c * (9 / 5)) + 32 print('攝氏溫度', c, '的華氏溫度是', f)
class Queue: """ Queue Stack provides implementation of all primary method of a queue such as enqueue, dequeue, peek """ def __init__(self): self.queue = [] def show(self): return self.queue def enqueue(self, val): """ Time complexity: O(1) Space complexity: O(1) """ self.queue.append(val) def dequeue(self): """ Time complexity: O(n) Space complexity: O(1) """ if len(self.queue) == 0: raise IndexError("dequeue from an empty queue") else: return self.queue.pop(0) def peek(self): """ Time complexity: O(1) Space complexity: O(1) """ if len(self.queue) == 0: raise IndexError("queue is empty") return self.queue[0]
""" Create a simple array class where each element must be an integer type and: - has a .len() method which outputs the length of the array - has a .get(i) method which outputs the value at a given index - has a a .set(val,i) method which replaces the val at index i """ class Array(object): def __init__(self, size): self.size = size # define a fixed size of the array self.array = [None] * size # define array field with the value of the given array (arr) self._n = 0 # count the number of elements given to the array def __str__(self): """ Show the array if the instance variable was printed """ return self.array def set(self, val, ind): """ set function takes in a value and index and inserts the given value to the array in the given index :param val: given integer value to add to the array :param ind: integer represents the index in which the value should be added to the array :return: TypeError if the given value is not an int """ if type(val) != int: # raise type error if value not int type raise TypeError elif ind > self.size: # if the given value index greater than the fixed size of the array raise an error raise IndexError else: self._n += 1 self.array[ind] = val def get(self, ind): """ :param ind: integer represents the needed value's position in the array :return: element at index ind """ if not 0 <= ind < len(self.array): raise IndexError('Invalid index') return self.array[ind] def len(self): """ :return: the number of elements in the array """ return self._n if __name__ == '__main__': Array(5)
""" Write a function that inputs a list of lists and returns if it can form a tree with the root as the first element of the list and each other element a subtree. """ def isTree(l, value=True): if len(l) == 0: return True if len(l) == 1: return type(l[0]) != list if type(l[0]) != list: for ele in l[1:]: if type(ele) != list: return False value = isTree(ele) else: return False return value
class Stack(object): """ class Stack provides implementation of all primary method of a stack such as push, pop, isEmpty, size, and show """ def __init__(self): self.stack = [] def show(self): """ Time complexity: O(1) Space complexity: O(1) """ return self.stack def push(self, item): """ add a given element to the end of the stack """ """ Time complexity: O(1) Space complexity: O(1) """ self.stack.append(item) def pop(self): """ delete the last element of the stack """ """ Time complexity: O(1) Space complexity: O(1) """ if self.size() > 0: self.stack.pop() else: raise IndexError def peek(self): """ Time complexity: O(1) Space complexity: O(1) """ try: return self.stack[-1] except IndexError: return None def size(self): """ Time complexity: O(1) Space complexity: O(1) """ return len(self.stack)
import unittest # import the unittest module to test the class methods from implementation_8.binary_search_tree import BST class TestBSTTree(unittest.TestCase): def test_BST_insert(self): # Set up tree tree = BST() self.assertEqual(tree.createBST([1, 2, 0, 4, 1.5]), "0-1-1.5-2-4") def test_search(self): tree = BST() tree.createBST([1, 2, 0, 4, 1.5]) val = 3 self.assertEqual(tree.search(val), False) def test_search_2(self): tree = BST() tree.createBST([1, 2, 0, 4, 1.5]) val = 2 self.assertEqual(tree.search(val), True) if __name__ == '__main__': unittest.main()
""" Write a binarySearch(array, val) function that inputs a sorted array/list (ascending order) and returns if the value is in the array using BinarySearch (should be O(logN) time) """ # def binary_search(l, target): # """ # Iterative binary search algorithm # """ # start = 0 # end = len(l) - 1 # while start <= end: # mid = (end + start) // 2 # if l[mid] == target: # return True # elif l[mid] > target: # end = mid - 1 # else: # start = mid + 1 # return False def binary_search_rec(arr, target, l, r, mid): if len(arr) == 0: return False if arr[mid] == target: return True elif arr[mid] > target: r = mid - 1 return binary_search_rec(arr[l: r+1], target, l, r, (l + r) // 2) else: arr = arr[mid + 1: r+1] r = mid return binary_search_rec(arr, target, l, r, (l + r) // 2) def binarySearch(arr, target): """ binarySearch function takes in an array (arr) and a target values, it returns True if target in arr, False otherwise TimeComplexity: O(log(n)) SpaceComplexity: O(1)) """ # intiate the left pointer, right pointer and mid point l = 0 r = len(arr) - 1 mid = (l + r) // 2 return binary_search_rec(arr, target, l, r, mid)
import unittest # import the unittest module to test the class methods from implementation_10.undirected_graphs import UndirectedGraph class TestUndirectedGraph(unittest.TestCase): def testIsVertex(self): graph = UndirectedGraph() graph.insert_vertex("A") self.assertEqual(graph.isVertex("A"), True) self.assertEqual(graph.isVertex("C"), False) def testIsEdge(self): graph = UndirectedGraph() graph.insert_vertex("A") graph.insert_vertex("D") graph.insert_edge("A", "D", 100) self.assertEqual(graph.isEdge("A", "D"), True) self.assertEqual(graph.isEdge("A", "K"), False) def testUpdateWeight(self): graph = UndirectedGraph() graph.insert_vertex("A") graph.insert_vertex("D") graph.insert_edge("A", "D", 100) self.assertEqual(graph.update_weight("A", "D", 1200), "A --- D --- 1200") def testUpdateWeightOfNonExistingVertices(self): graph = UndirectedGraph() graph.insert_vertex("A") graph.insert_vertex("D") with self.assertRaises(KeyError): graph.update_weight("A", "K", 1200) def testRemoveVertex(self): graph = UndirectedGraph() graph.insert_vertex("A") graph.insert_vertex("D") graph.delete_vertex("A") self.assertEqual(graph.isVertex("A"), False) def testRemoveEdge(self): graph = UndirectedGraph() graph.insert_vertex("A") graph.insert_vertex("D") graph.insert_edge("A", "D", 100) graph.delete_edge("A", "D") self.assertEqual(graph.isEdge("A", "D"), False) # test deleting non-existing edge with self.assertRaises(KeyError): graph.delete_edge("A", "D") def testInsertAnExistingEdge(self): graph = UndirectedGraph() graph.insert_vertex("A") graph.insert_vertex("D") graph.insert_edge("A", "D", 100) with self.assertRaises(KeyError): # insert the same edge with its previous weight graph.insert_edge("A", "D", 100) if __name__ == '__main__': unittest.main()
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self): self.len = 0 self.root = None def createBST(self, l): """ Time Complexity: O(n*log(n)) Space_Complexity: O(1) """ # update the length of the BST self.len = len(l) # check if the list is empty if len(l) < 1: return "" for ele in l: # check if there is a root if not self.root: self.root = Node(ele) # if the root exists, insert every element else: self.__insert_ele(self.root, ele) return self.inOrderTraversal() # private helper method to insert the elements in their right position def __insert_ele(self, start, val): if start.value < val: if start.right: self.__insert_ele(start.right, val) else: start.right = Node(val) elif start.value > val: if start.left: self.__insert_ele(start.left, val) else: start.left = Node(val) def search(self, val): """ Time Complexity: O(log(n)) Space_Complexity: O(1) """ start = self.root while start: if start.value == val: return True elif start.value > val: start = start.left else: start = start.right return False def searchRecursive(self, val): """ Time Complexity: O(log(n)) Space_Complexity: O(1) """ def __helper(val, root): if root: if root.value == val: return True elif root.value > val: return __helper(val, root.left) else: return __helper(val, root.right) else: return False return __helper(val, self.root) # inOrderTraversal returns the values of nodes in the tree as sorted list (ASC order) def inOrderTraversal(self): """ Time Complexity: O(n) Space_Complexity: O(1) """ traverse = [] f = self.__inOrderTraversal(self.root) for _ in range(self.len): traverse.append(next(f)) return traverse def __inOrderTraversal(self, root): if root: yield from self.__inOrderTraversal(root.left) yield root.value yield from self.__inOrderTraversal(root.right) # find the kth smallest element in the BST def kthSmallestInBST(self, root, K): f = self.__inOrderTraversal(root) for _ in range(K): ans = next(f) return ans # check if a binary search tree is valid or not def isValid(self, root): f = self.__inOrderTraversal(root) if root: pre = next(f) while True: try: new = next(f) if new <= pre: return False pre = new except: return True else: return True def rangeSumBST(self, root, L, R): ans = 0 stack = [root] while stack: node = stack.pop() if node: if L <= node.value <= R: ans += node.value if L < node.value: stack.append(node.left) if node.value < R: stack.append(node.right) return ans t = BST() t.createBST([15, 9, 21, 7, 13, 19, 23, 5, 11, 17]) print(t.rangeSumBST(t.root, 21, 23))
import matplotlib.pyplot as plt #PLOTDATA Plots the data points x and y into a new figure # PLOTDATA(x,y) plots the data points and gives the figure axes labels of # population and profit. def plotData(x, y): plt.ion() plt.figure() plt.plot(x, y, 'x') plt.axis([4, 24, -5, 25]) plt.xlabel("Population of City in 10,000s") # setting the x label as population plt.ylabel("Profit in $10,000s") # setting the y label
# a = 10 # b = 14 # 13으로 수정하면 첫 번째 조건문을 만족하지 않음 # if (a % 2 == 0) and (b % 2 == 0): # 첫 번째 조건문 # print('두 수 모두 짝수입니다.') # if (a % 2 == 0) or (b % 2 == 0): # 두 번째 조건문 # print('두 수 중 하나 이상이 짝수입니다.') a = 9 b = 14 if (a % 2 == 0) and (b % 2 == 0) : print('두 수 모두 짝수') if (a % 2 == 0) or (b % 2 == 0) : print('두 수 중 하나는 짝수')
import random print(''' --------------------------------------- The Random Number Guessing Game Begins! --------------------------------------- ''') scores = [] def start_game(): global scores randomNumber = random.randint(1, 10) attempts = 0 if scores: print(f"\n------ The HIGHSCORE is {min(scores)} ------") while True: attempts += 1 try: player_guess = input('Guess a number between 1 and 10: ') player_guess = int(player_guess) if player_guess < 1 or player_guess > 10: print("You must enter a number from 1 to 10.") continue elif player_guess < randomNumber: print("It's higher!") continue elif player_guess > randomNumber: print("It's lower!") continue except (ValueError, TypeError) as err: print("That's not a valid value. Try again.") print(f"({err})") else: print(f"\nYou got it! It took you {attempts} attempt(s) to guess the number {randomNumber}.") scores.append(attempts) player_response = input("Would you like to play again? [y]es/[n]o: ") if player_response.lower() in ('y', 'yes'): start_game() break # Kick off the program by calling the start_game function. start_game() print(''' ---------------------------- Game over. Hope you had fun! ---------------------------- ''')
#! /usr/bin/env python # -*- coding: utf-8 -*- def digitos(n): indice=1 while n>9: n=n/10 indice +=1 print indice a=input("ingrese el numero ") digitos(a)
#! /usr/bin/env python # -*- coding: utf-8 -*- def mayusculas (cadena): cont = 0 for i in cadena: if i != i.lower(): cont += 1 print "La cadena tiene "+ str(cont)+" mayusculas" a=raw_input("ingrese una palabra ") print mayusculas(a)
peso = float(input("Por favor informe seu peso: ")) altura = float(input("Por favor informe sua altura: ")) imc = float imc = peso / (altura * altura) if imc < 16.00: print("seu IMC é de: {:.2f} Categoria: Baixo peso Grau III".format(imc)) elif imc <= 16.99: print("seu IMC é de: {:.2f} Categoria: Baixo peso Grau II".format(imc)) elif imc <= 18.49: print("seu IMC é de: {:.2f} Categoria: Baixo peso Grau I".format(imc)) elif imc <= 24.99: print("seu IMC é de: {:.2f} Categoria: Peso ideal".format(imc)) elif imc <= 29.99: print("seu IMC é de: {:.2f} Categoria: Sobrepeso".format(imc)) elif imc <= 34.99: print("seu IMC é de: {:.2f} Categoria: Obesidade Grau I".format(imc)) elif imc <= 39.99: print("seu IMC é de: {:.2f} Categoria: Obesidade Grau II".format(imc)) else: print("seu IMC é de: {:.2f} Categoria: Obesidade Grau III".format(imc))
# import necassary packages import random class Product: """ Product class that takes name (mandatory), price (default=10), weight (default=20), flammability (default=0.5) """ def __init__(self, name, price=10, weight=20, flammability=0.5): """ This method is to initialize the class Product by taking in name, price, weight and flammability. """ self.name = str(name) self.price = int(price) self.weight = int(weight) self.flammability = float(flammability) self.identifier = random.randint(1000000, 9999999) def stealability(self): """ This method determines if a product is stealable or not. calculates the price divided by the weight, and then returns a message: if the ratio is less than 0.5 return "Not so stealable...", if it is greater or equal to 0.5 but less than 1.0 return "Kinda stealable.", and otherwise return "Very stealable!" """ if (self.price / self.weight) < 0.5: return "Not so stealable..." elif ((self.price / self.weight) >= 0.5) and ((self.price / self.weight) < 1.0): return "Kinda stealable." else: return "Very stealable!" def explode(self): """ This method determines if a product is flammability or not. calculates the flammability times the weight, and then returns a message: if the product is less than 10 return "...fizzle.", if it is greater or equal to 10 but less than 50 return "...boom!", and otherwise return "...BABOOM!!" """ if (self.flammability * self.weight) < 10: return "...fizzle." elif ((self.flammability * self.weight) >= 10) and ( (self.flammability * self.weight) < 50 ): return "...boom!" else: return "...BABOOM!!" class BoxingGlove(Product): """ Subclass BoxingGlove that inherits from Product class """ def __init__(self, name, price=10, weight=10, flammability=0.5): """ Signature to instantiate the class is the same as class Product i.e. pass name (mandatory) and other parameters are optional :param name: string :param price: default 10 :param weight: default 10 :param flammability: default 0.5 """ super().__init__(name, price, weight, flammability) def explode(self): """ This method to always return "...it's is a glove" """ return "...it's a glove" def punch(self): """ This method returns "That tickles." if the weight is below 5, "Hey that hurt!" if the weight is greater or equal to 5 but less than 15, and "OUCH!" otherwise """ if self.weight < 5: return "That tickles." elif (self.weight >= 5) and (self.weight < 15): return "Hey that hurt!" else: return "OUCH!"
# -*- coding: utf-8 -*- """ __title__ = '03 匿名函数_lambda_map_reduce_filter.py' __author__ = 'yangyang' __mtime__ = '2018.03.16' """ ''' python匿名函数:lambda 匿名函数作用:1.节省代码量。2.看着更优雅。 python: map(function,iterable,...) Python函数编程中的map()函数是将func作用于seq中的每一个元素,并将所有的调用的结果作为一个list返回。 reduce函数: 在Python 3里,reduce()函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里 用的话要 先引 from functools import reduce reduce函数的定义: reduce(function, sequence[, initial]) -> value function参数是一个有两个参数的函数,reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。 第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。 filter :过滤一个可迭代对象 ''' # lambda # square = lambda x,y:x**y # print(square(2,3)) # compare = lambda x,y:x*y if x<y else x - y # print(compare(3,2)) #map # square2 = map((lambda x:x**2),range(1,5)) # print(list(square2)) # reduce # # from functools import reduce # # print(reduce(lambda x,y:x*y,range(1,5),2)) # filter res = filter(lambda x:x*x%2==0,range(1,10)) print(list(res))
# -*- coding: utf-8 -*- # __title__ = '06 __repr__方法.py' # __author__ = 'yangyang' # __mtime__ = '2018.03.20' #__str__与__repr__ 是在类(对象)中对类(对象)本身进行字符串处理。 # __str__ 与 __repr__ 在我看来,__repr__ 是隐形显示的给开发人员看的,__str__ 是给用户看的 class A(object): def __str__(self): return "__str__" def __repr__(self): return "__repr__" a = A() b = A a # __repr__ ,在console 中显示,在py文件中不显示。 print(a) #__str__ print(b) # <class 'A'>
# -*- coding: utf-8 -*- """ __title__ = '02 属性查找与绑定方法.py' __author__ = 'ryan' __mtime__ = '2018/3/18' """ country = 'china' class UserInfo(object): address = 'SH' def __init__(self,name,sex,age): self.name = name self.sex = sex self.age = age def learn(self,country): print(" %s studying in %s"%(self.name,country)) def eat(self): print("%s is sleeping"%(self.name)) user1 = UserInfo('ryan','male',18) user2 = UserInfo('cherry','female',16) user3 = UserInfo('curry','male',20) # 1.查看对象的私有特征 print(user1.__dict__) print(user2.__dict__) print(user3.__dict__) # 2.查看类中的数据属性 # 结果得出,类中的数据属性的 memory ID 都是一样的。 print(UserInfo.address,id(UserInfo.address)) print(user1.address,id(user1.address)) print(user2.address,id(user2.address)) print(user3.address,id(user3.address)) # 3.查看类中的函数属性 # 类中的函数属性:是绑定给对象使用的,绑定到不同的对象是不同的绑定方法,对象调用绑定方式时,会把对象本身当作第一个传入,传给self print(user1.learn) user1.learn(country) print(user2.learn) # 结果: <bound method UserInfo.learn of <__main__.UserInfo object at 0x10b75bdd8>> # 结论: bound method 绑定方法。相当于不同对象调用一种功能,但是各自执行不同的方法。类中定义的函数,是绑定给对象使用的。那个对象在调用,那就是那个对象在使用这个功能。 # 4.对象属性的查找顺序 # 查找顺序:先从自己的名称空间里面找自己的属性,然后在从类里面找属性(类还包括父类等),类里面没有直接报错。 user1.country = 'USA' UserInfo.country = 'china' print(UserInfo.__dict__) print(user1.__dict__)
# l = [4,7,3,1,8,5,2,6] # # def bubble_sort(sample_list): # changed = True # while changed: # changed = False # for i in range(len(sample_list) - 1 ): # if sample_list[i+1] < sample_list[i]: # temp = sample_list[i+1] # sample_list[i+1] = sample_list[i] # sample_list[i] = temp # changed = True # #print(sample_list) # # bubble_sort(l) # l = [4,7,3,1,8,5,2,6] # # def insertion_sort(sample_list): # for i in range(len(sample_list) - 1): # if sample_list[i+1] < sample_list[i]: # temp = sample_list[i+1] # j = i # while j >= 0: # if temp < sample_list[j]: # sample_list[j+1] = sample_list[j] # if j > 0: # j -= 1 # else: # sample_list[j] = temp # break # else: # sample_list[j+1] = temp # break # # insertion_sort(l) # # print(l) #l = [4,7,3,1,8,5,2,6] # def selection_sort(sample_list): # for i in range(len(sample_list)): # min_value = sample_list[i] # min_index = i # # for j in range(i,len(sample_list)): # if sample_list[j] < min_value: # min_value = sample_list[j] # min_index = j # if min_index != i: # temp = sample_list[i] # sample_list[i] = min_value # sample_list[min_index] = temp # #print("i : " + str(i) + " min_index : " + str(min_index) + " min_value : " + str(min_value) + " sample_list : " + str(sample_list)) # # selection_sort(l) # # print(l) ## recursive implementation of selection sort # def selection_sort(sample_list,start): # min_value = sample_list[start] # min_index = start # for j in range(start,len(sample_list)): # if sample_list[j] < min_value: # min_value = sample_list[j] # min_index = j # if min_index != start: # temp = sample_list[start] # sample_list[start] = min_value # sample_list[min_index] = temp # if start == len(sample_list) - 1: # return # else: # selection_sort(sample_list,start+1) # # selection_sort(l,0) # # print(l) def merge_sort(sample_list): if len(sample_list) < 2: return sample_list[:] else: middle = int(len(sample_list)/2) left = merge_sort(sample_list[:middle]) right = merge_sort(sample_list[middle:]) #print("left : " + str(left) + " right " + str(right)) return merge(left,right) def merge(left,right): i,j = 0,0 result = [] while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 while i < len(left): result.append(left[i]) i += 1 while j < len(right): result.append(right[j]) j += 1 #print("result : " + str(result)) return result l = [4,7,3,1,8,5,2,6] sorted_l = merge_sort(l) print(sorted_l)
lst = [1, 2, [3, 4, [5, 6]], 7, 8] flat_lst = [] def remove_nesting(l): for ele in l: if isinstance(ele, list): remove_nesting(ele) else: flat_lst.append(ele) remove_nesting(lst) print(flat_lst)
# Write a function that accepts two strings as arguments and returns True if # either string occurs anywhere in the other, and False otherwise. def isIn(str1, str2): """ Assumes str1 and str2 are strings. Returns True if str1 is within str2 and vice versa. """ return str1 in str2 or str2 in str1
def triplets(numlist): # Square and sort the list sqrd = list(map(lambda x: x ** 2, numlist)) sqrd.sort() # For loop beginning at last element, and goes to 1st decrementing by 1 each time for i in range(len(sqrd)-1, 1, -1): # Set j to first element and k to element before i j = 0 k = i-1 # No need to check past each other, so only when j < k. Meet in middle approach while (j < k): # print(sqrd[i], sqrd[j], sqrd[k]) # If pythagorean triplet found return true or whatever interviewer wants as ret if (sqrd[j] + sqrd[k] == sqrd[i]): return True # Else no triplet found else: # if a^2 + b^2 too small increase j if (sqrd[j] + sqrd[k] < sqrd[i]): j = j + 1 # else a^2 + b^2 too large already so decrease k else: k = k - 1 # no triplet found, return false return False print(triplets([1, 5, 2, 3, 4, 6, 8])) print(triplets([4])) print(triplets([-3, 4, 5])) # Is this okay? If interviewer were to ask to handle this, modify sqrd func print(triplets(["a", "b", "c"])) # Is this okay? Should I gracefully handle bad input like this?
""" File Name: utils.py Description: This task involves writing tools for reading and processing the data, as well as defining data structures to store the data. The other tasks import and use these tools. Author: Himani Munshi Date: 12/10/2017 """ #TASK 0 from rit_lib import * Maindata = struct_type("Maindata", (str, 'country'), (list, 'values')) Metadata = struct_type("Metadata", (str, 'region'), (str, 'income')) CountryValue = struct_type("CountryValue", (str, 'country'), (float, 'value')) Range = struct_type("Range", (str, 'country'), (int, 'year1'), (int, 'year2'), (float, 'value1'), (float, 'value2')) def read_data(filename): """ This function reads the data and metadata files and stores them in two dictionaries, one for each. The key for both the dictionaries is the country code and the value for one dictionary is an object of data structure Maindata and for the other is an object of data structure Metadata. parameter used: filename - a string, giving the partial name of the data file returns two dictionaries (data structures) representing the data contained in the main data and metadata files """ path = "data/" + filename + "_data.txt" MainDct = {} #code -> Maindata (key -> value) MetaDct = {} #code -> Metadata (key -> value) #Building MainDct with open(path) as fd: fd.readline() #ignores the header for line in fd: temp = line.strip().split(",") #[country, code, values such as 50.1234 and so on] temp.pop() lst = [] #Building the second component of Maindata -> [(1960, 50.1234), (1961, 51.3555)...] year = 1960 for elt in temp[2:]: if elt != "": lst.append((year, float(elt))) else: lst.append((year, 0)) #unavailable life expectancy year += 1 MainDct[temp[1]] = Maindata(temp[0], lst) #Building MetaDct path = "data/" + filename + "_metadata.txt" with open(path) as fd: fd.readline() for line in fd: temp = line.strip().split(",") #[country code, region, income] MetaDct[temp[0]] = Metadata(temp[1], temp[2]) return MainDct, MetaDct def filter_region(data, region): """ This function filters data to only retain data for a specified region. Regardless of the specified region, this function always filters out the non-countries (larger groupings). parameters used: data - tuple containing two dictionaries MainDct and MetaDct region - a string specifying a particular region by which to filter returns two dictionaries (data structures) representing data that has been filtered to only retain data corresponding to the specified region """ f_MainDct = {} f_MetaDct = {} if region == "": return f_MainDct, f_MetaDct for key in data[1].keys(): if region == "all": if data[1][key].region != "": f_MetaDct[key] = data[1][key] f_MainDct[key] = data[0][key] if region == data[1][key].region: f_MetaDct[key] = data[1][key] f_MainDct[key] = data[0][key] return f_MainDct, f_MetaDct def filter_income(data, income): """ This function filters data to only retain data for a specified income category. Regardless of the specified income category, this function always filters out the non-countries (larger groupings). parameters used: data - tuple containing two dictionaries MainDct and MetaDct income - a string specifying a particular income category by which to filter returns two dictionaries (data structures) representing data that has been filtered to only retain data corresponding to the specified income category """ f_MainDct = {} f_MetaDct = {} if income == "": return f_MainDct, f_MetaDct for key in data[1].keys(): if income == "all": if data[1][key].income != "": f_MetaDct[key] = data[1][key] f_MainDct[key] = data[0][key] if income == data[1][key].income: f_MetaDct[key] = data[1][key] f_MainDct[key] = data[0][key] return f_MainDct, f_MetaDct def main(): """ This function: 1. reads the data and metadata files 2. prints the total number of entities in the data file 3. prints the total number of countries in the data file 4. prints a summary of the different regions and the number of countries included in each region 5. prints a summary of the different income categories and the number of countries included in each category 6. prompts the user to specify a region, and prints the names and country codes of all countries in that region; if the user enters an invalid region, prints an appropriate message and continues to the next requirement 7. prompts the user to specify an income category, and prints the names and country codes of all countries in that income category; if the user enters an invalid income category, prints an appropriate message and continues to the next requirement 8. enters a loop prompting the user for a country name or code - if the user enters a valid country name or country code, prints out the life expectancy values for that country - if the user enters an invalid country name or country code, prints an appropriate message - if the user hits enter to quit, exits the loop """ data = read_data("worldbank_life_expectancy") MainDct = data[0] MetaDct = data[1] print("Total number of entities:", str(len(MainDct))) #counting the number of countries countryCount = 0 for values in MetaDct.values(): if values.region != "": countryCount += 1 print("Number of countries/territories:", str(countryCount)) print() print("Regions and their country count:") region_summary = {} # key -> region, value -> CountryCount for value in MetaDct.values(): if value.region != "": if value.region in region_summary: region_summary[value.region] += 1 else: region_summary[value.region] = 1 for key in region_summary.keys(): print(key + ": " + str(region_summary[key])) print() print("Income categories and their country count:") income_summary = {} # key -> income, value -> CountryCount for value in MetaDct.values(): if value.region != "": if value.income in income_summary: income_summary[value.income] += 1 else: income_summary[value.income] = 1 for key in income_summary.keys(): print(key + ": " + str(income_summary[key])) print() region = input("Enter region name: ") flag = False print_dct = {} for key in MetaDct.keys(): if MetaDct[key].region == region: filtered_region = filter_region(data, region) print_dct[key] = filtered_region[0][key].country flag = True if flag == False: print("Region does not exist.") else: print("Countries in the '" + region + "' region: ") for key in print_dct.keys(): print(print_dct[key], " (", key, ")", sep = "") print() income = input("Enter income category: ") print_dct_filter = {} flag = False for key in MetaDct.keys(): if MetaDct[key].income == income: filtered_income = filter_income(data, income) print_dct_filter[key] = filtered_income[0][key].country flag = True if flag == False: print("Income category does not exist.") else: print("Countries in the '" + income + "' income category:") for key in print_dct_filter.keys(): print(print_dct_filter[key], " (", key, ")", sep = "") print() flag = False user_input = input("Enter name of country or country code (Enter to quit): ") while user_input != "": for key in MainDct.keys(): if user_input == key or user_input == MainDct[key].country: print("Data for " + user_input + ":") lst = MainDct[key].values flag = True for elt in lst: if elt[1] != 0: print("Year:", elt[0], " Life expectancy:", elt[1]) if flag == False: print("'" + user_input + "'" + "is not a valid country name or code") print() user_input = input("Enter name of country or country code (Enter to quit): ") if __name__ == '__main__': main()
""" 3. Совместить валидацию email и валидацию пароля и вместо принтов райзить ошибки если пароль или email не подходит по критериям (критерии надежности пароля можно брать с прошлого ДЗ или придумать новые). Ошибки брать на выбор """ # PASSWORD AND EMAIL VALIDATOR # ------------------------------------------ # EMAIL VALIDATOR email: str = input('Input email: ') if '@' not in email: raise SyntaxError("Email must include '@'-symbol!") elif '.' not in email: raise SyntaxError("Email must include at least one '.'-symbol!") at_sign_index = email.index('@') for sign in {'.', '@'}: if email[at_sign_index + 1] == sign or email[at_sign_index - 1] == sign: raise RuntimeError("ERROR: '.' can't stand next to '@'") elif email[-1] == sign or email[0] == sign: raise RuntimeError("ERROR: '.' or '@' can't be the first or the last symbol!") print(f"'{email}' is ok. Good job!") # PASSWORD VALIDATOR passw: str = input('Please input new password: ') if passw: if len(passw) < 8: raise RuntimeError('Strong password must consist of at least 8 characters!') elif passw.isalpha() or passw.isnumeric(): raise SyntaxError('Strong password must be a mixture of letters and numbers!') elif passw.isalnum(): raise SyntaxError('Strong password must include at least one special character, e.g. ! @ # ? ]') elif passw.islower(): raise SyntaxError('Strong password must include at least one uppercase letter!') elif passw.isupper(): raise SyntaxError('Strong password must include at least one lowercase letter!') else: print(f"'{passw}' is a strong-enough password. Good job!") else: print("You didn't enter any symbol!")
from collections import Counter """ 3. Реализовать функцию, которая принимает строку и расделитель и возвращает словарь {слово: количество повторений} (частотный словарь) """ def converter(str1: str, sep1: str): dict1 = dict(Counter(str1.split(sep1))) return dict1 my_str = input('String ') delimiter = input('delimiter ') print(converter(my_str, delimiter))
""" Создать класс воина, создать 2 или больше объектов воина с соответствующими воину атрибутами. Реализовать методы, которые позволять добавить здоровья, сменить оружие. Реализовать возможность драки 2х воинов с потерей здоровья, приобретения опыта. Следует учесть: - у воина может быть броня - здоровье не может быть меньше 0 - броня не может быть меньше 0 - здоровье не тратится пока броня не 0 Было бы неплохо добавить возможность воину носить несколько видов оружия и при сломаном текущем заменить его (опционально) """ from random import randint, choice class Weapon: def __init__(self, name, power): self.name = name self.power = power class Warrior: def __init__(self, weapon: Weapon, name: str, health: int): self.weapon = weapon self.name = name self.health = health self.armor = 0 self.experience = 0 self.status = 'alive' def add_health(self, value): if self.status == 'dead': print(f"{self.name} is dead! Sorry, we can't change it!") return self.health += value if self.health < 0: self.health = 0 self.status = 'dead' print(f'{self.name} is dead!') def add_experience(self, value): self.experience += value self.add_weapon_power() def add_weapon_power(self): # увеличиваем мощность оружия пропорционально опыту воина if self.experience > 9: self.weapon.power = round(self.weapon.power * 1.6) elif self.experience > 6: self.weapon.power = round(self.weapon.power * 1.4) elif self.experience > 3: self.weapon.power = round(self.weapon.power * 1.2) def change_weapon(self, weapon): self.weapon = weapon self.add_weapon_power() def add_armor(self, value): if self.status == 'dead': print(f"{self.name} is dead! Sorry, we can't change it!") return self.armor += value if self.armor < 0: self.add_health(self.armor) self.armor = 0 def hit_another(self, another_warrior): if self.status == 'dead': print(f"{self.name} is dead! He can't hit anybody!") return if another_warrior.status == 'dead': print(f"{another_warrior.name} is already dead! Don't hit him!") return if another_warrior.armor: another_warrior.add_armor(-self.weapon.power) else: another_warrior.add_health(-self.weapon.power) if another_warrior.status == 'dead': print(f'!!!!! {self.name} won !!!!!') if another_warrior.experience: self.add_experience(another_warrior.experience) else: self.add_experience(1) if another_warrior.weapon.power > self.weapon.power: self.change_weapon(another_warrior.weapon) print(f'{self.name} got {self.weapon.name}!') def random_choose_weapon(): weapon_list = [] for i in range(50): weapon_list.append(Weapon( name='Weapon-' + str(i), power=randint(5, 50) )) return choice(weapon_list) def main_fighting_area(): warrior1 = Warrior(name='Oleg', health=randint(80, 200), weapon=random_choose_weapon()) warrior1.add_armor(randint(1, 40)) warrior1.add_experience(randint(0, 10)) warrior2 = Warrior(name='Vasyl', health=randint(80, 200), weapon=random_choose_weapon()) warrior2.add_armor(randint(10, 40)) warrior2.add_experience(randint(0, 10)) counter = 1 print(f'\nInitial status:') print(f'{warrior1.name} H={warrior1.health} A={warrior1.armor} E={warrior1.experience} WP={warrior1.weapon.power}\t\t' f'{warrior2.name} H={warrior2.health} A={warrior2.armor} E={warrior2.experience} WP={warrior2.weapon.power}\n') while warrior1.status == 'alive' and warrior2.status == 'alive': print(f'Round {counter}') warrior1.hit_another(warrior2) warrior2.hit_another(warrior1) print(f'{warrior1.name} H={warrior1.health} A={warrior1.armor} E={warrior1.experience} WP={warrior1.weapon.power}\t\t' f'{warrior2.name} H={warrior2.health} A={warrior2.armor} E={warrior2.experience} WP={warrior2.weapon.power}\n') counter += 1 main_fighting_area()
# -*- coding: utf-8 -*- """ Created on Tue Sep 27 20:38:13 2016 @author: changsongdong To show a basic convolutional neural network built using TensorFlow """ import tensorflow as tf import numpy as np from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt sess = tf.InteractiveSession() lr = 0.1 # learning rate batchsize = 506 # mini-batch size epoch = 3000 # training epochs display = 50 # display after every ten epochs # sigmoid: # lr = 0.01, batchsize = 506, epoch = 2000, train acc = 0.411067, test acc=0.418605 # lr = 0.01, batchsize = 506, epoch = 3000, train acc = 0.467391, test acc=0.433653 # lr = 0.1, batchsize = 506, epoch = 2000, train acc = 0.405731, test acc=0.435021 # lr = 0.1, batchsize = 506, epoch = 3000, train acc = 0.562055, test acc=0.514364 # add 3th conv layer:lr = 0.1, batchsize = 506, epoch = 3000, train acc = 0.678261, test acc = 0.622435 # add 4th conv layer:lr = 0.1, batchsize = 506, epoch = 3000, train acc = 0.731028,test acc =0.64827 # first hidden layer kernelsize 5*1 train acc = 0.528063, test acc = 0.525308 def get_data(set_type): """Get data from files and storage them in an array. set_type the type of data set you want to build, including train dataset, dev dataset and eval dataset """ data_path = {'train': 'train/lab/hw2train_labels.txt', 'dev': 'dev/lab/hw2dev_labels.txt', 'eval': 'eval/lab/hw2eval_labels.txt'} #load the label file contents into a array label_array = np.loadtxt(data_path[set_type], dtype='string') labelset = [int(i) for i, j in label_array] j = 0 total_dataset = [] #build the data set and label set for i in range(len(label_array)): with open(label_array[i][1]) as data_file: data = data_file.readlines() if len(data) < 70: # delete label from label_set del labelset[j] continue else: dataset = [] for i in np.arange(70): dataset.extend(data[i].split()) total_dataset.append(dataset) j += 1 #labelset = np.asarray(labelset) label_set = np.zeros([len(labelset), 9]) for i in range(len(label_set)): label_set[i][labelset[i]] = 1 data_set = np.zeros([len(total_dataset), 16 * 70]) for i in range(len(data_set)): data_set[i] = total_dataset[i] return data_set, label_set, labelset #return the shuffled data set and label set train_data, train_label, trainlabelset = get_data('train') test_data, test_label, testlabelset = get_data('dev') #train_data = np.loadtxt("train_data") #train_label = np.loadtxt("train_label") #test_data = np.loadtxt("test_data") #test_label = np.loadtxt("test_label") num_examples = len(train_data) # number of total training samples # dataset x and label set y x = tf.placeholder(tf.float32, [None, 1120]) y = tf.placeholder(tf.float32, [None, 9]) t = tf.Variable(testlabelset) # weight initialization function def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) # layer definition def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID') x_input = tf.reshape(x, shape=[-1, 70, 16, 1]) # reshape input # first hidden layer parameters initialization W_conv1 = weight_variable([5, 16, 1, 8]) b_conv1 = bias_variable([8]) o_conv1 = tf.nn.sigmoid(conv2d(x_input, W_conv1) + b_conv1) # second hidden layer parameters initialization W_conv2 = weight_variable([5, 1, 8, 9]) b_conv2 = bias_variable([9]) o_conv2 = tf.nn.sigmoid(conv2d(o_conv1, W_conv2) + b_conv2) # multi-class logistic regression (softmax) a_output = tf.reduce_sum(o_conv2, 1) a_flat = tf.reshape(a_output, [-1, 9]) y_hat=tf.nn.softmax(a_flat) # cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_hat), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(lr).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_hat,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess.run(tf.initialize_all_variables()) for i in range(epoch): # shuffle data in each epoch perm = np.arange(num_examples) np.random.shuffle(perm) train_data = train_data[perm] train_label = train_label[perm] if i % display == 0: train_accuracy = accuracy.eval(feed_dict={x: train_data, y: train_label}) print("step %d, training accuracy %g"%(i, train_accuracy)) # mini-batch gradient descent for start in np.arange(0, num_examples, batchsize): data_batch = train_data[start:start+batchsize] label_batch = train_label[start:start+batchsize] train_step.run(feed_dict={x: data_batch, y: label_batch}) print("test accuracy %g"%accuracy.eval(feed_dict={x: test_data, y: test_label})) # ============== draw confusion matrix ============== prediction=tf.argmax(y,1) y = prediction.eval(feed_dict={y: test_label}) prediction=tf.argmax(y_hat,1) y_pred = prediction.eval(feed_dict={x: test_data}) matrix = confusion_matrix(y, y_pred) index = ['0', '1', '2', '3', '4', '5', '6', '7', '8'] np.set_printoptions(precision=2) plt.figure() plot_confusion_matrix(cm, index, title='Confusion Matrix') plt.show()
"""A cli memory game board. A representation of a memory game board and functions to interact with it. """ import string from random import shuffle class Board: """A memory game board.""" def __init__(self): self.rows = 4 self.columns = 4 self.bg_board = [] self.fg_board = [] self.games_history = {'games': 0} def set_board_size(self, columns, rows): """Set the game board's number of columns and rows. Will raise UserWarning in input params are invalid - not even number of cells or not between 4-52 cells. :param columns: int number of columns. :param rows: int number of rows. :return: None. """ if rows * columns < 4: raise UserWarning(f'Game bored mast have at least 4 cells ({rows} X {columns} = {rows * columns}).') if rows * columns % 2 != 0: raise UserWarning(f'Game bored mast have an even number of cells ({rows} X {columns} = {rows * columns}).') if rows * columns / 2 > len(string.ascii_uppercase): raise UserWarning(f'Game bored mast not have more then {len(string.ascii_uppercase) * 2} cells \ ({rows} X {columns} = {rows * columns}).') self.rows = rows self.columns = columns def new_board(self): """Set (or reset) game bored representation to starting position. Set foreground and background boards - foreground with asterisks, background with randomise placed pairs of letters. :return: None """ self.fg_board = ['*' for _ in range(self.columns * self.rows)] self.bg_board = [string.ascii_uppercase[i] for i in range(int(self.columns * self.rows / 2))] self.bg_board = self.bg_board + self.bg_board shuffle(self.bg_board) def coordinates_to_index(self, col, row): """Convert from 2d coordinates to the 1d index on game's board. :param col: int column coordinate. :param row: int row coordinate. :return: int cell 1D index. """ return self.columns * row + col def is_game_over(self): """Check if game is over (all pairs are revealed - no more moves). :return: True if game is over. False otherwise. """ return False if '*' in self.fg_board else True def is_unknown(self, cell): """Check if given cell index is unknown - no revealed yet. :param cell: int cell index. :return: True if unknown. False otherwise. """ return True if '*' == self.fg_board[cell] else False def is_match(self, cell1, cell2): """Check if the 2 given cell indexes are holding a matching pair. :param cell1: int cell index. :param cell2: int cell index. :return: True if matching pair. False otherwise. """ return True if self.bg_board[cell1] == self.bg_board[cell2] else False def reveal(self, cell): """Reveal a cell on the foreground boeard and display (print) it. :param cell: int cell index. :return: None. """ self.fg_board[cell] = self.bg_board[cell] self.display() def unreveal(self, cell1, cell2): """Cover given cells on the foreground boeard and display (print) it. :param cell1: int cell index. :param cell2: int cell index. :return: None. """ self.fg_board[cell1] = '*' self.fg_board[cell2] = '*' self.display() def display(self): """Printout the bored with the current cells shapes and coordinates. :return: None """ print(' ' + ' '.join([str(i) for i in range(self.columns)])) for y in range(self.rows): print(str(y) + ' ' + ' | '.join(self.fg_board[y * self.columns:y * self.columns + self.columns]) + ' ') if self.rows != y + 1: print(' ---' + '+---' * (self.columns - 1)) print() def add_game_to_history(self, turns): """Add this game to the board's game history. 1. Increment number of games. 2. For current game's number of shapes, add/update numbers of turns to win if previously nonexistent or bigger than current one. :param turns: int number of turns to win current board. :return: None. """ self.games_history['games'] += 1 number_of_shapes = str(int(self.columns * self.rows / 2)) if number_of_shapes not in self.games_history or self.games_history[str(number_of_shapes)] > turns: self.games_history[str(number_of_shapes)] = turns def print_games_history(self): """Display board's games history. print a summery of all games played on this board: * Number of games played. * Best game for each number of shapes played (minimum number of turns). :return: None. """ print(f"You have played {self.games_history['games']} game{'' if 1 == self.games_history['games'] else 's'}.") print('Best games:') for shapes in self.games_history: if 'games' == shapes: continue print(f'\t{shapes} shapes board: {self.games_history[shapes]} turns.')
import math import os import random import re import sys def climbingLeaderboard(scores, alice): scores = list(set(scores)) scores.sort(reverse=True) j = len(scores)-1 ranks = [] for i in alice: if i not in scores: while scores[j] < i and j >= 0: j -= 1 scores.insert(j+1, i) ranks.append(scores.index(i)+1) else: temp = scores.index(i)+1 ranks.append(temp) j = temp return ranks if __name__ == '__main__': scores_count = int(input()) scores = list(map(int, input().rstrip().split())) alice_count = int(input()) alice = list(map(int, input().rstrip().split())) result = climbingLeaderboard(scores, alice) for i in result: print(i)
def findRotationCount(array): size = len(array) for i in range(size-1): if array[i+1]<array[i]: return i+1 return 0 array = [7, 9, 11, 12, 5] count = findRotationCount(array) if count!=0: print("Array should be rotated",count,"clockwise times to arrange it in sorted manner") else: print("Array is already in sorted manner.")
def reverseArray(arr, start, end): while (start < end): arr[start], arr[end] = arr[end], arr[start] start = start + 1 end = end - 1 # Function to right rotate arr # of size n by d def rightRotate(arr, d, n): reverseArray(arr, 0, n - 1) reverseArray(arr, 0, d - 1) reverseArray(arr, d, n - 1) arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] n = len(arr) k = 3 print("Initially:\n", arr) rightRotate(arr, k, n) print("After Rotation:\n", arr) print() # I dont know anything about this. # This code runs perfect but I dont know how. # Credit: Geeks for Geeks
""" Given 2 strings A and B, and a character X. You have to insert string B into string A in such a way that after you have performed the join operation, the resulting string contains a substring that contains only character X of length len. Find the maximum possible value of len. You are allowed to split the string A at index any you want and insert string B. It is not necessary to split the string A. Please note that you are not allowed to split the string B. - NOTE: A substring is a contiguous sequence of characters within a string. The list of all substrings of the string "apple" would be "apple", "appl", "pple", "app", "ppl", "ple", "ap", "pp", "pl", "le", "a", "p", "l", "e", "". Input Format The first line of input contains T, the number of test cases. For each test case, there will be 3 separate lines. The first line will contain String A, the second line will contain String B and the third line will contain a single character X Constraints 1 ≤ T ≤ 103 1 ≤ length of String A,B ≤ 104 Both String A & B and Character X will contain lower case alphabets. Output Format For each Test Case print a single line denoting len which is the maximum length of the substring containing only character X Sample Input 0 5 omvdvanhh hveohvykr h dserkta uxhukbl c nvfpcbgsl fpbrofonl p hkqxm ofnmh m oujotoie eeexmiee e Sample Output 0 3 0 1 1 4 Explanation 0 For the First Test Case, we do not split the first string and join the second string at the end of the first string, which gives us a substring containing only 'h' having length 3. For the second test case, the character 'c' is not present in any of the strings, hence the answer is 0. """ t = int(input()) while(t>0): a = input() b = input() c = input() # print(a,b,c) index = a.rfind(c) res = a[0:index+1] + b + a[index+1:] count = 0 counting = False for i in range(len(res)): if res[i]==c: count+=1 counting = True if res[i]!=c and counting: break print(count) t-=1
# check uppercase , lowercase, digits and special character in a array up=0 lo=0 d=0 s=0 array= input("Enter the value you want to check: ") x=len(array) for i in range (0,x): if(array[i].isupper()): print("UPPERCASE CHARACTERS : ",array[i]) up+=1 elif(array[i].islower()): print("\n LOWERCASE CHARACTERS : ",array[i]) lo+=1 elif(array[i].isdigit()): print("\n DIGITS : ",array[i]) d+=1 else: print("\n special character: ",array[i]) s+=1 #Space is counted in this print("Upper case count: ",up) print("Lower case count: ",lo) print("Number count: ",d) print("Special character count: ",s)
from abc import ABC, abstractmethod class Aircraft(ABC): @abstractmethod def fly(self): pass @abstractmethod def land(self): pass class Jet(Aircraft): def fly(self): print("My jet is flying") def land(self): print("My jet has landed") jet1 = Jet() jet1.fly() jet1.land() num_epochs = 10 #1000 epochs learning_rate = 0.001 #0.001 lr input_size = 51 #number of features hidden_size = 2 #number of features in hidden state num_layers = 1 #number of stacked lstm layers num_classes = 1 #number of output classes lstm1 = LSTM1(num_classes, input_size, hidden_size, num_layers, x_train_tensors_final.shape[1]) #our lstm class criterion = torch.nn.MSELoss() # mean-squared error for regression optimizer = torch.optim.Adam(lstm1.parameters(), lr=learning_rate) #Training process for epoch in range(num_epochs): outputs = lstm1.forward(x_train_tensors_final) #forward pass optimizer.zero_grad() #caluclate the gradient, manually setting to 0 # obtain the loss function loss = criterion(outputs, y_train_tensors) loss.backward() #calculates the loss of the loss function optimizer.step() #improve from loss, i.e backprop if epoch % 1 == 0: print("Epoch: %d, loss: %1.5f" % (epoch, loss.item())) torch.save(lstm1, './model.pth') rand_midi = random_piano() rand_seq = piano2seq(rand_midi) rand_seq = rand_seq[0:51] rand_seq = Variable(torch.Tensor(rand_seq)) #converting to Tensors rand_seq = torch.reshape(rand_seq, (1,rand_seq.shape[0])) rand_seq = mm.transform(rand_seq) rand_seq = Variable(torch.Tensor(rand_seq)) #converting to Tensors rand_seq = torch.reshape(rand_seq, (1,1,rand_seq.shape[1])) print(rand_seq.shape) seq_predict = lstm1(rand_seq)#forward pass seq_predict = seq_predict.data.numpy() #numpy conversion print(seq_predict) ########################################## num_epochs = 10 #1000 epochs learning_rate = 0.001 #0.001 lr input_size = 51 #number of features hidden_size = 2 #number of features in hidden state num_layers = 1 #number of stacked lstm layers num_classes = 1 #number of output classes root = './' midi_load = process_midi_seq(datadir=root) train_size = int(0.8*midi_load.shape[0]) train_seq_data = midi_load[0:int(train_size),:] test_seq_data = midi_load[int(train_size):,:] train_labels = np.ones(train_seq_data.shape[0]) test_labels = np.ones(test_seq_data.shape[0]) for i in range(train_seq_data.shape[0]): rand_midi = random_piano() rand_seq = piano2seq(rand_midi) rand_seq = rand_seq[0:51] train_seq_data = np.vstack((train_seq_data, rand_seq)) train_labels = np.append(train_labels,0) for i in range(test_seq_data.shape[0]): rand_midi = random_piano() rand_seq = piano2seq(rand_midi) rand_seq = rand_seq[0:51] test_seq_data = np.vstack((test_seq_data, rand_seq)) test_labels = np.append(test_labels,0) mm = MinMaxScaler() train_seq_data = mm.fit_transform(train_seq_data) test_seq_data = mm.fit_transform(test_seq_data) x_train_tensors = Variable(torch.Tensor(train_seq_data)) x_test_tensors = Variable(torch.Tensor(test_seq_data)) y_train_tensors = Variable(torch.Tensor(train_labels)) y_test_tensors = Variable(torch.Tensor(test_labels)) x_train_tensors_final = torch.reshape(x_train_tensors, (x_train_tensors.shape[0], 1, x_train_tensors.shape[1])) x_test_tensors_final = torch.reshape(x_test_tensors, (x_test_tensors.shape[0], 1, x_test_tensors.shape[1])) crt = Critic(1) crt.train(x_train_tensors)
print("hello") # 定义一个函数 用 def def my_abs(x): if x >= 0: return x else: return -x # 可以函数引用传递给一个变量 然后变量当函数用(闭包) a = my_abs print(a(10)) n1 = 255 n2 = 1000 print(hex(n1)) print(hex(n2))
# written by Pasha Pishdad # Student ID: 40042599 # Assignment 1 # Driver from Assignment1Functions import * if __name__ == "__main__": run = True while run: # calling the function threshold_and_grid_size() to get the threshold and grid size threshold_and_grid_size() # calling the function number_crimes("crime_dt.shp") to create coordinates based on the shape file n_crimes = number_crimes("crime_dt.shp") # calling the function gridify(n_crimes) to make the initial grid gridify(n_crimes) # calling the function solve() to find the shortest path solve() # check to see if the user want to exit or continue running = input("Press 'Y' or 'y' to continue, press any other key to exit: \n") run = running.upper() == 'Y'
"""CSC108: Fall 2021 -- Assignment 1: Unscramble This code is provided solely for the personal and private use of students taking the CSC108 course at the University of Toronto. Copying for purposes other than this use is expressly prohibited. All forms of distribution of this code, whether as given or with any changes, are expressly prohibited. All of the files in this directory and all subdirectories are: Copyright (c) 2021 Michelle Craig, Tom Fairgrieve, Sadia Sharmin, and Jacqueline Smith. """ # Move constants SHIFT = 'S' FLIP = 'F' CHECK = 'C' # Constant for hint functions HINT_MODE_SECTION_LENGTH = 3 def get_section_start(section_num: int, section_len: int) -> int: """Return the starting index of the section corresponding to section_num if the length of a section is section_len. >>> get_section_start(1, 3) 0 >>> get_section_start(2, 3) 3 >>> get_section_start(3, 3) 6 >>> get_section_start(4, 3) 9 """ return # Write the rest of your functions here def is_valid_move (move_input: str) -> bool: """Return valid move move_input >>> is_valid_move('S') True >>> is_valid_move('G') False >>> is_valid_move('C') True """ if move == SHIFT or move == FLIP or move == CHECK: return true # def get_num_sections (answer_string: str, section_num: int) -> int: """Return number of sections section_num in the answer answer_string """ return # def is_valid_section (valid_section: int, answer_string: str, section_length: int) -> bool: """Return """ return # def check_section (game_state: str, answer_string: str, valid_section: int, section_length: int) -> bool: """Return the """ return # def change_section (game_sate: str, applied_move: str, section_num: int, section_length: int) -> str: """Return updated game state game_state after applying """ return # def section_needs_flip (game_state: str, answer_string: str, valid_section_num: int) -> bool: """Return """ return # def get_move_hint (game_state: str, answer_string: str, scrambled_section_num: int) -> str: """Return a move that will help user come closer to the solving the section with the index scrambled_section_num in the str game_state coming to the answer answer_string >>>get_move_hint('rde') """ return
''' Calc 2.1 can do all the functions Calc 2 can do, but also Trig and last num equations This part is the main script Was other part of my OOP version of calc ''' from Calc.CalcCore import * while True: op = int(input(" [Addition] [Subtraction] [Multiplication] [Division]\n" " 0 1 2 3\n" " [Exponent] [Square Root] [Squared] [Sine] [Cosine] \n" " 4 5 6 7 8\n" "[Tangent] [Quadratic Factoring] [Synthetic Division] [Last Num]\n" " 9 10 11 12\n" ">: ")) if op <= 4: calc = SimpleCalcCore(op, float(input("Enter first num: ")), float(input("Enter second num: "))) print(calc.solve()) elif 5 <= op <= 6: calc = SimplerCalcCore(op, float(input("Enter num: "))) print(calc.solve()) elif op == 10: calc = SimpleRootCore(op, float(input("Enter first num: ")), float(input("Enter second num: ")), float(input("Enter third num: "))) print(calc.solve()) elif op == 11: top_power = int(input("Enter highest power in equation: ")) nums = [] for i in range(top_power): nums.append(float(input("Num: "))) calc = SyntheticDivCore(op, float(input("Enter divisor: ")), top_power, nums) print(calc.solve()) elif 7 <= op <= 9: calc = TrigCore(op, float(input("Enter number: ")), float(input("Enter multiplier: "))) print(calc.solve()) elif op == 12: if calc.solve() == float: try: last_num = calc.solve() new_op = int(input(" [Addition] [Subtraction] [Multiplication] [Division]\n" " 0 1 2 3\n" "[Exponent] [Square Root] [Squared] [Sine] [Cosine] [Tangent] \n" " 4 5 6 7 8 9\n" " [Back]\n" " 10\n" ">: ")) if new_op <= 4: calc = SimpleCalcCore(new_op, last_num, float(input("Enter number: "))) print(calc.solve()) elif 5 <= new_op <= 6: calc = SimplerCalcCore(new_op, last_num) print(calc.solve()) elif 7 <= new_op <= 9: calc = TrigCore(new_op, last_num, float(input("Enter multiplier: "))) elif new_op == 10: pass else: print("Error: Not a listed operator") except NameError: print("There is no last number") else: print("Last answer is not a single number") elif op == 13: print(last_num) else: print("Error: Not a listed operator")
""" 8-1. Message: Write a function called display_message() that prints one sentence telling everyone what you are learning about in this chapter. Call the function, and make sure the message displays correctly. """ def display_message(): """Display what I am learning about in the current chapter, `Functions`.""" print("I am learning what a function is in Python.") display_message()
""" 9-1. Restaurant: Make a class called Restaurant. The __init__() method for Restaurant should store two attributes: a restaurant_name and a cuisine_type. Make a method called describe_restaurant() that prints these two pieces of information, and a method called open_restaurant() that prints a message indicating that the restaurant is open. Make an instance called restaurant from your class. Print the two attributes individually, and then call both methods. """ class Restaurant: """A simple attempt to model a restaurant.""" def __init__(self, name, cuisine): "Initialize name and cuisine attributes." super().__init__() self.name = name self.cuisine = cuisine def describe(self): """Display the name of the restaurant and the cuisine it serves.""" print(f"Our restaurant {self.name} provides {self.cuisine} food.") def open(self): """Announce the opening of the restaurant.""" print("The restaurant is open.") tonito = Restaurant("Tonito", "Latin") tonito.describe() tonito.open()
""" 5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3. • Store the numbers 1 through 9 in a list. • Loop through the list. • Use an if-elif-else chain inside the loop to print the proper ordinal ending for each number. Your output should read "1st 2nd 3rd 4th 5th 6th 7th 8th 9th", and each result should be on a separate line. """ numbers = list(range(1, 10)) for number in numbers: if number == 1: print("1st") elif number == 2: print("2nd") elif number == 3: print("3rd") elif number == 4: print("4th") elif number == 5: print("5th") elif number == 6: print("6th") elif number == 7: print("7th") elif number == 8: print("8th") elif number == 9: print("9th")
""" 7-1. Rental Car: Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as “Let me see if I can find you a Subaru.” """ car_brand = input("What kind of rental car would you like? ") print(f"Let me see if I can find you a {car_brand}")