text
stringlengths
37
1.41M
# !/usr/bin/python # -*- coding: utf-8 -*- def myLog(x, b): ''' x: a positive integer b: a positive integer; b >= 2 returns: log_b(x), or, the logarithm of x relative to a base b. ''' # Your Code Here assert type(x) is int assert type(b) is int and b >= 2 p = 0 while True: if x >= pow(b, p): max_p = p p += 1 else: break return max_p
from random import randint # Generate a 4 digit number pass def credit_pass(): password = "" while len(password) < 4: password += str(randint(0,9)) return password # Generate a card number def card_number(): card = [4] while len(card) != 16: card.append(randint(0,9)) if len(card) == 16: if luhn(card) == True: card = ''.join([str(c) for c in card]) return card else: card = [4] # Check the valid of a credit card by the algorithm Luhn def luhn(card): # Keep thee last digit last_digit = card[-1] #Copy the card variable copy_card = card.copy() # Remove it copy_card.pop() # Reverse card copy_card = card[::-1] # Multiply odd position by 2 and remove 9 if greater than 9 for i in range(0, len(copy_card)): if (i+1) % 2 != 0: copy_card[i] = copy_card[i] * 2 if copy_card[i] > 9: copy_card[i] = copy_card[i] - 9 # sum all the numbers sum_ = sum(copy_card) # Check the last digit with mod 10 of the sum if last_digit == (sum_ % 10): # Return True return True # Return false and generate another credit number return False # Generate the back code of the credit card def cc_code(): code = "" while len(code) < 3: code += str(randint(0,9)) return code
from turtle import * for i in range(3): color('red') forward(100) left(120) for i in range(4): color('blue') forward(100) left(90) for i in range(5): color('brown') forward(100) left(72) for i in range(6): color('yellow') forward(100) left(60) for i in range(7): color('gray') forward(100) left(52) mainloop()
# age = 10 # if age < 18: # print('baby') # age = 10 # is_baby = age < 10 # print(is_baby) # num = 101 # is_odd = num % 2 == 1 # print(is_odd) # text = 'xin chao' # text_is_not_empty = len(text) > 10 # print(text_is_not_empty) # from math import * # num = int(input('nhap so:')) # print(abs(num)) # num = int(input('nhap so:')) # if num > 0: # print('tri tuyet doi la:',num) # else: # print('tri tuyet doi la:',-num) # num = int(input('nhap so:')) # if num > 0: # print('tri tuyet doi la:',num) # elif num == 0: # print('la so khong') # elif num == 1: # print('la so mot') year = int(input('nhap nam sinh: ')) age = int(2019-year) if age > 18: print('Adult') if 13 < age < 18: print('Teenager') if age < 12: print('Baby')
class DependentOperand: """ Class that stores data regarding the dependent operand """ __dependent_criterion: str __relational_operator: str # Can be <, >, <=, >=, ==, ~= __dependent_criterion_value: str def __init__(self): self.__dependent_criterion = '' self.__relational_operator = '' self.__dependent_criterion_value = '' def __eq__(self, other: 'DependentOperand') -> bool: """ Override equals just in case :param other: :return: """ return (self.__relational_operator is other.__relational_operator) and \ (self.__dependent_criterion is other.__dependent_criterion) and \ (self.__dependent_criterion_value is other.__dependent_criterion_value) def to_dictionary(self) -> dict[str: str]: return { "dependent criterion" : self.__dependent_criterion, "relational operator" : self.__relational_operator, "criterion value" : self.__dependent_criterion_value } def set_dependent_criterion_value(self, value: str) -> 'DependentOperand': self.__dependent_criterion_value return self def dependent_criterion_value(self) -> str: return self.__dependent_criterion_value def set_relational_operator(self, operator: str) -> 'DependentOperand': self.__relational_operator = operator return self def relational_operator(self) -> str: return self.__relational_operator def set_dependent_criterion(self, criterion: str) -> 'DependentOperand': self.__dependent_criterion = criterion return self def dependent_criterion(self) -> str: return self.__dependent_criterion def dependent_operand_exist(self): if self.dependent_criterion() and self.dependent_criterion_value() and self.relational_operator(): return True elif not(self.dependent_criterion() and self.dependent_criterion_value() and self.relational_operator()): return False else: raise Exception('Invalid State')
import datetime def days_diff(date1, date2): d1 = datetime.datetime(date1[0], date1[1], date1[2]) d2 = datetime.datetime(date2[0], date2[1], date2[2]) return abs((d2 - d1).days)
# https://py.checkio.org/mission/brackets/ def brackets_checkio(expression): brackets = {'{': '}', '(': ')', '[': ']', } chars_set = {'{', '}', '(', ')', '[', ']', } chars = list(filter(lambda x: x in chars_set, expression)) stack = [] # if no brackets, it's good if len(chars) == 0: return True # if number of brackets is odd, guaranteed to be bad elif len(chars) % 2 != 0: return False # use a stack to pop off the last opened bracket and see if it matches with the closing bracket else: for char in chars: if char in brackets.keys(): stack.append(char) else: last_open_bracket = stack.pop() if char != brackets[last_open_bracket]: return False return True if __name__ == '__main__': assert brackets_checkio("((5+3)*2+1)") == True, "Simple" assert brackets_checkio("{[(3+1)+2]+}") == True, "Different types" assert brackets_checkio("(3+{1-1)}") == False, ") is alone inside {}" assert brackets_checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators" assert brackets_checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant" assert brackets_checkio("2+3") == True, "No brackets, no problem"
#inheritance #is a relationship #Car is a vehicle #Truck is a vehicle class Vehicle(): def __init__(self,name): self.vehicle_name = name def name(self): print(self.vehicle_name) class Car(Vehicle): def drive(self): print(self.vehicle_name," is drive") class Truck(Vehicle): def wheel(self): print(self.vehicle_name,"--> has 8 wheel") a = Car("Toyota") a.name() a.drive() b = Truck("tata") b.name() b.wheel()
#Multiple inheritance #is a relationship #Car is a vehicle #Truck is a vehicle class Vehicle(): def __init__(self,name): self.vehicle_name = name def cname(self): print(self.vehicle_name) class Driver(): def __init__(self,name): self.driver_name = name def dname(self): print(self.driver_name) class Car(Vehicle, Driver): def __init__(self,cname,dname): Vehicle.__init__(self,cname) Driver.__init__(self,dname) def drive(self): print(self.vehicle_name," is drive") class Truck(Vehicle): def wheel(self): print(self.vehicle_name,"--> has 8 wheel") a = Car("Toyota","Rahim Islam") a.cname() #parent class - Vehicle a.drive() #child class a.dname() #parent class - Driver b = Truck("tata") b.cname() b.wheel()
#Object Oriented Programming(oop) #Object ''' i = 10 str = "codinglaugh" list = [1,2,3,4,5,6] list.append(6) str.__len__() ''' class Vehicle: pass car = Vehicle() car.name = "Toyota" car.Wheel = 4 car.driver = "Solimoddin" print(car.name,car.driver) truck = Vehicle() truck.name = "Tata" truck.Wheel = 8 truck.driver = "Kolimoddin" print(truck.name,truck.driver)
from .abstract_view import AbstractView import pygame class GameOverView(AbstractView): """ Display the Game over view. Inherits from "AbstractView" """ def __init__(self, window, maze_result, maze): """ initialize private attribute maze result Args: maze_result (bool): if player has 5 items in list then maze_result is True. Otherwise maze result is False Raises: ValueError: maze result must be Boolean """ if type(maze_result) != bool: raise ValueError("Game result must be win or lose") self._maze_result = maze_result self._maze = maze self._window = window self._window.fill((255, 255, 255)) pygame.font.init() self._arial = pygame.font.SysFont('arial', 18) # initialization self._display_message() pygame.display.update() def _display_message(self): """ Template method: display the message according to True or False True: win, False: lose Returns: str: display the text according to win or lose """ if self._maze_result: msg = f"You won the game, your score is: {self._maze._score}. Congratulations" msg_instruction = "Type your name in the console and press 'q' to quit" else: msg = f"You lost, your score is: {self._maze._score}. Press 'q' to quit" msg_instruction = "" msg_surface = self._arial.render(msg, True, (0, 0, 0)) msg_text = msg_surface.convert_alpha() msg_s = self._arial.render(msg_instruction, True, (0, 0, 0)) msg_t = msg_s.convert_alpha() self._window.blit(msg_text, (155, 180)) self._window.blit(msg_t, (155, 200)) def _display_instructions(self): """ No instruction """ pass
""" collects countries available for get query """ import xml.etree.ElementTree as ET import pickle import requests def get_result(day, month, year): """ returns dict of country names/country id based on api """ if int(day) < 10: day = "0{}".format(day) if int(month) < 10: month = "0{}".format(month) get_xml = requests.get( 'http://www.cbr.ru/scripts/XML_daily.asp?date_req=\ {}/{}/{}'.format(day, month, year) ) elems = {} tree = ET.fromstring(get_xml.content) for element in tree: el_id = element.items()[0][1] name = element.find("./Name").text elems[name] = el_id return elems if __name__ == '__main__': with open("countries.txt", "wb") as out: C = get_result(20, 5, 2018) pickle.dump(C, out)
limit = 10 result = list(map(lambda x: 2 ** x, range(limit))) print("total terms:",limit) for i in range(limit): print("power",i,"is",result[i])
import numpy as np arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) print(arr[1, 1:4]) print(arr[0:2, 2]) print(arr[0:2, 1:4]) # [7 8 9] # [3 8] # [[2 3 4] # [7 8 9]]
n = int(raw_input()) now = 1 fact = [] for i in range(1, 45): now *= i fact.append(now) while n > 0: n -= 1 a = int(raw_input()) print(fact[a - 1])
n = int(raw_input()) if n < 2: print("WRONG ANSWER") elif n > 3: print("RUNTIME ERROR") else : print("ACCEPTED")
def triangular(n): x = long(n ** 0.5) if x * x == n: return True return False while 1: n = input() if n == 0: break if triangular(8 * n + 1): print 'YES' else: print 'NO'
def ok(a): a = a.split(' ') b = '' for i in a: b += i return b a = raw_input() b = raw_input() if a == b: print("Accepted") elif ok(a) == ok(b): print("Presentation Error") else: print("Wrong Answer")
suma = 0.00 for i in range(12): a = float(input()) suma += a suma /= 12.00 print ("$" + str(suma))
count = 0 sum = 0 print ("Before",count,sum) for value in [9,41,12,3,74,15]: count = count + 1 sum = sum + value print (count, sum, value) print ("After", count, sum, sum/count)
# -*- coding: utf-8 -*- """ Created on Wed May 31 14:15:40 2017 @author: yuwang This is the Python code for parsing the data table in xls or xlsx extension. """ import os import xlrd import xlwt import math import datetime """ ---------Core-------- """ def isyear(A): if type(A) is float: P = math.modf(A) eps = 0.00001; Deci = P[0] Inti = P[1] if abs(Deci) <= eps: Y = Inti else: return False elif type(A) is int: Y = A; elif (type(A) is str) and len(A)<15: B = [int(s) for s in A.split() if s.isdigit()] BB = [isyear(b) for b in B] return any(BB) else: return False if Y in range(1700,datetime.datetime.now().year+30): return True else: return False def isvalue(A): if type(A) in [float,int]: return True elif (type(A) is str) and (any(c.isdigit() for c in A)) and (len(A)<15): return True else: return False def isblank(A): if type(A) is str: AA = A for c in 'Nn/Aa ': AA = AA.replace(c,'') if (len(AA)>0) and (any(c.isalpha() for c in AA)): return False else: return True else: return False def istitle(A): if (type(A) is str) and any(c.isalpha() for c in A): return True else: return False def RorC(sheet): for i in range(0,sheet.nrows): for j in range(0,sheet.ncols): if isyear(sheet.cell(i,j).value) is True: if isyear(sheet.cell(i,j+1).value) is True: return 'Row'+str(i) elif isyear(sheet.cell(i+1,j).value) is True: return 'Col'+str(j) else: Error = 'Error: Not consistent year' print(Error) return Error Error = 'Error: cannot find any years' print(Error) return Error def titlepos(sheet,I,L): tpos = L-1 II = -1 for i in range(I+1,sheet.nrows): if isblank(sheet.cell(i,L).value) is True: continue elif (isvalue(sheet.cell(i,L).value) is True) and (II < 0): II = i elif (isvalue(sheet.cell(i,L).value) is True) and (II > 0): III = i break else: Error = 'Error: find incognitive values' print(Error) return 0 while (sheet.cell(II,tpos).value==sheet.cell(III,tpos).value or (isblank(sheet.cell(II,tpos).value) is True) or (isblank(sheet.cell(III,tpos).value) is True)) and (tpos > 0): tpos = tpos -1 if (istitle(sheet.cell(II,tpos).value) is True) and (istitle(sheet.cell(III,tpos).value) is True) and (sheet.cell(II,tpos).value!=sheet.cell(III,tpos).value): return tpos else: Error = 'Error: cannot find titles' print(Error) def isemptyrow(sheet,i,L,R): for j in range(L,R+1): if isblank(sheet.cell(i,j).value) is True: pass elif isvalue(sheet.cell(i,j).value) is True: return False else: Error = 'Error: find incognitive values' print(Error) return False return True def transpose(sheet,bookname,sheetname,sym,dirout): W = [] I = sheet.nrows J = sheet.ncols for i in range(0,I): W.append(sheet.row_slice(i,0,J)) for j in range(0,len(W[-1])): W[-1][j] = W[-1][j].value outbook = xlwt.Workbook() outsheet = outbook.add_sheet(sheetname) for i in range(0,I): for j in range(0,J): outsheet.write(j,i,W[i][j]) dir = dirout + sym + bookname + '_' + 'Transposed_Temp' +'.xls' outbook.save(dir) return dir def parser(dirin,dirout): book = xlrd.open_workbook(dirin) for cc in range(len(dirin)-1,-1,-1): if (dirin[cc]=='.'): dd=cc elif (dirin[cc]=='\\') or (dirin[cc]=='/'): sym = dirin[cc] bookname = dirin[cc+1:dd] break sheetnames = book.sheet_names() for s in range(0,book.nsheets): sheet = book.sheet_by_index(s) structure = RorC(sheet) if structure[0:5]=='Error': print('Error: cannot recognize the structure, see error info above. Pass.') continue elif structure[0:3]=='Row': I = int(structure[3:]) for j in range(0,sheet.ncols-1): if isyear(sheet.cell(I,j).value) is True: L = j break for j in range(sheet.ncols-1,0,-1): if isyear(sheet.cell(I,j).value) is True: R = j break Years = sheet.row_slice(I,L,R+1) for i in range(0,len(Years)): Years[i]=Years[i].value W = [['Years']+Years+['Row']] LL = titlepos(sheet,I,L) for i in range(I+1,sheet.nrows): if isemptyrow(sheet,i,L,R) is True: continue else: W.append([sheet.cell(i,LL).value]+sheet.row_slice(i,L,R+1)) for j in range(1,len(W[-1])): W[-1][j] = W[-1][j].value W[-1]=W[-1]+[i+1] outbook = xlwt.Workbook() RLen = len(W[0]) for R in W[1:]: outsheet = outbook.add_sheet('Row '+str(R[-1])) outsheet.write(0,0,'Years') outsheet.write(0,1,R[0]) for i in range(1,RLen-1): outsheet.write(i,0,W[0][i]) outsheet.write(i,1,R[i]) outbook.save(dirout + sym + bookname + '_' + sheetnames[s] +'.xls') else: dirinter = transpose(sheet,bookname,sheetnames[s],sym,dirout) parser(dirinter,dirout) os.remove(dirinter) """ --------Debug--------- """ """ dir = "/Users/yuwang/Documents/PPI/Downloader_Git/Sample_Data/sbsummar.xls" dirout = "/Users/yuwang/Documents/PPI/Downloader_Git/Sample_Data/Parsed_Data" book = xlrd.open_workbook(dir) parser(dir,dirout) """
# Items that exist in each room and the functions you can use to interact with them #TODO Define items in each room room0items = ['leaflet'] room1items = ['fish'] room2items = [] room3items = [] room4items = [] room5items = [] room6items = [] room7items = ['lantern'] room8items = [] room9items = [] room10items = [] room11items = ['longsword'] allItems = [room0items, room1items, room2items, room3items, room4items,room5items,room6items,room7items,room8items,room9items,room10items,room11items] # Returns item to be added to inventory if it exists in this room and removes it from the list of items in the coom def pick_up(itemName, roomNum): if itemName in allItems[roomNum]: allItems[roomNum].remove(itemName) return itemName else: print("Not a valid item to pick up") return -1 # Puts the item down in the current room, adds it to the item list of the current room, # and returns 0 to indicate that it was successfully removed. def put_down(itemName, roomNum): print("You put down the ", itemName) # TODO Add item to room item list allItems[roomNum].append(itemName) return 0 def useItem(itemName,itemList): if itemName in itemList: print("You used the ", itemName) return True else: print('You do no have that item in inventory ') return False def printroom(): print(room0items)
""" A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case. """ #code faux, la récursive ne fonctionne pas def isPower(a,b): if a%b == 0: if isPower(a/b, b): return True else: return False #code correct avec recursive def is_power(a, b): """Checks if a is power of b.""" if a == b: return True elif a%b == 0: return is_power(a/b, b) else: return False a=4 b=2 print (isPower(a,b)) print(is_power(a,b))
#compte le nombre de fois qu'une lettre apparait dans 1 string from list import has_duplicates def checkString(s): listLetters={} for c in s: if c not in listLetters: listLetters[c]=1 else: listLetters[c] +=1 return listLetters myCar={'marque':'aston', 'modèle':'DB5', 'année':1964, 'couleur':'grey'} def dicoLoop(h): for c in h: print(c,h[c]) for c in h: print(c) def invert_dict(d): inverse = {} for key in d: val = d[key] if val not in inverse: inverse[val] = [key] else: inverse[val].append(key) return inverse known = {0:0, 1:1} def fibonacci(n): if n in known: return known[n] res = fibonacci(n-1) + fibonacci(n-2) known[n] = res return res """ Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary. """ def checkDico(w): fin=open('words2.txt') myDico={} for word in fin: myDico[word.strip()]='' if w in myDico: return True else: return False #renvoie dictionnaire inversé def invert_dict(d): inverse = {} for key in d: if d[key] not in inverse: inverse[d[key]] = [key] else: inverse[d[key]].append(key) return inverse #version avec setdefault def invert_dict2(d): inverse = {} for key in d: inverse.setdefault(d[key],key) return inverse """ If you did Exercise 10.7, you already have a function named has_duplicates that takes a list as a parameter and returns True if there is any object that appears more than once in the list. Use a dictionary to write a faster, simpler version of has_duplicates """ test_list=['lapin','cheval','chien','chat','cheval'] def has_duplicate2(the_liste): tempDic={} for i in the_liste: if i not in tempDic: tempDic[i]='' else: return True return False print(has_duplicate2(test_list))
#project-1 import random a=random.randint(1,3) def win(comp,human): if comp=='s' and human=='w': print("Oops-comp wins") elif comp=='s' and human=='g': print("Yeah-you win") elif comp=='s' and human=='s': print("Tie") if comp=='w 'and human=='s': print("Yeah-you win") elif comp=='w' and human=='g': print("Oops-comp win") elif comp=='w' and human=='w': print("Tie") if comp=='g' and human=='s': print("Oops-comp win") elif comp=='g' and human=='w': print("Yeah-you win") elif comp=='g' and human=='g': print("Tie") print("Computer has chosen its choice kindly enter yours----") if a==1: comp='s' elif a==2: comp ='w' elif a==3: comp='g' human=input("Enter your choice\n") k=win(comp,human) comp_choice=comp print("Computer chose - " + comp_choice)
# PROJECT-3 print("\n****WELCOME TO CHAT-BAZAR****\n") print("PLEASE SELECT YOUR ORDER: ") print("PANEER: 250/PLATE") print("CHICKEN: 500/PLATE") print("PANEER-TIKKA: 300/PLATE") print("BHOJAN-THAL: 200/PLATE") print("MANCHURIAN: 150/PLATE") print("CHOWMEIN: 50/PLATE") print("After Ordering The Food Please Enter (EXIT) And Quantity (0) To Confirm Your Order!\n") dict = {'PANEER': 250, 'CHICKEN': 500, 'PANEER-TIKKA': 300, 'BHOJAN-THAL': 200, 'MANCHURIAN': 150, 'CHOWMEIN': 50} list = list(dict.keys()) sum = 0 cNt = 0 while True: odr = input("Enter Your Order Please: \n") quantityS = int(input("Enter Qnantity: ")) cNt += 1 if odr == 'EXIT': break elif odr in list: k = dict[odr]*quantityS sum += k print(f'The Total Of {odr} With Quantity {quantityS} is: {str(k)}') else: print("OOPS! Please Enter The Items Given In The Menu: ") print("This Item Entered Above Will Not Count In Your Bill!THANKS ") print("Thanks For Ordering The Food!") print("Your Bill Total is ", sum) if cNt > 5: sum = (1/5)*sum # 20%profit print('CONGRULATIONS! YOU ORDERED MORE THAN 5 ITEMS SO YOUR DISCOUNTED BILL AMOUNT IS:', sum)
#PROJECT-2 import random n = random.randint(1, 100) print(n) numberSn = None guess=0 while (numberSn != n): numberSn = int(input("Enter A Number: ")) guess+=1 if (numberSn == n): print("Awesome! Right Answer") else: if (numberSn > n): print("Oops! Enter a Smaller Number: ") else: print("Oops! Enter a Greater Number: ") with open("hiscore.txt","r") as f: hiscore = int(f.read()) if(guess<hiscore): print("You have just broken the high score!") with open("hiscore.txt", "w") as f: f.write(str(guess))
#!/usr/bin/env python3 import sys import os import hashlib def check_hash(filepath: str, obj: list) -> None: """This method checks if hashes match. :param filepath: File location path :param obj: Argument list obj[0] - filename obj[1] - hash_method obj[2] - hash_string :return: none """ path = os.path.join(filepath, obj[0]) path = os.path.normpath(path) try: with open(path, "r", encoding="utf-8") as check_file: check_file = check_file.read() hash_object = hashlib.new(obj[1]) # create a hash object with a need hash method hash_object.update(check_file.encode()) # create hash string if hash_object.hexdigest() == obj[2]: # Checking that the hashes match print(f"{obj[0]}\tOK") else: print(f"{obj[0]}\tFAIL") except IOError as error: if error.args[0] == 2: # file not found print(f"{obj[0]}\tNOT FOUND") else: print(error) # other error def main() -> int: """Entry point. :param: None :return: status code """ _help = """Call example:\n <your program> <path to the input file> <path to the directory containing the files to check>""" if len(sys.argv) != 3: if sys.argv[1] == "--help": print(_help) return 0 print("[ERROR] - Invalid number arguments. Please type --help to see help.") return -1 path_to_input_file: str = sys.argv[1] # The path to the file that contains the list of scanned files path_to_containing_files: str = sys.argv[2] # The path where the scanned files are located if os.path.isfile(path_to_input_file) is False: print("[ERROR] - File does not exist") return -1 with open(path_to_input_file, "r", encoding="utf-8") as input_file: input_file = input_file.readlines() for line in input_file: check_hash(path_to_containing_files, line.split()) return 0 if __name__ == "__main__": sys.exit(main())
var input = print("Give me one number") var usernum = parseInt(userinput, 10) sum = sum + usenum print("User number is: "+ usernum +")
# 'Data Science from Scratch' Chapter 1 exampl # Create list of users userNames = ["Hero", "Dunn", "Sue", "Chi", "Thor", "Clive", "Hicks", "Devin", "Kate", "Klein"] users = [] for ind, name in enumerate( userNames ): users.append( {"id": ind, "name": name}) # Helper function to get id get_id = lambda userlist: map( lambda user: user["id"], userlist) # Friendship friendships = [(0,1), (0,2), (1,2), (1,3), (2,3), (3,4), (4,5), (5,6), (5,7), (6,8), (7,8), (8,9)] # Store as directed graph g = friendships g.extend(map(lambda(i,j): (j,i), friendships)) # Add the list of friends to each user for user in users: user["friends"] = [] for i,j in g: users[i]["friends"].append(users[j]) # Number of friends each user has number_of_friends = lambda (user): len(user["friends"]) # Total numnber of connections number_of_connections = reduce(lambda acc, el: acc + number_of_friends(el), users, 0) # Sort by popularity map(lambda user:(user["name"], number_of_friends(user)), sorted(users, key=lambda user:number_of_friends(user), reverse=True)) # Friend of a friend # A friend of a friend is someone who is not your friend # but is the friend of one of your friends # Want to keep track of how many ways we are foaf with each person from collections import Counter def foaf(user): all_id = get_id(reduce( lambda acc, user: acc + user["friends"], user["friends"], [])) # Remove user id and user friends id ignore_id = get_id(user["friends"]) + [user["id"]] foaf_id = filter( lambda id: id not in ignore_id, all_id) return Counter(foaf_id) # Mutual interests # Store interests as a lookup from user id to list of interests interests_dict = {0: ["Hadoop", "Big Data", "HBase", "Java", "Spark", "Storm", "Cassandra"], 1: ["NoSQL", "MongoDB", "Cassandra", "HBase", "Postgres", "Python", "scikit-learn", "scipy"], 2: ["numpy", "statsmodels", "pandas"], 3: ["R", "Python", "statistics", "regression", "probability"], 4: ["machine learning", "regression", "decision trees", "libsvm"], 5: ["Python", "R", "Java", "C++"], 6: ["statistics", "theory", "probability", "mathematics"], 7: ["machine learning", "scikit-learn", "Mahout", "neural networks"], 8: ["neural networks", "deep learning", "Big Data", "artificical intelligence"], 9: ["Hadoop", "java", "MapReduce", "Big Data"]} # Invert to look up from interest to list of user ids from collections import defaultdict users_dict = defaultdict(list) for k in interests_dict.keys(): map(lambda v: users_dict[v].append(k), interests_dict[k]) def most_common_interests_with(user): user_interests = interests_dict[user["id"]] id_list = map( lambda interest: users_dict[interest], user_interests) all_ids = filter(lambda x: x!= user["id"], reduce( lambda acc, ids: acc+ids, id_list, [])) return Counter(all_ids) # Find topics of interest topic_count = map( lambda k: (k.lower(), len(users_dict[k])), users_dict.keys()) topic_dict = defaultdict(int) for topic, count in topic_count: topic_dict[topic] += count Counter(topic_dict)
from collections import OrderedDict import os import pandas as pd def get_book_content(): csv_path = os.path.dirname(os.path.realpath(__file__)) + '/test_example.csv' print('Test CSV File :: ', csv_path) df = pd.read_csv(csv_path, header=None).rename( columns={0: 'chapter', 1: 'sentence', 2: 'text'}) book_dict = OrderedDict() for index, row in df.iterrows(): ch_id = row['chapter'] s_id = row['sentence'] text = row['text'] # print(ch_id, " -> ", s_id, " -> ", text) if ch_id not in book_dict: book_dict[ch_id] = [] book_dict[ch_id].append(text) return book_dict def get_book_metadata(): dict_metadata = { "book_id": "fdcap_book", "title": "Crime and Punishment", "lang": "en", "isTranslation": "true", "totalChapters": "2", "authors": [ { "name": "Herr Isaac Riley", "translator": "true" }, { "name": "Fyodor Dostoevsky" } ], "description": "Crime and Punishment (Russian: Преступление и наказание) is a novel written by Russian author " "Fyodor Dostoevsky.First published in a journal named The Russian Messenger, it appeared in " "twelve monthly installments in 1866, and was later published as a novel", "source": "https://en.wikisource.org/wiki/Crime_and_Punishment" } return dict_metadata
# --- Day 7: Handy Haversacks --- from urllib.request import urlopen data = urlopen('https://raw.githubusercontent.com/MarynaLongnickel/AdventOfCode2020/main/Day7/day7.txt').read().decode().split('\n')[:-1] dic = {} dic2 = {} for d in data: d = d.split(' bags contain ') k = d[0] v = d[1].replace('s, ', '').replace('s.', '').replace(', ', '').split('bag')[:-1] v = [x[:-1] for x in v if x != 'no other '] for i in v: i = i[2:] if i not in dic.keys(): dic[i] = [] dic[i].append(k) dic2[k] = v q = ['shiny gold'] found = [] while q: bag = q.pop() if bag in dic.keys(): for i in dic[bag]: if i not in found: found.append(i) q.append(i) print(len(found)) # ---------------------- PART 2 ------------------------ def count_bags(b): return sum([int(i[0]) + int(i[0]) * count_bags(i) for i in dic2[b[2:]]]) if len(dic2[b[2:]]) > 0 else 0 print(count_bags('1 shiny gold'))
def prime_number(n): """ this function takes in a number then generates all the prime numbers in the range of that number and append to a list which is the output """ primes = [] if n<2: return False else: for prime in range(2, n): for b in range(2, prime): if (prime % b == 0): break else: primes.append(prime) return primes
class Room(object): def __init__(self, name, description): self.name = name self.description = description self.paths = {} def go(self, direction): return self.paths.get(directions, None) def add_paths(self, paths): self.paths.update(paths) hogsmeade = Room("Hogsmeade", """ The prisinors from Azbaban have escaped and you and you fellow Aurors have been tasked with rallying them up and turning them into the Ministry of Magic. You are hurrying about Hogsmeade, trying to stay safe while capturing the rebels. You burst into Zonko's in time to catch an escaped convict attempting to steal all opf the gold out of the safe. You take aim to disarm him as he draws a stolen wand to your chest. YOu have to choose: LAY DOWN your wand or DISARM the prisonor. """) three_bromsticks = Room("Three Broomsticks", """ You successfully disarm the rebel, secure the stolen wand, and capture the prisonor. You cast Petrificous Totalus, making it easier for you to drag him along to the Three Broomsticks, Auror gathering spot. As you approach the Three Broomsticks, you can tell something is off. It is eeriely quiet, and none of your team appears to have arrived. You look inside, and you see your team silenced and hanging from the ceiling from their feet, a Death Eater trick. There are escaped convicts enjoyinh butterbeer by the gallon. laughing as they torture the captured Aurors. YOu bring your prisonor to the front door, about to burst in when you see there is a magical lock on it. It requires a four digit code, and getting it wrong three times would result in complete annihalation of the city. """) courtyard = Room("Courtyard", """ You correctly enter the code and charge into the Three Broomsticks. The convicts become silent, then scramble to get their wands. Too late for them, as you have already released your group and conjured their wands back to them. You gather all of the convicts, and bring them outside to go to the dspoist point. As you go to the Portkey, stormy clouds gather in the skies, and lightening blinds you. You gather yourself just in time to see a crowd of Death Eaters descend from the sky. In front is Draco Malfoy, the newest leader, eager to avenge his parents death. He advises you to turn over the convicts to him, or suffer a painful fate. The Portkey starts quivering, just out of reach. Ten more seconds, and you wil fail your mission. You must either GIVE IN the Malfoy's threats, or RISK making it to the Portkey in time for travel. """) the_house = Room("The House", """ You touch the Portkey just in time, traveling fasted than the speed of light. You arrive at the deposit point to be greeted by the greatest Auror of all, Nyphadora Tonks. She thanks you for your hard work, and send the prisonors back to Azkaban, equipped with more security than ever. She asks if you would like to head another mission, this time delivering socks to free houseelves. yes or no? """) the_end_yes = Room("The End", """ You agree to another mission. Tonks presents another Portkey and a sack of socks. She wishes you luck on your journey, and advises that all freed elves will find roo, board, and work at Hogwarts. """) the_end_no = Room("The End", """ You decline another mission. She lets you know that her door will always be open when you want work. You Apparate to your house, and settle in your favorite chair with an ice cold Butterbeer. """) the_house.add_paths({ 'yes': the_end_yes, 'no': the_end_no }) generic_death = Room("death", "You died.") courtyard.add_paths({ 'give in': generic_death, 'risk': the_house }) three_broomsticks.add_paths({ '*': generic_death, '3825': courtyard }) hogsmeade.add_paths({ 'lay down': generic_death, 'disarm': three_broomsticka }) START = 'hogsmeade' def load_room(name): """ There is a potentail security problem here. Who gets to set the name? Can that expose a vaiable? """ return globals().get(name) def name_room(room): """ Same possible security problem. What's a better solution than this globals lookup? """ for key, value in globals().items(): if value == room: return key
from readint import readinput def gcd(x, y): """ input: 2 integers x and y with x >= y >= 0 output: greatest common divisor of x and y """ if (y == 0): return x return gcd(y, x % y) def main(): x = readinput("x") y = readinput("y") if y > x: x, y = y, x ans = gcd(x, y) print ("GCD of %d and %d = %d" % (x, y, ans)) if __name__ == '__main__': main()
# python-3 def inputmatrix_values(row, col): print ("Enter matrix values row by row - space separated") r = 1 matrix = [] while r <= row: row_in = input("row %d: " % r) rowvals = row_in.split(" ") try: rowvals = [int(val) for val in rowvals] except ValueError: print ("Bad integer value. plz try again..") print ("Enter matrix values row by row - space separated") r = 1 continue if len(rowvals) != col: print ("Wrong number of cols. Expected: %d, Got: %d" % (col, len(rowvals))) print ("Enter matrix values row by row - space separated") r = 1 continue matrix.append(rowvals) r += 1 print (matrix) return matrix def matrixmultiply(A, B): if (A is None) or (B is None): print ("One of matrix is None") return None rowA = len(A) colA = len(A[0]) rowB = len(B) colB = len(B[0]) if colA != rowB: print ("matrix multiplication not possible.") return None C = [] for i in range(rowA): c_row = [] for j in range(colB): total = 0 for k in range(rowA): total += A[i][k] * B[k][j] c_row.append(total) C.append(c_row) return C def matrix_input(): print ("Enter values space separated") while True: matrix = input("rows and cols for matrix: ") matrix = matrix.strip() matrix = matrix.split(" ") try: if len(matrix) != 2: print ("Too few or too many values for row/col") continue matrix = [int(f) for f in matrix] A = inputmatrix_values(matrix[0], matrix[1]) return A except ValueError: print ("Bad row/col input. Try again..") def printmatrix(M): if M is None: return row = len(M) col = len(M[0]) for i in range(row): for j in range(col): print (M[i][j], sep=" ", end=" ") print () def test_matrix_mul(): print ("Input for Matrix A") A = matrix_input() print ("\n") print ("Input for Matrix B") B = matrix_input() C = matrixmultiply(A, B) print ("\n") print ("Matrix A: ") printmatrix(A) print ("Matrix B: ") printmatrix(B) print ("Matrix C = A * B") printmatrix(C) def main(): test_matrix_mul() if __name__ == '__main__': main()
# multiplication of 2 binary numbers using grade school technique from binary_addition import binary_sum def binary_number_input(msg): while True: x = input(msg) found = True for i in x: if i != '0' and i != '1': found = False print ("Bad binary input! Plz try again..") break if found: return x def binary_mult(x, y): y = y[::-1] index = 0 ilist = [] for i in y: if i == '1': s = "0" * index z = x + s ilist.append(z) index += 1 # for n in ilist: # print (n) ans = "0" for n in ilist: ans = binary_sum(ans, n) print ("x * y = ", ans) def main(): x = binary_number_input("First Binary Number X: ") y = binary_number_input("Second Binary Number Y: ") binary_mult(x, y) if __name__ == '__main__': main()
def readinput(k): bstr = raw_input("Enter a binary string %s: " % k) return bstr def bitsum(a, b, carry): """ assumes a, b and carry are single bits returns result = (sum of bits, carry) """ result = (0, 0) c = a + b if c == 1 and carry == 0: result = 1, 0 elif c == 1 and carry == 1: result = 0, 1 elif c == 2 and carry == 0: result = 0, 1 elif c == 2 and carry == 1: result = 1, 1 elif c == 0: result = carry, 0 else: print "sum: ", c, " carry: ", carry print "ERR: Should not have come here!" return result def binsum(x, y): """ Assumes x and y are binary strings, returns sum of x and y as binary string """ xlen = len(x) ylen = len(y) diff = abs(xlen - ylen) z = "0" * diff if xlen > ylen: y = z + y elif ylen > xlen: x = z + x # print "X: ", x # print "Y: ", y result = [] carry = 0 for i in range(xlen-1, -1, -1): # print "x, y, carry: ", x[i], " ", y[i], " ", carry sm, carry = bitsum(int(x[i]), int(y[i]), carry) # print "sum: ", sm, " carry: ", carry result.append(sm) if carry == 1: result.append(carry) result = result[::-1] result = ''.join(str(r) for r in result) return result def main(): x = readinput("x") y = readinput("y") result = binsum(x, y) print "Sum is: ", result if __name__ == '__main__': main()
n=int(input("ENTER THE NUMBER")) sum=0 for i in range(n,0,-1): sum=sum+i print(sum)
english=float(input("enter english marks")) tamil=float(input("enter tamil marks")) science=float(input("enter science marks")) maths=float(input("enter maths marks")) socialscience=float(input("enter social science marks")) x=int("5") total=english+tamil+science+maths+socialscience print(f"english-{english}") print(f"tamil-{tamil}") print(f"science-{science}") print(f"maths-{maths}") print(f"socil science-{socialscience}") print(f"_______________________") print(f"total={english+tamil+science+maths+socialscience}") average=(english+tamil+science+maths+socialscience)/5 print(f"average={(english+tamil+science+maths+socialscience)/x}")
name=str(input("PLEASE ENTER TOUR USERNAME:")) password=int(input("PLEASE ENTER YOUR PASSWORD:")) user=str("balamurugan") pswd=int("9876543210") if (user and pswd)==(name and password): print("WELLCOME SIR") else: print("Please Enter Correct Username and Password")
for i in range(5): for j in range(5): if (j==0) or (i==4): print("*",end=" ") else: print(" ",end=" ") print()
''' def [function_name]([parameters]): [function_definition] def add(x, y): """ Returns x + y. :param x: int. :param y: int. :return: int sum of x and y. """ return x + y ''' def f(x): return x * 2 def f(): return 1 + 1 result = f() print(result) def f(x, y, z): return x + y + z result = f(1, 2, 3) print(result) def f(): z = 1 + 1 result = f() print(result) def even_odd(x): if x % 2 == 0: print("even") else: print("odd") print(even_odd(2)) print(even_odd(3)) def add_it(x, y=10): return x + y result = add_it(2) print(result) def f(x=2): return x**x print(f()) print(f(4))
x = 10 while x > 0: print('{}'.format(x)) x -= 1 print("Happy New Year!") i = 1 while i <= 5: if i == 3: i += 1 continue print(i) i += 1 while input('y or n?') != 'n': for i in range(1, 6): print(i)
my_dict1 = dict() print(my_dict1) my_dict2 = {} print(my_dict2) fruits = {"Apple": "Red", "Banana": "Yellow" } print(fruits) facts = dict() # add a value facts["code"] = "fun" facts["Bill"] = "Gates" facts["founded"] = 1776 # lookup a key print(facts["founded"]) print(facts) bill = dict({"Bill Gates": "charitable" }) print("Bill Gates" in bill) print("Bill Gates" not in bill) books = {"Dracula": "Stoker", "1984": "Orwell", "The Trial": "Kafka"} del books["The Trial"] print(books)
def find(a,b): s=a+b p=a*b r=a/b return s,p,r a=int(input("Enter First No. : ")) b=int(input("Enter Second No. : ")) s,p,r=find(a,b) print("Sum is : ",s) print("product is : ",p) print("remainder is : ",r)
import random low=25 point =5 for i in range (1,5): Number=low + random.randrange(0,point); print(Number,end=":") point-=1; print()
# In the name of Allah, Most Gracious, Most Merciful # / # # # # # ?? n = input() scores = {} records = {} for i in range(n): name, score = raw_input().split() score = int(score) if name not in scores: scores[name] = 0 records[name] = [] scores[name] += score records[name].append((scores[name], i)) highest = sorted(scores.values())[-1] winner = ('', 1<<28) for name, score in scores.items(): if score == highest: for record, i in records[name]: if record >= highest and i < winner[1]: winner = (name, i) break print winner[0]
def staircase(n): first, second = 1,1 for index in range(n): first, second = second, first + second return first # Test Cases print(staircase(4)) # 5 print(staircase(5)) # 8
# a-97 # z-122 import string as s alphabet = s.ascii_letters[:26] # to get only letters with lowercase def char2bits(s=''): return bin(ord(s))[2:].zfill(8) #rint(char2bits('d')) def bits2char(b=None): return chr(int(b, 2)) #print(bits2char(char2bits('d'))) def encrypt_vernam(message, key, decode=False): while len(message)>len(key): key+=key ## constants fake_null = ''.zfill(8) message=message[::-1] ## is reversed fo next operation bin_key=[] message_key=[] for i in range(len(key)): bin_key.append( char2bits(key[i])) try: message_key.append ( char2bits(message[i]) ) except: message_key.append ( fake_null ) message_key=message_key[::-1] for i in range(len(key)): message_key[i] = bin(int(message_key[i],2)^int(bin_key[i],2))[2:].zfill(8) ## decode from bytes to chars ## but before this we have to remove all '00000000' elements in message_key messaged ='' for i in message_key: messaged+=bits2char(i) return messaged #test_key='zwrnijr23j)@#94u!@@HWIEUh' #test_message='hello world' #print(encrypt_vernam(test_message, test_key)) #print(encrypt_vernam(encrypt_vernam(test_message, test_key),test_key,True)) def checker(k): ''' input: int return: int ** It is used only for Cezar cipher. If added number is out of range of ASCII ENG alphabet then it is returns to the start of alphabet [or to the end] ** ''' if k > 122: return 97+k-123 #IMPORTANT CHECK BEFORE USE! #Al right! elif k < 97: return 122+k-96 else: return k def checker_vigener(k): while k > 122: k = 97 + k - 123 while k < 97: k = 122 + 96 - k k = checker_vigener(k) return k #print(checker_vigener(130)) def make_full_alph(key): ''' input: str return: str ** In case key lenght is less than 26 it adds unique letter from alphabet ** ''' key = correct_key(key) return key+alphabet.translate(alphabet.maketrans('', '', key)) def goal_translter(key): ''' input: str return: str ** Cezar cipher. It adds ASCII number of which word to ASCII number of ENG alphabet. As result we gets new alphabet ** ''' return "".join([chr(checker(ord(l)+key)) for l in alphabet]) def correct_key(key): ''' input: str return: str **delete all non unique words in key** ''' result_key = '' for i in key: if i not in result_key: result_key += i return result_key def crypt(text, key, decode=False): ''' input: str, str, bool return: str ** Returns encoded[decoded] text with Monoalphabetic cipher.** ''' converted_alphabet = make_full_alph(key) text = text.lower().translate(text.lower().maketrans('', '', s.punctuation + "1234567890")) # getting rid off all numbers and punctuations signs if decode: translition = text.maketrans(converted_alphabet, alphabet) else: translition = text.maketrans(alphabet, converted_alphabet) return text.translate(translition) def vigener_cipher(text, key, decode=False): text = text.lower().translate(text.lower().maketrans('', '', s.punctuation + "1234567890 ")) # getting rid off all numbers and punctuations signs while len(key) < len(text): key += key if decode: for k in range(len(text)-1): text = text[:k]+chr(checker(ord(text[k])-ord(key[k])+96))+text[k+1:] text=text[:-1] + chr(checker(ord(text[-1])-ord(key[-1])+96)) else: for k in range(len(text)): text = text[:k]+chr(checker(ord(text[k])+ord(key[k])-96))+text[k+1:] text=text[:-1] + chr(checker(ord(text[-1])+ord(key[-1])-96)) return text # print(crypt("sdfdgfdgf","abf"))
""" An if statement activates if the condition is true: """ a = 1 b = 2 c = 3 if a == b: print("This Is False") # Wont be written if b < c: print("This is True) # Will be written
print("Exercise 11: "); list1 = [1, 2, 3, 4, 5]; l1 = len(list1); list2 = [6, 7, 8, 9, 10]; l2 = len(list2); def recursion(list, i): if i == 0: return (list[i]); else: return (list[i] * recursion(list, i-1)); print("\nTesting two arrays for recursively getting the products of their elements"); print("\nContents of List 1: ", list1); print("Product of List 1 using recursion: ", recursion(list1, l1-1)); print("\nContents of List 2: ", list2); print("Product of the List 2 using recursion: ", recursion(list2, l2-1)); def iteration(list, i): product = 1; for x in range(i): product = product * list[x]; return product; print("\nTesting two arrays for getting the products of their elements through iteration"); print("\nContents of List 1: ", list1); print("Product of List 1 using iteration: ", iteration(list1, l1)); print("\nContents of List 2: ", list2); print("Product of the List 2 using iteration: ", iteration(list2, l2));
print("Exercise 3: "); print("\na. float(123) = ", float(123) ); print("This turns 123 into a float type and then prints it out."); print("\nb. float('123') = ", float('123') ); print("This turns the input of '123' into a float and prints the actual value of 123 without the apostrophies"); print("\nc. float('123.23') = ", float('123.23')); print("This turns the input of '123.23' into a float and prints it out wihout the apostrophies"); print("\nd. float(123.23) = ", float(123.23)); print("This turns the input 123.23 into a float type and then prints it out"); print("\ne. int(123.23) = ", int(123.23)); print("This turns the input 123.23 into an int type and then prints out the value 123 instead since ints don't have decimals."); print("\nf. int(float('123.23')) = ", int(float('123.23'))); print("This turns the input '123.23' into a float first and then into an int after, and then prints out the value which is 123."); print("\ng. str(12) = ", str(12)); print("This turns the input 12 into a string type and prints it out, so on screen the 12 is of type int now"); print("\nh. str(12.2) = ", str(12.2)); print("This tunrs the input 12.2 into a string type and then proceeds to print it"); print("\ni. bool('a') = ", bool('a')); print("This turns a into a boolean type and then it prints out True meaning the it's a true bool type"); print("\nj. bool(0) = ", bool(0)); print("This turns 0 into a boolean type and then printed out false, most likely because 0 always represents false and 1 represents true"); print("\nk. bool(0.1) = ", bool(0.1)); print("This turns the value 0.1 into boolean type and then printed out true");
class Player: def __init__(self): self.display = 'A' self.num_water_buckets = 0 self.row = 0 self.col = 0 def set_row(self, row): self.row = row def set_col(self, col): self.col = col def add_bucket(self): self.num_water_buckets +=1 def remove_bucket(self): self.num_water_buckets -= 1 def __str__(self): return "Player" def __repr__(self): return self.__str__() def move(self, move): #for player movement, respective keys provide respective update to coordinates if move == "s": return [1, 0] if move == "w": return [-1, 0] if move == "a": return [0, -1] if move == "d": return [0, 1] if move == "q": return [0, 0] if move == "e": return [0, 0] if move == "S": return [1, 0] if move == "W": return [-1, 0] if move == "A": return [0, -1] if move == "D": return [0, 1] if move == "Q": return [0, 0] if move == "E": return [0, 0]
from abc import ABC, abstractmethod from typing import TypeVar, List, Iterator # Define some generic types T = TypeVar("T") K = TypeVar("K") class AbstractStore(ABC): @abstractmethod def __len__(self) -> int: pass @staticmethod def add(self, value: T) -> K: """Returns key""" pass @abstractmethod def get(self, key: K) -> T: pass @abstractmethod def remove(self, key: K) -> None: pass @abstractmethod def __iter__(self) -> Iterator[T]: pass @abstractmethod def save(self) -> None: """Persist values""" pass @abstractmethod def load(self, **kwargs) -> None: """Load data from external persistance mechanism. Args will vary with mechanism """ pass @abstractmethod def dump(self) -> List[T]: """Returns a list of the values stored to allow for values to be persisted elsewhere """ return list(self)
import sys list1=sys.argv[1].split(",") def add_last (a): a.append ( a[len(a)-1] ) return a add_last (list1) print list1
from typing import List class Question: def __init__(self, text: str, answer: str, *args, **kwargs): self.text = text self.answer = answer def display(self) -> None: raise NotImplementedError('Method "display" must be implemented on Question class') class TrueFalse(Question): def display(self) -> None: print(self.text) print('Yes or No') class MultiChoice(Question): def __init__(self, text: str, answer: str, choices: List[str]): super().__init__(text, answer) self.choices = choices def display(self) -> None: print(self.text) for (l, a) in zip(['A', 'B', 'C', 'D'], self.choices): print(f'{l}) {a}') def display_questions(questions: List[Question]) -> None: print(f'Starting quiz with {len(questions)} questions...\n\n') for question in questions: question.display() print('-'*20, '\n') if __name__ == '__main__': questions: List[Question] = [ TrueFalse('Is my cat cute?', 'yes'), MultiChoice('What is my name?', 'Zsolt', ['Zsolt', 'Niki', 'Jani', 'Gabi']) ] display_questions(questions)
class Coche(object): """Abstraccion de los objetos coche.""" def __init__(self, gasolina): self.gasolina = gasolina print("Tenemos " + str(gasolina) + " litros") def arrancar(self): if self.gasolina > 0: print ("Arranca coche!") else: print ("No arranca...") def conducir(self): if self.gasolina > 0: print ("Quedan" , self.gasolina , "litros") #AQUÍ NO PIDE CONVERTIR str(self.gasolina) porque se concatenó con comas ',' y no con self.gasolina -= 1 #el operador '+' else: print ("No se mueve...") gas=10 Camaro=Coche(gas) for i in range(gas+1): Camaro.conducir()
class Persona(object): def __init__(self, name): #__init__ FUNCIÓN DE INICIALIZACIÓN, DONDE SE INTRODUCEN LOS OBJETOS DONDE QUE SERÁN NECESARIOS PARA CORRER EL PROGRAMA self.name = name def saluda(self): print("Hola " + self.name) def despidete(self): print("Adios " + self.name) p=Persona("Ana") p.saluda() p.despidete() c=Persona("Jessica") c.saluda() c.despidete()
uno=1 dos=2 tres=3 print(uno<dos<tres) #Esta comparación encadenada significa que las comparaciones (uno<dos) y (dos<tres) son realizadas al mismo tiempo es_mayor=tres!=dos print(es_mayor)
import random class Baraja(): def __init__(self): trajes=["♤", "♡", "♧", "♢"] rangos=["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] #Baraja de 52 cartas disponibles self.barajas=[] #Ciclo for para cada traje en trajes for traje in trajes: #ciclo for para cada rango en rangos for rango in rangos: #concatena el rango y el traje y appen a self.barajas() self.barajas.append(rango+" de "+traje) def barajear(self): random.shuffle(self.barajas) print(self.barajas) def repartir(self): print(self.barajas.pop()) mi_baraja=Baraja() mi_baraja.barajear() mi_baraja.repartir() mi_baraja.repartir() mi_baraja.repartir() mi_baraja.repartir()
#La diagonal invertida es utilizada para "escapar" comillas simples y dobles; por ejemplo: 'it's me' #Imprime el siguiente texto utilizando una cadena: the name of this ice-cream is "sweet'n'tasty" dont_worry="Don't worry about aphostrophes" print(dont_worry) print("\"sweet\" is an ice-cream") print('text') msg="The name of this ice-cream is \"Sweet'n'Tasty\"" print(msg)
import unittest import src.generate_world as generate_world from src import cell_types from src.cell import Cell class TestGenerateWorld(unittest.TestCase): def test_generate_world_size_too_small(self): """ Tests that a board is not created for a board that is too small """ self.assertIsNone(generate_world.generate_world(4, 0, 0, 0)) def test_generate_world_board_too_big(self): """ Tests that a board is not created for a board that is too big """ self.assertIsNone(generate_world.generate_world(26, 0, 0, 0)) def test_generate_world_incorrect_probabilities(self): """ Tests that a board is not created with incorrect probabilities """ self.assertIsNone(generate_world.generate_world(5, 1, 1, 1)) def test_generate_world_correct(self): """ Tests that a board is created with correct input """ board_size = 5 board = generate_world.generate_world(board_size, .1, .1, .1).board self.assertIsNotNone(board) self.assertEqual(board_size, len(board)) empty_count = 0 for row in board: self.assertEqual(board_size, len(row)) for cell in row: self.assertIsNotNone(cell.cell_type) if cell.cell_type == cell_types.EMPTY: empty_count += 1 self.assertGreaterEqual(empty_count, 2) class TestCreateBoard(unittest.TestCase): def test_generate_board_correct(self): """ Tests that a board is created with correct input """ board_size = 5 board = generate_world.create_board(board_size, .1, .1, .1).board self.assertIsNotNone(board) self.assertEqual(board_size, len(board)) empty_count = 0 for row in board: self.assertEqual(board_size, len(row)) for cell in row: self.assertIsNotNone(cell.cell_type) if cell.cell_type == cell_types.EMPTY: empty_count += 1 self.assertGreaterEqual(empty_count, 2) class TestCreateCell(unittest.TestCase): def test_create_cell(self): """ Tests that a cell is created by create cell """ cell = generate_world.create_cell(0, .2, 0) self.assertIsNotNone(cell) def test_probability(self): """ Tests that the cell probability creation works correctly """ empty_cells = [ generate_world.create_cell(0, 0, 0) for _ in xrange(100) ] obsical_cells = ( [generate_world.create_cell(1, 0, 0) for _ in xrange(100)] ) pit_cells = ( [generate_world.create_cell(0, 1, 0) for _ in xrange(100)] ) wumpus_cells = ( [generate_world.create_cell(0, 0, 1) for _ in xrange(100)] ) self.assertTrue( all(cell.cell_type == cell_types.EMPTY for cell in empty_cells) ) self.assertTrue( all(cell.cell_type == cell_types.OBSTACLE for cell in obsical_cells) ) self.assertTrue( all(cell.cell_type == cell_types.PIT for cell in pit_cells) ) self.assertTrue( all(cell.cell_type == cell_types.WUMPUS for cell in wumpus_cells) ) class TestValidInput(unittest.TestCase): def test_valid_input_size_too_small(self): """ Tests that input is not valid for a board that is too small """ self.assertFalse(generate_world.valid_input(4, 0, 0, 0)) def test_valid_too_big(self): """ Tests that input is not for a board that is too big """ self.assertFalse(generate_world.valid_input(26, 0, 0, 0)) def test_valid_input_incorrect_probabilities(self): """ Tests that input is invalid with incorrect probabilities """ self.assertFalse(generate_world.valid_input(5, 1, 1, 1)) def test_valid_input_correct(self): """ Tests that valid input is valid """ self.assertTrue(generate_world.valid_input(5, .1, .1, .1)) class TestCheckProb(unittest.TestCase): def test_board_too_small(self): """ Tests that board that is too small doesn't work """ self.assertFalse(generate_world.check_board_size(4)) def test_board_too_big(self): """ Tests that a board that is too big doesn't work """ self.assertFalse(generate_world.check_board_size(26)) def test_valid_board_size(self): """ Tests that valid board size works """ self.assertTrue(generate_world.check_board_size(5)) class CheckProb(unittest.TestCase): def test_check_prob_incorrect(self): """ Test check probability of incorrect """ self.assertFalse(generate_world.check_prob(1, 1, 1)) def test_check_prob_correct(self): """ Test check probability of correct """ self.assertFalse(generate_world.check_prob(1, 0, 0)) class TestChooseEmptyCell(unittest.TestCase): def test_choose_empty_cell(self): """ Test checks that an empty cell is chosen """ empty_cells = [[0, 0]] self.assertEqual([0, 0], generate_world.choose_empty_cell(empty_cells)) class TestPlaceEmptyCell(unittest.TestCase): def test_place_in_empty_cell(self): """ Test checks that the correct item is placed in an empty cell """ empty_cells = [[0, 0]] board = [[Cell(cell_types.EMPTY)]] generate_world.place_in_empty_cell(board, cell_types.GOLD, empty_cells) self.assertEqual(cell_types.GOLD, board[0][0].cell_type)
""" ..module:: read_yaml :synopsis: Open a provided file path and load the yaml-formatted contents into a dictionary. """ import os import yaml #-------------------- def read_yaml(path, output=True): """ Open a provided file path and load the yaml-formatted contents into a dictionary. Return an error string if there is a failure. :param path: File path of a .yaml file to pull contents from. :type path: string """ # Try to open a yaml config file. try: stream = open(path, 'r') except FileNotFoundError: err = "{0} does not exist!".format(path) raise FileNotFoundError(err) else: if output: print("Opening {0}".format(path)) # Use yaml.load to read the contents into a dictionary. try: contents = yaml.load(stream) except yaml.YAMLError: err = "{0} is not a YAML formatted file!".format(path) raise TypeError(err) stream.close() if isinstance(contents, dict): return contents else: err = "{0} did not produce a YAML dictionary!".format(path) raise TypeError(err) #-------------------- if __name__ == "__main__": f = "../fake/k2sff_test.hlsp" d = read_yaml(f) print(d)
import logging def new_logger(filename, lvl=logging.DEBUG): """ This module establishes Python logging to a new user-provided log file at a specified message level. By operating on the root logger, parent modules can set up a new log file and allow child modules to simply use 'logging' commands. This enables multiple log file creation while running through a GUI. :param filename: The desired file to write logging messages to. :type filename: str :param lvl: The lowest level of messages to capture in the log. (Defaults to logging.DEBUG) :type lvl: int """ # An empty getLogger call returns the root log. logger = logging.getLogger() # Setting the handlers attribute to an empty list removes any existing # file handlers. logger.handlers = [] # Format the message strings to log. format = logging.Formatter('%(levelname)s from %(module)s: %(message)s') # Create a new file handler with the requested file name. handler = logging.FileHandler(filename, mode='w') handler.setFormatter(format) # Update the new properties of the root logger. logger.setLevel(lvl) logger.addHandler(handler) return logger
''' Simulate housing data, then run EM algorithm ''' import numpy as np import pandas as pd from matplotlib import pyplot as plt import scipy.optimize as opt import scipy.integrate as sci_integrate from scipy.stats import norm, expon ############################# ##### Generate the Data ##### ############################# ################## ##### Houses ##### ################## N = 20 num_size = 3 data = pd.DataFrame() data['size'] = np.random.randint(low=1, high=1 + num_size, size=N) def gen_room(data, num_size): # Generate room data data_new = np.zeros(data.shape[0]) for i in range(1, num_size + 1): relevant_data = data['size'] == i len_ = len(data[relevant_data]) data_new[relevant_data] \ = np.random.randint(low=i, high=i + 2, size=len_) return data_new data['beds'] = gen_room(data, num_size) data['baths'] = gen_room(data, num_size) ############################## ##### Price and Duration ##### ############################## beta = np.array([2, 1.75, 3]) sigma_L = 1 alpha = 1 c = 0 gamma = 1 epsilon = 1 eta = 10 data['x_i_beta'] = data @ beta data['p_L'] = np.random.normal(loc=data['x_i_beta'], scale=sigma_L) data['value_gap'] = data['p_L'] - data['x_i_beta'] data['lambda'] = (alpha / np.exp(data['value_gap']) - c) ** (1 / (1 + gamma) ) data['duration'] = np.random.exponential(scale = 1 / data['lambda']) data['p'] = data['p_L'] - eta * data['duration'] ** (1 / (1 + epsilon) ) ############### ##### MLE ##### ############### def integrand_MLE(p_L, house_rooms, duration, params): beta_0, beta_1, beta_2, sigma_L, alpha, \ c, gamma, epsilon, eta = params beta = np.array([beta_0, beta_1, beta_2]) value_gap = p_L - house_rooms @ beta lambda_ = (alpha / np.exp(value_gap) - c) ** (1 / (1 + gamma) ) #if abs(np.exp(value_gap)) == np.inf: # print('Issue is with value_gap') # return 0 if abs(np.exp( - 1 / 2 * (value_gap / sigma_L) ** 2) ) == np.inf: print('Issue is with value_gap squared') return 0 if abs(np.exp( - lambda_ * duration) ) == np.inf: print('Issue is with lambda') return 0 val = lambda_ * np.exp( - lambda_ * duration) \ * np.exp( - 1 / 2 * (value_gap / sigma_L) ** 2) if abs(val) == np.inf: print('Issue is with val') return 0 return val def integrate_MLE(data, params): duration = data['duration'] house_rooms = np.array([data['size'], data['beds'], \ data['baths']]) val = sci_integrate.quad(integrand_MLE, - np.inf, np.inf,\ args=(house_rooms, duration, params))[0] return val def crit(params, *args): beta_0, beta_1, beta_2, sigma_L, alpha, \ c, gamma, epsilon, eta = params beta = np.array([beta_0, beta_1, beta_2]) print('--------------------------------------') print('beta guess:', beta) house_rooms, p, duration = args[0] first_term = - 2 * np.log(sigma_L * np.sqrt(2 * np.pi) ) \ - 1 / 2 * ( (p - house_rooms @ beta \ + eta * duration ** (1 / (1 + epsilon) ) ) \ / sigma_L) ** 2 second_term_data = pd.concat([house_rooms, duration], axis=1) second_term = second_term_data.apply(integrate_MLE, axis=1, params=params) second_term = np.log(second_term) log_lik = np.sum(first_term) + np.sum(second_term) print('log lik:', log_lik) return - log_lik def run_MLE(): beta_0_0 = 2 beta_0_1 = 1.75 beta_0_2 = 3 sigma_L_0 = 1 alpha_0 = 1 c_0 = 0 gamma_0 = 1 epsilon_0 = 1 eta_0 = 10 params_init = np.array([beta_0_0, beta_0_1, beta_0_2, sigma_L_0, alpha_0, \ c_0, gamma_0, epsilon_0, eta_0]) args = np.array([data[['size', 'beds', 'baths']], data['p'], data['duration']]) results = opt.minimize(crit, params_init, args=args, method='L-BFGS-B') beta_0_MLE, beta_1_MLE, beta_2_MLE, sigma_L_MLE, alpha_MLE, c_MLE, \ gamma_MLE, epsilon_MLE, eta_MLE = results.x beta_MLE = np.array([beta_0_MLE, beta_1_MLE, beta_2_MLE]) print('beta_MLE:', beta_MLE) print('sigma_L_MLE:', sigma_L_MLE) print('alpha_MLE:', alpha_MLE) print('c_MLE:', c_MLE) print('gamma_MLE:', gamma_MLE) print('epsilon_MLE:', epsilon_MLE) print('eta_MLE:', eta_MLE) # calculate standard errors using inverse Hessian # Invese Hessian Matrix from optimizer function vcv_mle = (results.hess_inv).matmat(np.eye(9)) print('VCV_mle =', vcv_mle) stderr_beta_0_MLE = np.sqrt(vcv_mle[0,0]) stderr_beta_1_MLE = np.sqrt(vcv_mle[1,1]) stderr_beta_2_MLE = np.sqrt(vcv_mle[2,2]) stderr_beta_MLE = np.array((stderr_beta_0_MLE, \ stderr_beta_1_MLE, stderr_beta_2_MLE)) stderr_sigma_L_MLE = np.sqrt(vcv_mle[3,3]) stderr_alpha_MLE = np.sqrt(vcv_mle[4,4]) stderr_c_MLE = np.sqrt(vcv_mle[5,5]) stderr_gamma_MLE = np.sqrt(vcv_mle[6,6]) stderr_epsilon_MLE = np.sqrt(vcv_mle[7,7]) stderr_eta_MLE = np.sqrt(vcv_mle[8,8]) print('Standard error for beta estimate =', stderr_beta_MLE) print('Standard error for sigma_L estimate =', stderr_sigma_L_MLE) print('Standard error for alpha estimate =', stderr_alpha_MLE) print('Standard error for c estimate =', stderr_c_MLE) print('Standard error for gamma estimate =', stderr_gamma_MLE) print('Standard error for epsilon estimate =', stderr_epsilon_MLE) print('Standard error for eta estimate =', stderr_eta_MLE) ############## ##### EM ##### ############## def integrand_p_L(p_L, house_rooms, duration, params): beta_0, beta_1, beta_2, sigma_L, alpha, \ c, gamma, epsilon, eta = params beta = np.array([beta_0, beta_1, beta_2]) value_gap = p_L - house_rooms @ beta lambda_ = (alpha / np.exp(value_gap) - c) ** (1 / (1 + gamma) ) val_1 = expon.pdf(duration, scale=1 / lambda_) val_2 = norm.pdf(p_L, loc=house_rooms @ beta, scale=sigma_L) return val_1 * val_2 def integrate_EM(data, params): duration = data['duration'] house_rooms = np.array([data['size'], data['beds'], \ data['baths']]) val = sci_integrate.quad(integrand_p_L, - 30, 30,\ args=(house_rooms, duration, params))[0] return val def posterior_p_L(p_L, house_rooms, duration, p, params): beta_0, beta_1, beta_2, sigma_L, alpha, \ c, gamma, epsilon, eta = params beta = np.array([beta_0, beta_1, beta_2]) value_gap = p_L - house_rooms @ beta lambda_ = (alpha / np.exp(value_gap) - c) ** (1 / (1 + gamma) ) numerator_1 = p == p_L - eta * duration # Below is hypothetical solution to issue of above line being # measure zero: #numerator_1 = norm.pdf(p - (p_L - eta * duration \ # ** (1 / (1 + epsilon) ) ) ) / norm.pdf(0) numerator_2 = expon.pdf(duration, scale=1 / lambda_) numerator_3 = norm.pdf(p_L, loc=house_rooms @ beta, scale=sigma_L) denominator_1 = norm.pdf(p, loc=house_rooms @ beta - eta \ * duration ** (1 / (1 + epsilon) ), scale=sigma_L) denominator_2_data = pd.concat([house_rooms, duration], axis=1) denominator_2 = denominator_2_data.apply(integrate_EM, axis=1, params=params) numerator = numerator_1 * numerator_2 * numerator_3 denominator = denominator_1 * denominator_2 #print('Numerator', numerator) #print('Denominator', denominator) #stop return numerator / denominator def integrand_EM(p_L, house_rooms, duration, p, params, params_old): beta_0, beta_1, beta_2, sigma_L, alpha, \ c, gamma, epsilon, eta = params beta = np.array([beta_0, beta_1, beta_2]) value_gap = p_L - house_rooms @ beta lambda_ = (alpha / np.exp(value_gap) - c) ** (1 / (1 + gamma) ) #if abs(np.exp(value_gap)) == np.inf: # print('Issue is with value_gap') # return 0 #if abs(np.exp( - 1 / 2 * (value_gap / sigma_L) ** 2) ) == np.inf: # print('Issue is with value_gap squared') # return 0 #if abs(np.exp( - lambda_ * duration) ) == np.inf: # print('Issue is with lambda') # return 0 val_1 = posterior_p_L(p_L, house_rooms, duration, p, params_old) log_val_1 = p == p_L - eta * duration ## Set any values where p != p_L - eta * duration to have ## 1e-10 probability, so don't encounter log(0) errors #log_val_1[log_val_1 == 0] = 1e-10 # Below is hypothetical solution to issue of above line being # measure zero: #log_val_1 = norm.pdf(p - (p_L - eta * duration \ # ** (1 / (1 + epsilon) )) ) / norm.pdf(0) log_val_2 = expon.pdf(duration, scale=1 / lambda_) log_val_3 = norm.pdf(p_L, loc=house_rooms @ beta, scale=sigma_L) val_2 = np.log(log_val_1) \ + np.log(log_val_2) + np.log(log_val_3) val = np.sum(val_1 * val_2) if abs(val) == np.inf: print('Issue is with val') return 0 return val def calc_Q_EM(params, *args): house_rooms, duration, p, params_old = args val = sci_integrate.quad(integrand_EM, - 30, 30,\ args=(house_rooms, duration, p, params, params_old))[0] print('Params_old:', params_old) print('Params_new:', params) print('Q:', val) return - val def run_EM(): beta_0_0 = 2 beta_0_1 = 1.75 beta_0_2 = 3 sigma_L_0 = 1 alpha_0 = 1 c_0 = 0 gamma_0 = 1 epsilon_0 = 1 eta_0 = 10 params_old = np.array([beta_0_0, beta_0_1, beta_0_2, sigma_L_0, alpha_0, \ c_0, gamma_0, epsilon_0, eta_0]) params_new = np.zeros(params_old.shape) thresh = 1e-5 i = 0 while True: print('Loop', i) i += 1 args = (data[['size', 'beds', 'baths']], data['duration'], data['p'], params_old) results = opt.minimize(calc_Q_EM, params_old.copy(), \ args=args, method='L-BFGS-B') params_new = results.x diff_params = np.sum( (params_old - params_new) ** 2) params_old = params_new.copy() if diff_params < thresh: print('params_new:', params_new) break run_EM()
# 要するにもっとも長くしりとりが続く順番を求めよ words = [ 'Brazil', 'Croatia', 'Mexico', 'Cameroon', 'Spain', 'Netherlands', 'Chile', 'Australia', 'Colombia', 'Greece', 'Cort d\'Ivoire', 'Japan', 'Uruguay', 'Costa Rica', 'England', 'Italy', 'Switzerland', 'Equador', 'France', 'Honduras', 'Argentina', 'Bosnia and Harzegovina', 'Iran', 'Nigeria', 'Germany', 'Portugal', 'Ghana', 'USA', 'Belgium', 'Algeria', 'Russia', 'Korea Republic' ] longst_chain = [] def chain(word: str, current_chain: list, usables: list): global longst_chain current_chain.append(word) print(f'Start: {current_chain[0]}, List: {current_chain}') #print(f' Usables: {usables}') #input() if len(current_chain) > len(longst_chain): longst_chain = current_chain[:] for next_word in usables: if word[-1] != next_word[0]: #print(f'Skip {word}, {next_word}') continue pos = usables.index(next_word) arg_words = usables[:] arg_words.pop(pos) chain(next_word, current_chain[:], arg_words) if __name__ == "__main__": upper_words = [v.upper() for v in words] for word in upper_words: pos = upper_words.index(word) arg_words = upper_words[:] arg_words.pop(pos) chain(word, [], arg_words) print(f'Length: {len(longst_chain)}, List: {longst_chain}')
BOY = 'B' GIRL = 'G' n = 30 memo = {} def add(current: list) -> int: counts = len(current) # 30 人並んだら終了 if counts >= n: return 1 # 前回並んだ人 last = current[-1] if counts > 0 else 'N' # メモがあればそこから応答 if (last, counts) in memo: return memo[(last, counts)] # 男女を繋げる cnt = 0 for cur in [BOY, GIRL]: # 女性は連続して並べない if last == GIRL and cur == GIRL: continue # パターンをカウント cp = current[:] cp.append(cur) cnt += add(cp) # メモ化 memo[(last, counts)] = cnt # カウント応答 return cnt print(add([]))
# 10 以上の数字で、2,8,10 進数表記で回文になるものを捜す。 def is_palindrome(v): bin_str = bin(v)[2:] oct_str = oct(v)[2:] dig_str = str(v) return bin_str == bin_str[::-1] and \ oct_str == oct_str[::-1] and \ dig_str == dig_str[::-1] if __name__ == "__main__": tmp = 11 while not is_palindrome(tmp): tmp += 2 print(f'{tmp}, {bin(tmp)}, {oct(tmp)}')
from Tkinter import * root = Tk() wid = 800 hei = 800 w = Canvas(root, scrollregion=(0,0,wid,hei), bg="white", width=wid, height=hei) w.pack() def drawDragon(n): turns = [] for i in range(n): newturns = [] newturns.append(1) last = 1 for turn in turns: newturns.append(turn) last *= -1 newturns.append(last) turns = newturns location = [100,150] w.create_rectangle(2*location[0],2*location[1],2*location[0]+2,2*location[1]+2,fill='black',width=0) location[0] += 1 lastDirection = [1,0] for turn in turns: w.create_rectangle(2*location[0],2*location[1],2*location[0]+2,2*location[1]+2,fill='black',width=0) newDirection = [lastDirection[1]*turn,lastDirection[0]*-1*turn] location[0] = location[0] + newDirection[0] location[1] = location[1] + newDirection[1] lastDirection = newDirection w.create_rectangle(2*location[0],2*location[1],2*location[0]+2,2*location[1]+2,fill='black',width=0) drawDragon(16) root.mainloop()
import random import os class hangman: def __init__(self, words, file_path=None): self.target_word = "" self.lifes = 6 self.lifes_lost = 0 self.render_word = "" self.chars_entered = [] self.games_lost = 0 self.games_won = 0 self.wrong_answers = 0 self.right_answers = 0 self.current_game_won = False self.current_game_lost = False self.words = words if not file_path == None: self.load_data(file_path) self.alphabet = [chr(97+num) for num in range(26)] def choice_word(self): self.target_word = random.choice(self.words) return self.target_word def set_words(self, words): self.words = words def load_data(self, file_path): if not os.path.exists(file_path): print("No Words found.") return with open(file_path, "r") as word_file: self.words = [word.replace("\n", "") for word in word_file.readlines()] def find_index(self, char): return [i for i, ltr in enumerate(self.target_word) if ltr == char] def render_game(self): return " ".join(self.render_word) def stats(self): return (self.games_won, self.games_lost, self.right_answers, self.wrong_answers, ) def start_round(self): self.choice_word() self.chars_entered = [] self.lifes_lost = 0 self.current_game_won = False self.current_game_lost = False len_word = len(self.target_word) self.render_word = ["_" for i in range(len_word)] def playable(self, input_char): if not input_char in self.alphabet: return False if input_char in self.chars_entered: return False if self.current_game_won or self.current_game_lost: return False return True def remaining_lifes(self): return self.lifes - self.lifes_lost def action(self, input_char): input_char = chr(int(input_char)) if not self.playable(input_char): return None self.chars_entered.append(input_char) if not input_char in self.target_word: self.lifes_lost += 1 self.wrong_answers += 1 if self.remaining_lifes() <= 0: self.games_lost += 1 self.current_game_lost = True else: for index in self.find_index(input_char): self.render_word[index] = input_char self.right_answers += 1 if self.render_word.count("_") <= 0: self.games_won += 1 self.current_game_won = True return input_char if __name__ == "__main__": import words game = hangman(words.easy_words()) game.start_round() while True: game.action(ord(input()))
"Expt 5: Implement Bit plane slicing as explained. Include all 8 plane outputs." def bitplane(img, plane): "Returns the specified bitplane of the image" assert 0 <= plane <= 7 planeImg = img.point(lambda i: i & 2**plane or (255 if plane < 6 else 0)) return planeImg def allBitplanes(img): "Returns all the bitplanes of the image" bitplanes = [img.point(lambda i: i & 2**p or (255 if p < 6 else 0)) for p in range(8)] return bitplanes
import numpy as np, random, operator, matplotlib.pyplot as plt from math import sqrt class City: def __init__(self, id, x, y): self.pos = (x,y) self.ID = id def distance(self, city): xDis = abs(self.pos[0] - city.x) yDis = abs(self.pos[1] - city.y) distance = np.sqrt((xDis ** 2) + (yDis ** 2)) return distance def toString(self): return "City at " + str(self.pos)
"""The module read the file contents. Usage: fileread.py [filename ...] Description: In the absence of input file, reading comes from the standard input. Display the contents of the files produced on standard output. """ import signal import sys import const def sigint_handler(error, stack): """Handler keystrokes CTRL+C """ sys.stderr.write('\n') sys.exit(1) def copy_file_to_stdout(file_): """This function reads data from a file blocks and writes them to standard output. """ while True: block = file_.read(const.BUFFER_SIZE) if not block: break sys.stdout.write(block) def main(): """The main function """ signal.signal(signal.SIGINT, sigint_handler) const.setmode([sys.stdin, sys.stdout]) if len(sys.argv) == 1: copy_file_to_stdout(sys.stdin) sys.exit(0) if sys.argv[1] == '-h': print(__doc__) sys.exit(0) file_names = sys.argv[1:] for file_name in file_names: try: file_ = open(file_name, 'rb') copy_file_to_stdout(file_) file_.close() # sys.stdout.write(open(file_).read()) except IOError as error: sys.stderr.write('fileread.py: {}\n'.format(error)) if __name__ == '__main__': main()
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ s1, s2, i = 0, 0, 0 while l1: s1 += 10**i * l1.val l1 = l1.next i+=1 i = 0 while l2: s2 += 10**i * l2.val l2 = l2.next i+=1 l1pl2 = s1 + s2 res = tmp = ListNode(0) for i in range(len(str(l1pl2))): tmp.next = ListNode(l1pl2%10) l1pl2 = l1pl2//10 tmp = tmp.next return res.next
#환영 인사말 print("동전합산 서비스에 오심을 환영합니다.") print("가지고 계신 동전의 개수를 입력해주세요.") #보유 동전 개수를 키보드에서 입력 받음 coin500= int(input("500원짜리는?")) coin100= int(input("100원짜리는?")) coin50= int(input("50원짜리는?")) coin10= int(input("10원짜리는?")) #보유 동전의 총액을 계산 total= coin500 *500 +coin100 * 100 + \ coin50 *50 + coin10 *10 #보유 동전의 총액을 실행창에 출력 print("손님의 동전은 총",total,"원입니다.") #작별 인사말 print("저희 서비스를 이용해주셔서 감사합니다.") print("또 들려주세요.")
#ctto-----RockEt🚀 name=input("Enter your name\n") reg_num=input("Enter your reg_num\n") years_of_studies=input("What's your course duration?\n") print("Dear "+name+" you have "+years_of_studies+" years to complete your studies in our institude\n")
#!/usr/bin/env python # heap.py # max/min-heap data structure class Node: def __init__(self, payload): self.payload = payload self.parent = None self.left = None self.right = None class Heap: INIT_SIZE = 100 def __init__(self): self.array = [0 for i in xrange(INIT_SIZE)] self.size = 0 def insert(self, elem): if def findMin(self): if self.size >= 1: return self.array[0] else: return None
from random import randint def Solve(A, B): ''' Linear system solving for AX=B. Returns vector X ''' N=len(B) X=[0]*N def a(i, j, n): if n==N: return A[i][j] return a(i,j,n+1)*a(n,n,n+1)-a(i,n,n+1)*a(n,j,n+1) def b(i, n): if n==N: return B[i] return a(n,n,n+1)*b(i,n+1)-a(i,n,n+1)*b(n,n+1) def x(i): d=b(i,i+1) for j in xrange(i): d-=a(i,j,i+1)*X[j] return d/a(i,i,i+1) for k in xrange(N): X[k]=x(k) return X def Solve2(A, B): ''' Linear system solving for AX=B. Returns vector X ''' N=len(B) X=[0]*N def a(i, j, n, xi): if n==N: return A[(i + xi) % N][(j + xi) % N] return a(i,j,n+1,xi)*a(n,n,n+1,xi)-a(i,n,n+1,xi)*a(n,j,n+1,xi) def b(i, n, xi): if n==N: return B[(i + xi) % N] return a(n,n,n+1,xi)*b(i,n+1,xi)-a(i,n,n+1,xi)*b(n,n+1,xi) def x(i): return b(0, 1, i) / a(0, 0, 1, i) for k in xrange(N): X[k]=x(k) return X def Validate(A, B, X): ret = [] for i in range(3): Bi = 0.0 for j in range(3): Bi += A[i][j] * X[j] ret = ret + [Bi - B[i]] return ret def dot(A, B): return sum([ai*bi for (ai, bi) in zip(A, B)]) def scale(A, x): return [ai*x for ai in A] def add(A, B): return [ai+bi for (ai, bi) in zip(A, B)] def project(A, Pn, Pd): return add(A, scale(Pn, (Pd - dot(Pn, A)) / dot(Pn, Pn))) def Solve3(A, B, d=0.00001, i_max=100000): n = len(B) X = [0.0] * n for i in range(i_max): for j in range(n): X = project(X, A[j], B[j]) error = sum([abs(ei) for ei in Validate(A, B, X)]) if error < d: return X return X def ident(n): return [[1.0 if i==j else 0.0 for j in range(n)] for i in range(n)] def inverse(A): return [Solve(A, ort) for ort in ident(len(A))] def transpose(A): return [list(aj) for aj in zip(*A)] def mul(A, X): return [dot(aj, X) for aj in transpose(A)] def error(A, B, X): return sum(add(mul(A, X), scale(B, -1.0))) def solve(A, B, X): return X if error(A, B, X) < 0.00001 else solve(A[1:] + A[0], B[1:] + B[0], project(X, A[0], B[0])) for n in range(0, 1): A = [[], [], []] B = [] for i in range(0, 3): A += [] for j in range(0, 3): A[i] += [randint(-100, 100) / 100.0] B += [randint(-100, 100) / 100.0] try: X3 = Solve3(A, B) Ai = inverse(A) I = inverse(Ai) print A, '\n', Ai, '\n', I, '\n\n' print transpose(A) print B, X3, mul(Ai, B) except ZeroDivisionError: print 'No'
from collections import deque # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: queue = deque() if root is not None: queue.append(root) res = [] while len(queue) != 0: siz = len(queue) i = 0 s = 0 while i < siz: t = queue.popleft() i += 1 if t is not None: s += t.val if t.left is not None: queue.append(t.left) if t.right is not None: queue.append(t.right) res.append(s / siz) return res
import pygame import os WIDTH, HEIGHT = 900, 500 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("First Game!") WHITE = (255, 255, 255) FPS = 60 # Standard vel = 5 #Velocity to be used when left key is pressed, to move spaceship left SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40 YELLOW_SPACESHIP_IMAGE = pygame.image.load(os.path.join('Assets', 'spaceship_yellow.png')) # Resize the Yellow Spaceship YELLOW_SPACESHIP = pygame.transform.rotate( pygame.transform.scale(YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90) RED_SPACESHIP_IMAGE = pygame.image.load(os.path.join('Assets', 'spaceship_red.png')) # Resize the Yellow Spaceship RED_SPACESHIP = pygame.transform.rotate( pygame.transform.scale(RED_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 270) def draw_window(red, yellow): WIN.fill(WHITE) WIN.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y)) WIN.blit(RED_SPACESHIP, (red.x, red.y)) pygame.display.update() def main(): red = pygame.Rect(700, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT) clock = pygame.time.Clock() run = True while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False #the method is to use multiple keys at same time #there are other methods to use one key at a time keys_pressed = pygame.key.get_pressed() if keys_pressed[pygame.K_a]: #Left yellow.x -= vel if keys_pressed[pygame.K_d]: #Right, need one position to the rightside yellow.x += vel if keys_pressed[pygame.K_w]:#isntead of x being modified, its y being modififed, y is the height yellow.y -= vel if keys_pressed[pygame.K_s]: yellow.y += vel draw_window(red, yellow) pygame.quit() if __name__ == "__main__": main()
def main(): print("Money invested") money = int(input()) print("Annual rate (0-1)") ar = float(input()) print("Enter years into the future") years = int(input()) newmoney = 0 for i in range(years): newmoney = money*(1+ar) money = newmoney print("Your new money is:",float(newmoney)) main()
class AccountError(Exception):{} class BalanceError(Exception):{} class BankAccount: def __init__(self, acct_num): self.__acct_num = acct_num self.__int_bal = 0 @property def acct_num(self): return self.__acct_num @acct_num.setter def acct_num(self, new_acct_num): raise AccountError("Account number cannot be changed") @acct_num.deleter def acct_num(self): del self.int_bal self.__acct_num = None @property def int_bal(self): return self.__int_bal @int_bal.setter def int_bal(self,amount): if amount == 0: raise BalanceError("Cannot withdraw or deposite Zero amount") self.__int_bal = amount @int_bal.deleter def int_bal(self): if self.__int_bal < 0: raise BalanceError(f"Pending balances $ {self.__int_bal} /-") elif self.__int_bal > 0: print(f"Transfering $ {self.__int_bal} /-") self.__int_bal = 0 sourav = BankAccount(435679435) print(f"Your account number is {sourav.acct_num}") print(f"Your balance is $ {sourav.int_bal} /-") try: del sourav.acct_num except AccountError as e: print(f"Error: {e}") except BalanceError as e: print(f"Error: {e}") try: sourav.int_bal = 0 print(f"Your balance is $ {sourav.int_bal} /-") except AccountError as e: print(f"Error: {e}") except BalanceError as e: print(f"Error: {e}") try: sourav.int_bal = 100 print(f"Your balance is $ {sourav.int_bal} /-") except AccountError as e: print(f"Error: {e}") except BalanceError as e: print(f"Error: {e}") try: del sourav.acct_num print(f"Your balance is $ {sourav.int_bal} /-") except AccountError as e: print(f"Error: {e}") except BalanceError as e: print(f"Error: {e}") try: del sourav.int_bal print(f"Your balance is $ {sourav.int_bal} /-") except AccountError as e: print(f"Error: {e}") except BalanceError as e: print(f"Error: {e}") try: del sourav.acct_num print(f"Your balance is $ {sourav.int_bal} /-") except AccountError as e: print(f"Error: {e}") except BalanceError as e: print(f"Error: {e}")
#Bubble sort of numeric data without using 3rd variable #Try it online https://code.sololearn.com/c6uI3ZlD5Nj4 instr=list("57335527388546344") print("Input Str",instr) c=0 while c<len(instr)-1: n=0 while n<len(instr)-1: #print(instr[n],instr[n+1]) if int(instr[n])>int(instr[n+1]): instr[n]=int(instr[n])+int(instr[n+1]) instr[n+1]=int(instr[n])-int(instr[n+1]) instr[n]=int(instr[n])-int(instr[n+1]) #print("swapped") #print(instr) n+=1 c+=1 print("Output Str",instr) #Bubble sort with using 3rd variable# instr=list("57335gdueysf66473a") print("Input Str",instr) c=0 while c<len(instr)-1: n=0 while n<len(instr)-1: #print(instr[n],instr[n+1]) if instr[n]>instr[n+1]: i=instr[n] instr[n]=instr[n+1] instr[n+1]=i #print("swapped") #print(instr) n+=1 c+=1 print("Output Str",str(instr))
#PRINTS A TREE/LIST OF SUBCLASSES OF A GIVEN CLASS def printSubclassTree(thisclass,nest=0): if nest > 1: print(" |" * (nest - 1), end="") if nest > 0: print(" +--", end="") print(thisclass.__name__) for subclass in thisclass.__subclasses__(): printSubclassTree(subclass,nest + 1) printSubclassTree(BaseException)
# coding: utf-8 class MaxPriority: def __init__(self): self.nums = [] def out(self): print self.nums def Max(self): if len(self.nums) == 0: return 'empty queue' return self.nums[0] def __HeapArrange(self, i, size): li = 2 * i + 1 ri = 2 * i + 2 mi = i mn = self.nums[mi] if li < size and self.nums[li] > mn: mn = self.nums[li] mi = li if ri < size and self.nums[ri] > mn: mn = self.nums[ri] mi = ri if mi == i: return self.nums[mi] = self.nums[i] self.nums[i] = mn self.__HeapArrange(mi, size) def Pop(self): mi = self.nums[0] self.nums[0] = self.nums[-1] self.nums.pop(-1) self.__HeapArrange(0, len(self.nums)) return mi def Insert(self, num): self.nums.insert(0, num) self.__HeapArrange(0, len(self.nums)) def Increase(self, key, num): self.nums[key] += num if key < 0: key = len(self.nums) + key pi = (key + 1) / 2 - 1 while pi >= 0: self.__HeapArrange(pi, len(self.nums)) pi -= 1 if __name__ == '__main__': cc = MaxPriority() for i in range(0, 5): cc.Insert(i) cc.Pop() cc.out() cc.Increase(-1, 10) cc.out()
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: before = ListNode(-1) before.next = head fast_node = before for i in range(1, n + 2): fast_node = fast_node.next slow_node = before while fast_node != None: slow_node = slow_node.next fast_node = fast_node.next slow_node.next = slow_node.next.next return before.next
#!/usr/bin/env python # -*- coding: utf-8 -*- import scipy.ndimage as im import scipy.misc as sm import numpy as np import PIL from MyKMeans import MyKMeans class ColorQuantizer: """Quantizer for color reduction in images. Use MyKMeans class that you implemented. Parameters ---------- n_colors : int, optional, default: 64 The number of colors that wanted to exist at the end. random_state : int, RandomState instance or None, optional, default: None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Read more from: http://scikit-learn.org/stable/auto_examples/cluster/plot_color_quantization.html """ def __init__(self, n_colors=64, random_state=None): self.image = None self.centers = None np.set_printoptions(threshold=np.nan) self.d1 = 0 self.d2 = 0 self.d3 = 0 def read_image(self, path): """Reads jpeg image from given path as numpy array. Stores it inside the class in the image variable. Parameters ---------- path : string, path of the jpeg file """ self.image = im.imread(path) self.d1 = self.image.shape[0] self.d2 = self.image.shape[1] self.d3 = self.image.shape[2] self.image = self.image.reshape((self.image.shape[0]*self.image.shape[1]),self.image.shape[2]) def recreate_image(self, path_to_save): """Recreates image from the trained MyKMeans model and saves it to the given path. Parameters ---------- path_to_save : string, path of the png image to save """ self.image = self.image.reshape(self.d1,self.d2,self.d3) sm.imsave(path_to_save, self.image) pass def export_cluster_centers(self, path): """Exports cluster centers of the MyKMeans to given path. Parameters ---------- path : string, path of the txt file """ np.savetxt(path,self.kmeans.cluster_centers) def quantize_image(self, path, weigths_path, path_to_save): """Quantizes the given image to the number of colors given in the constructor. Parameters ---------- path : string, path of the jpeg file weigths_path : string, path of txt file to export weights path_to_save : string, path of the output image file """ """man_centers = np.zeros((64,3)) for i in range(64): man_centers[i] = (255/64.0)*np.random.randint(64) print man_centers""" self.kmeans = MyKMeans(random_state=None,n_clusters=64,max_iter=600,init_method="random") self.read_image(path) self.centers = self.kmeans.initialize(self.image) #image_array_sample = shuffle(image_array, random_state=0)[:1000] temp_image = np.array(self.image) np.random.shuffle(temp_image) self.kmeans.fit(temp_image[:7500]) labels = self.kmeans.predict(self.image) result = [] cents = self.kmeans.cluster_centers for i in range(self.d1*self.d2): result.append(cents[labels[i]]) self.image = np.array(result) self.recreate_image(path_to_save) self.export_cluster_centers(weigths_path) if __name__ == "__main__": if __name__ == "__main__": t = ColorQuantizer() t.quantize_image("../Docs/ankara.jpg","./ankara_cluster_centers.txt","./deneme-ankaradenemerand64.jpg")
import pygame import time import random #Szymon Czaplak def bullet_create(n,x,y): if n == 1: bullet_position_y.append(y) bullet_position_x.append(x) if n >= 2: bullet_position_y.append(y) bullet_position_x.append(x) bullet_position_y.append(y) bullet_position_x.append(x+9) if n >= 3: for i in range(0,10, 3): bullet_position_y.append(y) bullet_position_x.append(x+i) def bullet_update(): for i in range(1,len(bullet_position_y)): bullet_position_y[i]-=5 for i in range(len(bullet_position_y)): if(bullet_position_y[i]<0): bullet_position_y[i]=-12 bullet_position_x[i]=-12 for k in range(bullet_position_x.count(-12)): if(len(bullet_position_y)>1): bullet_position_y.remove(-12) bullet_position_x.remove(-12) def bullet_print(): for i in range(len(bullet_position_y)): pygame.draw.lines(screen,(0,128,125), True,[ (bullet_position_x[i],bullet_position_y[i]), (bullet_position_x[i],bullet_position_y[i]-5) ], 2) def enemy_show_up(life,lines, hight): for i in range(50,250,30): #pygame.draw.rect(screen, (85,23,51) , pygame.Rect(i,50 , 10, 10)) screen.blit(ENEMY,(i,hight)) enemy_x.append(i) enemy_y.append(hight) enemy_position.append(hight) pygame.display.flip() enemy_life.append(life) if(lines == 2): for i in range(50,250,30): screen.blit(ENEMY,(i,hight+50)) enemy_x.append(i) enemy_y.append(hight+50) enemy_position.append(hight+50) pygame.display.flip() enemy_life.append(life) def enemy_draw(): for i in range(len(enemy_y)): if(enemy_life[i] > 1): screen.blit(ENEMY,(enemy_x[i],enemy_y[i])) if(enemy_life[i] == 1): screen.blit(ENEMY_LOW,(enemy_x[i],enemy_y[i])) def enemy_move(counter, hight, if_down): movement=0.7 if(counter<20): movement for i in range(len(enemy_x)): if(enemy_position[i]==hight): enemy_x[i]+=0.7 else: enemy_x[i]-=0.7 else: for i in range(len(enemy_x)): if(enemy_position[i] == hight): enemy_x[i]-=0.7 else: enemy_x[i]+=0.7 if(if_down != 0): for i in range(len(enemy_y)): enemy_y[i]+=0.1 def enemy_bullet_create(hight): chosen_one=random.randrange(len(enemy_y)) if(enemy_bullet_position_y[-1]>enemy_y[chosen_one]+bullet_intensity): if(len(enemy_y)<3): enemy_bullet_position_y.append(enemy_y[chosen_one]+10) enemy_bullet_position_x.append(enemy_x[chosen_one]) #enemy_bullet_owner.append(enemy_y[random.randrange(len(enemy_y))]) if(random.randint(1,100)<70): enemy_bullet_life.append(1) else: enemy_bullet_life.append(0) else: enemy_bullet_position_y.append(enemy_y[chosen_one]+10) enemy_bullet_position_x.append(enemy_x[chosen_one]) enemy_bullet_life.append(1) def enemy_bullet_print(): for i in range(len(enemy_bullet_position_y)): if(enemy_bullet_life[i] >0): pygame.draw.lines(screen,(125,0,100), True,[ (enemy_bullet_position_x[i],enemy_bullet_position_y[i]), (enemy_bullet_position_x[i],enemy_bullet_position_y[i]+5) ], 2) def enemy_bullet_update(): for i in range(1,len(enemy_bullet_position_y)): enemy_bullet_position_y[i]+=2 licznik=0 for i in range(len(enemy_bullet_position_y)): if(enemy_bullet_position_y[i]>304): enemy_bullet_position_y[i]=308 enemy_bullet_position_x[i]=308 enemy_bullet_life[i]=-500 licznik+=1 for k in range(licznik): if(len(enemy_bullet_position_y)>1): enemy_bullet_position_y.remove(308) enemy_bullet_position_x.remove(308) enemy_bullet_life.remove(-500) def detect_collision(): for i in range(len(bullet_position_y)): for k in range(len(enemy_y)): if(bullet_position_y[i]>=enemy_y[k] and bullet_position_x[i]<=enemy_x[k]+10 and bullet_position_y[i]<=enemy_y[k]+10and bullet_position_x[i] >= enemy_x[k]): enemy_life[k]-=1 if(enemy_life[k]==0): enemy_y[k]=-500 enemy_x[k]=-500 enemy_life[k]=-500 enemy_position[k]=-500 SCORE[0]+=1 bullet_position_y[i]=-500 bullet_position_x[i]=-500 for i in range(len(enemy_y)): if(enemy_y[i]>300): return 1 if(len(boss_life)>0): if(x<=enemy_x[0]+145 and x+10>= enemy_x[0] and y<=enemy_y[0] + 49 and y+10>= enemy_y[0]): return 1 else: for i in range(len(enemy_x)): if(x<=enemy_x[i]+10 and x+10>= enemy_x[i] and y<=enemy_y[i] + 10 and y+10>= enemy_y[i]): return 1 if(len(boss_life) != 0): for i in range(len(bullet_position_y)): if(bullet_position_y[i]>=enemy_y[0] and bullet_position_x[i]<=enemy_x[0]+145 and bullet_position_y[i]<=enemy_y[0]+49and bullet_position_x[i] >= enemy_x[0]): boss_life[k]-=1 if(boss_life[k]==0): enemy_y[k]=-500 enemy_x[k]=-500 boss_life[k]=-500 SCORE[0]+=1 bullet_position_y[i]=-500 bullet_position_x[i]=-500 if(len(meteoryt_x)>0): for i in range(len(meteoryt_x)): for k in range(len(bullet_position_y)): if(meteoryt_type[i] == 1): if bullet_position_y[k]>=meteoryt_y[i] and bullet_position_x[k]<=meteoryt_x[i]+10 and bullet_position_y[k]<=meteoryt_y[i]+10 and bullet_position_x[k] >= meteoryt_x[i] : bullet_position_y[k] = -500 bullet_position_x[k] = -500 elif(meteoryt_type[i] == 2): if bullet_position_y[k]>=meteoryt_y[i] and bullet_position_x[k]<=meteoryt_x[i]+20 and bullet_position_y[k]<=meteoryt_y[i]+20 and bullet_position_x[k] >= meteoryt_x[i] : bullet_position_y[k] = -500 bullet_position_x[k] = -500 for i in range(len(meteoryt_x)): for k in range(1, len(enemy_bullet_position_y)): if(meteoryt_type[i] == 1): if enemy_bullet_position_y[k]>=meteoryt_y[i] and enemy_bullet_position_x[k]<=meteoryt_x[i]+10 and enemy_bullet_position_y[k]<=meteoryt_y[i]+10 and enemy_bullet_position_x[k] >= meteoryt_x[i] : enemy_bullet_position_y[k] = -500 enemy_bullet_position_x[k] = -500 enemy_bullet_life[k] = -500 elif(meteoryt_type[i] == 2): if enemy_bullet_position_y[k]>=meteoryt_y[i] and enemy_bullet_position_x[k]<=meteoryt_x[i]+20 and enemy_bullet_position_y[k]<=meteoryt_y[i]+20 and enemy_bullet_position_x[k] >= meteoryt_x[i] : enemy_bullet_position_y[k] = -500 enemy_bullet_position_x[k] = -500 enemy_bullet_life[k] = -500 for i in range(enemy_bullet_position_x.count(-500)) : enemy_bullet_position_x.remove(-500) enemy_bullet_position_y.remove(-500) enemy_bullet_life.remove(-500) if(len(bonus_x)>0): for i in range(len(bullet_position_x)): for k in range(len(bonus_x)): if(bullet_position_x[i] >= bonus_x[k] and bullet_position_x[i] <= bonus_x[k] + 10 and bullet_position_y[i] <= bonus_y[k]+10 and bullet_position_y[i] >= bonus_y[k]): bonus_x[k] = 500 bullet_type[0] += 1 SCORE[0]+=100 if(len(boss_life) ==0): if(enemy_y.count(-500)>0): enemy_y.remove(-500) enemy_x.remove(-500) enemy_position.remove(-500) enemy_life.remove(-500) else: if(enemy_y.count(-500)>0): enemy_y.remove(-500) enemy_x.remove(-500) boss_life.remove(-500) return 1 for i in range(1, len(enemy_bullet_position_y)): for k in range(len(enemy_y)): if(enemy_bullet_position_y[i]>=y and enemy_bullet_position_x[i]<=x+10 and enemy_bullet_position_y[i]<=y+10 and enemy_bullet_position_x[i] >= x): if(enemy_bullet_life[i]>0): bullet_type[0]=1 player_life[0]-=1 enemy_bullet_position_x[i]=-500 enemy_bullet_position_y[i]=-500 enemy_bullet_life[i]=-500 if(player_life[0] == 0): return 1 for i in range(enemy_bullet_position_x.count(-500)): enemy_bullet_position_x.remove(-500) enemy_bullet_position_y.remove(-500) enemy_bullet_life.remove(-500) if(len(meteoryt_x) !=0): for i in range(len(meteoryt_x)): if(meteoryt_type[i] ==1): if(x<=meteoryt_x[i]+10 and x+10>= meteoryt_x[i] and y<=meteoryt_y[i] + 10 and y+10>= meteoryt_y[i]): return 1 elif(meteoryt_type[i]==2): if(x<=meteoryt_x[i] + 20 and x+10>= meteoryt_x[i] and y<=meteoryt_y[i] + 20 and y+10>= meteoryt_y[i]): return 1 def meteoryt_make(x): k=random.randrange(150, 300) meteoryt_x.append(x) meteoryt_y.append(k) meteoryt_type.append(random.randrange(1,3)) def meteoryt_create(intensity): for i in range(350,10000, intensity): meteoryt_make(i) def meteoryt_draw(): for i in range(len(meteoryt_y)): if(meteoryt_type[i]==1): screen.blit(METEORYT1,(meteoryt_x[i],meteoryt_y[i])) else: screen.blit(METEORYT2,(meteoryt_x[i],meteoryt_y[i])) meteoryt_x[i]-=0.9 def boss_show_up(): screen.blit(BOSS,(50,50)) boss_life.append(180) enemy_x.append(50) enemy_y.append(50) enemy_position.append(50) pygame.display.flip() enemy_life.append(4) def boss_draw(): if(len(enemy_x) > 0): screen.blit(BOSS,(enemy_x[0],enemy_y[0])) def boss_bullet_create(zmienna): if(enemy_bullet_position_y[-1]>140): for i in range(zmienna, 159, 26): enemy_bullet_position_y.append(50+49) enemy_bullet_position_x.append(50+i) enemy_bullet_life.append(1) def bonus_create(high, timex): l=time.time() - timex if(l > random.randrange(2,11)): if(len(bonus_y)==0): bonus_y.append(high) bonus_x.append(-10) def bonus_print(): if(len(bonus_y)>0): screen.blit(BONUS, (bonus_x[0],bonus_y[0])) def bonus_move(): if(len(bonus_x) > 0): bonus_x[0]+=1.5 def instrukcja(): pygame.init() screen=pygame.display.set_mode((300, 300)) screen.fill((0,0,0)) screen.blit(INSTRUKCJA, (0 , 0)) pygame.display.flip() while True: pressed = pygame.key.get_pressed() for event in pygame.event.get(): if(pressed[pygame.K_SPACE]): return def Menu(): pygame.init() screen=pygame.display.set_mode((300, 300)) menu_position=1 screen.fill((0,0,0)) instructions=small_font.render("Sterowanie po menu strzalkami, a wybor spacja", 1, (14,24,51)) txt=myfont.render("Space Invanders", 1, (0,225,225)) play=myfont.render("Play", 1, (0,225,225)) instr=myfont.render("Instrukcja", 1, (0,225,225)) ext=myfont.render("Exit", 1, (0,225,225)) screen.blit(txt, (50,50)) pygame.display.flip() while True: screen.fill((0,0,0)) screen.blit(txt, (50,50)) screen.blit(instructions,(10,270)) nacisk=pygame.key.get_pressed() if(menu_position == 1): play2=myfont.render("Play", 1, (178,34,34)) screen.blit(play2, (50,100)) screen.blit(ext, (50,200)) screen.blit(instr, (50,150)) if(menu_position == 2): instr2=myfont.render("Instrukcja", 1, (178,34,34)) screen.blit(instr2, (50,150)) screen.blit(ext, (50,200)) screen.blit(play, (50,100)) if(menu_position == 3): ext2=myfont.render("Exit", 1, (178,34,34)) screen.blit(ext2, (50,200)) screen.blit(play, (50,100)) screen.blit(instr, (50,150)) for event in pygame.event.get(): if nacisk[pygame.K_UP]: if( menu_position != 1): menu_position-=1 if(nacisk[pygame.K_DOWN]): if( menu_position != 3): menu_position+=1 if nacisk[pygame.K_SPACE]: return menu_position pygame.display.flip() clock.tick(60) pygame.init() random.seed() clock=pygame.time.Clock() screen = pygame.display.set_mode((300, 300)) INSTRUKCJA=pygame.image.load('Instrukcje.png') ENEMY=pygame.image.load('enemy1.png') ENEMY_LOW=pygame.image.load('enemy_low.png') BOSS=pygame.image.load('boss.png') SHIP=pygame.image.load('ship.png') SHIP2=pygame.image.load('ship_2.png') TEXT=pygame.image.load('txt.png') METEORYT1=pygame.image.load('meteoryt1.png') METEORYT2=pygame.image.load('big_met.png') BONUS = pygame.image.load('bonus.png') pygame.font.init() myfont=pygame.font.SysFont('monospace', 25) small_font=pygame.font.SysFont('monospace', 15) while(1): player_life=[2] done = False x=150 y=200 bullet_position_y=[0] bullet_position_x=[-5] enemy_bullet_position_y=[302] enemy_bullet_position_x=[-5] enemy_bullet_life=[0] bullet_intensity=120 counter=[0] counter2=[0] enemy_y=[] enemy_x=[] enemy_life=[] enemy_position=[] enemy_down_move=1 level=0 bullet_speed=30 hight=50 SCORE=[0] boss_life=[] meteoryt_x=[] meteoryt_y=[] meteoryt_type=[] bullet_type = [1] bonus_y=[] bonus_x=[] while(1): menu_ret = Menu() if(menu_ret == 1): break elif(menu_ret == 2): instrukcja() elif(menu_ret == 3): exit() screen.fill((0,0,0)) game_start_time=time.time() while not done: if(len(enemy_x) == 0): enemy_down_move=1 lines=2 hight= 50 bonus_x=[] bonus_y=[] start_time=time.time() meteoryt_x=[] meteoryt_y=[] meteoryt_type=[] font1=pygame.font.SysFont('monospace',1) level+=1 display=myfont.render("level"+str(level), 1, (12,225,225)) screen.blit(display, (125,125)) pygame.display.flip() time.sleep(1) if(level<=3): enemy_show_up(1,1, hight) lines=1 pygame.display.flip() elif(level>3 and level<5): bullet_intensity=100 enemy_show_up(level-2,2,hight) pygame.display.flip() elif(level>=5 and level<7): screen.fill((0,0,0)) txt=myfont.render("Survive!", 1, (12,225,225)) enemy_down_move=0 screen.blit(txt, (110, 125)) pygame.display.flip() time.sleep(1) bullet_intensity=70 meteoryt_create(80) enemy_show_up(level-2,2,hight) elif(level>=7 and level<9): bullet_intensity=100 enemy_show_up(level-2,2,hight) pygame.display.flip() elif(level>=9 and level<11): screen.fill((0,0,0)) txt=myfont.render("Survive !", 1, (12,225,225)) enemy_down_move=0 screen.blit(display, (110,125)) pygame.display.flip() time.sleep(1) bullet_intensity=70 meteoryt_create(80) enemy_show_up(level-2,2,hight) elif(level>=11 and level <13): enemy_down_move=0 bullet_intensity=67 meteoryt_create(65) enemy_show_up(level-2,2,hight) pygame.display.flip() elif(level >=13): enemy_down_move=0 meteoryt_create(80) boss_show_up() pressed=pygame.key.get_pressed() if (pressed[pygame.K_SPACE]): if(bullet_position_y[-1]<y-bullet_speed): bullet_create(bullet_type[0], x, y) bullet_update() bullet_print() for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if(level!=13): enemy_bullet_create(hight) else: if(counter2[0] == 0): boss_bullet_create(15) counter2[0]=1 elif(counter2[0] == 1): boss_bullet_create(0) counter2[0]=0 enemy_bullet_update() enemy_move(counter[0], hight, enemy_down_move) counter[0]+=1 if(counter[0]==40): counter[0]=0 done=detect_collision() screen.fill((0, 0, 0)) if pressed[pygame.K_UP]: if not (y<0): y-=3 if pressed[pygame.K_DOWN]: if not (y>290): y+=3 if pressed[pygame.K_LEFT]: if not (x==0): x-=3 if pressed[pygame.K_RIGHT]: if not (x>290): x+=3 color = (255, 100, 0) if(player_life[0] == 2): screen.blit(SHIP,(x,y)) elif(player_life[0] == 1): screen.blit(SHIP2,(x,y)) meteoryt_draw() bonus_move() bonus_print() score_txt=small_font.render("Score: "+str(SCORE[0]), 20, (12,225,225)) screen.blit(score_txt, (0,0)) time_txt=small_font.render("time: "+str(time.time() - game_start_time), 20, (12,225,225)) screen.blit(time_txt, (198,0)) if(level>=7): bonus_create(random.randrange(1,40),start_time) if(level != 13): enemy_draw() pygame.display.flip() enemy_bullet_print() bullet_print() pygame.display.flip() else: boss_draw() bullet_print() enemy_bullet_print() pygame.display.flip() clock.tick(60) if(level != 13 or ( level == 13 and len(boss_life) >0)): screen.fill((0,0,0)) pygame.font.init() myfont=pygame.font.SysFont('monospace', 30) textsurface = myfont.render('GAME OVER', 1, (12,0,225)) screen.blit(textsurface, (90,125)) screen.blit(time_txt, (198,0)) screen.blit(score_txt, (0,0)) pygame.display.flip() time.sleep(4) elif(level == 13 and len(boss_life) == 0): screen.fill((0,0,0)) pygame.font.init() myfont=pygame.font.SysFont('monospace', 30) textsurface = myfont.render('Congratulations!', 1, (12,0,225)) screen.blit(textsurface, (70,125)) screen.blit(score_txt, (0,0)) screen.blit(time_txt, (198,0)) pygame.display.flip() time.sleep(4)
# input() def get_input(): matrix = list() # main loop for input() while True: # getting string from input i = input() # end if empty string if not i: break # save input string and its len() matrix.append(list(map(int, i.split()))) # return matrix return matrix # main function def main(matrix): # create a dummy empty matrix # with same rows/cols size sum_matrix = [[0 for k in range(len(matrix[0]))] for n in range(len(matrix))] # iterating all over rows for i in range(len(matrix)): # iterating over columns for j in range(len(matrix[0])): # here the magic happens! # compute the sum of each sub_matrix sum_matrix[i][j] = sum([sum(x[:j + 1]) for x in matrix[:i + 1]]) return sum_matrix # call main if __name__ == '__main__': # obtain input matrix = get_input() # get the output matrix and pretty print it nicely! print('\n'.join([' '.join(['{}'.format(e) for e in row]) for row in main(matrix)]))
#!/usr/bin/env python __author__ = "Rio" def compress_str(string): ''' Compress string where duplicated characters become number. >> compress_str('a') >> a >> compress_str('abc') >> a1b1c1 >> compress_str('aabb') >> a2b2 ''' if not string: return None if len(string) == 1: return string last = '' count = 1 result = [] for chr in string: if last == chr: count += 1 else: if last: result.append(last+str(count)) last = chr count = 1 result.append(last+str(count)) return ''.join(result)
#!/usr/bin/env python __author__ = 'Rio' from LinkedList import * def remove_dups_dict(lst): ''' Remove duplicates from a linked list. Use dictionary to check duplicates. Time Complexity: O(n), where n means the number of linked list. Space Complexity: O(n), additional storage is requested. >> lst = duplicates_list(10) >> >> lst = remove_dups(lst) >> ''' if not lst: return None current = lst content = {current.value: True} while current.next != None: if current.next.value not in content: content[current.next.value] = True current = current.next else: current.next = current.next.next def remove_dups(lst): ''' Remove duplicates from a linked list. Time Complexity: O(n^2), where n means the number of linked list. Space Compexity: O(1), no additional sapce is needed. ''' if not lst: return None current = lst while current: runner = current while runner.next != None: if runner.next.value == current.value: runner.next = runner.next.next else: runner = runner.next current = current.next if __name__ == "__main__": l = Node(0, Node(1, Node(2, Node(3, Node(4, Node(5, Node(5, Node(6)))))))) current = l while current: print current.value, current = current.next remove_dups_dict(l) current = l while current: print current.value current = current.next remove_dups(l) current = l while current: print current.value current = current.next
############################################################################################################## # # Python implementation of the Delaunay triangulation algorithm # as described in http://paulbourke.net/papers/triangulate/ # # developed by PanosRCng, https://github.com/PanosRCng # # # --> module usage # after imported, call the getTriangulation(vertex_list) # # the vertex_list is a list with instances of the Vertex class (as defined in this file) # returns the vertex_list, and a list with instances of the Triangle class (as defined in this file) # # (!) duplicate points will result in undefined behavior # def getTriangulation(vertex_list): global V V = vertex_list # initialize the triangle list triangle_list = [] # determine the supertriangle superTriangle = getSuperTriangle() # add the supertriangle to the triangle list triangle_list.append(superTriangle) # for each sample point in the vertex list for point in V[:-3]: # initialize the edge buffer edge_buffer = {} # for each triangle currently in the triangle list for triangle in triangle_list[:]: # if the point lies in the triangle circumcircle if triangle.isInCircumcircle(point): # add the three triangle edges to the edge buffer # delete all doubly specified edges from the edge buffer # this leaves the edges of the enclosing polygon only for edge in triangle.edges: if edge.id in edge_buffer.keys(): edge_buffer.pop(edge.id) else: edge_buffer[edge.id] = edge # remove the triangle from the triangle list triangle_list.remove(triangle) # add to the triangle list all triangles formed between the point # and the edges of the enclosing polygon for edge_id in edge_buffer.keys(): triangle_list.append(Triangle(point, edge_buffer[edge_id].A, edge_buffer[edge_id].B)) print len(triangle_list) # remove any triangles from the triangle list that use the supertriangle vertices sv = [superTriangle.A, superTriangle.B, superTriangle.C] for triangle in triangle_list[:]: if (triangle.A in sv) or (triangle.B in sv) or (triangle.C in sv): triangle_list.remove(triangle) # remove the supertriangle vertices from the vertex list del V[-3:] return [V, triangle_list] def getSuperTriangle(): # find the maximum and minimum vertex bounds. # this is to allow calculation of the bounding triangle xmin = V[0].x ymin = V[0].y xmax = xmin ymax = ymin for point in V[1:]: if point.x < xmin: xmin = point.x if point.x > xmax: xmax = point.x if point.y < ymin: ymin = point.y if point.y > ymax: ymax = point.y dx = xmax - xmin; dy = ymax - ymin; dmax = dx if (dx > dy) else dy xmid = (xmax + xmin) / 2.0 ymid = (ymax + ymin) / 2.0 # add supertriangle vertices to the end of the vertex list V1 = Vertex((xmid - 2.0 * dmax, ymid - dmax)) V2 = Vertex((xmid, ymid + 2.0 * dmax)) V3 = Vertex((xmid + 2.0 * dmax, ymid - dmax)) V.append(V1) V.append(V2) V.append(V3) return Triangle(V1, V2, V3) ####################################################################################################################################### class Vertex: def __init__(self, x, y): self.x = x self.y = y ####################################################################################################################################### class Edge: def __init__(self, A, B): if A.x <= B.x: self.A = A self.B = B self.id = (A, B) else: self.A = B self.B = A self.id = (B, A) ####################################################################################################################################### class Triangle: EPSILON = 0.0000000001 def __init__(self, A, B, C): self.A = A self.B = B self.C = C self.a = Edge(A, B) self.b = Edge(B, C) self.c = Edge(C, A) self.edges = [self.a, self.b, self.c] self.circumcircle_center = Vertex((0, 0)) self.circumcircle_radius = 0.0 # self.rsqr = 0.0 self.Circumcircle() def Circumcircle(self): if ((abs(self.A.y - self.B.y) < self.EPSILON) and (abs(self.B.y - self.C.y) < self.EPSILON)): print("CircumCircle: Points are coincident.") return False if (abs(self.B.y - self.A.y) < self.EPSILON): m2 = - (self.C.x - self.B.x) / float(self.C.y - self.B.y) mx2 = (self.B.x + self.C.x) / 2.0 my2 = (self.B.y + self.C.y) / 2.0 self.circumcircle_center.x = (self.B.x + self.A.x) / 2.0 self.circumcircle_center.y = m2 * (self.circumcircle_center.x - mx2) + my2 elif (abs(self.C.y - self.B.y) < self.EPSILON): m1 = - (self.B.x - self.A.x) / float(self.B.y - self.A.y) mx1 = (self.A.x + self.B.x) / 2.0 my1 = (self.A.y + self.B.y) / 2.0 self.circumcircle_center.x = (self.C.x + self.B.x) / 2.0 self.circumcircle_center.y = m1 * (self.circumcircle_center.x - mx1) + my1 else: m1 = - (self.B.x - self.A.x) / float(self.B.y - self.A.y) m2 = - (self.C.x - self.B.x) / float(self.C.y - self.B.y) mx1 = (self.A.x + self.B.x) / 2.0 mx2 = (self.B.x + self.C.x) / 2.0 my1 = (self.A.y + self.B.y) / 2.0 my2 = (self.B.y + self.C.y) / 2.0 self.circumcircle_center.x = (m1 * mx1 - m2 * mx2 + my2 - my1) / float(m1 - m2) self.circumcircle_center.y = m1 * (self.circumcircle_center.x - mx1) + my1 dx = self.B.x - self.circumcircle_center.x dy = self.B.y - self.circumcircle_center.y # self.rsqr = dx*dx + dy*dy self.circumcircle_radius = dx * dx + dy * dy def isInCircumcircle(self, point): dx = point.x - self.circumcircle_center.x dy = point.y - self.circumcircle_center.y drsqr = dx * dx + dy * dy; # return((drsqr - *rsqr) <= EPSILON ? TRUE : FALSE); return True if ((drsqr - self.circumcircle_radius) <= self.EPSILON) else False
from d2lzh_pytorch import linear_reg, data_process, rnn,plot import time import torch import torch.nn as nn import numpy as np import math def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params=None, lr=None, optimizer=None): """ The training function of chapter3, it is a more useful function. In Chapter3_6, it is used to train the softmax regconition. Parameters ---------- net : [function] input X and get y_hat, the main learning program train_iter : [producer] the train dataset test_iter : [producer] the test dataset loss : [function] input y and y_hat, get loss value num_epochs : [int] how many times do you want to learn through the whole training dataset? batch_size : [int] size of the batch params : [tensor], optional the weight and bias combine to be the params tensor, by default None lr : [float], optional learning rate, by default None optimizer : [function], optional the function to decrease the gradient, if you have a optimizer, you don't need to input the params and lr before but input them directly to the optimizer, by default None """ for e in range(num_epochs): # init train_loss_sum, train_acc_sum, n = 0.0, 0.0, 0 for X, y in train_iter: y_hat = net(X) l = loss(y_hat, y).sum() # depend on whether you have a optimizer # clean the grad of params if optimizer is not None: optimizer.zero_grad() elif params is not None and params[0].grad is not None: for p in params: p.grad.data.zero_() l.backward() # the function to decrease the gradient if optimizer is None: linear_reg.sgd(params, lr, batch_size) else: optimizer.step() # gain the loss and acc value of each iter train_loss_sum += l.item() train_acc_sum += (y_hat.argmax(dim=1) == y).float().sum().item() n += y.shape[0] # use those value stored in iter to gain the final value of every epochs test_acc = data_process.evaluate_accuracy(test_iter, net) print('epoch %d, loss %.3f, train acc %.3f, test acc %.3f' % (e+1, train_loss_sum/n, train_acc_sum/n, test_acc)) def train_ch5(net, train_iter, test_iter, batch_size, optimizer, device, num_epochs): """ The new version of training function, it contain the device selection and became a fully module function, better than train_ch3. Parameters ---------- net : [module] the net that want to apply train_iter : [producer] the train dataset test_iter : [producer] the test dataset batch_size : [int] size of the batch optimizer : [function] the function to decrease the gradient device : [device] the device want to run on num_epochs : [int] how many times do you want to learn through the whole training dataset? """ # apply the net on target device net = net.to(device) print('training on:', device) loss = torch.nn.CrossEntropyLoss() for e in range(num_epochs): batch_count = 0 train_l_sum, train_acc_sum, n, start = 0.0, 0.0, 0, time.time() for X, y in train_iter: # apply datas to target device X = X.to(device) y = y.to(device) y_hat = net(X) l = loss(y_hat, y) optimizer.zero_grad() l.backward() optimizer.step() # for some elements not on GPU should move to CPU for calculation train_l_sum += l.cpu().item() train_acc_sum += ((y_hat.argmax(dim=1) == y).sum().cpu().item()) n += y.shape[0] batch_count += 1 # use those value stored in iter to gain the final value of every epochs test_acc = data_process.evaluate_accuracy(test_iter, net) print('epoch %d, loss %.3f, train acc %.3f, test acc %.3f,time %.1f sec' % (e+1, train_l_sum/batch_count, train_acc_sum/n, test_acc, time.time()-start)) def train_and_predict_rnn(RNN, get_params, init_rnn_state, num_hiddens, vocab_size, device, corpus_indices, idx_to_char, char_to_idx, is_random_iter, num_epochs, num_steps, lr, clipping_theta, batch_size, pred_period, pred_len, prefixes): """ Train and predict a sequence with a function building step by step called RNN Parameters ---------- RNN : [function] the recycle neural network get_params : [function] the function that can return network's init params init_rnn_state : [tuple] network's start time state num_hiddens : [int] how many hidden parameters you want to add vocab_size : [int] the number of non-repeating character in this vocab device : [device] device you want to run on corpus_indices : [tensor] the index formation of input data idx_to_char : [tensor] index to character map char_to_idx : [tet] how many epoch would print a prediction pred_len : [int] the number of characters you want to predict prefixes : [string] the start characters of these character sequencesnsor] character to index map is_random_iter : [bool] choose the iter's type num_epochs : [int] number of epochs num_steps : [int] number of time steps lr : [float] learning rate clipping_theta : [float] use to be a threshold of gradients division batch_size : [int] how many times a batch would contain pred_period : [int] how many epoch would print a prediction pred_len : [int] the number of characters you want to predict prefixes : [string] the start characters of these character sequences """ # choose which function to load data if is_random_iter: data_iter_fn = data_process.data_iter_random else: data_iter_fn = data_process.data_iter_consecutive # get init params of network params = get_params() # use CrossEntropyLoss's exponent to be the perplexity loss = nn.CrossEntropyLoss() # repeat epoch times, to ensure a better result for e in range(num_epochs): # if it is not using random iter, init at the start of an epoch if not is_random_iter: state = init_rnn_state(batch_size, num_hiddens, device) l_sum, n, start = 0.0, 0, time.time() data_iter = data_iter_fn(corpus_indices, batch_size, num_steps, device) # load a batch of pair of data at a time from data_iter # this loop will loading data by time-step, one loop one step for X, Y in data_iter: if is_random_iter: # random_iter should re-init in every step calls state = init_rnn_state(batch_size, num_hiddens, device) else: # else we just need to detach it's state, in case the gradient # compution cost too much time for s in state: s.detach_() # pretreat our datas, get (batch_size ,vocab_size) inputs = rnn.to_onehot(X, vocab_size) # put it into RNN and get its output and new state # outputs will has num_steps (batch_size, vocal_size) matrixes # here you can see that inputs is totally new, state may be old outputs, state = RNN(inputs, state, params) # cat outputs to be (num_steps*batch_size, vocal_size) outputs = torch.cat(outputs, dim=0) # make y be (batch*num_steps), y is the gt answer y = torch.transpose(Y, 0, 1).contiguous().view(-1) # compute the loss l = loss(outputs, y.long()) # set gradient to be zero if params[0].grad is not None: for p in params: p.grad.data.zero_() # then backpropagate the gradient l.backward() # clip gradient rnn.grad_clipping(params, clipping_theta, device) # decent it linear_reg.sgd(params, lr, 1) # cal the whole loss l_sum += l.item()*y.shape[0] n += y.shape[0] # print some result if (e+1) % pred_period == 0: # use exp to cal perplexity here print('epoch %d, perplexity %f, time %.2f sec' % (e + 1, math.exp(l_sum / n), time.time() - start)) # print some prediction here for prefix in prefixes: print(' -', rnn.predict_rnn(prefix, pred_len, RNN, params, init_rnn_state, num_hiddens, vocab_size, device, idx_to_char, char_to_idx)) def train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device, corpus_indices, idx_to_char, char_to_idx, num_epochs, num_steps, lr, clipping_theta, batch_size, pred_period, pred_len, prefixes): """ Train the net which is constructed by pytorch module and predict strings Parameters ---------- model : [function] the recycle neural network num_hiddens : [function] the recycle neural network vocab_size : [int] the number of non-repeating character in this vocab device : [device] device you want to run on corpus_indices : [tensor] the index formation of input data idx_to_char : [tensor] index to character map char_to_idx : [tet] how many epoch would print a prediction num_epochs : [int] number of epochs num_steps : [int] number of time steps lr : [float] learning rate clipping_theta : [float] use to be a threshold of gradients division batch_size : [int] how many times a batch would contain pred_period : [int] how many epoch would print a prediction pred_len : [int] the number of characters you want to predict prefixes : [string] the start characters of these character sequences """ # init loss = nn.CrossEntropyLoss() optimizer=torch.optim.Adam(model.parameters(),lr=lr) model.to(device) state=None # repeat epoch times, to ensure a better result for e in range(num_epochs): l_sum, n, start = 0.0, 0, time.time() # here only use the consecutive version data_iter = data_process.data_iter_consecutive( corpus_indices, batch_size, num_steps, device) # load a batch of pair of data at a time from data_iter # this loop will loading data by time-step, one loop one step # X is now's data and Y is its answer for X, Y in data_iter: if state is not None: if isinstance(state, tuple): # for LSTM state = (state[0].detach(), state[1].detach()) else: # detach state from graph to prevent the highly cost state = state.detach() # predict and get outputs # outputs will has num_steps (batch_size, vocal_size) matrixes # here you can see that inputs is totally new, state may be old outputs, state = model(X, state) # make y be (batch*num_steps), y is the ground truth y = torch.transpose(Y, 0, 1).contiguous().view(-1) # compute the loss l = loss(outputs, y.long()) # set gradient to be zero optimizer.zero_grad() # then backpropagate the gradient l.backward() # clip gradient rnn.grad_clipping(model.parameters(), clipping_theta, device) # decent it optimizer.step() # cal the whole loss l_sum += l.item()*y.shape[0] n += y.shape[0] # use exp to cal perplexity try: perplexity=math.exp(l_sum/n) except OverflowError: perplexity=float('inf') # print some result if (e+1) % pred_period == 0: print('epoch %d, perplexity %f, time %.2f sec' % (e + 1, perplexity, time.time() - start)) # print some prediction here for prefix in prefixes: print(' -', rnn.predict_rnn_pytorch(prefix, pred_len, model, vocab_size, device, idx_to_char, char_to_idx)) def train_2d(trainer): """ Train gradient function pretreat from target function and return the decent trace. Parameters ---------- trainer : [function] the gradient function, input x1, x2 and s1, s2, return function value Returns ------- [tensor] the trace of target function's decention's inputs """ # s1, s2 here are states x1, x2, s1, s2 = -5, -2, 0, 0 results = [(x1, x2)] for i in range(20): # get new value x1, x2, s1, s2 = trainer(x1, x2, s1, s2) results.append((x1, x2)) print('epoch %d, x1 %f, x2 %f' % (i + 1, x1, x2)) return results def train_ch7(optimizer_fn, states, hyperparams, features, labels, batch_size=10, num_epochs=2): """ The training function of chapter7, it is a more useful function. In Chapter7, it is used with some different optimizer functions. Parameters ---------- optimizer_fn : [function] the optimizer function that wants to use states : [int] states delivered to optimizer hyperparams : [pair] hyperparams delivered to optimizer features : [tensor] batch of features labels : [tensor] batch of labels batch_size : [int], optional size of a batch, by default 10 num_epochs : [int], optional summary of number of epochs, by default 2 """ # using linear regression and squared loss for training net, loss = linear_reg.linreg, linear_reg.squared_loss # init params w = torch.nn.Parameter(torch.tensor(np.random.normal(0, 0.01, size=( features.shape[1], 1)), dtype=torch.float32), requires_grad=True) b = torch.nn.Parameter(torch.zeros( 1, dtype=torch.float32), requires_grad=True) # get loss def eval_loss(): return loss(net(features, w, b), labels).mean().item() # prepare data and strutures ls = [eval_loss()] data_iter = torch.utils.data.DataLoader( torch.utils.data.TensorDataset(features, labels), batch_size, shuffle=True) # for each epochs for _ in range(num_epochs): start = time.time() for batch_i, (X, y) in enumerate(data_iter): # using avg loss l = loss(net(X, w, b), y).mean() # clean gradients if w.grad is not None: w.grad.data.zero_() b.grad.data.zero_() l.backward() optimizer_fn([w, b], states, hyperparams) # save current loss if (batch_i+1)*batch_size % 100 == 0: ls.append(eval_loss()) # output results print('loss: %f, %f sec per epoch' % (ls[-1], time.time() - start)) plot.set_figsize() plot.plt.plot(np.linspace(0, num_epochs, len(ls)), ls) plot.plt.xlabel('epoch') plot.plt.ylabel('loss') plot.plt.show() def train_pytorch_ch7(optimizer_fn, optimizer_hyperparams, features, labels, batch_size=10, num_epochs=2): """ The training function of chapter7, but this is the pytorch library version Parameters ---------- optimizer_fn : [function] the optimizer function that wants to use optimizer_hyperparams : [pair] hyperparams delivered to optimizer features : [tensor] batch of features labels : [tensor] batch of labels batch_size : [int], optional size of a batch, by default 10 num_epochs : [int], optional summary of number of epochs, by default 2 """ # init the net, using one linear layer to simulate the linear regression net = nn.Sequential( nn.Linear(features.shape[-1], 1) ) loss = nn.MSELoss() optimizer = optimizer_fn(net.parameters(), **optimizer_hyperparams) # get loss def eval_loss(): return loss(net(features).view(-1), labels).item()/2 # prepare data and strutures ls = [eval_loss()] data_iter = torch.utils.data.DataLoader( torch.utils.data.TensorDataset(features, labels), batch_size, shuffle=True) # for each epochs for _ in range(num_epochs): start = time.time() # for each batches for batch_i, (X, y) in enumerate(data_iter): # divided by 2 is used to make sure the loss is equal to train_ch7's l = loss(net(X).view(-1), y)/2 optimizer.zero_grad() l.backward() optimizer.step() # save current loss if(batch_i + 1) * batch_size % 100 == 0: ls.append(eval_loss()) # output results print('loss: %f, %f sec per epoch' % (ls[-1], time.time() - start)) plot.set_figsize() plot.plt.plot(np.linspace(0, num_epochs, len(ls)), ls) plot.plt.xlabel('epoch') plot.plt.ylabel('loss') plot.plt.show() class Benchmark(): """ Time marking class. Using 'with' to create this class and automatically destory it. """ def __init__(self, prefix=None): # in initiation this class will construct a string telling the name of # this task self.prefix = prefix + ' ' if prefix else '' def __enter__(self): # then this class will start the time marker self.start = time.time() def __exit__(self, *args): # once current task completed, this class will exit and print the result print('%stime: %.4f sec' % (self.prefix, time.time() - self.start)) def train(train_iter, test_iter, net, loss, optimizer, device, num_epochs): """ Standard training function. Parameters ---------- train_iter : [producer] the train dataset test_iter : [producer] the test dataset net : [function] the chossing neural network function loss : [function] input y and y_hat, get loss value optimizer : [function] the function to decrease the gradient device : [device] the device you want to run on num_epochs : [int] how many times do you want to learn through the whole training dataset? """ # move the net to target device net = net.to(device) print("training on ", device) # for each epoch for epoch in range(num_epochs): train_l_sum, train_acc_sum, n, start = 0.0, 0.0, 0, time.time() batch_count = 0 # for each data pair in one epoch for X, y in train_iter: # remember to move the data to target device too X = X.to(device) y = y.to(device) # get the output from net y_hat = net(X) # cal loss l = loss(y_hat, y) optimizer.zero_grad() l.backward() # optimizer take next step optimizer.step() train_l_sum += l.cpu().item() train_acc_sum += (y_hat.argmax(dim=1) == y).sum().cpu().item() n += y.shape[0] batch_count += 1 # caculate test accuracy after training is over and output results test_acc = data_process.evaluate_accuracy(test_iter, net) print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f,time %.1f sec' % ( epoch + 1, train_l_sum / batch_count, train_acc_sum / n, test_acc, time.time() - start))
# coding=utf-8 import torch """ 这一节介绍了线性回归的基本概念和神经网络图 """ x = torch.ones(100) y = torch.ones(100) z = torch.zeros(100) # 两个向量相加一种方法是用循环逐元素相加,这种做法繁琐且速度极慢 for i in range(100): z = x[i]+y[i] # 另一种做法是直接做向量加法,这种做法速度快很多,所以在计算的时候最好将计算向量化 z = x+y # 多运用广播机制可以简化代码的编写(见2.2) a = torch.ones(10) b = 2 print(a+b) print('————————————')
# coding=utf-8 # 用这个来导入PyTorch包 import torch """ 这一节介绍了tensor基础的操作 """ # 默认数据格式是float32 x = torch.ones(2, 4) y = torch.zeros(2, 4) # tensor加法1 z = x+y # tensor加法2 z = x.add(y) # tensor加法3,注意pytorch中函数后缀是下划线的均代表此操作是原地操作 z = x.add_(y) print(z) print('————————————') # 可以获得tensor的索引,冒号和matlab一样用于得到一个范围值 y = x[0, :] # 对索引的操作会影响到原tensor的值,也就是此时y+1的操作会影响x的值 y += 1 print(y) print('————————————') # 利用名为mask的二进制tensor选取input中所需的元素组成tensor # 要注意得到的tensor是一维的 mask = torch.tensor([[False, False, True, True], [False, False, True, False]]) q = torch.masked_select(x, mask) print(q) print('————————————') # view可以改变tensor的形状,也就是重新排布tensor # 这个操作返回的tensor和原tensor共享内存,因为view实际上只是改变了观察的角度 # 要注意tensor必须能够正好符合重排 q = q.view(3, 1) # 如果想要返回副本,最好先clone得到新副本在view,reshape也能得到类似效果但不保证是副本 q = q.clone() print(q) print('————————————') # item函数可以将一个标量tensor转为一个普通数字 x = torch.rand(1) print(x) print(x.item()) print('————————————') # tensor还支持很多线代操作 # trace求对角线之和(迹),diag求对角线元素,triu/tril求上下三角 # t转置,dot内积,cross外积,inverse求逆,svd奇异值分解
#!/usr/bin/python def printMax(x,y): '''Print the maximum of the two integers. The tow input must be integers.''' if x>y: print x else: print y print printMax.__doc__ printMax(3,5) help(printMax)
"""Main flow.""" from brain_games.cli import welcome_user import prompt def flow(game): name = welcome_user() print(game.PHRASE_RULE) game_counter = 0 game_limit = 3 while game_counter < game_limit: question_expression, correct_answer = game.get_question_and_answer() print('Question: {}'.format(question_expression)) user_answer = prompt.string('Your answer: ') if user_answer == correct_answer: game_counter += 1 print("Correct!") else: print("'{}' is wrong answer ;(.".format(user_answer)) print("Correct answer was '{}'".format(correct_answer)) print("Let\'s try again, {}!".format(name)) break if game_counter == 3: print('Congratulations, {}!'.format(name))
"""Arithmetic progression Game.""" import random PHRASE_RULE = 'What number is missing in the progression?' def get_question_and_answer(): """Engine of the Game.""" number_start = random.randint(1, 100) number_dif = random.randint(1, 20) number_elements = random.randint(5, 10) progression_list = [] for i in range(1, number_elements + 1): progression_list.append(number_start) number_start = number_start + number_dif lost_item = random.randint(0, number_elements - 1) correct_answer = str(progression_list[lost_item]) progression_list[lost_item] = '..' progression_list_str = ' '.join(str(x) for x in progression_list) question_expression = '{}'.format(progression_list_str) return question_expression, correct_answer
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 import time import sys answer = input("Would you like to play a game? ") if answer.lower().strip() == "yes": #intro to the adventure, which will present three options to the player answer = input("\nYou wake to find yourself in a dimly lit stone corridor with rough wooden doors set in each side " "every few paces." "\nThere are no markings or discernible differences amongst the doors that you can see." "\nLook down the corridor in either direction reveals the same view from the dim light." "\nYou note that you don't see any source of the light." "\nThere are no lights overhead or on the walls." "\n\nWhat will you do?\n\n" "a. Open the door to your RIGHT.\n" "b. Open the door to your LEFT.\n" "c. Walk further down the corridor.\n" "(Enter: 'a', 'b' or 'c'): ") #player chose the door on the right if answer.lower().strip() == "a": print("\n\nYou reach for the handle of the door immediately to your right." "\nThe handle is neither warm nor cold to the touch." "\nThe wood of the door looks old, but in sound condition, and for the first time you notice that" "\nthere are faint carvings around the door inlay unlike anything you have seen before." "\nYou pause to trace your finger along the strange shapes and symbols,") #pausing and printing a series of dots for dramatic effect for i in range(3): sys.stdout.write(".") sys.stdout.flush() time.sleep(1) print("And start back from the door in pain!\n") time.sleep(1) print("Buried in your finger is a large splinter from the door, and a small spot of blood." "\nYou stick your finger in your mouth and quickly grab the handle of the door and turn." "\n\nIt's locked." "\n\nWhat will you do?\n\n" "a. Open the door behind you.\n" "b. Walk further down the corridor.\n" "(Enter: 'a' or 'b'): ") #player chose the door on the left if answer.lower().strip() == "b": print("\n\nYou reach for the handle of the door immediately to your left." "\nThe handle is neither warm nor cold to the touch." "\nYou hear a slight hum when you grasp the handle, and you pause to pull your hand away in hesitation." "\nThe noise is gone, and you are greeted once again by the (unnatural?) silence of the corridor." "\nResolving your nerves you grasp the door handle once more, ignoring the buzz in the back of your mind." "\nYou turn the handle.") # pausing and printing a series of dots for dramatic effect for i in range(3): sys.stdout.write(".") sys.stdout.flush() time.sleep(1) print("The door clicks open, and you are surprised by how silently it swings open." "\nIt's as though someone has been keeping the hinges well oiled though it looks like no one has" "\nentered this hall for an indeterminable time.") else: print("That's too bad!")