text
stringlengths
37
1.41M
import pandas as pd from keras.utils.np_utils import to_categorical def load_train(): return pd.read_csv('train.csv') def load_test(): return pd.read_csv('test.csv') def separate_train(train): Y_train = train['label'] X_train = train.drop(labels=['label'], axis=1) return (X_train, Y_train) def preprocess_input(X, Y): X = normalize(X) X = reshape(X) Y = encode_to_one_hot_vector(Y) return (X, Y) def normalize(X): return X.astype('float32') / 255 def reshape(X): return X.values.reshape(-1, 28, 28, 1) def encode_to_one_hot_vector(Y): return to_categorical(Y, num_classes=10)
''' Created on 2020. 8. 7. @author: GDJ24 ''' def calc(a, b, c) : if c == "+" : return a+b elif c == "-" : return a-b elif c == "*" : return a*b elif c == "/" : return a//b oper = input("연산자를 선택하세요. (+, -, *, /)") var1 = int(input("첫번째 수를 입력하세요.")) var2 = int(input("두번째 수를 입력하세요.")) res = calc(var1, var2, oper) print("계산: %d %s %d = %d" % (var1, oper, var2, res))
''' Created on 2020. 8. 7. @author: GDJ24 ''' def getSum(l) : sum = 0 for i in range(0, len(list)) : sum += list[i] return sum() def getMean(l) : sum = 0 for i in range(0, len(list)) : sum += list[i] return sum/len(list) list = [2,3,3,4,4,5,5,6,6,8,8] print("list의 값의 합: ",getSum(list)) print("list값의 평균: ",getMean(list)) tp = (2,3,3,4,4,5,5,6,6,8,8) print("tp의 값의 합: ",getSum(tp)) print("tp값의 평균: ",getMean(tp))
''' Created on 2020. 8. 7. @author: GDJ24 ''' def coffee_machine(button) : print() print("#1 뜨거운 물 준비") print("#2 종이컵 준비") if button == 1 : print("#3 보통커피를 탄다.") elif button == 2 : print("#3 설탕커피를 탄다.") elif button == 3 : print("#3 블랙커피를 탄다.") else : print("#3 커피 종류 없음") print("#4 물을 붓는다.") coffee = int(input("커피 종류를 입력하세요.(1. 보통, 2. 설탕, 3. 블랙)")) coffee_machine(coffee)
''' Created on 2020. 8. 11. @author: GDJ24 ''' class Car : color = "" speed = 0 num = 0 count = 0 #생성자 def __init__(self): self.speed = 0 # 인스턴스 변수 Car.count += 1 # 클래스 변수 self.num = Car.count # 인스턴스 변수 def printMessage(self): print("색상:%s, 속도:%dkm/h, 번호:%d, 생산번호:%d" % (self.color,self.speed,self.num, Car.count)) mycar1, mycar2 = None, None mycar1 = Car() # 객체화 mycar1.speed = 30 mycar1.printMessage() print() mycar2 = Car() # 객체화 mycar2.speed = 50 mycar2.printMessage() print() print("생산번호: %d" % (mycar1.count))
class IntComputer: def __init__(self, code, in_sequence=[]): """ This builds a new IntComputer object. `code` is a list of integers representing the code that the IntComputer should execute. `in_sequence` is a list of integer inputs that will be sequenctially supplied to the computer each time an input instruction is encountered. Methods are available should you wish to supply additional input after execution as started. This parameter is optional. """ self.code = { i: code[i] for i in range(len(code)) } self.instruction_pointer = 0 self.relative_base = 0 self.in_sequence = in_sequence self.in_index = 0 def __getMode(self, offset): return self.code[self.instruction_pointer] // (10 ** (1+offset)) % 10 def __get(self, offset): address = [ self.code[self.instruction_pointer + offset], self.instruction_pointer + offset, self.relative_base + self.code[self.instruction_pointer + offset] ][ self.__getMode(offset) ] assert address >= 0 return self.code.get(address, 0) def __write(self, offset, value): assert type(value) == type(0) position = self.instruction_pointer + offset assert position >= 0 address = [ self.code[position], -1, self.relative_base + self.code[position] ][ self.__getMode(offset) ] assert address >= 0 self.code[address] = value def full_run(self): """ Runs a computer until it stops. Returns a list of the outputs. """ outs = [] value = self.run() while value != None: outs.append(value) value = self.run() return outs def add(self, value): """ Adds a single value to the input stream. """ assert type(value) == type(0) self.in_sequence.append(value) def run(self): """ Runs a computer until it stops or it outputs any data. The internal state of the computer is kept so that this function can be called again to resume execution. This will return a single output upon an output instruction or it will return None. None represents the conclusion of the program's execution. """ while self.code[self.instruction_pointer] != 99: op = self.code[self.instruction_pointer] % 100 if op == 1: self.__write(3, self.__get(1) + self.__get(2)) self.instruction_pointer += 4 if op == 2: self.__write(3, self.__get(1) * self.__get(2)) self.instruction_pointer += 4 if op == 3: assert self.in_index < len(self.in_sequence) self.__write(1, self.in_sequence[self.in_index]) self.in_index += 1 self.instruction_pointer += 2 if op == 4: value = self.__get(1) self.instruction_pointer += 2 return value if op == 5: next_instruction_pointer = self.instruction_pointer + 3 if self.__get(1) != 0: next_instruction_pointer = self.__get(2) self.instruction_pointer = next_instruction_pointer if op == 6: next_instruction_pointer = self.instruction_pointer + 3 if self.__get(1) == 0: next_instruction_pointer = self.__get(2) self.instruction_pointer = next_instruction_pointer if op == 7: valueToStore = 0 if self.__get(1) < self.__get(2): valueToStore = 1 self.__write(3, valueToStore) self.instruction_pointer += 4 if op == 8: valueToStore = 0 if self.__get(1) == self.__get(2): valueToStore = 1 self.__write(3, valueToStore) self.instruction_pointer += 4 if op == 9: self.relative_base += self.__get(1) self.instruction_pointer += 2
# Here we print out a line. print "How old are you?", # Here we define a variable called age and then we ask for the user to input info. # That info is stored in the variable age. age = raw_input() # Here we print out a line. print "How tall are you?", # Here we define a variable called height and then we ask for the user to input info. # That info is stored in the variable height. height = raw_input() # Here we print out a line. print "How much do you weigh?", # Here we define a variable called weight and then we ask for the user in input info. # That info is stored in the variable weight. weight = raw_input() # Here we print a string where we use and call our variables defined above. # The values that were typed in by the user are used for the value of the variables. print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight)
import sys from datetime import datetime # Takes string value and attempts to # strip percentage and convert to float def convertPercentToFloat(passedValue): # Try catch block, attempt to convert passed value to float, if it fails throw exception try: return float(passedValue.strip('%')) except Exception as e: print("Error: Converting passed percentage string: " + passedValue + " to float failed.\n", e) sys.exit() # Takes string date as Day Month Year and return date object def convertDateStringToDate(passedDateStr): # Try catch block, attempt to convert passed value to date, if it fails throw exception try: return datetime.strptime(passedDateStr, '%d %B %Y').date() except Exception as e: print("Error: Converting passed date string: " + passedDateStr + " to date failed.\n", e) sys.exit() # Takes string paragraph and splits it into an array of strings, split on newline def splitStringOnNewLine(passedParagraph): # Try catch block, attempt to split passed string on newlines, if it fails throw exception try: return passedParagraph.splitlines() except Exception as e: print("Error: Splitting passed string: " + passedParagraph + " by newlines failed.\n", e) sys.exit()
#5x^3 − 17x^1 + 42x^0 #[42,-17,0,5] class Polynomial: def __init__(self,lst): self.lst = lst def __repr__(self): lst = [str(self.lst[n])+"x^"+str(n) for n in range(len(self.lst)-1,-1,-1)] return "+".join(lst) def eval(self,value): s = 0 for i in range(len(self.lst)): s += (value **i) * self.lst[i] return s def __add__(self,other): ls = [] count = 0 try: while True: ls.append(self.lst[count]+other.lst[count]) count += 1 except: ls.extend(self.lst[count:]) ls.extend(other.lst[count:]) return Polynomial(ls) def __mul__(self,other): ls = [0] p = Polynomial(ls) for i in range(len(self.lst)): lst = [0] * i for j in other.lst: lst.append(self.lst[i]*j) p = p + Polynomial(lst) return p def polySequence(self,start,end,step = 1): for i in range(start,end,step): yield self.eval(i) def derive(self): if len(self.lst) <= 1: return 0 ls = [self.lst[i]*i for i in range(1,len(self.lst))] return Polynomial(ls) def main(): p = Polynomial([42,-17,0,5]) p1 = Polynomial([1,1]) p2 = Polynomial([3,2]) pp = Polynomial([1,2]) p4 = Polynomial([1,4,0,2]) print(p4+p) for val in pp.polySequence(0,5): print(val)
import turtle class BinarySearchTreeMap: class Item: def __init__(self,key,value = None): self.key = key self.value = value def __repr__(self): return "("+str(self.key) + " : "+ str(self.value)+")" class Node: def __init__(self,item,left = None,right = None): self.item = item self.left = left self.right = right self.parent = None if self.left is not None: self.left.parent = self if self.right is not None: self.right.parent = self def num_children(self): count = 0 if self.left is not None: count += 1 if self.right is not None: count += 1 return count def disconnect(self): self.item = None self.left = None self.right = None self.parent = None def __repr__(self): return str(self.item) def __init__(self): self.root = None self.size = 0 def __len__(self): return self.size def is_empty(self): return len(self) == 0 def find(self,key): cur = self.root while cur is not None: if key == cur.item.key: return cur elif key > cur.item.key: cur = cur.right else: cur = cur.left return def __getitem__(self,key): node = self.find(key) if node is None: raise KeyError(str(key)+ " is not found in the tree.") return node.item.value def __setitem__(self,key,value): node = self.find(key) if node is not None: node.item.value = value else: self.insert(key,value) def insert(self,key,value = None): new_item = BinarySearchTreeMap.Item(key,value) new_node = BinarySearchTreeMap.Node(new_item) if self.is_empty(): self.root = new_node self.size += 1 else: cur = self.root while cur is not None: if key == cur.item.key: return elif key > cur.item.key: if cur.right is not None: cur = cur.right else: cur.right = new_node new_node.parent = cur self.size += 1 return elif key < cur.item.key: if cur.left is not None: cur = cur.left else: cur.left = new_node new_node.parent = cur self.size += 1 return def __delitem__(self,key): node = self.find(key) if node is None: raise KeyError(str(key) +" is not Found.") self.delete_node(node) def delete_node(self,node): num = node.num_children() item = node.item if node is self.root: if num == 0: node.disconnect() self.size -= 1 elif num == 1: if node.left is not None: self.root = node.left elif node.right is not None: self.root = node.right self.root.parent = None node.disconnect() self.size -= 1 else: max_of_left = self.subtree_max(node) node.item = max_of_left.item self.delete_node(max_of_left) else: if num == 0: parent = node.parent if node is parent.left: parent.left = None else: parent.right = None node.disconnect() self.size -= 1 elif num == 1: parent = node.parent if node.left is not None:#只有左边有 child = node.left else: child = node.right child.parent = parent if node.left is parent.left: parent.left = child else: parent.right = child node.disconnect() self.size -= 1 else: max_of_left = self.subtree_max(node.left) node.item = max_of_left.item self.delete_node(max_of_left) return item def subtree_max(self,root): while root.right is not None: root = root.right return root def inorder(self): for node in self.subtree_inorder(self.root): yield node def subtree_inorder(self,curr_node): if curr_node is None: return yield from self.subtree_inorder(curr_node.left) yield curr_node yield from self.subtree_inorder(curr_node.right) def __iter__(self): for node in self.inorder(): yield node.item.key def subtree_height(self,root): if root is None: return 0 left_height = self.subtree_height(root.left) right_height = self.subtree_height(root.right) return max(left_height,right_height)+1 def draw(self): turtle.tracer(0,0) self.subtree_draw(self.root) turtle.write(str(self.root.item),align = "center",font = 15) def subtree_draw(self,root): height = self.subtree_height(self.root) if root is not None: turtle.color("lightgreen") turtle.dot(20) turtle.color("black") if root.left is not None: left_level = height-self.subtree_height(root.left) angle = -180 + 10 * left_level length = 100 - left_level * 10 turtle.seth(-180 + 10 * left_level) turtle.fd(length) self.subtree_draw(root.left) turtle.write(str(root.left.item),align = "center",font = 15) turtle.seth(180+angle) turtle.fd(length) if root.right is not None: right_level = height-self.subtree_height(root.right) beta = -10 * right_level length = 100 - right_level * 10 turtle.seth(beta) turtle.fd(length) self.subtree_draw(root.right) turtle.write(str(root.right.item),align = "center",font = 15) turtle.seth(180 + beta) turtle.fd(length) bst1 = BinarySearchTreeMap() lst1 = [20,10,28,8,15,22,50,25] for i in lst1: bst1.insert(i) bst1.draw()
#Problem 1 class ArrayDeque: CAPACITY = 8 def __init__(self): self.data = [None] * ArrayDeque.CAPACITY self.size = 0 self.front = None self.back = None def __len__(self): return self.size def is_empty(self): return len(self) == 0 def first(self): if self.is_empty(): raise Exception("The Deque is Empty") return self.data[self.front] def last(self): if self.is_empty(): raise Exception("The Deque is Empty") return self.data[self.back] def enqueue_first(self,elem): if self.size == len(self.data): self.resize(2 * len(self.data)) if self.is_empty(): self.front = self.back = 0 else: self.front = (self.front - 1)%len(self.data) self.data[self.front] = elem self.size += 1 def enqueue_last(self,elem): if self.size == len(self.data): self.resize(2 * len(self.data)) if self.is_empty(): self.front = self.back = 0 else: self.back = (self.back + 1) % len(self.data) self.data[self.back] = elem self.size += 1 def dequeue_first(self): if self.is_empty(): raise Exception("The Deque is Empty") val = self.data[self.front] self.data[self.front] = None if self.is_empty(): self.front = self.back = None else: self.front = (self.front + 1) % len(self.data) self.size -= 1 return val def dequeue_last(self): if self.is_empty(): raise Exception("The Deque is Empty") val = self.data[self.back] self.data[self.back] = None if self.is_empty(): self.front = self.back = None else: self.back = (self.back - 1) % len(self.data) self.size -= 1 return val def resize(self,capacity): new = [None] * capacity for i in range(self.size): index = (self.front + i) % len(self.data) new[i] = self.data[index] self.data = new #Problem 2 from Stack import ArrayStack def balanced_expression(str_input): d = {"}":"{",")":"(","]":"["} stack = ArrayStack() for i in str_input: if i in "{[(": stack.push(i) else: try: out = stack.pop() if out != d[i]: return False except: return False return stack.is_empty() input_str = "([]{{[]})})" #print(balanced_expression(input_str)) #Problem 3 def get_tokens(input_str): start_ind = input_str.find("<") end_ind = input_str.find(">",start_ind) while start_ind != -1 and end_ind != -1: yield input_str[start_ind:end_ind+1] start_ind = input_str.find("<",end_ind) end_ind = input_str.find(">",start_ind) input_str = "af<abcd><asdf>asdflj</asdf>>asfsa</abcd>" for i in get_tokens(input_str): print(i) def is_matched_html(html_str): lst = [i for i in get_tokens(html_str)] stack = ArrayStack() for i in lst: if i[1] == "/": try: out = stack.pop() if out[1:-1] != i[2:-1]: return False except: return False else: stack.push(i) return stack.is_empty() print(is_matched_html(input_str))
# Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input()) for i in range(n): try: a, b = input().split(" ") a = int(a) b = int(b) print(a//b) except ZeroDivisionError as e: print("Error Code:", e) except ValueError as v: print("Error Code:", v)
# Task # Given an integer, , perform the following conditional actions: # If is odd, print Weird # If is even and in the inclusive range of to, print Not Weird # If is even and in the inclusive range of to, print Weird # If is even and greater than, print Not Weird n = int(input()) if (n % 2 != 0): print('weird') elif (n % 2 == 0 and n >= 2 and n <= 5): print('Not Weird') elif (n % 2 == 0 and n >= 6 and n <= 20): print('weird') else: print("Not Weird")
import threading class Stack: def __init__(self): self.items = [] self.lock = threading.Lock() def push(self, item): self.lock.acquire() try: self.items.append(item) finally: self.lock.release() def append(self, item): self.lock.acquire() try: self.items.append(item) finally: self.lock.release() def pop(self): self.lock.acquire() item='' try: item=self.items.pop() finally: self.lock.release() return item def peek(self): return self.items[len(self.items)-1] def size(self): ans=0 self.lock.acquire() try: ans= len(self.items) finally: self.lock.release() return ans
def foo(x): x = 5 var = 10 # immutable type foo(var) print(var) def foo2(a_list): a_list.append(10) a_list[0] = 0 my_list = [1,2,3,4] foo2(my_list) # list is mutable and can be changed print(my_list) #[0, 2, 3, 4, 10] def foo_rebind(a_list): a_list = [100, 200, 300] a_list.append(400) my_list2 = [1,2,3,4] foo_rebind(my_list2) #list is re-assigned to new list in function, so global list has no change print(my_list2) #[1, 2, 3, 4] def foo_rebind2(a_list): a_list = a_list + [100, 200, 300] #list is re-assigned a_list.append(400) my_list3 = [1,2,3,4] foo_rebind2(my_list3) #list is re-assigned to new list in function, so global list has no change print(my_list3) #[1, 2, 3, 4] def foo_not_rebind(a_list): a_list += [100, 200, 300] a_list.append(400) my_list4 = [1,2,3,4] foo_not_rebind(my_list4) #list is not re-assigned in function print(my_list4) #[1, 2, 3, 4, 100, 200, 300, 400]
#Dictionary, key-value pairs, unordered, mutable #create dictionary my_dict1 = {"name": "Max", "age": 34, "city": "New York"} print(my_dict1) print(my_dict1["name"]) my_dict2 = dict(name="Max", age=34, city="New York") print(my_dict2) print(my_dict2["age"]) #my_dict2["lastname "] #Key ERROR my_dict3 = my_dict2 my_dict3["email"] = "[email protected]" print(my_dict2) print(my_dict3) #same value my_dict4 = my_dict3.copy() del(my_dict4["email"]) print(my_dict4) my_dict5 = dict(my_dict3) print(my_dict5.pop("age")) #34 print(my_dict5) #{'name': 'Max', 'city': 'New York', 'email': '[email protected]'} my_dict5.popitem() print(my_dict5) #{'name': 'Max', 'city': 'New York'} #operation my_dict6 = my_dict1.copy() print("name" in my_dict6) #True print("last" in my_dict6) #False try: print(my_dict6["lastname"]) except: print("error") #loop for key in my_dict6: #my_dict6.keys() print(key+"->"+ str(my_dict6[key])) for value in my_dict6.values(): print(value) for key,value in my_dict6.items(): print(key+"->" + str(my_dict6[key])) #merge my_dict7 = dict(my_dict1) my_dict8 = {"name": "New", "age": 50, "lastName": "mylast"} my_dict7.update(my_dict8) print(my_dict7) print(my_dict8) #key is number my_dict9 = {1:8, 3:90, 5:125} print(my_dict9[3]) #3 is not an index #key is tuple, only tuple, no list my_tuple = ("tupe", "is key") tuple_dict = {my_tuple:"value"} print(tuple_dict)
def mygenerator(): yield 1 yield 2 yield 3 g1 = mygenerator() print(g1) for i in g1: print(i) g2 = mygenerator() print(next(g2)) print(next(g2)) print(next(g2)) g3 = mygenerator() print(sum(g3)) g4 = mygenerator() print(sorted(g4)) def countdown(num): while num > 0: yield num print(f"start {num}") num -= 1 print(countdown(5)) #<generator object countdown at 0x7fb3231cb6d0> g1 = countdown(10) print(next(g1)) #10 #it stops at yield statement print(next(g1)) #start 10 /n 9
#!/usr/bin/env python3 import pytest import string from math import * from coordinates import Coordinate as coord from collections import defaultdict from operator import itemgetter def num_to_char(num): return chr(97+num) def manhattan_distance(a, b): return abs(a.x - b.x) + abs(a.y - b.y) def test_manhattan_distance(): assert manhattan_distance(coord(x=1, y=1), coord(x=2, y=1)) == 1 assert manhattan_distance(coord(x=1, y=1), coord(x=3, y=1)) == 2 assert manhattan_distance(coord(x=1, y=1), coord(x=3, y=2)) == 3 assert manhattan_distance(coord(x=2, y=1), coord(x=3, y=2)) == 2 def calculate_closest_distances(grid_size, in_lines): distances_grid = defaultdict(dict) for y in range(1, grid_size[1]+1): for x in range(1, grid_size[0]+1): distances = dict() for i, p in enumerate(in_lines): distances[i] = manhattan_distance(coord(x=x, y=y), p) closest_points = sorted(distances.items(), key=itemgetter(1)) closest_point = closest_points[0] indicator = num_to_char(closest_point[0]).lower() if closest_points[0][1] == closest_points[1][1]: # The two points are at the same distance indicator = '.' #print('{} ({})'.format(num_to_char(closest_point[0]).upper(), closest_point[1])) distances_grid[x][y] = num_to_char(closest_point[0]).upper() if closest_point[1] == 0 else indicator return distances_grid def prepare_input(input_str): in_lines = [] for l in input_str.split('\n'): l = l.strip() if not l: continue x_str, y_str = l.strip().split(',') x = int(x_str.strip()) y = int(y_str.strip()) in_lines.append(coord(x=x, y=y)) return in_lines def max_size(in_lines): return (max(p.x for p in in_lines), max(p.y for p in in_lines)) def get_distances(input_str, print_grid=False): prepared_input = prepare_input(input_str) print('Max size') grid_size = max_size(prepared_input) print(grid_size) print() # Print start grid if print_grid: xy = defaultdict(dict) for i, p in enumerate(prepared_input): xy[p.x][p.y] = i for y in range(1, grid_size[1]+1): for x in range(1, grid_size[0]+1): try: print(num_to_char(xy[x][y]).upper(), end='') except KeyError: print('.', end='') print() print() distances = calculate_closest_distances(grid_size, prepared_input) return grid_size, distances def size_largest_area(grid_size, distances): # Chars at the edge extend infinite so we need to remove those remove_chars = set() for y in range(1, grid_size[1]+1): remove_chars.add(distances[1][y]) for x in range(1, grid_size[0]+1): remove_chars.add(distances[x][1]) areas = dict() for y in range(1, grid_size[1]+1): for x in range(1, grid_size[0]+1): areas[distances[x][y].lower()] = 0 if distances[x][y] in remove_chars: distances[x][y] == '' # Calculate area per char for y in range(1, grid_size[1]+1): for x in range(1, grid_size[0]+1): areas[distances[x][y].lower()] += 1 return sorted(areas.items(), key=itemgetter(1), reverse=True)[0] @pytest.fixture def example_input(): return ''' 1, 1 1, 6 8, 3 3, 4 5, 5 8, 9 ''' def print_grid(grid): for y in range(1, max(grid[1].keys())+1): for x in range(1, max(grid.keys())+1): print(grid[x][y], end='') print() print() def test_size_largest_area(example_input): grid_size, distances = get_distances(example_input, True) print_grid(distances) assert distances == { 1: {1: 'A', 2: 'a', 3: 'a', 4: '.', 5: 'b', 6: 'B', 7: 'b', 8: 'b', 9: 'b'}, 2: {1: 'a', 2: 'a', 3: 'd', 4: 'd', 5: '.', 6: 'b', 7: 'b', 8: 'b', 9: 'b'}, 3: {1: 'a', 2: 'd', 3: 'd', 4: 'D', 5: 'd', 6: '.', 7: '.', 8: '.', 9: '.'}, 4: {1: 'a', 2: 'd', 3: 'd', 4: 'd', 5: 'e', 6: 'e', 7: 'e', 8: 'e', 9: 'f'}, 5: {1: '.', 2: 'e', 3: 'e', 4: 'e', 5: 'E', 6: 'e', 7: 'e', 8: 'e', 9: 'f'}, 6: {1: 'c', 2: 'c', 3: 'c', 4: 'e', 5: 'e', 6: 'e', 7: 'e', 8: 'f', 9: 'f'}, 7: {1: 'c', 2: 'c', 3: 'c', 4: 'c', 5: 'e', 6: 'e', 7: 'f', 8: 'f', 9: 'f'}, 8: {1: 'c', 2: 'c', 3: 'C', 4: 'c', 5: 'c', 6: '.', 7: 'f', 8: 'f', 9: 'F'} } assert size_largest_area(grid_size, distances) == ('e', 17) if __name__ == '__main__': with open('06.input', 'r') as in_list: grid_size, distances = get_distances(in_list.read()) #print_grid(distances) print('nu size') print(size_largest_area(grid_size, distances))
import time from Person import Person class Race: segundos = 0 ganador = "" runK = 10000 pedalK = 20000 swimK = 1000 teamWrites = 2 travel = list() def stopWatch(self): self.initRecorrido() while True: resultado = False time.sleep(1) self.segundos = self.segundos + 1 for nTeam in range(self.teamWrites): if 0 >= self.travel[nTeam] <= self.runK: self.travel[nTeam] = self.runZ(nTeam) print("Total Recorrido " + str(self.travel[nTeam]) + "del Team " + str(nTeam)) if self.travel[nTeam] == self.runK: print("Cambio de Relevo team " + str(nTeam)) elif self.runK >= self.travel[nTeam] <= self.runK + self.pedalK: self.travel[nTeam] = self.pedalZ(nTeam) print("Total Recorrido " + str(self.travel[nTeam]) + "del Team " + str(nTeam)) if self.travel[nTeam] == self.runK + self.pedalK: print("Cambio de Relevo team " + str(nTeam)) elif self.runK + self.pedalK >= self.travel[nTeam] <= self.runK + self.pedalK + self.swimK: self.travel[nTeam] = self.swimZ(nTeam) print("Total Recorrido " + str(self.travel[nTeam]) + " del Team " + str(nTeam)) elif self.travel[nTeam] >= self.runK + self.pedalK + self.swimK: self.ganador = (str(nTeam)+" Con un tiempo de :"+str(int((self.segundos/60)/60))+":"+str(int(self.segundos/60))+":"+str(self.segundos)+ "Hras") resultado = True if resultado == True: break return self.ganador def initRecorrido(self): for x in range(self.teamWrites): self.travel.append(0) def runZ(self, nTeam): p = Person() for x in p.TeamList: if x.zona == p.typeSpeed[0] and x.nTeam == nTeam: return x.run(self.travel[nTeam],x.speed) def pedalZ(self, nTeam): p = Person() for x in p.TeamList: if x.zona == p.typeSpeed[1] and x.nTeam == nTeam: return x.run(self.travel[nTeam],x.speed) def swimZ(self, nTeam): p = Person() for x in p.TeamList: if x.zona == p.typeSpeed[2] and x.nTeam == nTeam: return x.run(self.travel[nTeam],x.speed)
from operator import itemgetter def topItems(noteslist, n): #noteslist = "notes.txt" например favNotes = [] nn = [] result = [] with open(noteslist, "r") as myfile: favNotes = myfile.readlines() for note in favNotes: x = favNotes.count(note) if note not in nn: nn.append(note) result.append((note, x)) return sorted(result, key=itemgetter(1))[-n:] print("Top 10 preferred notes:", "\n") print(topItems("notes.txt", 10)) print() print("Top 5 preferred perfumers:", "\n") print(topItems("authors.txt", 7))
from pprint import pprint def next_empty(puzzle): for r in range(9): for c in range(9): if puzzle[r][c] == 0: return r, c return None, None def is_valid(puzzle, guess, r, c): row_vals = puzzle[r] if guess in row_vals: return False col_vals = [puzzle[i][c] for i in range(9)] if guess in col_vals: return False r_s = (r // 3) * 3 c_s = (c // 3) * 3 for r in range(r_s, r_s + 3): for c in range(c_s, c_s + 3): if puzzle[r][c] == guess: return False return True def solve_sudoku(puzzle): r, c = next_empty(puzzle) if r is None: return True for guess in range(1, 10): if is_valid(puzzle, guess, r, c): puzzle[r][c] = guess if solve_sudoku(puzzle): return True puzzle[r][c] = 0 return False if __name__ == '__main__': board = [ [3, 9, 0, 0, 5, 0, 0, 0, 0], [0, 0, 0, 2, 0, 0, 0, 0, 5], [0, 0, 0, 7, 1, 9, 0, 8, 0], [0, 5, 0, 0, 6, 8, 0, 0, 0], [2, 0, 6, 0, 0, 3, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 4], [5, 0, 0, 0, 0, 0, 0, 0, 0], [6, 7, 0, 1, 0, 5, 0, 4, 0], [1, 0, 9, 0, 0, 0, 2, 0, 0] ] print(solve_sudoku(board)) pprint(board)
def binToDec(inNum): numberx=inNum dec_number= int(numberx, 2) return (dec_number) #print('The decimal conversion is:', dec_number) #print(type(dec_number)) print(binToDec(input("Enter binary number: ")))
''' Module that handles tasks related to processes ''' import os import subprocess import time import psutil def is_running(process_name): ''' Check if there is any running process that contains the given name process_name. ''' try: # Iterate over the all the running process for proc in psutil.process_iter(): try: # Check if process name contains the given name string. if process_name.lower() in proc.name().lower(): return True except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass except TypeError: return False return False def kill_process(process_name): ''' Closes a process ''' try: while True: try: for proc in psutil.process_iter(): if proc.name() == process_name: proc.kill() if not is_running(process_name): return except TypeError: pass time.sleep(1) except psutil.NoSuchProcess: return
""" Python job scheduling for humans. An in-process scheduler for periodic jobs that uses the builder pattern for configuration. Schedule lets you run Python functions (or any other callable) periodically at pre-determined intervals using a simple, human-friendly syntax. Inspired by Addam Wiggins' article "Rethinking Cron" [1] and the "clockwork" Ruby module [2][3]. Features: - A simple to use API for scheduling jobs. - Very lightweight and no external dependencies. - Excellent test coverage. - Works with Python 2.7 and 3.3 Usage: >>> import schedule >>> import time >>> def job(message='stuff'): >>> print("I'm working on:", message) >>> schedule.every(10).minutes.do(job) >>> schedule.every().hour.do(job, message='things') >>> schedule.every().day.at("10:30").do(job) >>> while True: >>> schedule.run_pending() >>> time.sleep(1) [1] http://adam.heroku.com/past/2010/4/13/rethinking_cron/ [2] https://github.com/tomykaira/clockwork [3] http://adam.heroku.com/past/2010/6/30/replace_cron_with_clockwork/ """ from schedule import Scheduler from schedule import CancelJob # The following methods are shortcuts for not having to # create a Scheduler instance: default_scheduler = Scheduler() jobs = default_scheduler.jobs # todo: should this be a copy, e.g. jobs()? def every(interval=1): """Schedule a new periodic job.""" return default_scheduler.every(interval) def run_pending(): """Run all jobs that are scheduled to run. Please note that it is *intended behavior that run_pending() does not run missed jobs*. For example, if you've registered a job that should run every minute and you only call run_pending() in one hour increments then your job won't be run 60 times in between but only once. """ default_scheduler.run_pending() def run_all(delay_seconds=0): """Run all jobs regardless if they are scheduled to run or not. A delay of `delay` seconds is added between each job. This can help to distribute the system load generated by the jobs more evenly over time.""" default_scheduler.run_all(delay_seconds=delay_seconds) def clear(): """Deletes all scheduled jobs.""" default_scheduler.clear() def cancel_job(job): """Delete a scheduled job.""" default_scheduler.cancel_job(job) def next_run(): """Datetime when the next job should run.""" return default_scheduler.next_run def idle_seconds(): """Number of seconds until `next_run`.""" return default_scheduler.idle_seconds
# https://projecteuler.net/problem=7 # Calculate the 10,001st prime number # For example: 13 is the 6th prime number (2, 3, 5, 7, 11, 13, 17, ...) import math # Function to check whether a number is a prime number def isPrime(number): if number > 1: # Prime number must bigger than 1 and not a negative number if number == 2: # 2 is a prime number return True if number % 2 == 0: return False for currentNumber in range(3, int(math.sqrt(number) + 1), 2): if number % currentNumber == 0: return False return True return False # Using generator to get the next prime number # This is a better way because we don't know when to stop def getNextPrime(startNumber): while True: if isPrime(startNumber): yield startNumber startNumber += 1 # Get the 10001st prime number # Simply check each number whether it is a prime. # If yes, increase the count until reach 10001 def main(): count = 1 # we already have 2 is the first prime number for number in getNextPrime(3): if count < 10001 - 1: count += 1 else: print number return if __name__ == "__main__": main()
# https://projecteuler.net/problem=1 # Find sum of all multiples of 3 and 5 # # All numbers divisible by 3 would be: 3, 6, 9, 12, ... # Sum all of them together: # = (3 + 6 + 9 + 12 + ...) # = 3 * (1 + 2 + 3 + 4 + ...) # # Similar for all numbers divisible by 5 from __future__ import division MAX_VALUE = 999 def sum_divisible_by(n): p = MAX_VALUE // n return ( n * p * (p + 1) ) // 2 # We have to subtract the result from all number divisible by 15 # because some numbers like 15, 30, 45, ... will be counted twice if __name__ == '__main__': print( sum_divisible_by(3) + sum_divisible_by(5) - sum_divisible_by(15) )
# https://projecteuler.net/problem=5 # Find the smallest number that evenly divisible by all of the numbers from 1 to 20 # For further divisibility rules, read the following link: # https://en.wikipedia.org/wiki/Divisibility_rule ################################################################################### import math # Check whether a number is a prime number def is_prime(number): if type(number) != int and type(number) != long: return False if number > 1: if number == 2: # 2 is a prime number return True if number % 2 == 0: # All prime number except 2 should be odd return False for currentNumber in range(3, int(math.sqrt(number) + 1), 2): if number % currentNumber == 0: return False return True return False # Get the next prime number, using generator def get_next_prime(start_number): while True: if is_prime(start_number): yield start_number start_number += 1 # def get_factors(): final = {} for number in range(2, 21): factors = [] for prime in get_next_prime(2): if number % prime == 0: while number % prime == 0: factors.append(prime) number /= prime if number == 1: break factors = {factor: factors.count(factor) for factor in set(factors)} for factor, freq in factors.items(): if not factor in final: final[factor] = 1 else: if freq > final[factor]: final[factor] = freq return final if __name__ == '__main__': factors = get_factors() result = 1 for factor, freq in factors.items(): result *= math.pow(factor, freq) print (result)
finalcount = 0 count = 0 def fizz_count(x): count = 0 for item in x: if item == "fizz": count = count + 1 return count fizzlist = ["fizz", "fizz", "fizz", "dog"] fizz_count(fizzlist) print(count) print(len(fizzlist)) print(fizzlist.count("fizz"))
answers=0 print('1. Какой язык программирования мы начали учить в этом семестре?') answer1=input() if answer1=='Python' or answer1=='python': answers+=1 print('Правильно') else: print('Не правильно') print('2. Каким образом в python тело функции отделяется от заголовка?') answer2=input() if answer2=='4 пробела' or answer2==' ' or answer2=='четыре пробела' or answer2=='пробелами': answers+=1 print('Правильно') else: print('Не правильно') print('3. Каким знаком в языке python должен заканчиваться заголовок функции?') answer3=input() if answer3==':' or answer3=='двоеточие' or answer3=='двоеточием': answers+=1 print('Правильно') else: print('Не правильно') print('4. Какое ключевое слово обозначает функцию ввода из консоли в python?') answer4=input() if answer4=='input': answers+=1 print('Правильно') else: print('Не правильно') print('5. Какое ключевое слово обозначает принудительное окончание функции?') answer5=input() if answer5=='break': answers+=1 print('Правильно') else: print('Не правильно') print('6. Какое главное отличие кодировки UTF-32 от UTF-8?') answer6=input() if answer6=='количество бит на символ': answers+=1 print('Правильно') else: print('Не правильно') print('7. Какова типизация языка python 2?') answer7=input() if answer7=='не строгая': answers+=1 print('Правильно') else: print('Не правильно') print('8. Какое ключевое слово обозначает функцию вывода текста в консоли в python?') answer8=input() if answer8=='print': answers+=1 print('Правильно') else: print('Не правильно') print('9. Каким типом данных обозначают пустые переменные в языке python?') answer9=input() if answer9=='null': answers+=1 print('Правильно') else: print('Не правильно') print('10. Какое ключевое слово используется для объявления функции в python?') answer10=input() if answer10=='def': answers+=1 print('Правильно') else: print('Не правильно') print('правильных ответо', answers)
#variables demonstrated print ("This program is a demo of how variables work") v = 1 print ("The value of v is now",v) v = v + 1 print ("v is now equal to itself plus one, making it worth",v) v = 51 print ("v can sotre a numerical value, that can be used elsewhere.") print ("For example, in this sentence, v is worth",v) print ("v times 5 equals",v*5) print ("But v still remains",v) print ("To make v five times bigger, you would need to type v = v * 5") v = v * 5 print ("There you are, v now equals", v, "and not", v/5)
#Clase objeto para simular objetos de tipo A,B y C #el traibuto tipo es de tipo entero #si tipo = 1 entonces el objeto es de tipo A #si tipo = 2 entonces el objeto es de tipo B #si tipo = 3 entonces el objeto es de tipo C class Objeto: def __init__(self, id, tipo): self.id = id self.tipo = tipo def getTipo(self): return self.tipo
print ("NOTE:\n") print ("Maturity period for PPF is 15 years . Hence gross is calculated for 15 years\n") print ("Enter your yearsly inverstment ...") inverstment = int(raw_input()) print ("Enter current interest rate ...") current_interest_rate = float(raw_input()) def ppfcal(inverstment,current_interest_rate): if inverstment > 0 and current_interest_rate > 0 : deposite = 0 for i in range(1,16): interestrate = (deposite+inverstment)*current_interest_rate / 100 deposite = deposite + inverstment + interestrate #print ("After %d year your deposite amount is %d" % (i,deposite)) print ("After 15 years you will get %d" % deposite ) else: print ("Please don\'t provide interestrate or inverstment 0 or less then 0.") ppfcal(inverstment,current_interest_rate)
# -*- coding: utf-8 -*- """ Created on Tue Feb 11 11:34:57 2014 @author: pruvolo """ # you do not have to use these particular modules, but they may help from random import randint import Image from math import pi,sin,cos,sqrt import numpy as np def build_random_function(min_depth, max_depth): #inputs a min and max depth and will output a nested list that contains strings of a random math equation flist=["prod","cos_pi","sin_pi",'divide2','square',"x","y"] if min_depth>0: #checks if its ok to add an x or y to the random equation rand=randint(0,4) # if it does not acheive min x and y cant be added to the list if rand==0: return[flist[rand],build_random_function(min_depth-1,max_depth-1),build_random_function(min_depth-1,max_depth-1)] elif rand==1 or rand==2 or rand == 3 or rand== 4: return[flist[rand],build_random_function(min_depth-1,max_depth-1)] else: if max_depth==0: #if max depth is acheived x and y must be chosen rand=randint(5,6) return[flist[rand]] else: rand=randint(0,6) if rand==0: return[flist[rand],build_random_function(min_depth-1,max_depth-1),build_random_function(min_depth-1,max_depth-1)] elif rand==1 or rand==2 or rand== 3 or rand==4: return[flist[rand],build_random_function(min_depth-1,max_depth-1)] else: return[flist[rand]] # your code goes here def evaluate_random_function(f, x, y): "inputs the build random function and x and y values and solves the random equation that is generated and outputs the answer" #all the if statements checks which function is used and solves the function if f[0] == 'prod': return evaluate_random_function(f[1],x,y)*evaluate_random_function(f[2],x,y) elif f[0] == 'cos_pi': return cos(evaluate_random_function(f[1],x,y)*pi) elif f[0] == 'sin_pi': return sin(evaluate_random_function(f[1],x,y)*pi) elif f[0] == 'x': return x elif f[0] == 'y': return y elif f[0] == "divide2": return (evaluate_random_function(f[1],x,y))/2 elif f[0] =='square': return (evaluate_random_function(f[1],x,y))*(evaluate_random_function(f[1],x,y)) # your code goes here def colors(min_depth,max_depth): im = Image.new("RGB",(350,350)) # creates the map im2=im.load() #creates three random equations for each color Rf=build_random_function(min_depth, max_depth) Gf=build_random_function(min_depth, max_depth) Bf=build_random_function(min_depth, max_depth) #divides n into 350 numbers between -1 and 1. Each represents a pixel on the map n=np.linspace(-1,1,350) xp=0 yp=0 #finds the color for each pixel on the map for xp in range(len(n)): for yp in range(len(n)): red=evaluate_random_function(Rf, n[xp],n[yp]) green=evaluate_random_function(Gf, n[xp],n[yp]) blue=evaluate_random_function(Bf, n[xp],n[yp]) #scales the color values to 250 red=int((red+1)*250/2) green=int((green+1)*250/2) blue=int((blue+1)*250/2) #combines the three colors for each pixel im2[xp,yp]=(red,green,blue) im.save("test2.bmp") colors(5,7) def remap_interval(val, input_interval_start, input_interval_end, output_interval_start, output_interval_end): """ Maps the input value that is in the interval [input_interval_start, input_interval_end] to the output interval [output_interval_start, output_interval_end]. The mapping is an affine one (i.e. output = input*c + b). TODO: please fill out the rest of this docstring """ # your code goes here
# ################################ # # DE2-COM2 Computing 2 # # Individual project # # # # Title: MAIN # # Authors: Amy Mather # # Last updated: 4th December 2018 # # ################################ # from copy import deepcopy import utils def calc_coord_scores(target, x, y): '''gives the squares that could have a tetris piece placed upon them a score the score represents how many sides are adjacent to the puzzle boundary''' width = len(target[0]) # The width of the target matrix height = len(target) # The height of the target matrix # The coordinates to check for adjaceny neighbors = [ [-1, 0], [0, -1], [0, 1], [1, 0] ] # How many edges are adjacent score = 0 # A pictorial representation of all the tetris pieces on top of one another # # # # # # # # # # # # # # # # # # every possible relative coordinate a tetris piece could have - this is to save # calculating the score for the same coordinate multiple times which would # occur if cycling through the coords of each tetris shape # coordinates are represented (y, x) coords_to_check = [ (0, 0), (0, 1), (0, 2), (0, 3), (1, -2), (1, -1), (1, 0), (1, 1), (1, 2), (2, -1), (2, 0), (2, 1), (3, 0)] # uses a tuple contaiing the coordiates (y, x) as a key, keeps track of each coordinates score coord_scores = {} for coord_mod in coords_to_check: score = 0 y_mod, x_mod = coord_mod cur_y = y + y_mod cur_x = x + x_mod if (cur_x >= 0 ) and (cur_y >= 0) and (cur_x < width) and (cur_y < height): if target[cur_y][cur_x]: for neighbor in neighbors: check_y, check_x = cur_y + neighbor[0], cur_x + neighbor[1] if (check_x > 0 ) and (check_y > 0) and (check_x < width) and (check_y < height): if not target[check_y][check_x]: score += 1 else: score += 1 coord_scores[coord_mod] = score return coord_scores def score_fit(shapeID, tetronimos, coord_scores): ''' uses the coordinate scores to calculate how snugly a piece fits the higher the score, the snugger the fit''' score = 0 i = 0 for coord_mod in tetronimos[shapeID]: i += 1 if tuple(coord_mod) in coord_scores: score += coord_scores[tuple(coord_mod)] else: return 0 return score def score(result): return result[1] def place(shapeID, x, y, solution_matrix, pieceID, tetronimos, target, limit_tetris): for coord_mod in tetronimos[shapeID]: cur_y = y + coord_mod[0] cur_x = x + coord_mod[1] solution_matrix[cur_y][cur_x] = (shapeID, pieceID) target[cur_y][cur_x] = 0 limit_tetris[shapeID] -= 1 return pieceID + 1 def Tetris(target, limit_tetris): tetronimos = [0] + [utils.generate_shape(x) for x in range(1, 20)] width = len(target[0]) # The width of the target matrix height = len(target) solution_matrix = deepcopy(target) total_shapes = 0 for shape in limit_tetris: total_shapes += limit_tetris[shape] for y in range(len(solution_matrix)): for x in range(len(solution_matrix[y])): if not solution_matrix[y][x]: solution_matrix[y][x] = (0, 0) pieceID = 1 for y in range(len(target)): for x in range(len(target[y])): if target[y][x]: biggest_score = 0 best_shape = 0 coord_scores = calc_coord_scores(target, x, y) if coord_scores != {}: results = [] for shapeID in limit_tetris: if limit_tetris[shapeID] > 0: if total_shapes > 2500: weighting = (limit_tetris[shapeID] / total_shapes) else: weighting = 1 weighting = (limit_tetris[shapeID] / total_shapes) shape_score = weighting * score_fit(shapeID, tetronimos, coord_scores) if shape_score > biggest_score: biggest_score = shape_score best_shape = shapeID if biggest_score > 0: pieceID = place(best_shape, x, y, solution_matrix, pieceID, tetronimos, target, limit_tetris) total_shapes -= 1 else: solution_matrix[y][x] = (0, 0) else: solution_matrix[y][x] = (0, 0) #places an block for y in range(len(target)): for x in range(len(target[y])): if target[y][x]: for shapeID in limit_tetris: if limit_tetris[shapeID] > 0: covering = 0 for coord_mod in tetronimos[shapeID]: new_y = y + coord_mod[0] new_x = x + coord_mod[1] if new_y >= 0 and new_x >= 0 and new_y < height and new_x < width: if target[new_y][new_x] and solution_matrix[new_y][new_x] == (0, 0): covering += 1 if solution_matrix[new_y][new_x] != (0, 0): covering = 0 break else: covering = 0 break if covering >= 3: pieceID = place(shapeID, x, y, solution_matrix, pieceID, tetronimos, target, limit_tetris) break #print('\n'.join([' '.join([str(char) for char in row]) for row in solution_matrix])) return solution_matrix
def konversiSuhu(C = "none", F = "none"): "mengkonversikan suhu dari Celcius ke Fahrenheit dan sebaliknya" suhu = 0 if (C == "none") and (F == "none"): print ("Suhu 0 Celcius setara dengan 32 Fahrenheit") elif (C == "none") and (F == "none"): suhu = (F - 32) * 5/9 print ("Suhu", F, "Fahrenheit setara dengan", int(suhu), "Celcius") elif (C != "none") and (F == "none"): suhu = (C * 9/5) + 32 print ("Suhu", C, "Celcius setara dengan", int(suhu), "Fahrenheit")
# 7.1 # a = int(input("ange multiplikationstabell")) # ber om multitabell # num = 1 # vårt första värde i multitabellen # c = 4 # antal gånge (-1) som tabellen körs # while num < c: # medan vårt första värde är mindre än antal gånge vi kör # b = a*num # # kommer vi multiplicera ditt tal med första värdet # num += 1 # sedan addera standardtalet med 1 # print(b) # skriver ut alla värden vi får # if num == c: # fortsätter så till vårt startvärde körts 3 ggr # e = input("fortsätt?") # ber om fortsättning eller inte # if e.lower() =="ja": # om ja, fortsätt med while loopen genom att lägga till 3 omgångar till # c += 3 # elif e.lower() =="nej": # stänger av vid nej # 7.2 # import random # för att slumpa värde # a = random.randint(0,99) # slumpar värde mellan 0 och 99 # b = int(input("Guess")) # ber dig gissa # c = 0 # våra försök # while a > b: # medan din gissning är mindre än talet # print("Higher") # ber dig säga något högre # b = int(input("Guess")) # gissa igen # c += 1 # lägg till ett försök på dig # while a < b: # blir det lägre nästa gång gör tvärtom # print("Lower") # b = int(input("Guess")) # c += 1 # lägg till et försök på dig # while a < b: # samma sak som innan fast inverterat för att kunna fixa alla kombinationer av gissningar för att hålla på hela tiden # print("Lower") # b = int(input("Guess")) # c += 1 # while a > b: # print("Higher") # b = int(input("Guess")) # c += 1 # if a == b: # när du gissar rätt # c += 1 # lägg på ett till försök # print("The answer is", a,",", "it took you", c, "tries") # säg att du fick rätt efter x antal försök
import turtle t = turtle.Turtle() t.hideturtle() t1 = turtle.Turtle() t1.hideturtle() scr = turtle.Screen() scr.bgcolor('black') def filler(x,y,length,x1,y1,len): t.begin_fill() t.fillcolor('white') t.up() t.goto(x,y)# moves that co ordinates t.down() t.circle(length) t.end_fill() t1.begin_fill() t1.fillcolor('yellow') t1.up() t1.goto(x1,y1) # moves that co ordinates t1.down() t1.circle(len) t1.end_fill() filler(0,-50,50,0,-30,30) filler(200,200,50,200,220,30) filler(-200,200,50,-200,220,30) filler(200,-200,-50,200,-220,-30) filler(-200,-200,-50,-200,-220,-30)
def convert_seconds(seconds): hours=seconds//3600 minutes=(seconds-hours*3600)//60 remaining_seconds=seconds-hours*3600-minutes*60 return hours,minutes,remaining_seconds
number_list = [-1, 1, 2, 5, 7, 8657, 2, 99997, 431, 3, 432, 4325] def find_max(list): largest = list[0] for i in list: temp = largest # print ("temp is :", temp) if temp < i: largest = i elif temp == i: largest = i else: largest = temp print ('larget number is :', largest) def find_min(list): smallest = None for i in list: temp = smallest if smallest is None: smallest = i elif temp < i: smallest = temp else: smallest = i print ('the smallest number is :', smallest) print(find_min(number_list))
# -*- coding: utf-8 -*- class Node(object): """Singly Linked List Node class""" def __init__(self, data, next_node): self.data = data self.next = next_node def __repr__(self): return str(self.data) class LinkedList(object): def __init__(self): self.head = None self.tail = None self.size = 0 def __len__(self): return self.size def __iter__(self): node = self.head while node is not None: yield node node = node.next def __repr__(self): return str(list(self)) def __getitem__(self, index): if not 0 <= index < len(self): raise IndexError('Index out of bounds.') for node_index, node in enumerate(self): if node_index == index: return node def __setitem__(self, index, value): if not 0 <= index < len(self): raise IndexError('Index out of bounds.') for node_index, node in enumerate(self): if node_index == index: node.data = value def __delitem__(self, index): # TODO pass def prepend(self, value): new_node = Node(value, self.head) self.head = new_node if len(self) == 0: self.tail = new_node self.size += 1 def append(self, value): new_node = Node(value, None) if len(self) == 0: self.head = new_node else: self.tail.next = new_node self.tail = new_node self.size += 1 def remove(self): if len(self) == 0: raise Exception("Can't remove element from an empty linked list.") if self.head.next is None: self.tail = None self.head = self.head.next self.size -= 1
import random def play_guessing_game(secret_number, max_tries): number_tries = 1 user_number = int(input('Please enter a number:')) while(secret_number != user_number) and number_tries < max_tries: if(secret_number > user_number): print("The secret number is greater ") else: print('The secret number is less') user_number = int(input('Please enter a number:')) number_tries = number_tries + 1 return number_tries def print_game_results(number_tries, max_tries): if(number_tries < max_tries): print('***************************************') print('Congrats! you found the correct number!') print('***************************************') else: print('***************************************') print(' OHHHHH NUMBER NOT FOUND - TRY AGAIN ') print('***************************************') # GUESSING NUMBER GAME - 3 tries secret_number = random.randint(1,11) max_number_tries = 3 number_tries = play_guessing_game(secret_number, max_number_tries) print_game_results(number_tries, max_number_tries)
def area_square(side_length): area = side_length * side_length print("The area is: " + str(area) +"cm2") area_square(10) area_square(20)
# coding: utf-8 # In[44]: #Implement a userdefined function myreduce() def myreduce(list): y=1 for n in list: y=y*int(n) return(y) l=input("Enter a list with number\n") l=l.split(',') myreduce(l) # In[126]: #Implement a userdefined filter function myfilter() def myfilter(list): z=[] for n in list: if(int(n) % 10 == 0): z.append(n) return(z) l=input("Enter a list with number\n") l=l.split(',') myfilter(l)
""" Formatando valores com modificadores :s - Texto (strings) nu :d - Inteiros (int) :f - Números de ponto flutuante (float) :.(NUMERO)f - Quantidade de casas decimais (float) :(CARCTERE) (> ou < ou ^) (QUANTIDADE) (TIPO - s, d ou f) > - Esquerda < - Direita ^ - Centro """ num_1 = 10 num_2 = 3 divisao = num_1 / num_2 print() print('{:.2f}'.format(divisao)) # Arredondamento para duas casas depois do ponto print() print(f'{divisao:.2f}') # Arredondamento para duas casas depois do ponto print() nome= 'Marcelo Marcondes' print(f'{nome:s}') # Declarando que a variável "nome" é uma String print() num_3 = 1 print() print(f'{num_3:0>10}') # Declarando que o valor a ser demonstrado deve conter 10 caracteres completando com zeros a esquerda print() num_4 = 1150 print() print(f'{num_4:0<10}') # Declarando que o valor a ser demonstrado deve conter 10 caracteres completando com zeros a direita print() print(f'{num_4:0>10.2f}') print() nome2 = ' Marcelo Marcondes ' print(len(nome)) print(f'{nome2:#^50}') # Declarando que a variável deve ter 50 carateres com o valor da variável no meio de # print() nome_formatado = '{:@>50}'.format(nome2) print(nome_formatado) print() nome3 = 'Marcelo' sobrenome = 'Marcondes' nome_indice = '{0:$^15} {1:#^15}'.format(nome3, sobrenome) # Selecionando a variável de acordo com o índice informado print(nome_indice) print() nome4 = 'Marcelo Marcondes' nome4 = nome4.ljust(30, '#') # Justifica no mome a esquerda (left) e preenche com o caracter informado "#" até a quantidade de caracteres informada "30" print(nome4) print() nome5 = 'Marcelo Marcondes' print(nome5.lower()) # Todas as letras ficarão minúsculas print() print(nome5.upper()) # Todas as letras ficarão maísculas print() print(nome5.title()) # A primeira letra de todas as palavras será maíscula e as demais minísculas
""" * Tipos de dados str - string = textos 'Assim' ou "Assim" int - inteiro = 123456 / 0 / -10 / -20 / 1500 float - número real/ponto flutuante = 1.25 / 2.56 / -3.60 bool - booleano/lógico = true/False 10 == 10 """ print("Marcelo", type("Marcelo")) print(123, type(123)) print(2.56, type(2.56)) print("L" == "l", type("L" == "l")) """ A função " type " exibe o tipo de dado informado """ print("10", type("10"), type(int("10"))) """ Type casting significa transformar o tipo do dado informado, no caso acima o dado foi alterado de "string" para "inteiro". """ # Exercício # Nome: string print('Marcelo', type('Marcelo')) # Idade: int print(42, type(42)) # Altura: float print(1.98, type(1.98)) # É maior de idade? print(42 > 18, type(42 > 18))
name ="Elif Sude" surname="Tural" counter = 0 def check(): global counter inputname = input("Enter name: ") inputsurname = input("Enter surname: ") if (name != inputname or surname != inputsurname): counter += 1 print("Name or surname incorrrect.") else: print("Welcome") counter = 99 #loopun durması için if (counter == 3): print("try again") while (counter < 3): check() counter1 = 0 courses = ["Math", "Physics", "Computer Science", "Chemistry", "Economics"] print("Please choose one of the courses below. (min:3, max:5)") for course in courses: print(course) selectedcourses = [] while (len(selectedcourses) < 3): selected = input("Enter course: ") if selected in courses and selected not in selectedcourses: selectedcourses.append(selected) print("Course successfully added.") elif selected == "": print("You should enter more than 3 courses to pass the class. ") answer = input("If you are sure, leave blank again. If you want to continue to take course, type something.") if answer == "": print("You failed class.") elif answer in courses and answer not in selectedcourses: selectedcourses.append(selected) print("Course successfully added.") else: print("Please enter a valid course.") print("From now on, courses are optional. Leave blank if you do not want to get them.") counter2 = len(selectedcourses) while (len(selectedcourses) < 5): extracourse = input("Enter course: ") if extracourse in courses and extracourse not in selectedcourses: selectedcourses.append(extracourse) print("Course successfully added.") elif extracourse == "": print("Okay.") else: print("Please enter a valid course.") print("Courses added.") while(True): examcourse = input("Choose one of the courses you have to take exam. ") if examcourse in selectedcourses: print("Course successfully selected.") break else: print("Please enter a valid course.") grades = { "midterm": 60, "final": 50, "project": 70, } print(grades) averagegrade = ((60* grades["midterm"]/100) + (50*grades["final"]/100) + (70*grades["project"]/100))/3 if averagegrade>90: print("Your score is AA") elif 70<averagegrade<90 : print("Your score is BB") elif 50<averagegrade<70 : print("Your score is CC") elif 30<averagegrade<50 : print("Your score is DD") elif 0<averagegrade<30: print("Your score is FF. You failed the class.")
import nltk from nltk.corpus import wordnet as wn def isFood(inputword): isfood = 0 thesyns = wn.synsets(inputword.lower()) for syn in thesyns: if isfood > 0: break theword=wn.synset(syn.name()) paths = theword.hypernym_paths() for route in paths: if route[-1].name().split('.')[0] not in inputword.lower(): #filter out hierarchies that are to not the exact word. continue # print(route) for item in route: if 'food' in item.name(): print("{} is probably a food.\n".format(inputword.upper())) return print("I don't think {} is a food.\n".format(inputword.upper())) def isthisafood(): ingredient = input("\nEnter a string: \n") ingredient = nltk.word_tokenize(ingredient) POS =nltk.pos_tag(ingredient) print(POS) print("\n") for word in ingredient: isFood(word) choice = input("\nIs there something else that might be a food? y/n?\n") if choice == 'y': isthisafood() else: return print("Not sure if it's a food? Maybe I can help!") isthisafood()
""" THis module is realeted to board basic one that appers without people and bombs """ class Board: """ THis class prints the board and populates blocks in the board""" def __init__(self, rows, columns, x_size, y_size): self.rows = rows self.columns = columns self.x_size = x_size self.y_size = y_size self.enemies = [] def createboard(self): """ This method creates empty board """ board = [[' ' for _ in range(self.columns)]for _ in range(self.rows)] return board def createwallblock(self, board, x_ind, y_ind, char): """ This is a general method to create Wall blocks on empty board """ for i in range(self.y_size): for j in range(self.x_size): board[x_ind + j][y_ind + i] = char return board def buildrigidboard(self, board): # populate border walls """ This method populates Wall blocks on empty board (boundary)""" row = self.rows - (self.rows % 2) col = self.columns - (self.columns % 4) for i in range(int(col/4)): self.createwallblock(board, 0, 4 * i, 'X') self.createwallblock(board, row - 2, 4 * i, 'X') for i in range(int(row/2 - 2)): self.createwallblock(board, 2*i + 2, 0, 'X') self.createwallblock(board, 2*i + 2, col - 4, 'X') return board def buildmiddlewalls(self, board): # populate symmetric middle walls """ This method populates Wall blocks on empty board (inner board)""" row = self.rows - (self.rows % 2) col = self.columns - (self.columns % 4) for i in range(1, int((row - 6) / 4 + 1)): for j in range(1, int((col - 12) / 8 + 1)): self.createwallblock(board, 4*i, 8*j, 'X') return board
phonebook = {"Chris": "555-111", "Katie": "555−2222", "Joanne": "555-333"} "" print() print("***** start section 1 - print dictionary ********") print() print(phonebook) print(len(phonebook)) mydictionary = dict(m=8,n=9) print(mydictionary) print() print("***** end section 1 ********") print() print() print("***** start section 2 - search dictionary ********") print() print(phonebook['Chris']) name = 'chris' if name in phonebook: print(phonebook[name]) else: print('Not Found') print() print("***** end section 2 ********") print() print() print("***** start section 3 - edit/append dictionary ********") print() phonebook['Chris'] = '555-444' phonebook['Joe'] = '555-0123' print(phonebook) print() print("***** end section 3 ********") print() print() print("***** start section 4 - delete/remove from dictionary ********") print() del phonebook['Chris'] print(phonebook) print() print("***** end section 4 ********") print() print() print("***** start section 5 - iterate through keys ********") print() for k in phonebook: print(k) print(phonebook[k]) print() print("***** end section 5 ********") print() print() print("***** start section 6 - iterate through values ********") print() print() print("***** end section 6 ********") print() """ print() print("***** start section 7 - iterate through both key and value pair********") print() for k,v in phonebook.items(): print(k, v) print() print("***** end section 7 ********") print() '''' print() print("***** start section 8 - using random and converting to list ********") print() print() print("***** end section 8 ********") print()
from customer import Customer class Restaurant(object): """A Restaurant. This class represents a restaurant in the simulation. This is the base class for different restaurant approaches. The main purpose of this class to define common interfaces for different approaches. If there are common tasks for all approaches that did not depend on a specific management style, they should be implemented here. Otherwise, they should be implemented in the subclasses. This class is abstract; subclasses must implement add_customer and process_turn functions. You may, if you wish, change the API of this class to add extra public methods or attributes. Make sure that anything you add makes sense for ALL approaches, and not just a particular approach. """ # === Private Attributes === # :type _p_queue: list[Customer] # is a customized priority queue based on each approach. # :type _total: int # describes the total number of customers served # :type _r_profit: float # describes total profit the restaurant makes. # :type _next_action: int # describes the next turn where a new customer's order is chosen. def __init__(self): """Initialize a restaurant. @:rtype: None """ self._p_queue = [] self._total = 0 self._r_profit = 0.0 self._next_action = 1 # There are some aspects of the doctest that call on _p_queue, however # it is not good convention to access a private attribute. Instead, we can # make a getter, a setter, and convert it into a property, and call on the # property in the doctest examples. def _get_p_queue(self): # """ # Return the _p_queue attribute of self. # # :rtype: int # # >>> pat = PatApproach() # >>> pat._get_p_queue() # [] # """ return self._p_queue def _set_p_queue(self, obj): # """ # Set _p_queue of Restaurant self to obj. # # :type obj: Object # :rtype: None # # >>> pat = PatApproach() # >>> pat._set_p_queue(['obj']) # >>> pat._get_p_queue() # ['obj'] # """ self._p_queue = obj p_queue = property(_get_p_queue, _set_p_queue) def add_customer(self, new_customer): """Add a new entering customer to the restaurant. :type new_customer: Customer The new customer that is entering the restaurant :rtype: None """ raise NotImplementedError(" Must de defined in approach subclasses!") def sort_customers(self): """ This helper function makes sure the customers are in proper order in the queue every time this function is called. :rtype: None # Note: writing docstring examples for this particular method becomes # tricky, as the simulator file is also required for a practical test # case. However, after extraneous and careful testing, I assure that #this method is correct. """ temp = [c for c in self._p_queue] self._p_queue = [] # clears the queue and adds every customer to a temporary list if len(temp) != 0: for t in temp: self.add_customer(t) def process_turn(self, current_turn): """Process the current_turn. This function will process the current turn. If the restaurant is not serving any customer now, and there are waiting customers, it should select one of them to serve. You can assume that all customers who entered the restaurant before or during this turn were already passed to the restaurant by simulator via calling the AddCustomer function. :type self: Restaurant :type current_turn: int The number of current turn :rtype: None >>> mat = MatApproach() >>> c1 = Customer('1\t11111\t10\t11\t12') >>> mat.add_customer(c1) >>> mat.process_turn(1) >>> mat.p_queue [] >>> c2 = Customer('3\t22222\t10\t11\t1') >>> mat.add_customer(c2) >>> mat.process_turn(3) >>> mat.p_queue [22222] >>> mat.process_turn(4) >>> mat.p_queue [22222] >>> mat.process_turn(5) >>> mat.p_queue [] """ for c in self._p_queue: if c.patience() + c.entry_turn() <= current_turn: self._p_queue.remove(c) # now must reorder all remaining customers self.sort_customers() self.process_turn(current_turn) # this removes any customer who has reached their maximum patience when # their order has not been chosen yet, and processes the turn again # in case there are multiple people running out of patience, or if # someone must be served on this turn. if current_turn >= self._next_action: if len(self._p_queue) != 0: current_customer = self._p_queue.pop(0) # makes sure the queue is not empty self._r_profit += current_customer.profit() self._total += 1 self._next_action = current_customer.prep() + current_turn # add the customer's prep time in order to choose a customer on # the turn after their order is finished. # Now, we have successfully served a customer # now must reorder all remaining customers self.sort_customers() else: pass def write_report(self, report_file): """Write the final report of this restaurant approach in the report_file. :type self: Restaurant :type report_file: File This is an open file that this restaurant will write the report into :rtype: None """ names = {'PatApproach()': 'Pat', 'MaxApproach()': 'Max', 'MatApproach()': 'Mat', 'PacApproach()': 'Pac'} s = "Results for the serving approach using {}'s suggestion:\n".\ format(names[str(self)]) s += 'Total profit: ${}\n'.format(self._r_profit) s += 'Customer served: {}\n'.format(self._total) report_file.write(s) def __repr__(self): """ Represent Restaurant self as a string that can be evaluated to produce an equivalent Restaurant. @rtype: str """ raise NotImplementedError(" Must de defined in approach subclasses!") class PatApproach(Restaurant): """A Restaurant with Pat management style. This class represents a restaurant that uses the Pat management style, in which customers are served based on their earliest arrival time. This class is a subclass of Restaurant and implements two functions: add_customer and __repr__. """ def add_customer(self, new_customer): """Add a new entering customer to the restaurant according to Pat's priority, which is based on the earliest arrival time. Overrides Restaurant.add_customer :type new_customer: Customer The new customer that is entering the restaurant :rtype: None >>> pat = PatApproach() >>> c1 = Customer('1\t11111\t10\t11\t12') >>> pat.add_customer(c1) >>> pat.p_queue [11111] >>> c2 = Customer('3\t22222\t11\t12\t13') >>> pat.add_customer(c2) >>> pat.p_queue [11111, 22222] >>> c3 = Customer('2\t33333\t12\t13\t14') >>> pat.add_customer(c3) >>> pat.p_queue [11111, 33333, 22222] """ lst = [x.entry_turn() for x in self._p_queue] # add all entry turns from all existing customers to a list. new_et = new_customer.entry_turn() lst.sort() if new_et in lst: # find last occurrence of the new_et value and insert after that # occurrence. back = lst[::-1] last = back.index(new_et) target = len(lst) - last else: lst.append(new_et) lst.sort() target = lst.index(new_et) self._p_queue.insert(target, new_customer) def __repr__(self): """ Represent PatApproach(self) as a string that can be evaluated to produce an equivalent PatApproach. Overrides Restaurant.__repr__ @rtype: str >>> p = PatApproach() >>> p PatApproach() """ return 'PatApproach()' class MatApproach(Restaurant): """A Restaurant with Mat management style. This class represents a restaurant that uses the Mat management style, in which customers are served based on their latest entry time. This class is a subclass of Restaurant and implements two functions: add_customer and __repr__. """ def add_customer(self, new_customer): """Add a new entering customer to the restaurant according to Mat's priority, which is based on the most recent arrival time. Overrides Restaurant.add_customer :type new_customer: Customer The new customer that is entering the restaurant :rtype: None >>> mat = MatApproach() >>> c1 = Customer('1\t11111\t10\t11\t12') >>> mat.add_customer(c1) >>> mat.p_queue [11111] >>> c2 = Customer('3\t22222\t11\t12\t13') >>> mat.add_customer(c2) >>> mat.p_queue [22222, 11111] >>> c3 = Customer('2\t33333\t12\t13\t14') >>> mat.add_customer(c3) >>> mat.p_queue [22222, 33333, 11111] """ lst = [x.entry_turn() for x in self._p_queue] # add all entry turns from all existing customers to a list. new_et = new_customer.entry_turn() lst.append(new_et) lst.sort() lst1 = lst[::-1] # reverse the list to order it from high (latest) entry time to low target = lst1.index(new_et) # find the placement of the entry turn of the new customer in comparison # to all of the other entry turns self._p_queue.insert(target, new_customer) def __repr__(self): """ Represent MatApproach(self) as a string that can be evaluated to produce an equivalent MatApproach. Overrides Restaurant.__repr__ @rtype: str >>> m = MatApproach() >>> m MatApproach() """ return 'MatApproach()' class MaxApproach(Restaurant): """A Restaurant with Max management style. This class represents a restaurant that uses the Max management style, in which customers are served based on their maximum profit. This class is a subclass of Restaurant and implements two functions: add_customer and __repr__. """ def add_customer(self, new_customer): """Add a new entering customer to the front of the restaurant queue according to Max's priority, which is based on the maximum profit of the customer. Overrides Restaurant.add_customer :type new_customer: Customer The new customer that is entering the restaurant :rtype: None >>> mx = MaxApproach() >>> c1 = Customer('1\t44444\t10\t11\t12') >>> mx.add_customer(c1) >>> mx.p_queue [44444] >>> c2 = Customer('2\t55555\t11\t12\t13') >>> mx.add_customer(c2) >>> mx.p_queue [55555, 44444] >>> c3 = Customer('3\t66666\t9\t13\t14') >>> mx.add_customer(c3) >>> mx.p_queue [55555, 44444, 66666] """ # for all of the customers, it needs to look through all of the # profits and add to the queue where the # highest profit is most prioritized. lst = [x.profit() for x in self._p_queue] # add all profits from all existing customers to a list. new_et = new_customer.profit() # separate the new customer's profit value. lst.append(new_et) lst.sort() lst1 = lst[::-1] # Reverse the list so that it displays from highest to lowest target = lst1.index(new_et) # find the placement of the profit of the new customer in comparison # to all of the other profits self._p_queue.insert(target, new_customer) def __repr__(self): """ Represent MaxApproach(self) as a string that can be evaluated to produce an equivalent MaxApproach. @rtype: str Overrides Restaurant.__repr__ >>> m = MaxApproach() >>> m MaxApproach() """ return 'MaxApproach()' class PacApproach(Restaurant): """A Restaurant with Pac management style. This class represents a restaurant that uses the Pac management style, in which customers are served based on their order's preparation time. This class is a subclass of Restaurant and implements two functions: add_customer and __repr__. """ def add_customer(self, new_customer): """Add a new entering customer to the front of the restaurant queue according to Pac's priority, which is based on the shortest order prep time of the customer. Overrides Restaurant.add_customer :type new_customer: Customer The new customer that is entering the restaurant :rtype: None >>> pc = PacApproach() >>> c1 = Customer('1\t77777\t10\t3\t12') >>> pc.add_customer(c1) >>> pc.p_queue [77777] >>> c2 = Customer('2\t88888\t11\t2\t13') >>> pc.add_customer(c2) >>> pc.p_queue [88888, 77777] >>> c3 = Customer('3\t99999\t9\t4\t14') >>> pc.add_customer(c3) >>> pc.p_queue [88888, 77777, 99999] """ # for all of the customers, it needs to look through all of the # prepare times and add to the queue where the least/shortest order # prepare time is most prioritized. lst = [x.prep() for x in self._p_queue] # add all prep times from all existing customers to a list. new_et = new_customer.prep() lst.sort() if new_et in lst: # find last occurrence of the new_et value and insert after that # occurrence. back = lst[::-1] last = back.index(new_et) target = len(lst) - last else: lst.append(new_et) lst.sort() target = lst.index(new_et) self._p_queue.insert(target, new_customer) def __repr__(self): """ Represent PacApproach(self) as a string that can be evaluated to produce an equivalent PacApproach. Overrides Restaurant.__repr__ @rtype: str >>> p = PacApproach() >>> p PacApproach() """ return 'PacApproach()' if __name__ == '__main__': import doctest doctest.testmod()
# Set of all keywords in the Jack grammar. KEYWORDS = { 'class', 'constructor', 'function', 'method', 'field', 'static', 'var', 'int', 'char', 'boolean', 'void', 'true', 'false', 'null', 'this', 'let', 'do', 'if', 'else', 'while', 'return', } # Set of all the symbols in the Jack grammar. SYMBOLS = { '{', '}', '(', ')', '[', ']', '.', ',', ';', '+', '-', '*', '/', '&', '|', '<', '>', '=', '~', } # Simple class that takes a token string as input and classifies it into the # correct type and correctly formats its value. class Token: def __init__(self, token: str): if token == '': self.type = 'eof' self.value = token elif token in KEYWORDS: self.type = 'keyword' self.value = token elif token in SYMBOLS: self.type = 'symbol' self.value = token elif token[0].isdigit(): self.type = 'integerConstant' self.value = int(token) elif token[0] == '"': self.type = 'stringConstant' self.value = token[1:-1] else: self.type = 'identifier' self.value = token def __repr__(self): return f'{self.type}: {self.value}' # Class to generate and store a list of Tokens from the given code, along with # metadata to be able to generate descriptive error messages later. class TokenList: def __init__(self, code: str): self.original = code self.tokens = [] self.map = [] self.pos = 0 i = 0 # Add a newline at the end of the code if there isn't one there if not code.endswith('\n'): code += '\n' # Try block to catch the iteration reaching the end of the code while # still scanning a identifier or literal. try: while i < len(code): char = code[i] # If the character is a forward slash, check if we're dealing # with a comment, and if so, skip till the end of the comment. if char == '/': # If the next character is also a slash, then this is a # one line comment, so skip up to the next newline char. if code[i + 1] == '/': i += 2 while code[i] != '\n': i += 1 i += 1 continue # If the next character is an asterix, then this is a block # comment, so skip until a block comment close is found. elif code[i + 1] == '*': i += 2 while code[i:i + 2] != '*/': i += 1 i += 2 continue # If the character is a symbol, generate a Token from it as is. if char in SYMBOLS: self.map.append(i) self.tokens.append(Token(char)) i += 1 # If the character is a digit, check if subsequent characters # are also digits. If they are, append them to the Token. elif char.isdigit(): self.map.append(i) token = char while code[(i := i + 1)].isdigit(): token += code[i] if code[i] in SYMBOLS or code[i].isspace(): self.tokens.append(Token(token)) else: self.error(ValueError('Invalid integer'), True) # If the character is a double quote, then this must be the # start of a string. Append characters until the next quote. elif char == '"': self.map.append(i) token = char while code[(i := i + 1)] != '"': token += code[i] token += code[i] self.tokens.append(Token(token)) i += 1 # If the character is an alphabet or underscore, then it may # either be the start of an identifier or keyword. elif char.isalpha() or char == '_': self.map.append(i) token = char while code[(i := i + 1)].isalnum() or code[i] == '_': token += code[i] if code[i] in SYMBOLS or code[i].isspace(): self.tokens.append(Token(token)) else: self.error(ValueError( f'Invalid character in identifier "{code[i]}"' ), True) # If the character is whitespace, just continue. elif char.isspace(): i += 1 # If it's none of the above, raise an error. else: self.error(ValueError('Invalid character'), True) # Add an extra EOF token. self.tokens.append(Token('')) except IndexError: raise ValueError('Unexpected EOF') # Function to add line and column metadata to a syntax error. def error(self, error: Exception, incomplete: bool = False): if incomplete: pos = self.map[-1] else: pos = self.map[self.pos - 1] code = self.original last_newline = pos - 1 while code[last_newline] != '\n' and last_newline > 0: last_newline -= 1 next_newline = pos + 1 while code[next_newline] != '\n' and next_newline < len(code): next_newline += 1 col_num = pos - last_newline line_num = 1 + code[ :last_newline + 1].count('\n') lines = '' if line_num > 1: l2l_newline = last_newline - 1 while code[l2l_newline] != '\n' and l2l_newline > 0: l2l_newline -= 1 lines += str(line_num - 1) + ' ' lines += ' ' * (len(str(line_num)) - len(str(line_num - 1))) lines += code[l2l_newline + 1 : last_newline] + '\n' lines += str(line_num) + ' ' lines += code[last_newline + 1 : next_newline] + '\n' lines += ' ' * len(str(line_num)) + ' ' + ''.join( char if char.isspace() else ' ' for char in code[last_newline + 1 : pos] ) + '^' message = f'Error in line {line_num}, col {col_num}\n\n' message += lines + '\n\nSyntax error: ' + str(error) raise ValueError(message) # Function to return the current token and prime the next token. def pop(self): token = self.tokens[self.pos] self.pos += 1 return token # Function to return a token "skip" positions from the current one. def get(self, skip: int = 0): return self.tokens[self.pos + skip] # Function to neatly display all the parsed tokens. def __str__(self): return str([str(token) for token in self.tokens])
# -*- coding: utf-8 -*- """ Created on Sun Aug 1 13:39:18 2021 @author: USUARIO """ Nombre=input("Ingrese Nombre: ") Apellido=input("Ingrese Apellido: ") Pais=input("Ingrese Pais: ") Ciudad=input("Ingrese Ciudad: ") Edad=input("Ingrese Edad: ") print("") print("Datos Personales") print("Nombre: ",Nombre) print("Apellido: ",Apellido) print("Pais: ",Pais) print("Ciudad: ",Ciudad) print("Edad: ",Edad)
from datetime import datetime date_entry = input('dwse imerominia etsi:ΗΗ/ΜΜ/ΕΕΕΕ')#mu vazi o user tin hmerominia year, month, day = map(int, date_entry.split(','))#apo edo ego tha paro ta year,month,day date = datetime(day, month, year) from datetime import date today = date.today().isoformat() print("simera exume",today) slo=today import re simera = re.sub("[^\w]", " ", slo).split()#kano tin simerini hmerominia se array kai meta tha kano upologismus #to simera einai lista me mera,mina,xrono tou shmera mera=year #edo eprepe na kano kapies alages giati tin hmera tin eperne gia xrono kai ton xrono gia mera, mhnas htan idios agia kapio logo alla den mas pirazi minas=month if minas in (1,3,5,7,8,10,12): print ("o minas pu mu dosate exi 31 meres") else : if minas in(4,6,9,11): print("o minas pu dosate exi 30 meres") else : print("o minas pu dosate einai o februarios kai exi 27 h 29 meres analogos") xronos=day simeramera=int(simera[2]) simeraminas=int(simera[1]) simeraxronos=int(simera[0]) if simeramera > mera : diaforamera= simeramera-mera else : diaforamera= mera - simeramera if simeraminas > minas: diaforaminas= simeraminas - minas else: diaforaminas= minas - simeraminas if simeraxronos > xronos: diaforaxronos= simeraxronos - xronos else: diaforaxronos= xronos - simeraxronos #tora tha metatrepso tis diafores se meres ores kai defterolepta wres1= 24 * diaforamera defterolepta1=wres1*3600 meres1=diaforaminas*30 wres2=meres1*24 defterolepta2=wres2*3600 meres2=diaforaxronos*365 wres3=meres2*24 defterolepta3=wres3*3600 sinolomeres= diaforamera + meres1 + meres2 sinolowres= wres1+wres2+wres3 sinolodeftera= defterolepta1+defterolepta2+defterolepta3 print("h diafora metaxi simerinis hmerominias kai aftis pu dosate se meres,wres,defterolepta einai",sinolomeres,sinolowres,sinolodeftera)
import sortLib as sl def mergesort(inputList): if len(inputList) == 1: return inputList # Floor Division mid = len(inputList)//2 list1 = mergesort(inputList[:mid]) list2 = mergesort(inputList[mid:]) return merge(list1, list2) def merge(list1, list2): retList = [] while (len(list1) > 0 and len(list2) > 0): if (list1[0] > list2[0]): retList.append(list2[0]) list2.pop(0) else: retList.append(list1[0]) list1.pop(0) if list1: retList.extend(list1) if list2: retList.extend(list2) return retList if __name__ == '__main__': ipList = sl.inputListCli() outList = mergesort(ipList) print outList
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 12 06:58:59 2018 @author: Sylvia """ #Following Links in Python #In this assignment you will write a Python program that expands on #http://www.py4e.com/code3/urllinks.py. The program will use urllib to #read the HTML from the data files below, extract the href= vaues from #the anchor tags, scan for a tag that is in a particular position relative #to the first name in the list, follow that link and repeat the process a #number of times and report the last name you find. import urllib.request,urllib.parse,urllib.error from bs4 import BeautifulSoup url = input('Enter URL-') repeat = input('Repeat Times-') position = input('Target Position-') count = 0 while count<int(repeat): html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html,'html.parser') tags = soup('a') pos = 0 for line in tags: pos+=1 if pos == int(position): print (line.contents[0]) url = line.get('href') count+=1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 24 17:39:55 2018 @author: Sylvia """ # Question 8: Longest Repetition # Define a procedure, longest_repetition, that takes as input a # list, and returns the element in the list that has the most # consecutive repetitions. If there are multiple elements that # have the same number of longest repetitions, the result should # be the one that appears first. If the input list is empty, # it should return None. def longest_repetition(list): if list == []: return None else: previous = 0 current = 1 i = 1 number = list[0] output = number while i < len(list): if number == list[i]: current = current + 1 else: if previous < current: previous = current output = number number = list[i] current = 1 else: current = 1 number = list[i] i = i + 1 if previous < current: output = number return output #For example, print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1]) # 3 print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']) # b print longest_repetition([1,2,3,4,5]) # 1 print longest_repetition([]) # None print longest_repetition([2,2,3,3,4,4,4])
# -*- coding: utf-8 -*- ##PANDAS #veri temizleme ve veri analizi modülü #iki veri yapısına sahiptir. series ve dataframe #numpy dizilerinde bulunan elemanlar aynı veri tipinde olurken pandas #birden fazla farklı veri tipine sahip olabilir. #seriler numpy dizilerine benzer import numpy as np import pandas as pd #serimizi oluşturduk sayılar=[0,1,2,3,4,5,6,7,8,9] seriler=pd.Series(data=sayılar) print(seriler.sum()) print(seriler.min()) print(seriler.max()) print(seriler.mean()) print(seriler.median()) print(seriler.var()) print(seriler.std()) sayılar2=[9,8,7,6,5,4,3,2,1,0] seriler2=pd.Series(data=sayılar2) print(seriler+seriler2) print(seriler+5) print(seriler2-seriler) print(seriler*seriler2) print(seriler*3) print(seriler2*3) #seriler=pd.Series(data,index) #data sabit değer alabilir #data liste aalbilir. #data numpy dizisi alabilir. #data dictionary(sözlük) degeri alabilir. sayılar=[0,1,2,3,4,5,6,7,8,9] numpy_array=np.array(sayılar)#nesne oluşturma print(numpy_array) #pandasta seri oluştur seriler=pd.Series(data=sayılar) print(seriler) my_index=['a','b','c','d','e','f','g','h','i','j'] seriler=pd.Series(data=sayılar, index=my_index ,dtype=float) print(seriler) #sözlük veri tipini data olarak kullanalım sözlük={'a':0,'b':1,'c':2,'d':3} #key ve value degerleri seriler=pd.Series(data=sözlük) print(seriler) #pandas serilerinin boyutunu ögrenme print(seriler.ndim) #veri tipi ögrenme print(seriler.dtype) #satır ve sutun sayısı ögrenme print(seriler.shape)
class Estudiante(object): def __init__(self, nombre_r, edad_r): self.nombre = nombre_r self.edad = edad_r def hola(self): #(%s texto) (%i numero) return "Mi nombre es %s y tengo %i" % (self.nombre, self.edad) e = Estudiante("Roberto", 28) s = e.hola() #print s lista_de_alumnos = list() for es in range(5): nombre = "Estudiante %i" % es e = Estudiante(nombre, 23) lista_de_alumnos.append(e) #print lista_de_alumnos for es in lista_de_alumnos: if es.nombre == "Estudiante 2": print "Soy el estudiante 2" else: print "No soy el estudiante 2"
#! /usr/bin/python def factorial(n): ret = n for i in range(1,n): ret *= i return ret n = 40 print ( factorial(n) / ( factorial(n-n/2) * factorial(n/2) ) )
### def minion_games(string): string = string vowels = 'EIUOA' kevin = 0 stuart = 0 length_s = len(string) for i in range(length_s): if string[i] in vowels: kevin = kevin + length_s - i else: stuart = stuart + length_s-i if kevin > stuart: print("Kevin", kevin) elif kevin < stuart: print("Stuart", stuart) else: print("Draw") minion_games('BANANA')
n = int(input("Podaj ilość liczb:")) l = [] for i in range(n): i = int(input("Podaj liczbe:")) l.append(i) l.sort() print(l) print(l[0]) print(l[-1])
import unittest class FunInterviewQuestion(unittest.TestCase): def test_reverse_string(self): sentense = "I am a happy person" expected = "Person happy a am I" ls_sentense = sentense.split() rv_list = list(reversed(ls_sentense)) new_sentense = " ".join(rv_list) result = new_sentense[0].upper() + new_sentense[1:] # result = " ".join(list(reversed(sentense.split())))[0].upper() + \ # " ".join(list(reversed(sentense.split())))[1:] self.assertEqual(expected, result) if __name__ == '__main__': unittest.main()
from random import * import time class Person(object): """ Person class aspects of personality based on Myers Briggs Personality types mood (int) -50 to 50 name (string) All boolean types: energy => Natural energy (extraverted to introverted) perception => (sensing to intuitive) judgement => (thinking to feeling) action => (judging to perceiving) Boolean values: true / false => extraverted / introverted; etc """ __slots__ = ("name", "mood", "energy", "perception", "judgement", "action") def __init__(self, name, m=bool(getrandbits(1)), e=bool(getrandbits(1)), p=bool(getrandbits(1)), j=bool(getrandbits(1)), a=bool(getrandbits(1))): """ Initializes a person with set personality and neutral mood """ self.name = name self.mood = m self.energy = e self.perception = p self.judgement = j self.action = a def __str__(self): """ Returns character mood and personality type """ ptype = "" if self.energy: ptype += "E" else: ptype += "I" if self.perception: ptype += "S" else: ptype += "I" if self.judgement: ptype += "T" else: ptype += "F" if self.action: ptype += "J" else: ptype += "P" return(self.name + ":\n" + "\tMood:\t" + str(self.mood) + "\n\tType:\t" + ptype) class Relationship(object): """ Relationship class p1 (Person) Person 1 p2 (Person) Person 2 commitment (int) in the short term, the decision to remain with another, and in the long term, the shared achievements and plans made with that other intimacy (int) feelings of attachment, closeness, connectedness, and bondedness passion (int) encompasses drives connected to both limerence and sexual attraction Based on Robert Sternberg's "Triangular Theory of Love" """ __slots__ = ("p1", "p2", "commitment", "intimacy", "passion") def __init__(self, adam, steve): """ Initializes a relationship with two people, setting zero values to begin """ self.p1 = adam self.p2 = steve self.commitment = 0 self.intimacy = 0 self.passion = 0 def __str__(self): """ Returns passion, commitment, and intimacy values in addition to an "rtype" or "Relationship Type" """ rtype = "" INTIMACY_THRESHOLD = 5 PASSION_THRESHOLD = 5 COMMITMENT_THRESHOLD = 5 if self.intimacy >= INTIMACY_THRESHOLD and self.passion <= INTIMACY_THRESHOLD and self.commitment <= INTIMACY_THRESHOLD: rtype = "Friendship" elif self.intimacy <= INTIMACY_THRESHOLD and self.passion >= PASSION_THRESHOLD and self.commitment <= INTIMACY_THRESHOLD: rtype = "Infatuated Love" elif self.intimacy <= INTIMACY_THRESHOLD and self.passion <= INTIMACY_THRESHOLD and self.commitment >= COMMITMENT_THRESHOLD: rtype = "Empty Love" elif self.intimacy >= INTIMACY_THRESHOLD and self.passion >= PASSION_THRESHOLD and self.commitment <= INTIMACY_THRESHOLD: rtype = "Romantic Love" elif self.intimacy >= INTIMACY_THRESHOLD and self.passion <= INTIMACY_THRESHOLD and self.commitment >= COMMITMENT_THRESHOLD: rtype = "Companionate Love" elif self.intimacy >= INTIMACY_THRESHOLD and self.passion >= PASSION_THRESHOLD and self.commitment <= COMMITMENT_THRESHOLD: rtype = "Fatuous Love" elif self.intimacy >= INTIMACY_THRESHOLD and self.passion >= PASSION_THRESHOLD and self.commitment >= COMMITMENT_THRESHOLD: rtype = "Consummate Love" elif self.intimacy < 0 and self.passion < 0: rtype = "Hatred" elif self.intimacy < 0 and self.passion > 0: rtype = "Lustful Distrust" else: rtype = "No Standing Relationship" return "Relationship between " + self.p1.name + " and " + self.p2.name + ":\n\tType:\t\t" + rtype + "\n\tCommitment:\t" + str(self.commitment) + "\n\tIntimacy: \t" + str(self.intimacy) + "\n\tPassion: \t" + str(self.passion) def sPrint(self): rtype = "" INTIMACY_THRESHOLD = 5 PASSION_THRESHOLD = 5 COMMITMENT_THRESHOLD = 5 if self.intimacy >= INTIMACY_THRESHOLD and self.passion <= INTIMACY_THRESHOLD and self.commitment <= INTIMACY_THRESHOLD: rtype = "Friendship" elif self.intimacy <= INTIMACY_THRESHOLD and self.passion >= PASSION_THRESHOLD and self.commitment <= INTIMACY_THRESHOLD: rtype = "Infatuated Love" elif self.intimacy <= INTIMACY_THRESHOLD and self.passion <= INTIMACY_THRESHOLD and self.commitment >= COMMITMENT_THRESHOLD: rtype = "Empty Love" elif self.intimacy >= INTIMACY_THRESHOLD and self.passion >= PASSION_THRESHOLD and self.commitment <= INTIMACY_THRESHOLD: rtype = "Romantic Love" elif self.intimacy >= INTIMACY_THRESHOLD and self.passion <= INTIMACY_THRESHOLD and self.commitment >= COMMITMENT_THRESHOLD: rtype = "Companionate Love" elif self.intimacy >= INTIMACY_THRESHOLD and self.passion >= PASSION_THRESHOLD and self.commitment <= COMMITMENT_THRESHOLD: rtype = "Fatuous Love" elif self.intimacy >= INTIMACY_THRESHOLD and self.passion >= PASSION_THRESHOLD and self.commitment >= COMMITMENT_THRESHOLD: rtype = "Consummate Love" else: rtype = "No Standing Relationship" return (self.p1.name + " and " + self.p2.name + " " + rtype) def progress(self): """ Representing day to day life Calculates random mood changes in both people Advances intimacy, passion, and commitment based on Myers Briggs compatibility combinations """ self.p1.mood += randint(-2,2) self.p2.mood += randint(-2,2) self.intimacy = randint(-2,3) + (self.p1.energy == self.p2.energy if 2 else 0) + (self.p1.mood // 5) + (self.p2.mood // 5) self.passion = randint(-1,3) + (self.p1.judgement == self.p2.judgement if 2 else 0) + (self.p1.mood // 5) + (self.p2.mood // 5) self.commitment = randint(-2,3) + (self.p1.energy == self.p2.energy if 1 else 0) + (self.p1.mood // 5) + (self.p2.mood // 5) def main(): """ Runs "life" for a set period of iterations """ seed() people = list() people.append(Person("Dave", 0, True, False, True, False)) people.append(Person("Charles", 0, bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)))) people.append(Person("Beth", 0, bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)))) people.append(Person("Kate", 0, bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)))) people.append(Person("Ian", 0, bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)))) people.append(Person("Devin", 0, bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)))) people.append(Person("Gina", 0, bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)))) people.append(Person("Krysta", 0, bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)), bool(getrandbits(1)))) """ Create connections for each person Excludes relationship with self """ connections = list() for i in range(0, len(people)): for j in range(i, len(people)): if i != j: connections.append(Relationship(people[i],people[j])) """ Advances relationships over a set number of iterations """ for r in range(0,50): for c in connections: #print("Mingling...") #print(c.p1) #print(c.p2) c.progress() #print(c) #time.sleep(2) """ Print connections and print people """ for c in connections: #print("Finals...") #print(c.p1) #print(c.p2) #c.progress() print(c) #time.sleep(2) for p in people: print(p) main()
class Node(object): def __init__(self, data): self.data = data self.leftChild = None self.rightChild = None class Bst(object): def __init__(self): self.root = None def insert(self, data): if not self.root: self.root = Node(data) else: self.insertNode(data, self.root) # O(log N) if the tree is balanced def insertNode(self, data, root): if data < root.data: if root.leftChild: self.insertNode(data, root.leftChild) else: root.leftChild = Node(data) else: if root.rightChild: self.insertNode(data, root.rightChild) else: root.rightChild = Node(data) def predeccor(self, root): if root.rightChild: return self.predeccor(root.rightChild) return root def removeNode(self, data, root): if not root: return root if data < root.data: root.leftChild = self.removeNode(data, root.leftChild) elif data > root.data: root.rightChild = self.removeNode(data, root.rightChild) else: if not root.leftChild and not root.rightChild: del root return None if not root.leftChild: tempNode = root.rightChild del root return tempNode if not root.rightChild: tempNode = root.leftChild del root return tempNode tempNode = self.predeccor(root.leftChild) root.data = tempNode.data root.leftChild = self.removeNode(tempNode.data, root.leftChild) return root def remove(self, data): if self.root: self.root = self.removeNode(data, self.root) def getMinValue(self): if self.root: return self.getMin(self.root) def getMin(self, root): if root.leftChild: return self.getMin(root.leftChild) return root.data def getMaxValue(self): if self.root: return self.getMax(self.root) def getMax(self, root): if root.rightChild: return self.getMax(root.rightChild) return root.data def traverse(self): if(self.root): self.traverseInorder(self.root) def traverseInorder(self, node): if node.leftChild: self.traverseInorder(node.leftChild) print(node.data) if node.rightChild: self.traverseInorder(node.rightChild) B = Bst() B.insert(10) B.insert(5) B.insert(15) B.insert(6) # print(B.getMinValue()) # print(B.getMaxValue()) B.traverse() print("Tree") B.remove(5) B.traverse() print("Tree") B.remove(10) B.traverse()
""" FILE: UnitTestCryptoGraph.py AUTHOR: Joby Mathew UNIT: COMP5008 Data Structures and Algorithms PURPOSE: Provides a Test Harness for Linked List REFERENCE: Lecture Slides Last Mod: 25th October, 2020 """ from LinkedList import DSALinkedList # Initializing the list testList = DSALinkedList() # Adding to the list assets = ['BNB', 'ETH', 'BTC', 'USDT', 'PAX', 'USD', 'BCC', 'GAS', 'UTC', 'BNT'] for val in assets: testList.insertFirst(val) print('List empty: ', testList.isEmpty()) print('\nDisplaying the values in the list') print(testList.listOfValues()) print('\nNumber of elements in the list:', testList.count()) print('\nDisplaying the first value in the list:', testList.peekFirst()) print('\nDisplaying the last value in the list:', testList.peekLast()) print('\nAdding UNT to the end of the list') testList.insertLast('UNT') print('Displaying the last value in the list:', testList.peekLast()) print('\nRemoving the first element') testList.removeFirst() print('Displaying the first value in the list:', testList.peekFirst()) print('\nRemoving the last element') testList.removeLast() print('Displaying the last value in the list:', testList.peekLast()) print('\nRemoving PAX') testList.remove('PAX') print('Checking if PAX exists in the list: ', testList.hasNode('PAX'))
import numpy as np from numpy import exp, array, random, dot import pandas as pd from sklearn import preprocessing """ Project demonstrating simple backpropogation in Neural networks. Data used is the marks of three exams which are used to predict final score """ min_max_scaler = preprocessing.MinMaxScaler() tests_score = np.array([[78,85,91],[65,78,51],[69,80,75],[96,94,91],[86,90,78],[68,76,65]]) final_score = np.array([[88],[71],[85],[95],[80],[60]]) #data preperation x_scaled = preprocessing.scale(tests_score) y_scaled = preprocessing.scale(final_score) x_minmax_scaled = min_max_scaler.fit_transform(x_scaled) y_minmax_scaled = min_max_scaler.fit_transform(y_scaled) class Neural_Net(object): #initialize hyper-parameters (ite is the number of iterations of gradiant descent) def __init__(self, x, y, lr, ite): self.x = x self.y = y self.lr = lr self.ite = ite self.innerlayer = 3 #input layer self.hiddenlayer = 7 self.outerlayer = 1 self.W_one = 2 * np.random.rand(self.hiddenlayer, self.innerlayer) - 1 self.W_two = 2 * np.random.rand(self.outerlayer, self.hiddenlayer) - 1 def backProp(self): for i in range(self.ite): #basic forward propogation stff self.z_1 = np.dot( self.W_one,self.x) self.a_1 = sigma(self.z_1) self.z_2 = np.dot(self.W_two, self.a_1) self.a_2 = self.sigma(self.z_2) #calculation of error and deltas for each layer self.error = (self.a_2 - self.y) self.delta_2 = self.error * self.sigma_der(self.z_2) self.error_2 = np.dot(self.W_two.T, self.delta_2) self.delta_1 = np.multiply(self.error_2, self.sigma_der(self.z_1)) #slope of cost with respective weights self.DJDW_2 = np.dot(self.delta_2, self.a_1.T) self.DJDW_1 = np.dot(self.delta_1, self.x.T) #updating weights with new values self.W_one -= self.lr * self.DJDW_1 self.W_two -= self.lr * self.DJDW_2 return 100 * self.a_2 def sigma(self,a): return 1 / (1 + np.exp(-a)) def sigma_der(self,a): return np.exp(-a)/((1+np.exp(-a))**2) NN = Neural_Net(x_minmax_scaled.T, y_minmax_scaled.T, 0.05, 10000) y_hat = NN.backProp() print(y_hat.T)
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ return list(x) s = Solution() o = s.reverse(123) print(o)
# Polynomial Regression #importing Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values #fitting linear regression to dataset from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X, y) #fitting Polynomial Regression to dataset from sklearn.preprocessing import PolynomialFeatures #transform X into Polynomial Matrix poly_reg = PolynomialFeatures(degree = 6) X_poly = poly_reg.fit_transform(X) # this regression is trained by X_poly that means by polynomial matrix lin_reg2 = LinearRegression() lin_reg2.fit(X_poly, y) #visualizing the Linear Regression Results plt.scatter(X, y, color = 'red') plt.plot(X, lin_reg.predict(X)) plt.xlabel = 'Experience Level' plt.ylabel = 'Salaries' plt.title = 'Salaries vs Experience' plt.show() #Visualizing the Polynomial Regression results plt.scatter(X, y, color = 'red') plt.plot(X, lin_reg2.predict(poly_reg.fit_transform(X))) plt.xlabel = 'Experience Level' plt.ylabel = 'Salaries' plt.title = 'Salaries vs Experience' plt.show() #predicting a new results with Linear Regression lin_reg.predict(6.5) #predicting a new results with Polynomial Regression lin_reg2.predict(poly_reg.fit_transform(6.5))
""" 773. Sliding Puzzle Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move. On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. Input: board = [[4,1,2], [5,0,3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2], [5,0,3]] After move 1: [[4,1,2], [0,5,3]] After move 2: [[0,1,2], [4,5,3]] After move 3: [[1,0,2], [4,5,3]] After move 4: [[1,2,0], [4,5,3]] After move 5: [[1,2,3], [4,5,0]] """ """ BFS find shortest check end: string to compare X traversal board transfer board -> string """ from collections import deque def slidingPuzzle(board: [[int]]) -> int: start = ''.join(str(d) for row in board for d in row) # "412503" queue = deque() seen = set() # seen append start status queue.append((start, start.index('0'))) step = 0 row = len(board) col = len(board[0]) def checkvalid(i,j): return 0<=i<len(board) and 0<=j<len(board[0]) while queue: # get next status level by level nextlevel = deque() for i in range(len(queue)): # get current status and idx of 0 cur, curidx = queue.popleft() seen.add(cur) # base case if cur == '123450': return step # cal x, y in board x = curidx // col y = curidx % col # go 4-directionally adjacent number and swapping it for i, j in [(0, 1), (1, 0),(-1, 0), (0, -1)]: if checkvalid(x+i, y+j): currow = x+i curcol = y+j # string is unmutable characters = [d for d in cur] characters[curidx], characters[currow* col + curcol] = characters[currow* col + curcol], '0' nextstate = ''.join(characters) # check whether in seen if nextstate not in seen: nextlevel.append((nextstate, currow* col + curcol)) step += 1 queue = nextlevel return -1
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self): return f"({self.val},{self.next})" # try printing, simply improved the result of it # one of Python’s “dunder” (double-underscore) methods and gets called when you try to convert an object into a string # through the various means that are available # >> > str(my_car) # 'a red car' # >> > '{}'.format(my_car) # 'a red car' # # The fact that these methods start and end in double underscores is simply a naming convention # to flag them as core Python features. # https://dbader.org/blog/python-repr-vs-str # f'Car({self.color!r}, {self.mileage!r})' # __class__.__name__ attribute, which will always reflect the class’ name as a string. # The string returned by __str__() is the informal string representation of an object and should be readable. # The string returned by __repr__() is the official representation and should be unambiguous. !r # >> > f"{new_comedian}" # 'Eric Idle is 74.' # >> > f"{new_comedian!r}" # 'Eric Idle is 74. Surprise!' # https://realpython.com/python-f-strings/#python-f-strings-the-pesky-details def __str__(self): return f'a {self.val} node' """fast low mod solution""" # time : O(n) space : O(1) class Solution: def rotateRight(self, head: 'ListNode', k: 'int') -> 'ListNode': if not head or not head.next or k == 0: return head # close the linked list into a ring p = head # defaults to none and 0 list_len = 0 # do a preprocess path O(n), just to figure out how long the link is while p != None: p = p.next list_len += 1 k %= list_len slow, fast = head, head # n-k times, k is the rotation you want to do for i in range(k): fast = fast.next # advance both fast and slow pointer until we get to the end of the list # make sure fast stops right before the end while fast.next is not None: slow = slow.next fast = fast.next # then there's going to be some pointer arithmetic O(1) fast.next = head head = slow.next slow.next = None return head
""" 116. Populating Next Right Pointers in Each Node """ class Node: def __init__(self, val: int = 0, left = None, right= None, next= None): self.val = val self.left = left self.right = right self.next = next from collections import deque class Solution: def connect(self, root): # level order traversal if not root: return root queue =deque() queue.append(root) while queue: newqueue = [] prev = None while queue: cur = queue.pop() cur.next = prev # add next level if cur.right: newqueue.append(cur.right) if cur.left: newqueue.append(cur.left) prev = cur """ add right + left ==> reverse newqueue""" queue = newqueue[::-1] print(queue) return root """ sol 2 useing next pointer leftmost = root while (leftmost.left != null) { head = leftmost while (head.next != null) { 1) Establish Connection 1 2) Establish Connection 2 using next pointers head = head.next } leftmost = leftmost.left } """
import collections # There are N students in a class. # Some of them are friends, while some are not. # Their friendship is transitive in nature. # For example, if A is a direct friend of B, and B is a direct friend of C, # then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends. # Given a N*N matrix M representing the friend relationship between students in the class. # If M[i][j] = 1, then the ith and jth students are direct friends with each other, # otherwise not. And you have to output the total number of friend circles among all the students. # Input: # [[1,1,0], # [1,1,0], # [0,0,1]] # Output: 2 # Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. # The 2nd student himself is in a friend circle. So return 2. """ Depth First Search go through all unvisited people(1) from 1 to n-1 (row) check all element in its column 1-n-1 if 1 : mark x,y and y,x visited -> # do dfs for this node: go to the column of this node check whether a 1: do dfs to the current node recursively find a circle output+ 1 return output """ from typing import List class Solution: def findCircleNumDFS(self, M: List[List[int]]) -> int: if not M: return 0 if len(M) == 1: return 1 output = 0 def dfs(i): for j in range(len(M)): if M[i][j] == 1: M[i][j] = M[j][i] = -1 dfs(j) M[i][j] = M[j][i] = 1 for i in range(len(M)): if M[i][i] == 1: dfs(i) output += 1 return output M = [[1, 1, 0], [1, 1, 0], [0, 0, 1]] print(Solution().findCircleNumDFS(M)) """ Breadth First Search go throught all the people and add it to the queue while deque: popleft to get the current person and visit this person (mark it -1) for j from 0 to col: if 1: queue.append this person """ def findCircleNummyBFS(M: List[List[int]]) -> int: if not M: return 0 if len(M) == 1: return 1 # turn the adj matrix to Adj list friend = collections.defaultdict(set) for i in range(len(M)): for j in range(i + 1, len(M[0])): if M[i][j] == 1: friend[i].add(j) friend[j].add(i) output, circles, seen = 0, [], set() print(friend) def bfs(queue, oneCircle): seen.add(queue[0]) for person in queue: oneCircle.add(person) for j in friend[person]: if j not in seen: seen.add(j) queue.append(j) return oneCircle for f in range(len(M)): if f not in seen: circles.append(bfs([f], set())) print(circles) return len(circles) # DFS & BFS def findCircleNumBFS(M: List[List[int]]) -> int: friend = collections.defaultdict(set) seen, circles, n = set(), [], len(M) for i in range(n): for j in range(i + 1, n): if M[i][j]: friend[i].add(j) friend[j].add(i) print(friend) # def dfs(person, circle): # you can also call it backtrack # nonlocal seen # seen.add(person) # circle.add(person) # for j in friend[person]: # if j not in seen: # dfs(j, circle) # return circle # # for person in range(n): # if person not in seen: # circles.append(dfs(person, set())) # print(circles) # return len(circles) def BFS(queue, circle): seen.add(queue[0]) for person in queue: circle.add(person) for j in friend[person]: if j not in seen: seen.add(j) queue.append(j) # Python list append is time consuming, so recursion DFS is better in time. return circle for person in range(n): if person not in seen: # if not visited before, create a new queue for another circle and traverse this one BFS circles.append(BFS([person], set())) print(circles) return len(circles) print(findCircleNummyBFS(M)) """ Union Find can do on both adj list and adj matrix no need to turn matrix to list pseudo code: 1. find parent function -- find the parent of a single node(assume that parent is the node itself at first) 2. union function -- simply union the x to be the parent of y \\ a list to store all the parent node for each person go through the friend of each person -> turn the person as parent node of the friend find and union return number of root parent node """ def unionFindFriendCircle(M: List[List[int]]) -> int: if not M: return 0 if len(M) == 1: return 1 unionTree = [i for i in range(len(M))] def find(person): if unionTree[person] == person: return unionTree[person] else: unionTree[person] = find(unionTree[person]) def union(personx, persony): unionTree[find(personx)] = find(persony) # go through half of the matrix for i in range(len(M)): for j in range(i + 1, len(M)): if M[i][j] == 1: union(i, j) print(unionTree) for i in range(len(unionTree)): unionTree[i] = find(unionTree[i]) print(unionTree) return len(set(unionTree)) print(unionFindFriendCircle(M)) ##################################### """ \\ friend cicle 1. print out friends of each person -go through s1 to get info of each employ -go through s2 to add friends for x,y separatly in a list """ s1 = [ "1,Richard,Engineering", "2,Erlich,HR", "3,Monica,Business", "4,Dinesh,Engineering", "6,Carla,Engineering", "9,Laurie,Directors" ] s2 = [ "1,2", "1,3", "1,6", "2,4" ] from collections import defaultdict def friendCycle1(employee_info, friend_relation): friend = defaultdict(set) for info in employee_info: num = info.split(',')[0] friend[num] = set() for relation in friend_relation: """ you can do x,y = ..split() to get the value""" x, y = relation.split(',') friend[x].add(y) friend[y].add(x) print(friend) for person, friends in friend.items(): """use join to print out a list !!!!""" print(person, ':', " ".join(friends)) friendCycle1(s1, s2) """ 2. for each department , count the number of person and how many people has friends not in this department build dictionary for employee --> department build another one for department --> [person] build another one for department --> [numofperson, numofdistrict] """ def friendCycle2(employee_info, friend_relation): friend = defaultdict(set) for relation in friend_relation: """ you can do x,y = ..split() to get the value""" x, y = relation.split(',') friend[x].add(y) friend[y].add(x) print(friend) employDepart = defaultdict(str) for info in employee_info: num,_,department = info.split(',') employDepart[num] = department print(employDepart) departmentDic = defaultdict(set) for num in employDepart: department = employDepart[num] departmentDic[department].add(num) print(departmentDic) result = defaultdict(list) for key, employees in departmentDic.items(): num = len(employees) district = 0 for employ in list(employees): """ !!!!!!!! careful about naminng !!!!!!!!""" for friends in friend[employ]: if employDepart[friends] != key: district = 1 break result[key] = [num, district] return result print(friendCycle2(s1, s2)) """ 3. find out whether those person are all connected with each other dfs traverse all inn friend dcitionary for all unvisited person do a dfs search, add unvisited person in the set mark visited return the set """ def friendCycle3(employee_info, friend_relation): friend = defaultdict(set) for relation in friend_relation: """ you can do x,y = ..split() to get the value""" x, y = relation.split(',') friend[x].add(y) friend[y].add(x) print(friend) def dfs(i): resultList.append(i) visited.add(i) for j in friend[i]: if j not in visited: dfs(j) # # visited = set() # resultList = [] # for i in friend: # if i not in visited: # dfs(i) from collections import deque queue = deque(list(friend.keys())[0]) resultList = [] visited = set() while queue: person = queue.popleft() resultList.append(person) visited.add(person) for j in friend[person]: if j not in visited: queue.append(j) print(resultList) return len(resultList) == len(employee_info) print(friendCycle3(s1,s2)) def countTinyPairs(a, b, k): if len(a) == len(b) == 0: return 0 length = len(a) res = 0 for i in range(length): num = str(a[i]) + str(b[length - 1 - i]) print(num) # i = 0 # while num[i] != '0': # i += 1 # print(int(num[i:])) if int(num[i:]) < k: res += 1 return res print(countTinyPairs([1,2], [1,2], 5))
""" 323. Number of Connected Components in an Undirected Graph """ """ use dfs - stack to traversal all connected ones count groups by iteration """ from collections import defaultdict def countComponents(self, n: int, edges: [[int]]) -> int: # build graph graph = defaultdict(set) for a, b in edges: graph[a].add(b) graph[b].add(a) visited = set() connected = defaultdict(list) def dfs(node, idx): stack = [node] while stack: cur = stack.pop() if cur not in visited: visited.add(cur) connected[idx].append(cur) for adj in graph[cur]: stack.append(adj) count = 0 for i in range(n): if i not in visited: dfs(i, count) count += 1 return count
import unittest class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right """ return the values of its boundary in anti-clockwise direction starting from root. """ class bt: def boundaryOfBinaryTree(self, root: TreeNode): if not root: return [] boundary = [root.val] def leftmost(node): """preorder for left most""" if not node or not node.left and not node.right: return boundary.append(node.val) if node.left: leftmost(node.left) else: leftmost(node.right) def leaves(node): """ inorder for bottom leaves""" if not node: return leaves(node.left) if node!=root and not node.left and not node.right: boundary.append(node.val) leaves(node.right) def rightmost(node): """postorder for right most""" if not node or not node.right and not node.left: return if node.right: rightmost(node.right) else: rightmost(node.left) boundary.append(node.val) leftmost(root.left) leaves(root) rightmost(root.right) return boundary class test(unittest.TestCase): def testbt(self): """ test boundaryOfBinaryTree in bt :return: """ inputbt = TreeNode(0, TreeNode(2), TreeNode(3)) res = bt().boundaryOfBinaryTree(inputbt) self.assertEqual(res, [0,2,3]) if __name__ == '__main__': unittest.main()
""" 406. Queue Reconstruction by Height Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] The number of people is less than 1,100. sort the array by some sequence **** understand lower height people is invisible to higher height people*** only need to focus on first sort the people by the height process the people who are tallest put person with less k at second sort -> essentially, order by the k as well go through person by person and constructing the array if a[0]>b[0] or a[1]<b[1] time complexity: bound by sort time quick/merge nlogn insertion o(n) time """ from typing import List class Solution(): def QueueReconstructionHeight(self, input: List[List]): input.sort(key=lambda x : (-x[0], x[1])) res = [] for person in input: res.insert(person[1],person) return res input = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]] print(Solution().QueueReconstructionHeight(input)) # [[5,0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next from collections import deque class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ if head is None or head.next is None: return """ # find the middle of linked list [Problem 876] # in 1->2->3->4->5->6 find 4 """ slow, fast = head, head # when even -> slow point to the second half # when odd -> slow point to the middle while fast and fast.next: slow = slow.next fast = fast.next.next """ # reverse the second part of the list [Problem 206] # convert 1->2->3->4->5->6 into 1->2->3->4 and 6->5->4 # reverse the second half in-place """ prev, curr = None, slow while curr: curr.next, prev, curr = prev, curr, curr.next # prev is the head of reversed linkedlist """ # merge two sorted linked lists [Problem 21] # merge 1->2->3->4 and 6->5->4 into 1->6->2->5->3->4 """ first, second = head, prev while second.next: first.next, first = second, first.next second.next, second = first, second.next
""" My idea is simple, it is kind of DP or linear search or whatever ... One observation is that the answer should reach the end of string s. Otherwise, you can always extend the hypothetical answer to the end of string s which will be lexicographically larger than the hypothetical answer. Next, let's assume the current dp answer is stored in a variable pre. The idea is that when moving one letter backward, pre either stays the same or it would be the current index. And when we compare current index substring against pre substring, we only need to compare upto index pre, because we already know the comparison results beyond pre, and we know it will be lexicographically smaller (because pre is the currently lexicographically largest substring index). The runtime complexity will be O(n), since we compare each letter once in the worst case. Space complexity is apprarently O(1) Note that I have put a naive string comparison in comment section which will be much slower (should be O(n^2) runtime), so replacing it with the comparison upto pre gives much faster runtime. """ class Solution: def lastSubstring(self, s: str) -> str: i ,j , k =0 ,1 ,0 n=len(s) while j+k<n: if s[i+k]==s[j + k] : k+=1 continue elif s[i+k]>s[j+ k ]: j=j+k+1 else: i=max(j,i + k+1) j=i+1 k=0 return s[i:]
# we all know that it's kind of difficult to figure out if a number is prime or not # that's sort when those problems that are unsolved # so I don't expect this to have a fantastic runtime # and I am thinking that it's just going to use a number of heuristics(启发的), right? # so one thing we can do here is to iterate from 1 to the root of the number, # that will give us all of the factors # it will cover everything above that, then we already have covered it from the lower bound # Once we have all the factors of the number, we just add those up and see if that equals the target number # so we can try this out # runtime is going to be square root of k, k the given number # add it's going to take another pass to add those numbers # the runtime of that will be the maximum number of factors of a number , # at least less than square root of k, which is what are we're bounded by import math import functools class Solution(object): # edge checks!! def checkPerfectNumber(self, num): factors = [] if num <= 0: return False """math.ceil() --- Return the ceiling of x, the smallest integer greater than or equal to x.""" """exponent (**) sign,----- which is used to find out the power of a number.""" for i in range(1, int(math.ceil(num ** 0.5))): # take the mode of each number if num % i == 0: factors.append(i) factors.append(num) sum = 0 if factors: # using reduce to ust do a little bit of shorthand sum = functools.reduce(lambda x, y: x + y, factors) - num return sum == num # you don't need to do this, but it's just kind of neat and fun to do # people may appreciate that here and there map reduce filter, # they can actually save you a little bit of time # But I would actually warn you against too many tricky things, # because later they can be pretty difficult to modify later on # import math class Solution2: # define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. # the input number n will not exceed 100,000,000. ( def checkPerfectNumber(self, num: int) -> bool: div = [] if num <= 0: return False for i in range(1, int(math.ceil(num ** 0.5))): if num % i == 0: # divisors div.append(i) # if (num//i) !=num: div.append(num // i) print(i, num // i) return sum(div) - num == num def checkPerfectNumberCondition(self, num: int) -> bool: sum = 0 if num <= 0: return False for i in range(1, int(math.ceil(num ** 0.5))): if num % i == 0: # divisors sum += i if (num // i) != num: sum += num // i if (sum > num): return False print(i, num // i) return sum == num # time : O(n ** 0.5) # Space complexity : O(1)O(1). """ for p = 2: 21(22 − 1) = 6 for p = 3: 22(23 − 1) = 28 for p = 5: 24(25 − 1) = 496 for p = 7: 26(27 − 1) = 8128. there is only 4 perfect """
from typing import List class Solution: # dfs def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: R, C = len(image), len(image[0]) color = image[sr][sc] if color == newColor: return image def dfs(r, c): if image[r][c] == color: image[r][c] = newColor if r >= 1: dfs(r - 1, c) if r + 1 < R: dfs(r + 1, c) if c >= 1: dfs(r, c - 1) if c + 1 < C: dfs(r, c + 1) dfs(sr, sc) return image # BFS & stack def floodBFSFill(self, image, sr, sc, newColor): """ :type image: List[List[int]] :type sr: int :type sc: int :type newColor: int :rtype: List[List[int]] """ if image[sr][sc] == newColor: return image temp = image[sr][sc] stack = [(sr, sc)] while stack: i, j = stack.pop() if image[i][j] == temp: image[i][j] = newColor if i + 1 < len(image): stack.append((i + 1, j)) if i - 1 >= 0: stack.append((i - 1, j)) if j + 1 < len(image[0]): stack.append((i, j + 1)) if j - 1 >= 0: stack.append((i, j - 1)) else: pass return image
""" 144. Binary Tree Preorder Traversal 1. recursive 2. non recursive O(n) O(n) """ class TreeNode: def __init__(self, val, r, l): self.val = val self.right = r self.left = l def preorderTraversal(self, root: TreeNode) : # root, left, right if not root: return [] res = [] def dfs(node): res.append(node.val) if node.left: dfs(node.left) if node.right: dfs(node.right) dfs(root) """ iterative -- root pop, \\right!! append, \\left append """ out = [] stack = [root] while stack: node = stack.pop() out.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return res """ 94. Binary Tree Inorder Traversal Morris Traversal """ def inorderTraversal(self, root: TreeNode): # left,root, right if not root: return [] res = [] def dfs(node): if node.left: dfs(node.left) res.append(node.val) if node.right: dfs(node.right) dfs(root) # nonrecursive stack = [] out = [] node = root while node or stack: while node: stack.append(node) node = node.left node = stack.pop() out.append(node.val) node = node.right return res """ 145. Binary Tree Postorder Traversal while stack pop root append val append \\left append \\right \\ reverse for list """ def postorderTraversal(self, root: TreeNode): # left, right , root if not root: return [] stack = [root] res = [] while stack: node = stack.pop() res.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) """use reverse to get post order!""" return res[::-1]
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __repr__(self): res = str(self.val) if self.next: res += str(self.next) return res # time O(N+K), which is O(n). # space O(1) class Solution: """iteration""" def reverseList(self, head: ListNode) -> ListNode: if not head or not head.next: return head prev, curr = None, head while curr: temp = curr.next curr.next = prev prev = curr curr = temp # python tackle statement from right side # curr.next, prev, curr = prev, curr, curr.next return prev """recursive""" def reverseList(self, head): return self.reverse(head, None) def reverse(self, curr: ListNode, prev: ListNode): if not curr: return prev temp = curr.next curr.next = prev prev = curr curr = temp return self.reverse(curr, prev) node = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) print(Solution().reverseList(node))
""" 135. Candy There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? """ """ left : should have candys for the left side right : should have candys for the right side get max of left and right \\ time O(n) \\ space O(n) optimization: use one array """ # 14 # [12,3,3,11,34,34,1,67] class Solution: def candy(self, ratings) -> int: if not ratings: return 0 if len(ratings) == 1: return 1 left = [1] * len(ratings) right = [1] * len(ratings) for i in range(1, len(ratings)): if ratings[i - 1] < ratings[i]: left[i] = left[i - 1] + 1 for i in range(len(ratings) - 2, -1, -1): if ratings[i + 1] < ratings[i]: right[i] = right[i + 1] + 1 res = 0 for i in range(len(ratings)): res += max(left[i], right[i]) return res
""" 46 permutations first of all there is no efficient way to do it it has to be brute force we're just going to generate every single combination let's take look at this one [1,2,3] you have 3 spots and the first element/ scenario you can have up to 3 different numbers second - 2, last position - only one number this is known as *factorial* then it's like N times N minus 1 times N-2 ... until you get to one we gonna do here is use backtracking traversal this path and get the combination then we have to go back and try first and another branch and go back to the top and go down to the next value likewise go up and down so the code to write this out is that you just do an iteration So we need to take just one of the values and then remove that from the set of potential candidates for the next iteration for..... one way we can do this is we could swap a value -- perform swap, right? swap(start, i) and swap the index at, say the start index and index of i and then we just call f(n) again, and we pass the start and the index + 1 right? so we move the start index up by 1. and then at the end of that, we swap it back. that's pretty much what the algorithms looks like in pseudo-code you just go through each element, transfer up into the front and then you need to call[f(n)] for the subsequent elements, processing the rest of the array tying to swap those elements and then for the base case, you would say, if ever the start index equals the end, so you reach the end of the array, then you found one combination and you are just return the array you have so the return value of this is going to be an array of these numbers. """ class Solution: # swap / get list / swap # backtracking """ distinct integers""" """interation version""" def permutationHelper(self, nums, start=0): if start == len(nums) - 1: return [nums[:]] res = [] for i in range(start, len(nums)): # self.swap(nums, start, i) nums[start], nums[i] = nums[i], nums[start] res += self.permutationHelper(nums, start + 1) nums[start], nums[i] = nums[i], nums[start] return res def permutation1(self, nums): return self.permutationHelper(nums, 0) """ choose from left numbers """ # principle is pretty similar but for this, you pass in the numbers that are valid for use # then you constructing this value array that you go through """iteration version""" def permutation1noswap(self, nums, values=[]): if not nums: return [values] res = [] for i in range(len(nums)): res += self.permutation1noswap(nums[:i] + nums[i+1:],values + [nums[i]] ) return res """recursive version""" def permutation1noswaprec(self, nums): res = [] stack = [(nums, [])] while(len(stack)): nums, values = stack.pop() if not nums: res += [values] """range(len(nums)) not nums!!!!""" for i in range(len(nums)): stack.append((nums[:i]+nums[i+1:], values + [nums[i]])) return res print( Solution().permutation1noswaprec([1, 2, 3]))
""" 102. Binary Tree Level Order Traversal """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from collections import deque class Solution: def levelOrder(self, root: TreeNode): if not root: return [] queue = [root] res = [] while queue: curres = [] nextlevel = [] for node in queue: curres.append(node.val) if node.left: nextlevel.append(node.left) if node.right: nextlevel.append(node.right) res.append(curres) queue = nextlevel # recursive -- bottom up l = [] def helper(node, level): if len(l) == level: # init level l[level] = [] l[level].append(node.val) if node.left: helper(node.left, level+1) if node.right: helper(node.right, level+1) helper(root, 0) print(l[::-1]) return res """ bottom up res[::-1] at last """ def zigzagLevelOrder(self, root: TreeNode): # left-right & right to left for each 2 level if not root: return [] queue = [root] res = [] level = 0 while queue: curres = [] nextlevel = [] level += 1 for node in queue: curres.append(node.val) if node.left: nextlevel.append(node.left) if node.right: nextlevel.append(node.right) if level % 2 == 0: res.append(curres[::-1]) else: res.append(curres) queue = nextlevel return res """ traversal vertical 1. use dic 2. go dfs record col and level 3. sort item by level """ def verticalOrder(self, root: TreeNode): if not root: return [] res = [] dic = {} def helper(node, col, level): if col not in dic: dic[col] = [] dic[col].append([level, node.val]) if node.left: helper(node.left, col - 1, level + 1) if node.right: helper(node.right, col + 1, level + 1) helper(root, 0, 0) cols = list(dic.keys()) for c in sorted(cols): dic[c].sort(key=lambda x: x[0]) cur = [] for i in dic[c]: cur.append(i[1]) res.append(cur) return res
# The knows API is already defined for you. # return a bool, whether a knows b # def knows(a: int, b: int) -> bool: # There will be exactly one celebrity def knows(a,b): return True class Solution: def findCelebrity(self, n: int) -> int: can = 0 def secondcele(m): for i in range(n): if i == m: continue if knows(m, i) or not knows(i, m): return False return True for i in range(1, n): if knows(can, i): can = i if secondcele(can): return can return -1 """ 0 1 2 0[[1,1,0] 1,[0,1,0], 2 [1,1,1]] 0,1? --> 1,2?no, --> end, go check this candidate with all people """ # 2: Logical Deduction
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ class NestedInteger: def isInteger(self) -> bool: """ @return True if this NestedInteger holds a single integer, rather than a nested list. """ def getInteger(self) -> int: """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list """ def getList(self): """ @return the nested list that this NestedInteger holds, if it holds a nested list Return None if this NestedInteger holds a single integer """ class NestedIterator: def __init__(self, nestedList: [NestedInteger]): """ define function flattenList(nestedList): for nestedInteger in nestedList: if nestedInteger.isInteger(): append nestedInteger.getInteger() to integers else: recursively call flattenList on nestedInteger.getList() :param nestedList: """ self.integers = [] self.pos = -1 def flattern(nested): for i in nested: if i.isInteger(): self.integers.append(i.getInteger()) else: flattern(i.getList()) flattern(nestedList) def next(self) -> int: self.pos +=1 return self.integers[self.pos] def hasNext(self) -> bool: return self.pos +1<len(self.integers)
############ # given a list find out a peek --> has both increasing and decreasing side # brute fore def peek(input): length = 0 for i in range(1, len(input)): left = i-1 right = i+1 leftcheck = True rightcheck = False lengthCur = 1 while left>=0 and input[left]<input[i]: lengthCur += 1 left -= 1 leftcheck = True while right<len(input) and input[right]<input[i]: lengthCur += 1 right += 1 rightcheck = True if leftcheck and rightcheck: length = max(length, lengthCur) return length # dynamic programming!!! # O(3n) def peekQuicker(nums): l = [0]*len(nums) r = [0]*len(nums) cur = 0 for i in range(len(nums)): if i ==0 or nums[i] <= nums[i-1]: cur = 1 else: cur += 1 l[i] = cur cur = 0 for i in range(len(nums)-1, -1, -1): if i == len(nums)-1 or nums[i]<=nums[i+1]: cur = 1 else: cur += 1 r[i] = cur # reverse right list --> we traversal from right to left # r.reverse() print(l, r) length = 0 for i in range(len(nums)): length = max(length, l[i] + r[i] - 1) return length print(peekQuicker([1,2,3,4,5,2,1]))
# valid binary search tree # should # # 5 # /\ # 4 7 # / # 2 # X # have restrictions on both upper and lower bound # traversal the tree and pass down # # # Pseudo code: # low < n.val < high # isValid(n.left, low, n.val) # isValid(n.right, n.val, high) # if node is null return True """recursive -- and 3 conditions together""" # in terms of # time complexity: we just go through each node once --> O(n) linear # space complexity: is going to be proportional to the size of the recursive stack that we building # like you can just keep recursing down and down and start building up this function stack # is linear with regards to this input O(N) class Node(object): def __init__(self, val, left = None, right = None ): self.val = val self.left = left self.right = right class Solution : """iteration""" def validHelper(self, node, low, high): if not node: return True val = node.val if low < val < high and self.validHelper(node.left, low, val) and self.validHelper(node.right, val, high): return True return False def validBinarySearchTree(self, node: Node): if not node: return True return self.validHelper(node, float('-inf'), float('inf')) """recursive: use stack""" def isValidBST(self, root: Node) -> bool: # iteration with stack!! important if not root: return True stack = [(root, float('-inf'), float('inf')), ] while stack: node, low, high = stack.pop() if not node: continue if low < node.val < high: stack.append((node.left, low, node.val)) stack.append((node.right, node.val, high)) else: return False return True """inorder """ def isValidBST(self, root: Node) -> bool: stack, inorder_lower = [], float('-inf') while stack or root: while root: stack.append(root) root = root.left root = stack.pop() # If next element in inorder traversal # is smaller than the previous one # that's not BST. if root.val <= inorder_lower: return False inorder_lower = root.val root = root.right return True # 5 # / \ # 4 7 node = Node(5) node.left = Node(4) node.right = Node(7) print(Solution().isValidBST(node)) # 5 # / \ # 4 7 # / # 2 node = Node(5) node.left = Node(4) node.right = Node(7) node.right.left = Node(2) print(Solution().validBinarySearchTree(node)) # False
""" helper(left, rigth, cur): if length of current string == 6: result append string if left< n: call helper with update parameters le """ from typing import List class Solution: def generateParenthesis(self, n: int) -> List[str]: result = [] if n == 0: return [] def helper(left, right, cur): if len(cur) == n * 2: result.append(cur) return if left < n: helper(left + 1, right, cur + '(') if right < n and left > right: helper(left, right + 1, cur + ')') helper(0, 0, "") return result def whilegenerate(self, n): result = [] stack = [(0, 0, "")] while stack: left, right, cur = stack.pop() if len(cur) == n * 2: result.append(cur) continue if left < n: stack.append((left + 1, right, cur + '(')) if right < n and left > right: stack.append((left, right + 1, cur + ')')) return result ''' +dynamic programming It is also possible to solve the problem explicitly using dynamic programming. Define f(n) as the set of all valid parentheses when there are n opening parentheses. Then symbolically, f(n+1) follows below recursive equation, f(n+1) = (f(0))f(n) + (f(1))f(n-1) + ... + (f(n-1))f(1) + (f(n))f(0) ((f(i))f(j) means that the valid parentheses of f(i) added by a pair of parentheses outside concatenated with the valid parentheses of f(j), i.e. this is a loop.) ''' # # Generate one pair: () # # Generate 0 pair inside, n - 1 afterward: () (...)... # # Generate 1 pair inside, n - 2 afterward: (()) (...)... # # ... # # Generate n - 1 pair inside, 0 afterward: ((...)) # # I bet you see the overlapping subproblems here. Here is the code: # # (you could see in the code that x represents one j-pair solution and y represents one (i - j - 1) pair solution, and we are taking into account all possible of combinations of them) class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ dp = [[] for i in range(n + 1)] dp[0].append('') for i in range(n + 1): for j in range(i): dp[i] += ['(' + x + ')' + y for x in dp[j] for y in dp[i - j - 1]] return dp[n]
# Input: word1 = "horse", word2 = "ros" # Output: 3 # Explanation: # horse -> rorse (replace 'h' with 'r') # rorse -> rose (remove 'r') # rose -> ros (remove 'e') # find the minimum number of operations required to convert word1 to word2. # h o r s e # 0 1 2 3 4 5 # r1 1 2 2 3 4 # o2 2 1 2 3 4 # s3 3 2 2 2 3 class Solution: def minDistance(self, word1: str, word2: str) -> int: len1 = len(word1) len2 = len(word2) if len1 * len2 == 0: return len1 + len2 """init [*m for _in n] ---- [n][m]""" dp = [[0] * (len2 + 1) for _ in range(len1 + 1)] for j in range(len2 + 1): dp[0][j] = j for i in range(len1 + 1): dp[i][0] = i """"after init no need to go to line/column 0""" for i in range(1, len1 + 1): for j in range(1, len2 + 1): leftdown = dp[i - 1][j - 1] if word1[i - 1] == word2[j - 1] else (dp[i - 1][j - 1] + 1) minstep = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, leftdown) dp[i][j] = minstep return dp[len1][len2]
""" 112. Path Sum O(n) """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def hasPathSum(self, root: TreeNode, sum: int) -> bool: if not root: return False # make sure node is a leaf if root.val == sum and not root.left and not root.right: return True else: return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) """recursive""" def hasPathSum(self, root: TreeNode, sum: int) -> bool: if not root: return False stack = [(root, sum - root.val)] while stack: node, cur = stack.pop() if cur == 0 and not node.left and not node.right: return True if node.right: stack.append((node.right, cur - node.right.val)) if node.left: stack.append((node.left, cur - node.left.val)) return False """ 113. Path Sum II For every leaf, we perform a potential O(N)operation of copying over the pathNodes nodes to a new list to be added to the final pathsList. Hence, the complexity in the worst case could be O(n2) space O(n) """ class Solution: def recursive(self, node, cur, path): if not node: return """ check whether is leaf node""" if cur == 0 and not node.left and not node.right: self.res.append(path) return """ no need to add cur<sum... -- may have negative nums""" """ only need to append Val in list!! """ if node.left: self.recursive(node.left, cur - node.left.val, path + [node.left.val]) if node.right: self.recursive(node.right, cur - node.right.val, path + [node.right.val]) def pathSum(self, root: TreeNode, sum: int): if not root: return [] # make sure node is a leaf self.res = [] self.recursive(root, sum - root.val, [root.val]) return self.res """ 437. Path Sum III use preorder to traversal tree use dictionary to record sum and counts \\ Prefix Sum === Number of Continuous Subarrays that Sum to Target \\ preorder traversal need dic[cur] -= 1 to prevent parallel """ from collections import defaultdict class Solution: def pathSum(self, root, target): dic = {0: 1} self.count = 0 def dfs(node, sums): if not node: return cur = sums + node.val if cur - target in dic: self.count += dic[cur - target] dic[cur] = dic.get(cur, 0) + 1 dfs(node.left, cur) dfs(node.right, cur) # remove the current sum from the hashmap # in order not to use it during # the parallel subtree processing dic[cur] -= 1 dfs(root, 0) return self.count
""" deep copy of the graph initialize a dictionary to pair old node with new one traversal the tree BFS 1. create queue with [initial root nodes] 2. while loop when queue not empty: popleft queue get the cur node for neighbour in this old node if node not in dic: create new node and pair it with old one in dic queue append this old node new node(pair with old node) append this new children 3. return root create new nodes on the go """ """ # 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 [] def __str__(self): print(self.val, self.neighbours) from collections import deque class Solution: def __init__(self): self.visited = {} def copyDFS(self, node: Node): if not node: return node # Create a clone for the given node. # Note that we don't have cloned neighbors as of now, hence []. newnode = Node(node.val, []) # The key is original node and value being the clone node. self.visited[node] = newnode # Iterate through the neighbors to generate their clones # and prepare a list of cloned neighbors to be added to the cloned node. for neighbor in node.neighbors: # If the node was already visited before. # Return the clone from the visited dictionary. if neighbor not in self.visited: self.cloneGraph(neighbor) newnode.neighbors.append(self.visited[neighbor]) return newnode def copyGraph(self, node: Node): if not node: return node root = Node(node.val, []) queue = deque() # queue will append nodes -- root nodes may not be only one queue.append(node) # pair each node with a new node(one child has multiple parents) dictionary = {node: root} # BFS traversal while queue: item = queue.popleft() for neighbour in item.neighbors: if neighbour not in dictionary: newnode = Node(neighbour.val, []) dictionary[neighbour] = newnode queue.append(neighbour) dictionary[item].neighbors.append(dictionary[neighbour]) return root node = Node(2, [Node(3, []), Node(4, []), Node(5, [Node(1, [])])]) Solution().copyGraph(node)
""" use a dictionary mark groups for all ele in the list We should be able to greedily color the graph if and only if it is bipartite: one node being blue implies all it's neighbors are red, all those neighbors are blue, and so on. for each list in graph: for each uncolored ele in list: start the coloring process by doing a dfs on that node and we let every neighbour colored differently with current node use a stack to perform dfs --> add uncolored node in it as a todo list... """ # graph record for 0,..n graph[0] means the neighbour of 0 graph = [[1,3], [0,2], [1,3], [0,2]] graph2 = [[1,2,3], [0,2], [0,1,3], [0,2]] # DFS solution def bipartite(graph): def dfs(node): print(node, dic[node]) for neighbour in graph[node]: if neighbour in dic: if dic[neighbour] == dic[node]: return False else: continue else: dic[neighbour] = 1-dic[node] print(neighbour, dic[neighbour]) if not dfs(neighbour): return False return True dic = {} for item in range(len(graph)): if item not in dic: dic[item] = 0 if not dfs(item): return False return True from collections import deque def bipartiteBFS(graph): color = {} queue = deque() for node in range(len(graph)): if node not in color: color[node] = 0 queue.append(node) while queue: n = queue.popleft() for neighbour in graph[n]: if neighbour in color: if color[neighbour] == color[n]: return False else: continue else: color[neighbour] = 1-color[n] queue.append(neighbour) return True print(bipartiteBFS(graph)) print(bipartiteBFS(graph2)) # BFS solution def isBipartite(self, graph) -> bool: from collections import deque queue = deque() color = {} for i in range(len(graph)): if i not in color: color[i] = 0 queue.append(i) while queue: node = queue.popleft() for nb in graph[node]: if nb in color: if color[nb] == color[node]: return False else: color[nb] = 1 - color[node] queue.append(nb) return True def isBipartite(self, graph) -> bool: def dfs_color(i): for nb in graph[i]: if nb in color: if color[nb] == color[i]: return False else: color[nb] = 1 - color[i] if not dfs_color(nb): return False return True color = {} for i in range(len(graph)): if i not in color: color[i] = 0 if not dfs_color(i): return False return True
""" Design a hit counter which counts the number of hits received in the past 5 minutes. Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1. It is possible that several hits arrive roughly at the same time. """ # Optimized and Scalable Solution # compare with dictionary: dic may have endless list & need to sort the time # The third solution creates an array of 300 elements. Every element of the array comprises of [frequency, timestamp]. # Timestamp 1 maps to index 0. Timestamp 100 maps to index 99. # Use modulo mathematics to update it. hit: O(1). get_hit: O(300). This solution will scale perfectly! class HitCounter: def __init__(self): """ Initialize your data structure here. """ self.time = [[0,t+1] for t in range(300)] def hit(self, timestamp: int) -> None: """ Record a hit. @param timestamp - The current timestamp (in seconds granularity). """ # ts = 301 means (301-1)%300 i = (timestamp-1)%300 if self.time[i][1]== timestamp: self.time[i][0]+=1 else: self.time[i]=[1, timestamp] def getHits(self, timestamp: int) -> int: """ Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). """ res = 0 for i in range(300): """compare whether in range timestamp-self.time[i][1]""" if timestamp-self.time[i][1]<300: res += self.time[i][0] return res # Your HitCounter object will be instantiated and called as such: # obj = HitCounter() # obj.hit(timestamp) # param_2 = obj.getHits(timestamp) # HitCounter counter = new HitCounter(); # # hit at timestamp 1. # counter.hit(1); # # // hit at timestamp 2. # counter.hit(2); # # // hit at timestamp 3. # counter.hit(3); # # // get hits at timestamp 4, should return 3. # counter.getHits(4); # # // hit at timestamp 300. # counter.hit(300); # # // get hits at timestamp 300, should return 4. # counter.getHits(300); # # // get hits at timestamp 301, should return 3. # counter.getHits(301);
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: """using list->int->list""" # The basic idea is to convert the linked lists to integer values (using a similiar approach as atoi). # Then create a new linked list from the sum by adding the digits in reverse. def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: n1 = self.getInt(l1) if l1 else 0 n2 = self.getInt(l2) if l2 else 0 return self.getList(n1 + n2) if (n1+n2) !=0 else ListNode(0) def getInt(self, l : ListNode): ret = 0 while l: ret = ret*10 + l.val l = l.next return ret def getList(self, n): cur = None while n >0: n, left = divmod(n, 10) cur = ListNode(left, cur) return cur """using stack""" def addTwoNumber(self, l1, l2): s1 = [] s2 = [] curr1, curr2 = l1, l2 while (curr1 or curr2): if curr1: s1.append(curr1.val) if curr2: s2.append(curr2.val) if curr1: curr1 = curr1.next if curr2: curr2 = curr2.next head = None acc = 0 while (len(s1) > 0 or len(s2) > 0): val1 = s1.pop() if len(s1) > 0 else 0 val2 = s2.pop() if len(s2) > 0 else 0 val = val1 + val2 + acc head = ListNode(val % 10, head) acc = val // 10 if acc > 0: head = ListNode(acc, head) return head l1 = ListNode(2) l1.next = ListNode(4) l1.next.next = ListNode(3) # 342 + 465 = 807 l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(4) answer = Solution().addTwoNumbers(l1, l2) while answer: print(answer.val, end=' ') answer = answer.next # 807
import urllib.request from bs4 import BeautifulSoup def get_html(url): response = urllib.request.urlopen(url) return response.read() def parse(html): soup = BeautifulSoup(html, features = "html.parser") div = soup.find('div', class_ = 'module-kurs_nbrb') tr = div.find_all('tr') # print(type(tr)) result = {"data": [], "1 USD": [], "1 EUR": [], "100 RUB": []} print(tr[0]) """ tags = div.find_all('td') if tags.text != "": result = result + tags.text + "\t" print(tags.text) """ print(result) """ today_data = tomorrow_data = tr[2] today_USD = tr[7] tomorrow_USD = tr[8] print(today_data, tr[2], tr[7], tr[8]) """ def main(): parse(get_html('https://select.by/kurs/')) if __name__ == '__main__': main()
cases = int(input()) for i in range(cases): input() Mg ,Mm = map(int,input().split()) Lg = input().split() Lm = input().split() while len(Lg) > 0 and len(Lm) > 0: minLg=min(Lg) minLm = min(Lm) if minLg==minLm: Lm.remove(minLm) elif minLm>minLg: Lg.remove(minLg) elif minLg>minLm: Lm.remove(minLm) if len(Lg) == 0 and len(Lm) == 0: print("uncertain") else: if len(Lg)== 0: print("MechaGodzilla") elif len(Lm)== 0: print("Godzilla") if Mg == 0 and Mm == 0: print("uncertain") # print("cases:",cases) # print("Mg:",Mg," Mm:",Mm) # print("Lg: ",Lg) # print("Lm: ",Lm)
a = int(input("Enter your number: ")) b = int(input("Enter your number: ")) def addition(): total = a + b print("Two number addition: ", total) def subtration(): sub = a - b print("Two number sub: ", sub) def main(): addition() subtration() main()
""" Algorithm for the sequence 1, 2, 3, 6, 11, 20, 37. the algorithm for this sequence is to take the first 3 numbers and the sum of those number will become the fourth number, so to get the fifth number you take the second, third and fourth number to and the sum will be the fifth number (2+3+6 = 11) so the algorith will be num_1 num_2 and num_3 and the sum of those is the new num num_1 will become num _2 num_2 will become num_3 and num_3 will become the sum of num_1, num_2 and num_3 then print the sum """ n = int(input("Enter the length of the sequence: ")) # Do not change this line num_1 = 1 num_2 = 2 num_3 = 3 counter = 3 print (num_1) print (num_2) print (num_3) while counter < n: sum = num_1 + num_2 + num_3 print (sum) counter += 1 num_1 = num_2 num_2 = num_3 num_3 = sum
""" A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar. Sentence-length palindromes may be written when allowances are made for adjustments to capital letters, punctuation, and word dividers, such as " ", "Was it a car or a cat I saw?" or "No 'x' in Nixon". Write a function that takes a string as an argument and returns True if the string is a palindrome and False otherwise. Also write code that calls the function with the input as an argument and prints out the appropriate message. Example input/output: Enter a string: No 'x' in Nixon. "No 'x' in Nixon." is a palindrome. Enter a string: blabla "blabla" is not a palindrome. """ # palindrome function definition goes here def is_palindrome(a_str): a_str = a_str.casefold() rev_str = reversed(a_str) if list(a_str) == list(rev_str): return True in_str = input("Enter a string: ") is_str_palindrome = is_palindrome(in_str) if is_str_palindrome: print (in_str, "is a palindrome.") else: print (in_str, "is not a palindrome.") # call the function and print out the appropriate message