text
stringlengths
37
1.41M
import os import csv #Declare variables candidates = [] uniqueCandidates = [] #Open election_data.csv as long as election_data is in the same folder as this file path = os.path.join(".","election_data.csv") with open(path,'r') as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") next(csvreader) #Iterate through the entire list, determine total num votes and all unique candidates for row in csvreader: candidates.append(row[2]) if(row[2] not in uniqueCandidates): uniqueCandidates.append(row[2]) #Create a list of vote counts voteCount = [] for names in uniqueCandidates: voteCount.append(candidates.count(names)) #Print Election Results total vote count print("Election Results\n-------------------------") print(f"Total Votes: {len(candidates)}\n-------------------------") #For each unique candidate, calculate the percentage of votes and print number of votes for item in uniqueCandidates: print(f'''{item}: {"{0:.3f}".format((candidates.count(item)/len(candidates))*100)} ({candidates.count(item)}) ''') #Find out what the max votes is and pass the index back to unique candidates and return the winning candidate print("-------------------------") print(f"Winner: {uniqueCandidates[voteCount.index(max(voteCount))]}") print("-------------------------") #create budgetDataOutput.csv which contains the above information printed to the terminal with open("electionDataOutput.txt","w") as output: output.write("") output.write("Election Results\n-------------------------\n") output.write(f"Total Votes: {len(candidates)}\n-------------------------\n") for item in uniqueCandidates: output.write(f'''{item}: {"{0:.3f}".format((candidates.count(item)/len(candidates))*100)} ({candidates.count(item)}) \n''') output.write("-------------------------\n") output.write(f"Winner: {uniqueCandidates[voteCount.index(max(voteCount))]}\n") output.write("-------------------------")
#!/usr/bin/env python import sys, re def isValidInput(string): # fix regex ... it allows (+)^number result = re.match(r'\([-]?([1-9]+[0-9]*)*([a-z](\^[1-9]+[0-9]*)?)*[+-]([1-9]+[0-9]*)*([a-z](\^[1-9]+[0-9]*)?)*\)\^[1-9]+[0-9]*', string) return result != None and result.group(0) == string def badInput(): print 'Error: incorrect input. Expected the following format:' print ' --> (<a>[+,-]<b>)^<n>, where a,b,n can contain any' print ' --> valid combination of variables and positive ints,' print ' --> but n must only contain positive ints.' def splitAB(ab): a = '-' if ab[0] == '-' else '' b = '-' if '+' not in ab else '' ab = ab[1:] if ab[0] == '-' else ab split = ab.split('+') if '+' in ab else ab.split('-') a += split[0] b += split[1] return (a, b) def getVariables(string): a = '' b = '' ab, n = string.split(')') n = n.replace('^', '') ab = ab.replace('(', '') split = splitAB(ab) a, b = ('', '') if len(split) != 2 else split return (a, b, n) def choose(n, k): factorials = [n, n-k, k] results = [] for factorial in factorials: total = 1 for i in xrange(1, factorial + 1): total *= i results += [total] return results[0] / (results[1] * results[2]) def solveBinomial(a, b, n): finals = [] for k in xrange(n + 1): finals += ['(%i)(%s)^%i(%s)^%i' % (choose(n, k), a, n - k, b, k)] print ' + '.join(finals) def main(argc, argv): if argc == 1 and isValidInput(argv[0]): a, b, n = getVariables(argv[0]) print 'a = ' + a print 'b = ' + b print 'n = ' + n if a == '' or b == '': badInput() solveBinomial(a, b, int(n)) else: badInput() if __name__ == '__main__': main(len(sys.argv) - 1, sys.argv[1:])
# of cars available cars = 100 # how many passengers fit in each car space_in_a_car = 4.0 #how many drivers are available drivers = 30 #how many passengers passengers = 90 # of cars that won't be used cars_not_driven = cars - drivers # of cars that will be used cars_driven = drivers # how many passengers can be driven carpool_capacity = cars_driven * space_in_a_car number of passengers that will fit per car average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have" , passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car."
#print("How old are you?", end=' ') #age = input() #print("How tall are you?", end=' ') #height = input() #print("How much do you weigh?", end=' ') #weight = input() #print(f"So, you're {age} old, {height} tall, and {weight} heavy.") #print("Let's try something else.") #name = input('What do they call you? ') #print(f"{name}? That's a weird name.") age = input("How old are you? ") height = input("How tall are you? ") weight = input("How much do you weigh? ") print(f"So, you're {age} years old, {height} tall, and {weight} lbs heavy.")
def kitty(treats, catnip): print "Kitty is hungry for %s!" % treats print "Especially after having %r oz of catnip. ^^" % catnip kitty("babies", 100) tasty = "birds" oz = 50 kitty(tasty, oz) kitty(tasty + tasty, oz + 20) print "this one" kitty(kitty(tasty, oz), oz) treats = raw_input('What food do we have?') kitty(treats, 1) kitty("cuddles" , 3 + 6) food1 = "manatees" food2 = "anteaters" kitty(food1 + " and " + food2, 5) oz = round(float(raw_input('How much catnip did you buy?!'))) kitty("meat" , oz) kitty("oranges" , 5.5)
import random from typing import List # simple model of reinforcement learning # an environment that will give the agent random rewards # for a limited number of steps, regardless of the agent's actions class Environment: """ providing observations and giving rewards. The environment changes its state based on the agent's actions. """ # initialize its internal state. def __init__(self): self.steps_left = 10 # return the current environment's observation to the agent. def get_observation(self) -> List[float]: return [0.0, 0.0, 0.0] # environment basically has no internal state in this case. # query the set of actions it can execute. def get_actions(self) -> List[int]: return [0, 1] # two possible actions in this case # signaled the end of the episode to the agent def is_done(self) -> bool: return self.steps_left == 0 # handles an agent's action and returns the reward for this action def action(self, action: int) -> float: if self.is_done(): raise Exception("Game is over") self.steps_left -= 1 return random.random() class Agent: def __init__(self): self.total_reward = 0.0 def step(self, env: Environment): current_obs = env.get_observation() actions = env.get_actions() reward = env.action(random.choice(actions)) self.total_reward += reward if __name__ == "__main__": env = Environment() agent = Agent() while not env.is_done(): agent.step(env) print("Total reward got: %.4f" % agent.total_reward)
#! /usr/bin/env python #-*- coding: utf-8 -*-import numpy import os import pandas as pd import time import numpy as np from collections import OrderedDict from datetime import datetime import string def ReverseWords(str): _len = len(str) if _len<2: return str else: i = 0 j = _len-1 while i<j: temp = str[j] str[j] = str[i] str[i] = temp i = i+1 j = j-1 return str b = ReverseWords("hello") print b
from person import Person, Consts class Teacher(Person): def __init__(self, name, age): super(Teacher, self).__init__(name, age) self.job = 'teacher' def get_price(self): return Consts.BASE_PRICE[self.job] - (self.age - Consts.MIN_AGE) * Consts.AGE_MUL def calc_life_cost(self): return Consts.BASE_COST[self.job] + (self.age - Consts.MIN_AGE) * Consts.AGE_MUL def calc_income(self): return Consts.BASE_INCOME[self.job][self.work_place.get_expertise()] - (self.age - Consts.MIN_AGE) * Consts.AGE_MUL
from threading import Thread, Lock lock = Lock() def synchronized(f): def g(*args): lock.acquire() f(*args) lock.release() return g a = 0 @synchronized def f(): global a for i in range(3000000): a += 1 number_of_threads = 2 t = [Thread(name=i, target=f) for i in range(number_of_threads)] for i in range(number_of_threads): t[i].start() for i in range(number_of_threads): t[i].join() print(a)
from film import Film from periodical import Periodical from book import Book from video import Video class SearchEngine(object): def __init__(self, books_path, periodic_path, video_path, film_path): '''Reads and parses all of the specified files and stores the objects in a list''' self.__media = list() self.__read_books(books_path) self.__read_periodics(periodic_path) self.__read_videos(video_path) self.__read_films(film_path) def __read_books(self, path): '''calls private read_file func and creates obj''' lines = self.__read_file(path) for line in lines: self.__media.append(Book(line)) def __read_periodics(self, path): '''calls private read_file func and creates obj''' lines = self.__read_file(path) for line in lines: self.__media.append(Periodical(line)) def __read_videos(self, path): '''calls private read_file func and creates obj''' lines = self.__read_file(path) for line in lines: self.__media.append(Video(line)) def __read_films(self, path): '''calls private read_file func and creates obj''' lines = self.__read_file(path) for line in lines: self.__media.append(Film(line)) def __read_file(self, path): '''open and read file, then split each piece of data in line returns a list of lists, each contained list represents a line''' data = list() for line in open(path, 'r'): data.append(line.strip('\n').split('|')) return data def search_by_title(self, title): '''searches through all records and checks for match based on supplied data returns a list of objects that match the supplied criteria ''' matches = list() for record in self.__media: if record.compare_title(title): matches.append(record) return matches def search_by_call_number(self, call_number): '''searches through all records and checks for match based on supplied data returns a list of objects that match the supplied criteria ''' matches = list() for record in self.__media: if record.compare_title(call_number): matches.append(record) return matches def search_by_subjects(self, subjects): '''searches through all records and checks for match based on supplied data returns a list of objects that match the supplied criteria ''' matches = list() for record in self.__media: if record.compare_title(subjects): matches.append(record) return matches def search_by_other(self, field, data): '''searches through all records and checks for match based on supplied data returns a list of objects that match the supplied criteria ''' matches = list() for record in self.__media: if record.compare_other(field, data): matches.append(record) return matches
from string import ascii_lowercase import random def main(): with open('words.txt') as file: words = file.readline().split() print(f'Found {len(words)} words in input file') word_to_guess = random.choice(words) attempt_number = 0 max_attempts = 20 all_letters = set(ascii_lowercase) used_letters = set() for attempt in range(max_attempts): possible_letters = all_letters - used_letters print(f'Possible letters are:\r\n {" - ".join(possible_letters)}') chosen_letter = input(f'You have {max_attempts - attempt_number} attempts left. Please choose one of possible ' f'letters\r\n') if chosen_letter not in possible_letters: print(f'Wrong input, please use only letters from possible letters listed above\r\n') continue if chosen_letter in word_to_guess: print(f'Great job! OTKROITE BUKVU {chosen_letter}\r\n') used_letters.add(chosen_letter) if chosen_letter not in word_to_guess: print(f'Unfortunately letter {chosen_letter} is not present in a secret word') used_letters.add(chosen_letter) opened_letters_contatenated = "".join([letter for letter in word_to_guess if letter in used_letters]) print(f'Here is the word after {attempt} attempt: {opened_letters_contatenated}') if opened_letters_contatenated == word_to_guess: print(f'VI VIIGRALI AAVTOMOBIL@!!!\r\nYour word was: {word_to_guess}') break if __name__ == '__main__': main()
# Python The process of python learning. import requests import os url = 'http://img0.dili360.com/rw5/ga/M00/45/C5/wKgBy1guyueAFg1vABWJTEejlTU417.tub.jpg' root = 'c:/pics/' path = root + url.split('/')[-1] def get_pic(): try: if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r = requests.get(url) r.raise_for_status() with open(path,'wb') as f: f.write(r.content) f.close() print('succeed') except: print('shit!') if __name__ == '__main__': get_pic()
compras = ['tomate','queijo','suco'] print (compras [-1]) #desse modo o python vai retornar recursivamente #os valoes sortados da direita para a esquerda #o numero negativo deve estar sempre com o valor #total dos itens na lista. e o ultimo valor #sera apresentado de forma negativa
# the woodcutters house import time # define the global variables needed for this level inventory = [] no_of_cupboard_entries = 0 snake_dead = False def fig_puzzle(): # user the global inventory list global inventory # introduce the puzzle time.sleep(1) print("Before you can go in you must solve a little puzzle.") time.sleep(1) # ask the user to guess the word answer = input("There is a secret word on the house. What is it?").lower() # if they get it wrong - give them the first clue and ask again if answer != "fig": time.sleep(1) print("No. The word is on the wall") time.sleep(1) answer = input("There is a secret word on the house. What is it?").lower() # if they get it wrong again - give them the second clue and ask again if answer != "fig": time.sleep(1) print("No. The word is typed with asterixes.") time.sleep(1) answer = input("There is a secret word on the house. What is it?").lower() # if they get it wrong a thord time - use a loop to tell them the answer and keep asing until they get it right while answer != "fig": time.sleep(1) print("No. The word is FIG.") time.sleep(1) answer = input("There is a secret word on the house. What is it?").lower() time.sleep(1) # once the puzzle is solved procede print("Now we can go inside but we must be very careful.") time.sleep(1) print("The Witch has set some traps for you!") # ask the user if they want an apple - dont take 'NO' for an answer! apple = input("Would you like to take an apple from the tree?").lower() while apple not in ["yes", "y"]: apple = input("Would you like to take an apple from the tree?").lower() # add the apple to inventory time.sleep(1) print("Keep the apple safe.") print("I will let us in now.") time.sleep(1) inventory.append("apple") def witch(): # witch graphic print("========================================================================") print("= ********************* =") print("= \ \ =") print("= * * =") print("= / \ =") print("= * *___________ =") print("= / ************************* =") print("= ***************&&&&&&&&& ** =") print("= &&&&&&&&&&&&&&&&&& / =") print("= &&&&&&&&&&&&&&&&& (O)______ =") print("= & &&&&&&&&&&&&&&& ____________\ =") print("= & &&&&&&&&&&&&&&& | u u =") print("= & & &&&&&&&&&&&& |__n_n_n__ =") print("= & & &&&&&&&&&&&& ____________) =") print("= & & &&&&&&&&&& _/ =") print("= & & / =") print("= & =") print("========================================================================") # witch dialogue time.sleep(1) print("Ha ha! Now I've got you!") time.sleep(1) print("I will send you home at once.") # bring the raven back to let us know we have to go home time.sleep(1) print("========================================================================") print("= =") print("= *** =") print("= ********* =") print("= ********** **** =") print("= *************************************** =") print("= **************************************************** =") print("= ************************************** ** =") print("= ***************************** =") print("= ************************ =") print("= ******************* =") print("= ************* =") print("= ***** =") print("= * * =") print("= * * =") print("= * ***** =") print("= * =") print("= ******* =") print("========================================================================") time.sleep(1) print("I am very sorry but the Witch has sent us home.") time.sleep(1) print("You will have to try again later.") # finish the game quit() def stick(): # use the global inventory global inventory time.sleep(1) # let the user know where they are print("We are in the hallway.") time.sleep(1) print("It is very dark but you can see a long stick by the wall.") time.sleep(1) # ask the user if they want the stick - if yes they add it to the inventory take_stick = input("Are you going to take it?").lower() if take_stick in ["y", "yes"]: inventory.append("stick") time.sleep(1) print("You now have a stick and an apple") def cupboard(): global no_of_cupboard_entries # increment the number of time the cupboard has been visited by 1 each time no_of_cupboard_entries = no_of_cupboard_entries + 1 time.sleep(1) # only the red broomstick is there on the first visit if no_of_cupboard_entries < 2: print("It is very cold in here.") time.sleep(1) print("All you can see is a RED broomstick.") time.sleep(1) # if they take the red broomstick the witch shows up and sends them home take_broom = input("Are you going to take it?").lower() if take_broom in ["y", "yes"]: time.sleep(1) print("Silly! Silly! Silly!") time.sleep(1) witch() # any other input and they go back to the hallway else: time.sleep(1) print("You leave the room.") time.sleep(1) hallway() # from the second visit on - a green broomstick appears else: print("It is very cold in here.") time.sleep(1) print("All you can see is a RED broomstick.") time.sleep(1) print("and a GREEN broomstick.") time.sleep(1) take_one = input("Are you going to take one?").lower() while take_one not in ["y", "n", "yes", "no"]: take_one = input("Are you going to take one?").lower() # if they want to take one - ask what colour if take_one in ["y", "yes"]: take_broom = input("Which broomstick do you want?").lower() while take_broom not in ["r","g", "red", "green"]: # if an invalid answer is entered - this function calls itself cupboard() # if red - the witch comes if take_broom in ['r', 'red']: time.sleep(1) print("Silly! Silly! Silly!") time.sleep(1) witch() # if green - we find Esther and this level ends else: time.sleep(1) print("Well done!") time.sleep(1) print("You have found") time.sleep(1) print("Esther") time.sleep(1) print("Remember this password: ") time.sleep(1) # this is the password to get to level 2 print("snow") else: time.sleep(1) print("You leave the room.") time.sleep(1) hallway() def stairs(): global snake_dead global inventory answers = 0 # let the user know where they are print("We are on the stairs.") time.sleep(1) print("There is a nasty snake here.") time.sleep(1) print("Its mouth is open wide.") # check is the snake dead if not snake_dead: time.sleep(1) print("I think it wants to eat you.") time.sleep(1) throw_object = input("What can you throw at the snake?.").lower() while throw_object not in inventory and answers < 2: time.sleep(1) answers = answers + 1 print("That will not work.") time.sleep(1) print("I think it wants to eat you.") time.sleep(1) throw_object = input("What can you throw at the snake?.").lower() # the apple kills the snake if throw_object == "apple": time.sleep(1) print("What a good shot you are.") print("You have killed the snake") time.sleep(1) print("At the top of the stairs there is a note on the wall.") print("It says...........") time.sleep(1) # print a clue! print("* * * * * * * * * * * * * * * * *") print("* Esther is in the house *") print("* hidden well from you *") print("* Look again and you may find *") print("* that one broom is now two. *") print("* * * * * * * * * * * * * * * * *") snake_dead = True time.sleep(1) print("You go back down the stairs.") hallway() ## This elif and else statement need to be fleshed out once the witch is elif throw_object == "stick": time.sleep(1) print("What a pity.") time.sleep(1) print("The stick was an evil magic wand.") print("Now the Witch is coming") time.sleep(1) witch() else: time.sleep(1) print("Now the snake is getting angry.") time.sleep(1) print("It has called the Witch.") witch() # if the snake is dead we use a different message else: time.sleep(1) print("The snake is dead.") time.sleep(1) print("There is nothing at the top of the stairs.") print("A loud voice tells you that Esther is not up there.") time.sleep(1) print("You go back down the stairs.") hallway() def kitchen(): # define a list of allowed answers allowed_ans = ["y","n","yes","no"] time.sleep(1) print("There is a huge cooking pot hanging over a very hot fire.") time.sleep(1) print("I wonder what is in there.") time.sleep(1) # do you want to look in the pot? look_in = input("Are you going to look in the pot?").lower() while look_in not in allowed_ans: look_in = input("Are you going to look in the pot?").lower() # if no go back to the hallway if look_in in ["n", "no"]: time.sleep(1) print("You leave the room.") time.sleep(1) hallway() # if yes the witch comes up else: time.sleep(1) print("Silly! Silly! Silly!") time.sleep(1) witch() def backroom(): # define a list of allowed answers allowed_ans = ["y","yes"] time.sleep(1) print("There is nothing in here except a small wooden box in the corner.") time.sleep(1) # do you want to look in the box? open_box = input("Would you like to open the box?").lower() # if the answer is not "y" or "yes", you leave the room if open_box not in allowed_ans: time.sleep(1) print("You leave the room.") time.sleep(1) hallway() else: time.sleep(1) print("There is a note inside and is says ..........") time.sleep(1) # print a clue! print("* * * * * * * * * * * * * * * * *") print("* It's not in this room *") print("* that you will find *") print("* the Witch's broom. *") print("* * * * * * * * * * * * * * * * *") time.sleep(1) print("You leave the room.") time.sleep(1) hallway() def hallway(): # define a list of rooms adjacent to the hallway hallway_rooms = ["kitchen", "backroom", "cupboard", "stairs"] time.sleep(1) # introduce the hallway print("We are in the hallway.") print("It is very dark but you can see") time.sleep(1) print("a door leading to the kitchen") time.sleep(1) print("a door leading to the backroom") time.sleep(1) print("a cupboard") time.sleep(1) print("and some stairs") time.sleep(1) # ask the user where they want to go and validate input next_room = input("Where do you wish to go?").lower() while next_room not in hallway_rooms: time.sleep(1) print("Sorry, I don't understand.") time.sleep(1) next_room = input("Where do you wish to go?").lower() # go to the selected room if next_room == "kitchen": kitchen() elif next_room == "backroom": backroom() elif next_room == "cupboard": cupboard() elif next_room == "stairs": stairs() def outside(): # this function acts as a main function for this part of the game # print the graphic print("========================================================================") print("= ___ =") print("= | |________________________________________ =") print("= / \ =") print("= / \ =") print("= /_________________________________________________\ =") print("= | ***_______ | =") print("= | *________| | =") print("= | * | =") print("= | *******___ *** | § =") print("= | *_________| | §§§ =") print("= | ******____| ****** | §O§§§ =") print("= | * * | §O§§O§§ =") print("= | * () () * *** () | § % § =") print("= | () () () () * * () | % =") print("= |_________()____()____()__()______******___()____| % =") print("= =") print("= =") print("========================================================================") # introduce the house ans ask th user if they want to enter print("This is the Woodcutter's house") time.sleep(1) house_entry = input("Would you like to go in?").lower() while house_entry not in ["y","n","yes","no"]: time.sleep(1) house_entry = input("Would you like to go in?").lower() if house_entry in ['n','no']: time.sleep(1) print("Come on. You will have to be brave.") # call the fig puzzle function fig_puzzle() # go inside - ask does the user want to take the stick stick() # start exploring from the hallway hallway()
pi=22/7 r=float(input("input the radius of the circle:")) area=pi*(r**2) print("the area of the circle with radius: "+str(r)+" is: "+str(area))
'''21 -Crie uma classe chamada Ingresso que possui um valor em reais e um método imprimeValor(). a. crie uma classe VIP, que herda Ingresso e possui um valor adicional. Crie um método que retorne o valor do ingresso VIP (com o adicional incluído). b. crie uma classe Normal, que herda Ingresso e possui um método que imprime: "Ingresso Normal". c. crie uma classe CamaroteInferior (que possui a localização do ingresso e métodos para acessar e imprimir esta localização) e uma classe CamaroteSuperior, que é mais cara (possui valor adicional). Esta última possui um método para retornar o valor do ingresso. Ambas as classes herdam a classe VIPame. ''' class Ingresso(): def preco_ingresso(self): pass class IngressoVip(Ingresso): def preco_ingresso(self): valor_ingresso=200.00 # def ing_vip(self): valor_temp=float(input("digite o valor adiciona do camarote vip com relação " "ao ingresso normal {0:.2f} : ".format(valor_ingresso))) ingresso_vip = valor_temp + valor_ingresso print("o preço do ingresso VIP é {0:.2f}".format(ingresso_vip)) class IngressoNormal(Ingresso): def preco_ingresso(self): valor_ingresso = 200.00 #def ing_normal(self): print("o preço do ingresso normal é de {0:.2f}".format(valor_ingresso)) class CamaroteInferior(Ingresso): def preco_ingresso(self): valor_ingresso = 200.00 # def camarote_inf(self): preco_temp=float(input('digite o preço adicional do camarote inferior com ' 'relação ao preco normal de {0:.2f} : '.format(valor_ingresso))) local_cam_inf=input("digite o local onde se solcaliza o camarote inferior: ") cama_inf=preco_temp + valor_ingresso print("o preço do camarote inferior é de {0:.2f} e esta localizado: {1}" .format(cama_inf,local_cam_inf)) class CamaroteSuperior(Ingresso): def preco_ingresso(self): valor_ingresso = 200.00 #def camarote_sup(self): preco_temp = float(input( 'digite o preço adicional do camarote superior com' ' relação ao preco normal de {0:.2f} : '.format( valor_ingresso))) local_cam_sup = input("digite o local onde se solcaliza o camarote superior: ") cama_sup = preco_temp + valor_ingresso print("o preço do camarote superior é de {0:.2f} e esta localizado: {1}" .format(cama_sup, local_cam_sup)) menu=True while menu: op = int(input("1- para o preço do ingreso normal\n" "2- para o preço do ingreso VIP\n" "3- para o preço do ingreso do camarote inferior\n" "4- para o preço do ingreso do camarote superior\n" "5- para sair\n" "opção: ")) if op==1: normal=IngressoNormal() normal.preco_ingresso() elif op==2: vip=IngressoVip() vip.preco_ingresso() elif op==3: inferior=CamaroteInferior() inferior.preco_ingresso() elif op ==4: superior=CamaroteSuperior() superior.preco_ingresso() elif op ==5: menu=False
#12 - Ler dois valores # (considere que não serão lidos valores iguais) e escrever o maior deles. num2=0 num1=0 repetido=True while repetido: num1=int(input("digite um numero a ser comparado: ")) num2=int(input("digite um numero a ser comparado e que não seja repetido: ")) if num1!=num2: repetido=False else: print("numero igual, repita de novo\n") if num1>num2: print("o numero maior é o: ",num1,", o menor é o: ",num2) elif num2>num1: print("o numero maior é o: ",num2,", o menor é o: ",num1)
# 9 - faça um método que receba um número X e uma palavra no console e # repita x vezes a essa frase. num=input("digite uma palavra: ") quant=int(input("digite a quantidade de vezes que se deseja printar este numero: ")) for i in range(quant): print(num)
import torch import torch.nn as nn X = torch.tensor([[1], [2], [3], [4]], dtype=torch.float32) Y = torch.tensor([[2], [4], [6], [8]], dtype=torch.float32) X_test = torch.tensor([5], dtype=torch.float32) #Create an Xtest tensor for testing n_samples, n_features = X.shape print(n_samples, n_features) input_size = n_features output_size = n_features #Model model = nn.Linear(input_size,output_size) print(f'Prediction before training: f(5) = {model(X_test).item():.3f}') #call the item() method since X_test consists of only one item to obtain the float value #Training Loop learning_rate = 0.01 n_iters = 100 loss = nn.MSELoss() #Mean Squared Error loss optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) for epoch in range(n_iters): #forward pass y_pred = model(X) l = loss(Y, y_pred) l.backward() optimizer.step() optimizer.zero_grad() #To empty gradient after each iteration step if epoch % 10 == 0: #print at every 10 step [w,b] = model.parameters() print(f'epoch {epoch+1}: w = {w[0][0].item():.3f}, loss = {l:.8f}') print(f'Prediction after training: f(5) = {model(X_test).item():.3f}')
""" Hi, here's your problem today. This problem was recently asked by Microsoft: Given the root of a binary tree, print its level-order traversal. For example: 1 / \ 2 3 / \ 4 5 The following tree should output 1, 2, 3, 4, 5. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def print_level_order(root): # Fill this in. root = Node(1, Node(2), Node(3, Node(4), Node(5))) print_level_order(root) # 1 2 3 4 5 Upgrade to PRO and get in-depth solutions to every problem from ex-Google and ex-Facebook engineers TechLead and Joma. Ready to fast-track your career? Join our premiere tech interview training program techinterviewpro.com. If you liked this problem, let your friends know at dailyinterviewpro.com. Have a great day! """ ''' ScriptGeek's solution: Start with the root node, push it onto a stack. Actually, this root node will be placed in an array and then the array will be pushed onto a stack. The array represents all the nodes on the same level. The root node is lonely all by itself on its level so it is the only one that goes into the array. So while the stack has a level within, pop the level off the stack and iterate through its contents (nodes). Append the value of each node to a string. If each node has a child place the child in an array. After the iterative loop, if the array has any nodes within, push this array onto the stack. Repeat until the stack is empty. ''' class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def print_level_order(root): s = [] s.append([root]) output = "" while (len(s) > 0): level = s.pop() nextlevel = [] for n in level: output += str(n.val) + " " if (n.left != None): nextlevel.append(n.left) if (n.right != None): nextlevel.append(n.right) if (len(nextlevel) > 0): s.append(nextlevel) print (output) root = Node(1, Node(2), Node(3, Node(4), Node(5))) print_level_order(root) # 1 2 3 4 5
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. Given a stack of N elements, interleave the first half of the stack with the second half reversed using only one other queue.This should be done in-place. Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue. For example, if the stack is [1, 2, 3, 4, 5], it should become [1, 5, 2, 4, 3]. If the stack is [1, 2, 3, 4], it should become [1, 4, 2, 3]. Hint: Try working backwards from the end state. Upgrade to premium and get in-depth solutions to every problem, including this one. Since you were referred by one of our affiliates, you'll get a 10% discount on checkout! If you liked this problem, feel free to forward it along so they can subscribe here! As always, shoot us an email if there's anything we can help with! Ready to interview? Take Triplebyte's quiz and skip straight to final interviews with top tech companies! """ def stack_interleave(stack): q = [] count = 1 # start at 1st value in stack while(count < len(stack)): temp = stack.pop() subcount = len(stack) while(subcount > count): subcount -= 1 q.append(stack.pop()) stack.append(temp) while(len(q)>0): stack.append(q.pop(0)) count += 1 return stack print(f"[1,2,3,4,5]: {stack_interleave([1,2,3,4,5])}") print(f"[1,2,3,4]: {stack_interleave([1,2,3,4])}")
""" Hi, here's your problem today. This problem was recently asked by Facebook: Starting at index 0, for an element n at index i, you are allowed to jump at most n indexes ahead. Given a list of numbers, find the minimum number of jumps to reach the end of the list. Example: Input: [3, 2, 5, 1, 1, 9, 3, 4] Output: 2 Explanation: The minimum number of jumps to get to the end of the list is 2: 3 -> 5 -> 4 Here's a starting point: def jumpToEnd(nums): # Fill this in. print jumpToEnd([3, 2, 5, 1, 1, 9, 3, 4]) # 2 """ # ScriptGeek's solution: """ My solution uses an n-ary tree. The input array of values is used to generate this tree. Each relationship between index positions within the array is represented in the tree. After all relationships are created the determination is complete. At each point where the node for the last index position is created a depth comparison is made. The depth of the node is the same as the number of jumps. If the depth of the node is lesser than the previously determined depth, then this value becomes the new depth. When all the nodes are created the depth is returned. """ # class used for building an n-ary tree data structure class Node: def __init__(self, name, index, value): self.name = name self.index = index self.value = value self.children = [] self.depth = 0 self.parent = None # calculates all possible pathways which can be taken to get the 1st element jumped # over to the last element position and returns the least number of jumps. def jumpToEnd(nums): # create the root node and push it to the stack node = Node("root", 0, nums[0]) stack = [] stack.append(node) minDepthToLastIndexPos = len(nums) # iterate until there are no more nodes in the stack while (len(stack) > 0): node = stack.pop() clamp_max = len(nums) clamp_min = node.index + 1 # clamp the index positions to the input array size fromIndex = min(clamp_max, max(clamp_min, node.index + 1)) toIndex = min(clamp_max, max(clamp_min, node.index + 1 + node.value)) # if node is for last position and the depth is lesser, remember this depth if (node.index == len(nums) - 1): if (minDepthToLastIndexPos > node.depth): minDepthToLastIndexPos = node.depth # remember this node as the parent node parentNode = node # add all the children for i in range(fromIndex, toIndex): node = Node(str(nums[i]), i, nums[i]) node.parent = parentNode node.depth = parentNode.depth + 1 stack.append(node) return minDepthToLastIndexPos # test this solution value = jumpToEnd([3,2,5,1,1,9,3,4]) print (f"minimum number of jumps: {value}")
#Matthew Lee #GUI Math Quiz Test v2.2 - 07/03/2021 #IMPORTS import random from tkinter import * from tkinter import Tk #FUNCTIONS class Math(): def __init__(self, parent): self.name = "" self.age = 0 self.result = 0 """Welcome""" self.Welcome = Frame(parent) self.Welcome.grid(row=0, column=0) #title self.TitleLabel = Label(self.Welcome, text = "Welcome", bg = "light blue", fg = "white", width = 20, padx = 30, pady = 10, font = ("comic sans ms", "14", "bold italic")) self.TitleLabel.grid(row = 0, columnspan = 2) #Enter name - Label and Enter self.LabelName = Label(self.Welcome, text = "Enter Name: ", fg = "black", padx = 5, pady = 5, font = ("comic sans ms", "10", "bold italic")) self.LabelName.grid(row = 1, column = 0) self.EnterName = Entry(self.Welcome) self.EnterName.grid(row = 1, column = 1) #Enter age - Label and Enter self.LabelAge = Label(self.Welcome, text = "Enter Age: ", fg = "black", padx = 5, pady = 5, font = ("comic sans ms", "10", "bold italic")) self.LabelAge.grid(row = 2, column = 0) self.EnterAge = Entry(self.Welcome) self.EnterAge.grid(row = 2, column = 1) #Return self.Return = Label(self.Welcome, fg = "red", font = ("comic sans ms", "10", "italic")) self.Return.grid(row = 3, column = 1) self.Return.configure(text = "") #Difficulty Buttons self.LabelDiff = Label(self.Welcome, text = "Select difficulty", fg = "black", padx = 5, pady = 5, font = ("comic sans ms", "10", "bold italic")) self.LabelDiff.grid(row = 4, column = 0) #setup self.difficulty_list = ["Easy", "Medium", "Hard"] self.diff_lvl = StringVar() self.diff_lvl.set(0) self.diff_btns = [] #Radio button creation for i in range(len(self.difficulty_list)): rb = Radiobutton(self.Welcome, variable = self.diff_lvl, value = i, text = self.difficulty_list[i], anchor = W, padx = 50, width = "5", height = "2") self.diff_btns.append(rb) rb.grid(row = i+5, column = 0, sticky = W) #Button to quiz self.Toquiz = Button(self.Welcome, text = "Next", activebackground = "yellow", command = lambda:[self.UserDetails(), self.QuestionGen()]) self.Toquiz.grid(row = 8, column = 0) """Quiz""" #set score global score global count score = 0 count = 0 self.Quiz = Frame(parent) #Title Banner self.TitleQuiz = Label(self.Quiz, text = "Question 1 \nScore: 0/5", bg = "light blue", fg = "white", width = 20, padx = 30, pady = 10, font = ("comic sans ms", "14", "bold italic")) self.TitleQuiz.grid(row = 0, columnspan = 2) #Question self.Question = Label(self.Quiz, padx = 5, pady = 5, font = ("comic sans ms", "10")) self.Question.grid(row = 1, column = 0) #Answer box self.AnswerBox = Entry(self.Quiz) self.AnswerBox.grid(row = 1, column = 1) #Check Answer box self.ButtonCheck = Button(self.Quiz, text = "Check Answer", activebackground = "yellow", command = lambda:[self.Check()]) self.ButtonCheck.grid(row = 2, column = 0) #Feedback self.feedback = Label(self.Quiz, padx = 5, pady = 5, font = ("comic sans ms", "10")) self.feedback.grid(row = 2, column = 1) """Score""" self.Score_page = Frame(parent) #Title self.TitleScore = Label(self.Score_page, text = "YOUR SCORE", bg = "light blue", fg = "white", width = 20, padx = 30, pady = 10, font = ("comic sans ms", "14", "bold italic")) self.TitleScore.grid(row = 0, columnspan = 4) #Report Report_info = ["Name", "Age", "Score"] self.report_labels = [] for i in range(len(Report_info)): ColumnHeading = Label(self.Score_page, text = Report_info[i], width = "7", height = "2", font = ("comic sans ms", "14", "bold")) self.report_labels.append(ColumnHeading) ColumnHeading.grid(row = 1, column = i) #User Details self.name_display = Label(self.Score_page, textvariable = self.name) self.name_display.grid(row = 2, column = 0) self.age_display = Label(self.Score_page, text = "") self.age_display.grid(row = 2, column = 1) self.result_display = Label(self.Score_page, text = "") self.result_display.grid(row = 2, column = 2) #Home Button self.ButtonHome = Button(self.Score_page, text = "Home", activebackground = "yellow", command = lambda:[self.ShowWelcome()]) self.ButtonHome.grid(row = 3, column = 0) """FUNCTIONS""" def End(self): #Should run when count reaches 5 self.Quiz.grid_remove() self.name_display.configure(text = self.name) self.age_display.configure(text = self.age) self.result_display.configure(text = self.result) #Open score page self.Score_page.grid() def ShowQuiz(self): #Removes Welcome and plays self.Welcome.grid_remove() self.Quiz.grid() def ShowWelcome(self): #Clears user details for next user self.EnterName.delete(0, 'end') self.EnterAge.delete(0, 'end') #Removes Quiz and shows welcome self.Score_page.grid_remove() self.Welcome.grid() def UserDetails(self): #Check age if self.EnterName.get() == "": self.Return.configure(text = "Please enter \nyour name!") else: try: if int(self.EnterAge.get()) <= 5: self.Return.configure(text = "You're too young!") elif int(self.EnterAge.get()) >= 16: self.Return.configure(text = "You're too old!") else: self.ShowQuiz() except ValueError: self.Return.configure(text = "Please enter your \nage in numbers") def QuestionGen(self): #Generate questions #list num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #Picks numbers self.number_1 = random.choice(num_list) self.number_2 = random.choice(num_list) self.total = self.number_1 + self.number_2 self.add = self.number_1, "+", self.number_2, "=" #config self.Question.configure(text = self.add) def Check(self): global score global count try: self.answer = self.AnswerBox.get() self.answer_mod = int(self.answer) #Clears self.AnswerBox.delete(0, 'end') if self.answer_mod == self.total: self.feedback.configure(text = "Correct!") #Adds score += 1 count += 1 self.TitleQuiz.configure(text = "Question {} \nScore: {}/5".format(count + 1, score)) #Question count check if count == 5: #Collect Info self.name = self.EnterName.get() self.age = str(self.EnterAge.get()) self.result = str(score) #reset score = 0 count = 0 self.End() else: self.QuestionGen() else: self.feedback.configure(text = "Incorrect!") count += 1 self.TitleQuiz.configure(text = "Question {} \nScore: {}/5".format(count + 1, score)) if count == 5: #Collect Info self.name = self.EnterName.get() self.age = str(self.EnterAge.get()) self.result = str(score) #reset score = 0 count = 0 self.End() else: self.QuestionGen() except ValueError: self.feedback.configure(text = "Please enter \na number") """MAINLOOP""" #Begin code if __name__ == "__main__": root = Tk() frames = Math(root) root.title("Math quiz") root.mainloop()
#################################### # Location Functions #################################### #################################### # adapted from # https://www.freecodecamp.org/forum/t/make-a-script-read-gps-geolocation/241607 #################################### import requests import math def getUserLocation(): ipRequest = requests.get("https://get.geojs.io/v1/ip.json") userIp = ipRequest.json()["ip"] geoRequestUrl = "https://get.geojs.io/v1/ip/geo/" + userIp + ".json" geoRequest = requests.get(geoRequestUrl) geoData = geoRequest.json() userLocation = {"latitude" : float(geoData["latitude"]), "longitude" : float(geoData["longitude"]), "city" : geoData["city"]} return userLocation #################################### # adapted from # https://nathanrooy.github.io/posts/2016-09-07/haversine-with-python/ #################################### # apply Haversine formula to calculate distance between two coordinate points def getDistance(lat1, long1, lat2, long2, unit): if lat1 is None or long1 is None or lat2 is None or long2 is None: return None # formula r = 6371000 # radius of Earth in meters phi1 = math.radians(lat1) phi2 = math.radians(lat2) deltaPhi = math.radians(lat2 - lat1) deltaLambda = math.radians(long2 - long1) a = math.sin(deltaPhi / 2.0) ** 2 + \ math.cos(phi1) * math.cos(phi2) * \ math.sin(deltaLambda / 2.0) ** 2 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) # output in various units distance = {"meters" : r * c, "km" : (r * c) / 1000.0, "miles" : (r * c) * 0.000621371} return distance[unit]
from matplotlib import colors import numpy as np from numpy.core.fromnumeric import argmax from tqdm import tqdm import pandas as pd import matplotlib.pyplot as plt class NeuralNetwork: """ Feedforward neural network / Multi-layer perceptron classifier. Uses back propagation to optimise the error function Parameters: iterations : Number of Epochs hiddenUnits : Number of neurons in the hidden layer eta : Learning rate """ def __init__(self, iteration = 1000, eta= 0.01, hiddenUnits = 15): self.iteration = iteration self.eta = eta self.hiddenUnits = hiddenUnits def sigmoid(self, v): """Compute the logistic function()sigmoid""" return 1 / (1 + np.exp(-np.clip(v, -250, 250))) def forward(self, X): """ This method takes a datapoint, pass it through the forward path of neural network and returns the induced local field and activation scores of the output layer """ netInputHidden = np.dot(self.weight_h.T, X) + self.bias_h netOutHidden = self.sigmoid(netInputHidden) self.netInputOuterLayer = np.dot(self.weight_o.T, netOutHidden) + self.bias_o netOutOuterLayer = self.sigmoid(self.netInputOuterLayer) return netOutHidden, netOutOuterLayer def derivativeSigmoid(self, v): """Compute the derivative of logistic function()sigmoid""" return v * (1 - v) def fittingWithBackPropagation(self, dataset, label, validationX, validationLabel): """ This method takes training and testing dataset, trains the model on the given dataset by using the backpropagation and plots the loss vs epoch and accuracy vs epoch curve. It also prints out the accuracies on the training as well as testing set """ #Initialisation of parameters self.weight_h = np.random.normal(0, 0.1, (dataset.shape[1], self.hiddenUnits)) self.weight_o = np.random.normal(0, 0.1, (self.hiddenUnits, label.shape[1])) self.bias_h = np.random.normal(0, 0.1, (self.hiddenUnits)) self.bias_o = np.random.normal(0, 0.1, (label.shape[1])) validationAccuracies = [] trainingAccuracies = [] error = [] validationError = [] for _ in tqdm(range(self.iteration)): averageTrainingError = 0 averageValidationError = 0 for datapoint, d in zip(dataset, label): y_hidden, y_out = self.forward(datapoint) e = d - y_out averageTrainingError += 0.5 * np.sum((d - y_out) ** 2) deltaOut = e * self.derivativeSigmoid(y_out) self.weight_o = self.weight_o + self.eta * np.outer(y_hidden, deltaOut) self.bias_o = self.bias_o + self.eta * deltaOut deltaHidden = self.derivativeSigmoid(y_hidden) * np.sum(np.dot(self.weight_o, deltaOut)) self.weight_h = self.weight_h + self.eta * np.outer(datapoint, deltaHidden) self.bias_h = self.bias_h + self.eta * deltaHidden for datapoint, d in zip(validationX, validationLabel): y_hidden, y_out = self.forward(datapoint) averageValidationError += 0.5 * np.sum((d - y_out) ** 2) averageTrainingError /= dataset.shape[0] averageValidationError /= validationX.shape[0] validationError.append(averageValidationError) error.append(averageTrainingError) trainingAccuracies.append(accuracy(self, dataset, label)) validationAccuracies.append(accuracy(self, validationX, validationLabel)) self.plot(trainingAccuracies, validationAccuracies, error, validationError) def plot(self, trainigAccuracy, validationAccuracy, error, validationError): movingAverage = 10 smoothenedTrainigAccuracy = [] smoothenedTestingAccuracy = [] smoothenedTrainigError = [] smoothenedTestingError = [] #smoothing the loss and accuracy on moving average of 10 for i in range(0, self.iteration, movingAverage): smoothenedTrainigAccuracy.append(sum(trainigAccuracy[i:i+movingAverage])/movingAverage) smoothenedTestingAccuracy.append(sum(validationAccuracy[i:i+movingAverage])/movingAverage) smoothenedTrainigError.append(sum(error[i:i+movingAverage])/movingAverage) smoothenedTestingError.append(sum(validationError[i:i+movingAverage])/movingAverage) f, (ax1,ax2) = plt.subplots(2, 1, sharex=True) ax1.plot(range(0, self.iteration, movingAverage), smoothenedTrainigError, color = "r", label = "Training") ax1.plot(range(0, self.iteration, movingAverage), smoothenedTestingError, color = "g", label = "Validation") ax1.legend() ax1.set_title("Error VS Iterations") ax1.set_ylabel("Error Function") ax2.plot(range(0, self.iteration, movingAverage), smoothenedTrainigAccuracy, color = "r", label = "Training") ax2.plot(range(0, self.iteration, movingAverage), smoothenedTestingAccuracy, color = "g", label = "Validation") ax2.set_title("Accuracy VS Iterations") ax2.set_xlabel("Iterations") ax2.set_ylabel("Accuracy(%)") ax2.legend() plt.suptitle('Hidden Units "' + str(self.hiddenUnits) + '"' + ' and Learning rate "' + str(self.eta) + '"') plt.show() def takeHyperParameters(): print("\nEnter the following hyperparameters\n") iterations = int(input("Enter the number of Epochs for which you want to train the model : ")) eta = float(input("Enter the value of learning rate : ")) hiddenUnits = int(input("Enter the number of hidden units : ")) return iterations, eta, hiddenUnits def accuracy(nn, X, y): Tp = 0 for data, d in zip(X, y): a,b = nn.forward(data) if argmax(b) == argmax(d): Tp += 1 accuracy = round(Tp/y.shape[0] * 100, 2) return accuracy def crab(): with open("crabData.csv") as file: data = [] for line in file: data.append(line.strip().split(",")) file.close() np.random.seed(4738) data = np.array(data) data = data[1:,:] np.random.shuffle(data) dataDivisior = int(data.shape[0]*0.8) X = data[:dataDivisior, 3:].astype(np.float) validationX = data[dataDivisior:, 3:].astype(np.float) Y = np.array(pd.get_dummies(data[:, 1])) trainingLabel = Y[:dataDivisior,:] validationLabel = Y[dataDivisior:,:] iterations, eta, hiddenUnits = takeHyperParameters() network = NeuralNetwork(iteration = iterations,hiddenUnits=hiddenUnits, eta= eta) network.fittingWithBackPropagation(X, trainingLabel, validationX, validationLabel) print("Training Accuracy : " + str(accuracy(network, X, trainingLabel)) + "%") print("Testing Accuracy : " + str(accuracy(network, validationX, validationLabel)) + "%") def Iris(): df = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/iris/iris.data', header=None) np.random.seed(1210) permutaion = np.random.permutation(150) df = df.iloc[permutaion] Y = np.array(pd.get_dummies(df[4])) data = np.array(df) data = data[:,:4] dataDivisior = int(data.shape[0]*0.8) X = data[:dataDivisior,:].astype(np.float) trainingLabel = Y[:dataDivisior,:] validationLabel = Y[dataDivisior:,:] validationX = data[dataDivisior:, :].astype(np.float) iterations, eta, hiddenUnits = takeHyperParameters() network = NeuralNetwork(iteration = iterations,hiddenUnits=hiddenUnits, eta= eta) network.fittingWithBackPropagation(X, trainingLabel, validationX, validationLabel) print("Training Accuracy : " + str(accuracy(network, X, trainingLabel)) + "%") print("Testing Accuracy : " + str(accuracy(network, validationX, validationLabel)) + "%") def main(): print("\n\t\t\tWelcome") while True: print("\nChoose from the following on which dataset you want to train your model") menu = input("1. Press 1 for Iris dataset(Classification between Setosa, Versicular and Virginka)\n2. Press 2 for Crab dataset(Classification between Male and Female)\n3. Press Q/q to quit : ") if menu == "1": Iris() elif menu == "2": crab() elif menu == "Q" or menu == "q": break else: print("\nEnter Valid Entry\n") if __name__ == "__main__": main()
from matplotlib import colors import numpy as np from numpy.core.fromnumeric import argmax from tqdm import tqdm import pandas as pd import matplotlib.pyplot as plt class NeuralNetwork: """ Feedforward neural network / Multi-layer perceptron classifier. Uses back propagation to optimise the error function Parameters: iterations : Number of Epochs hiddenUnits : Number of neurons in the hidden layer eta : Learning rate mu : Momentum Co efficient """ def __init__(self, iteration = 1000, eta= 0.01, hiddenUnits = 15, mu = 0.1): self.iteration = iteration self.eta = eta self.hiddenUnits = hiddenUnits self.mu = mu def sigmoid(self, v): """Compute the logistic function()sigmoid""" return 1 / (1 + np.exp(-np.clip(v, -250, 250))) def forward(self, X): """ This method takes a datapoint, pass it through the forward path of neural network and returns the induced local field and activation scores of the output layer """ netInputHidden = np.dot(self.weight_h.T, X) + self.bias_h netOutHidden = self.sigmoid(netInputHidden) netInputOuterLayer = np.dot(self.weight_o.T, netOutHidden) + self.bias_o netOutOuterLayer = self.sigmoid(netInputOuterLayer) return netOutHidden, netOutOuterLayer def derivativeSigmoid(self, v): """Compute the derivative of logistic function()sigmoid""" return v * (1 - v) def fittingWithBackPropagation(self, dataset, label, validationX, validationLabel): """ This method takes training and testing dataset, trains the model on the given dataset by using the backpropagation and plots the loss vs epoch and accuracy vs epoch curve. It also prints out the accuracies on the training as well as testing set """ np.random.seed(100) #Initialisation of parameters self.weight_h = np.random.normal(0, 0.1, (dataset.shape[1], self.hiddenUnits)) self.weight_o = np.random.normal(0, 0.1, (self.hiddenUnits, label.shape[1])) self.bias_h = np.random.normal(0, 0.1, (self.hiddenUnits)) self.bias_o = np.random.normal(0, 0.1, (label.shape[1])) update_o = np.zeros(self.weight_o.shape) update_h = np.zeros(self.weight_h.shape) validationAccuracies = [] trainingAccuracies = [] trainingError = [] validationError = [] for _ in tqdm(range(self.iteration)): #Going through each epoch averageTrainingError = 0 averageValidationError = 0 for datapoint, d in zip(dataset, label): #Going through each datapoint #Going through foward path y_hidden, y_out = self.forward(datapoint) #Doing back propagation e = d - y_out averageTrainingError += 0.5 * np.sum((d - y_out) ** 2) deltaOut = e * self.derivativeSigmoid(y_out) update_o = self.eta * np.outer(y_hidden, deltaOut) + self.mu * update_o self.weight_o = self.weight_o + update_o self.bias_o = self.bias_o + self.eta * deltaOut deltaHidden = self.derivativeSigmoid(y_hidden) * np.sum(np.dot(self.weight_o, deltaOut)) update_h = self.eta * np.outer(datapoint, deltaHidden) + self.mu * update_h self.weight_h = self.weight_h + update_h self.bias_h = self.bias_h + self.eta * deltaHidden # Going through validation data and tracking the error and accuracies for datapoint, d in zip(validationX, validationLabel): y_hidden, y_out = self.forward(datapoint) averageValidationError += 0.5 * np.sum((d - y_out) ** 2) averageTrainingError /= dataset.shape[0] averageValidationError /= validationX.shape[0] validationError.append(averageValidationError) trainingError.append(averageTrainingError) trainingAccuracies.append(accuracy(self, dataset, label)) validationAccuracies.append(accuracy(self, validationX, validationLabel)) #Plotting the accuracy vs epoch and accuracy vs loss curves self.plot(trainingAccuracies, validationAccuracies, trainingError, validationError) def plot(self, trainigAccuracy, validationAccuracy, trainingError, validationError): """ This method takes the error function and accuracy of training and validation set and plot their curves """ movingAverage = 10 smoothenedTrainigAccuracy = [] smoothenedValidationAccuracy = [] smoothenedTrainigError = [] smoothenedValidationError = [] #Smoothening the loss and accuracy curves over the moving average of 10 for i in range(0, self.iteration, movingAverage): smoothenedTrainigAccuracy.append(sum(trainigAccuracy[i:i+movingAverage])/movingAverage) smoothenedValidationAccuracy.append(sum(validationAccuracy[i:i+movingAverage])/movingAverage) smoothenedTrainigError.append(sum(trainingError[i:i+movingAverage])/movingAverage) smoothenedValidationError.append(sum(validationError[i:i+movingAverage])/movingAverage) f, (ax1,ax2) = plt.subplots(2, 1, sharex=True) ax1.plot(range(0, self.iteration, movingAverage), smoothenedTrainigError, color = "r", label = "Training") ax1.plot(range(0, self.iteration, movingAverage), smoothenedValidationError, color = "g", label = "Validation") ax1.legend() ax1.set_title("Error VS Iterations") ax1.set_ylabel("Error Function") ax2.plot(range(0, self.iteration, movingAverage), smoothenedTrainigAccuracy, color = "r", label = "Training") ax2.plot(range(0, self.iteration, movingAverage), smoothenedValidationAccuracy, color = "g", label = "Validation") ax2.set_title("Accuracy VS Iterations") ax2.set_xlabel("Iterations") ax2.set_ylabel("Accuracy(%)") ax2.legend() plt.suptitle('Hidden Units "' + str(self.hiddenUnits) + '"' + ', Learning rate "' + str(round(self.eta, 2)) + '"' + ' and Momentum coeficient "' + str(round(self.mu, 2)) + '"') plt.show() def takeHyperParameters(): '''This function takes the hyperparameters from the user and return these hyoer parameters''' print("\nEnter the following hyperparameters\n") iterations = int(input("Enter the number of Epochs for which you want to train the model : ")) eta = float(input("Enter the value of learning rate : ")) hiddenUnits = int(input("Enter the number of hidden units : ")) mu = float(input("Enter the momentum coefficient : ")) return iterations, eta, hiddenUnits, mu def accuracy(nn, X, y): """ This method takes the dataset and runs it through the forward path of the network, gets the activation score of the output layer, check it against the given label and give a prediction about which class it belongs to. By taking the account of true predictions, at the end it returns the accuracy of the model on the dataset """ tp = 0 for data, d in zip(X, y): a,b = nn.forward(data) if argmax(b) == argmax(d): tp += 1 accuracy = round(tp/y.shape[0] * 100, 2) return accuracy def crab(): """ This method loads the crab dataset and train a neural network model the dataset """ #Loading the crab dataset with open("crabData.csv") as file: data = [] for line in file: data.append(line.strip().split(",")) file.close() np.random.seed(4738) #Cleaning and splitting the data in training and testing data data = np.array(data) data = data[1:,:] np.random.shuffle(data) dataDivisior = int(data.shape[0]*0.8) X = data[:dataDivisior, 3:].astype(np.float) validationX = data[dataDivisior:, 3:].astype(np.float) #One hot encoding the labels Y = np.array(pd.get_dummies(data[:, 1])) trainingLabel = Y[:dataDivisior,:] validationLabel = Y[dataDivisior:,:] iterations, eta, hiddenUnits, mu = takeHyperParameters() #initialising and training the network network = NeuralNetwork(iteration = iterations,hiddenUnits=hiddenUnits, eta= eta, mu = mu) network.fittingWithBackPropagation(X, trainingLabel, validationX, validationLabel) print("Training Accuracy : " + str(accuracy(network, X, trainingLabel)) + "%") print("Testing Accuracy : " + str(accuracy(network, validationX, validationLabel)) + "%") def Iris(): """ This method loads the Iris dataset and train a neural network model the dataset """ #Loading the Iris Dataset df = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/iris/iris.data', header=None) np.random.seed(1210) #Cleaning and splitting the data in training and testing data permutaion = np.random.permutation(150) df = df.iloc[permutaion] #One hot encoding the labels Y = np.array(pd.get_dummies(df[4])) data = np.array(df) data = data[:,:4] dataDivisior = int(data.shape[0]*0.8) X = data[:dataDivisior,:].astype(np.float) trainingLabel = Y[:dataDivisior,:] validationLabel = Y[dataDivisior:,:] validationX = data[dataDivisior:, :].astype(np.float) iterations, eta, hiddenUnits, mu = takeHyperParameters() #initialising and training the network network = NeuralNetwork(iteration = iterations,hiddenUnits=hiddenUnits, eta= eta, mu = mu) network.fittingWithBackPropagation(X, trainingLabel, validationX, validationLabel) print("Training Accuracy : " + str(accuracy(network, X, trainingLabel)) + "%") print("Testing Accuracy : " + str(accuracy(network, validationX, validationLabel)) + "%") def main(): """This method ask the user about the dataset on which you want to train your model and direct the program to that dataset""" print("\n\t\t\tWelcome") while True: print("\nChoose from the following on which dataset you want to train your model") menu = input("1. Press 1 for Iris dataset(Classification between Setosa, Versicular and Virginka)\n2. Press 2 for Crab dataset(Classification between Male and Female)1\n3. Press Q/q to quit : ") if menu == "1": Iris() elif menu == "2": crab() elif menu == "Q" or menu == "q": break else: print("\nEnter Valid Entry\n") if __name__ == "__main__": main()
# 1. count() - call t his method to count specific char in string # 2. upper() - Call this method to return an upper case version of any string. # 3. lower() - Call this method to return a lower case version of any string. # 4. provide comparision example using a .lower() method # 5. islower() - call this method to check if string is lowercase or not # 6. isupper() - call this method to check if string is uppercase or not some_string = "Lorem ipsum dolor sit amet, an postulant conclusionemque eum. Ex deleniti pertinax est, mei probo euismod intellegebat at. Fierent indoctum vel cu. Qui graeci maiorum nominavi ei, ex nonumy ponderum duo. Atqui quidam mea te. Ius accusamus cotidieque at, et duo aliquip dolores, munere iudicabit expetendis eu his. Ignota delicatissimi pri ne, magna harum te est, cu eum laudem legendos." # 1. count() - call t his method to count specific char in string print('there are ' + str(some_string.count('a')) + '\'a\'found in given text') print('===============================') # 2. upper() - Call this method to return an upper case version of any string. print(some_string.upper()) print('===============================') # note: the original string is still the same, print(some_string) print('===============================') # 3. lower() - Call this method to return a lower case version of any string. print(some_string.lower()) print('===============================') # 4. provide comparison example using a .lower() method '''user can enter any value(uppercase or lowercase) in form of input, logic should be able to compare it''' user_input = input('Play again(Yes/No): ') while user_input.lower() == 'yes': user_input = input('Play again(Yes/No): ') print('Ok, bye!') print('===============================') # 5. islower() - call this method to check if string is lowercase or not print (some_string.islower()) #now change the string to lowercase using the lower() method some_string = some_string.lower() #check again print (some_string.islower()) print('===============================') # 6. isupper() - call this method to check if string is uppercase or not print (some_string.isupper()) #now change the string to uppercase using the upper() method some_string = some_string.upper() #check again print (some_string.isupper()) print('===============================')
import time import calendar # 时间戳 print(time.time()) # 获取当前时间 localtime = time.localtime(time.time()) print("本地时间为 :", localtime) # 格式化时间 localtime = time.asctime(time.localtime(time.time())) print("本地时间为 :", localtime) # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 将格式字符串转换为时间戳 a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y"))) cal = calendar.month(2016, 1) print("以下输出2016年1月份的日历:") print(cal) print("Start : %s" % time.ctime()) # 线程睡眠5秒 time.sleep(5) print("End : %s" % time.ctime())
# -*- coding: UTF-8 -*- import time import calendar ticks = time.time() print(ticks) print(time.localtime(time.time())) localtime = time.asctime(time.localtime(time.time())) print("本地时间为 :", localtime) # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 将格式字符串转换为时间戳 a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y"))) import calendar cal = calendar.month(2017, 11) print("以下输出2017年11月份的日历:") print(cal) def printme(str): "打印传入的字符串到标准显示设备上" print(str) return printme("我要调用用户自定义函数!") printme(str="我要调用用户自定义函数!") # 可写函数说明 def printinfo(name, age=35): "打印任何传入的字符串" print("Name: ", name); print("Age ", age); return; # 调用printinfo函数 printinfo(age=50, name="miki"); printinfo(name="miki"); # 可写函数说明 def printinfo(arg1, *vartuple): "打印任何传入的参数" print("输出: ") print(arg1) for var in vartuple: print(var) return # 调用printinfo 函数 printinfo(10); printinfo(70, 60, 50); sum = lambda arg1, arg2: arg1 + arg2 printme(sum(1, 2))
"""Unit tests for the TravelPoint class. A TravelPoint stores information about a given location that is part of a journey. The attributes include name, departure_time and arrival_time. """ import unittest # Standard unittest framework. import location # The module implementing the TravelPoint class. class TestTravelPoint(unittest.TestCase): """Tests for the TravelPoint class.""" def test_invalid_arrival_time_is_rejected(self): """A ValueError is raised if the arrival time is not valid.""" with self.assertRaises(ValueError) as cm: location.TravelPoint( 'Narnia', '2019/13/15 10:20', '2019/10/15 10:00') self.assertEqual( 'The departure_time must have the format YYYY/MM/DD HH:MM', str(cm.exception)) def test_invalid_departure_time_is_rejected(self): """A ValueError is raised if the departure time is not valid.""" with self.assertRaises(ValueError) as cm: location.TravelPoint( 'Narnia', '2019/10/15 10:20', '2019/10/15 10:') self.assertEqual( 'The arrival_time must have the format YYYY/MM/DD HH:MM', str(cm.exception)) def test_departure_time_may_be_none(self): """The departure time may be None.""" location.TravelPoint( 'Narnia', arrival_time='2019/10/15 10:00', departure_time=None) def test_arrival_time_may_be_none(self): """The departure time may be None.""" location.TravelPoint( 'Narnia', departure_time='2019/10/15 10:20', arrival_time=None) def test_only_time_may_be_none(self): """Both times cannot be None.""" with self.assertRaises(ValueError) as cm: location.TravelPoint( 'Narnia', arrival_time=None, departure_time=None) self.assertEqual( 'At least one of arrival or departure time must be set', str(cm.exception)) if __name__ == '__main__': unittest.main()
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def eat(self): pass class Mammal(Animal): def eat(self): print("nom nom") # @abstractmethod decorator is used so any subclass created must have its own implementation.
class Student(): class_="student" def __init__(self,name,age,mark1,mark2,mark3): self.name = name self.age = age self.mark1 = mark1 self.mark2 = mark2 self.mark3 = mark3 def calcAverage(self): return int(self.mark1 + self.mark2 + self.mark3)/3 Artas = Student("Artas","22", 89, 91, 67) print(Artas.calcAverage())
math = int(input("What is your Maths mark?: ")) phys = int(input("What is your physics mark?: ")) chem = int(input("What is your chemistry mark?: ")) avg = (math + phys + chem) // 3 if avg > 70: print("A") elif avg > 60: print("B") elif avg > 50: print("C") elif avg > 40: print("D") else: print("F You failed")
# Глава 2. Сортировка выбором def find_smallest(arr): smallest = arr[0] smallest_index = 0 for i in range (1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selection_sort(arr): newArr = [] for i in range(len(arr)): smallest = find_smallest(arr) newArr.append(arr.pop(smallest)) return newArr print(selection_sort([5, 3, 6, 2, 10]))
#coding=utf8 import random import math #Функция ввода массива случайных натуральных чисел #(для удобства тестирования) def randArr(length): numbers = [] for i in range(length): numbers.append(random.randint(0,100)) return numbers #Функция ввода массива натуральных чисел пользователем def arrImput(): print("Введите массив натуральных чисел\nЧисла будут записаны до введения пробела") numbers = [] while(1): number = raw_input() if(number == ' '): break else: if (int(number) < 0): print("Введите натуральное число") else: numbers.append(number) numbers = list(map(int, numbers)) return numbers #Пузырьковая сортировка #Элементы от нулевого до предпоследнего сдвигаются по массиву вправо, пока не встанут слева от большего элемента def bubbleSort(numbers): length = len(numbers)-1 for i in range(length): for j in range(length-i): if(numbers[j+1]<numbers[j]): temp = numbers[j+1] numbers[j+1] = numbers[j] numbers[j] = temp return numbers #Гномья сортировка def gnomeSort(numbers): i = 1 #Массив проверяется, начиная с первого элемента и до последнего while (i<len(numbers)): #Если элемент больше предыдущего, индекс увеливается и происходит шаг по массиву вперед if(numbers[i]>=numbers[i-1]): i += 1 else: #Если элемент меньше предыдущего, они меняются местами tmp = numbers[i-1] numbers[i-1] = numbers[i] numbers[i] = tmp #И происходит шаг назад по массиву i -= 1 if (i == 0): i = 1 return numbers #Блочная сортировка def bucketSort(numbers, depth = 0): numSum = 0 flag = 0 #Создается двухмерный массив блоков #20 блоков для возможности работы с отрицательными числами buckets = [] for i in range(20): buckets.append([]) #Каждое число из заданного массива распределяется по блокам #Индекс блока в массиве блоков для данного числа такой же, как цифра данного числа, находящаяся на порядке таком же, как глубина рекурсии for i in range(len(numbers)): if(numbers[i] < 0): #Для работы с отрицательными числами token = (-1)*numbers[i] flag = 1 else: token = numbers[i] flag = 0 remainder = (token // (10 ** depth))%10 #Определение цифры numSum += remainder #Сумма цифр всех чисел на данном уровне рекурсии #Определение индексов чисел if(flag == 1): index = 9 - remainder else: index = 10 + remainder buckets[index].append(numbers[i]) #Перезапись массива из блоков numIndex = 0 for i in range(20): for j in range(len(buckets[i])): numbers[numIndex] = buckets[i][j] numIndex += 1 depth += 1 #Если в данном порядке цифры всех чисел не равны нулю, переход на следующий уровень рекурсии - седующий порядок if(numSum != 0): bucketSort(numbers, depth) return numbers #Пирамидальная сортировка def heapSort (numbers): #Свап элементов массива def swapItems (i1, i2): if numbers[i1] < numbers[i2]: tmp = numbers[i1] numbers[i1] = numbers[i2] numbers[i2] = tmp #Спуск больших элементов вниз def siftDown (parent, limit): while (1): child = parent * 2 + 2 #выбирается наименьший потомок if child < limit: if numbers[child] < numbers[child - 1]: child -= 1 #выбранный потомок свапается с предком swapItems(parent, child) #за предка принимается потомок parent = child else: break #Тело функции heapSort length = len(numbers) #Формирование первичной пирамиды for i in range((length // 2) - 1, -1, -1): siftDown(i, length) #Окончательное упорядочивание for i in range(length - 1, 0, -1): swapItems(i, 0) siftDown(0, i) return numbers #Ввод массива и вывод результатов сортировок numbers = arrImput() print("Array "+str(numbers)) bubbleSorted = bubbleSort(numbers) print("\nBubble Sort \t"+str(bubbleSorted)) gnomeSorted = gnomeSort(numbers) print("Gnome Sort \t"+str(gnomeSorted)) buckedSorted = bucketSort(numbers) print("Bucket Sort \t" + str(buckedSorted)) heapSorted = heapSort(numbers) print("Heap Sort \t" + str(heapSorted))
import pandas as pd import numpy as np from scipy.io import loadmat import matplotlib.pyplot as plot import scipy.optimize as opt from sklearn.metrics import classification_report ''' Training a neural network 1.Randomly initialize weights 2.Implement forward propagation to get h(x(i)) for any x(i) 3.Implement code to compute cost function J(theta) 4.Implement backprop to compute partial derivatives for i = 1:m: Perform forward propagation and backpropagation using example(x(i), y(i)) (get activations a(l) and delta terms for l = 2.....L) delta(l) = delta(l) + a(l)*delta(l+1) 5.Use gradient checking to compare partial derivatives computed using backpropagation vs. using numerical estimate of gradient of J(theta) Then disable gradient checking code 6.Use gradient descent or advanced optimization method with backpropagation to try to minimize J(theta) as a function of parameters theta ''' init_lamda = 1 epsilon_init = 0.12 epsilon = 0.1E-3 def get_dataset(): #linux下 data = loadmat('/home/y_labor/ml/machine-learning-ex4/ex4/ex4data1.mat') weight = loadmat('/home/y_labor/ml/machine-learning-ex4/ex4/ex4weights.mat') #windows下 # data = loadmat('C:\\Users\ydf_m\Desktop\machinelearning\machine-learning-ex4\ex4\ex4data1.mat') # weight = loadmat('C:\\Users\ydf_m\Desktop\machinelearning\machine-learning-ex4\ex4\ex4weights.mat') x = data['X'] y = data['y'] theta1 = weight['Theta1'] theta2 = weight['Theta2'] return x, y, theta1, theta2 def visual_data(x): select_some = np.random.choice(np.arange(x.shape[0]), 100) image = x[select_some, :] fig, ax_array = plot.subplots(10, 10, sharex=True, sharey=True, figsize=(8, 8)) for row in range(10): for col in range(10): ax_array[row, col].matshow(image[10*row+col].reshape(20, 20)) plot.xticks([]) plot.yticks([]) plot.show() def sigmoid(x): return 1/(1 + np.exp(-x)) def feedforward(x, theta): theta1, theta2 = roll(theta) hidden1_in = np.dot(x, theta1.T) hidden1_out = np.insert(sigmoid(hidden1_in), 0, 1, axis=1) output_in = np.dot(hidden1_out, theta2.T) output_out = sigmoid(output_in) return x, hidden1_in, hidden1_out, output_in, output_out def coding_y(y): coding = np.empty((y.shape[0], 10)) i = 0 for j in y: coding[i] = np.zeros(10) coding[i][j-1] = 1 i += 1 return coding def unroll(theta1, theta2): return np.hstack((theta1.flatten(), theta2.flatten())) def roll(theta): return theta[:25*401].reshape(25, 401), theta[25*401:].reshape(10, 26) def cost(theta, x, y): x, hidden1_in, hidden1_out, output_in, h = feedforward(x, theta) J = 0 for i in range(len(x)): j1 = np.dot(y[i], np.log(h[i])) j2 = np.dot((1 - y[i]), np.log(1 - h[i])) J += -(j1 + j2) return J / len(x) def regularized_cost(theta, x, y, lamda=init_lamda): Theta = 0 theta1, theta2 = roll(theta) for i in range(theta1.shape[0]): Theta += sum(theta1[i, 1:] ** 2) for i in range(theta2.shape[0]): Theta += sum(theta2[i, 1:] ** 2) return cost(theta, x, y) + lamda * Theta / (2 * len(x)) def random_initial(size, epsilon = epsilon_init): return np.random.uniform(-epsilon, epsilon, size) def partial_g(x): return sigmoid(x) * (1 - sigmoid(x)) def gradient(theta, x, y): x, hidden1_in, hidden1_out, output_in, output_out = feedforward(x, theta) theta1, theta2 = roll(theta) # print(hidden1_in.shape, hidden1_out.shape, output_in.shape, output_out.shape, theta1.shape, theta2.shape) delta3 = output_out - y delta2 = np.dot(delta3, theta2[:, 1:]) * partial_g(hidden1_in) partial2 = np.dot(delta3.T, hidden1_out) partial1 = np.dot(delta2.T, x) partial = unroll(partial1, partial2) / len(x) return partial def regularized_gradient(theta, x, y, lamda = init_lamda): x, hidden1_in, hidden1_out, output_in, output_out = feedforward(x, theta) partial1, partial2 = roll(gradient(theta, x, y)) theta1, theta2 = roll(theta) theta1[:, 0] = 0 theta2[:, 0] = 0 partial1 += lamda * theta1 / len(x) partial2 += lamda * theta2 / len(x) partial = unroll(partial1, partial2) return partial def gradient_checking(theta, x, y, e = epsilon): def a_numeric_grad(plus, minus): return (regularized_cost(plus, x, y) - regularized_cost(minus, x, y)) / (2* e) numeric_grad = [] for i in range(len(theta)): plus = theta.copy minus = theta.copy plus[i] = plus[i] + e minus[i] = minus[i] - e grad_i = a_numeric_grad(plus, minus) numeric_grad.append(grad_i) numeric_grad = np.array(numeric_grad) analytic_grad = regularized_gradient(theta, x, y) diff = np.linalg.norm(numeric_grad - analytic_grad) / np.linalg.norm(numeric_grad + analytic_grad) print(diff) def training(x, y): pass init_theta = random_initial(10285) result = opt.minimize(fun=regularized_cost, x0=init_theta, args=(x, y), method='TNC', jac=regularized_gradient) return result def accuracy(theta, x, y): x, hidden1_in, hidden1_out, output_in, output_out = feedforward(x, theta) y_i = np.argmax(output_out, axis=1) + 1 print(classification_report(y, coding_y(y_i))) if __name__ == '__main__': x, y, theta1, theta2 = get_dataset() theta = unroll(theta1, theta2) x = np.insert(x, 0, 1, axis=1) y = coding_y(y) result = training(x, y) print(result) accuracy(theta, x, y)
from agents import * # DEFINCION DEL AGENTE class Aspiradora(Agent): location = random.randint(0,1) print("las aspiradora inicia en location {}".format(location)) def moveright(self): self.location += 1 def moveleft(self): self.location -= 1 def suck(self, thing): '''returns True upon success or False otherwise''' if isinstance(thing, Dirt): return True return False # DEFINICION DEL ENVIROMENT Y LAS COSAS class Dirt(Thing): pass class Floor(Environment): def percept(self, agent): '''return a list of things that are in our agent's location''' things = self.list_things_at(agent.location) return things def execute_action(self, agent, action): '''changes the state of the environment based on what the agent does.''' if action == "moveright": print('{} esta en {} y decide moverse a la derecha'.format(str(agent)[1:-1], agent.location)) agent.moveright() elif action == "moveleft": print('{} esta en {} y decide moverse a la izquierda'.format(str(agent)[1:-1], agent.location)) agent.moveleft() elif action == "suck": items = self.list_things_at(agent.location, tclass=Dirt) if len(items) != 0: if agent.suck(items[0]): # Have the dog eat the first item print('{} aspiro {} en la posicion: {}' .format(str(agent)[1:-1], str(items[0])[1:-1], agent.location)) self.delete_thing(items[0]) # Delete it from the Park after. def is_done(self): result = not any(isinstance(thing, Dirt) for thing in self.things) if result: print("¡¡¡la aspiradora limpió todo el piso!!!") return result def program(percepts): '''Returns an action based on the dog's percepts''' for p in percepts: if isinstance(p, Dirt): return 'suck' if roomba.location == 0: # location 0 is left, location 1 is right return 'moveright' else: return 'moveleft' piso = Floor() suciedad = Dirt() suciedad2 = Dirt() roomba = Aspiradora(program) piso.add_thing(roomba, roomba.location) piso.add_thing(suciedad, 0) piso.add_thing(suciedad2, 1) piso.run(5)
# 2. Написать программу сложения и умножения двух шестнадцатеричных чисел. # При этом каждое число представляется как массив, элементы которого — цифры # числа. Например, пользователь ввёл A2 и C4F. Нужно сохранить их как # [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно. # Сумма чисел из примера: [‘C’, ‘F’, ‘1’], # произведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’]. from collections import deque NUMB_LEN = 16 summ = deque() numb = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] first = list(input("input first number: ").upper()) second = list(input("input second number: ").upper()) plus_one = 0 for i in range(max(len(first), len(second))): try: a = numb.index(first[-(i + 1)]) + numb.index(second[-(i + 1)]) + plus_one if a > NUMB_LEN - 1: plus_one = 1 summ.append(numb[a - NUMB_LEN]) else: plus_one = 0 summ.append(numb[a]) except IndexError: try: a = numb.index(first[-(i + 1)]) + plus_one if a > NUMB_LEN - 1: plus_one = 1 summ.append(numb[a - NUMB_LEN]) else: plus_one = 0 summ.append(numb[a]) except IndexError: a = numb.index(second[-(i + 1)]) + plus_one if a > NUMB_LEN - 1: plus_one = 1 summ.append(numb[a - NUMB_LEN]) else: plus_one = 0 summ.append(numb[a]) if plus_one: summ.append("1") summ.reverse() print("".join(summ)) # Кажется немного перемудрил с кодом, да еще и много задвоенного, но уже нет времени править # (завтра не будет времени на учебу, а хотел успеть сдать ПЗ) # жду критики кода :)
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. import random SIZE = 20 MIN_ITEM = 0 MAX_ITEM = 50 array = [random.randint(MIN_ITEM, MAX_ITEM) for i in range(SIZE)] min_el = MAX_ITEM max_el = MIN_ITEM min_index = 0 max_index = 0 for i in range(len(array)): if array[i] < min_el: min_el, min_index = array[i], i if array[i] > max_el: max_el, max_index = array[i], i print(array) array[min_index], array[max_index] = array[max_index], array[min_index] print(array)
'''Demo Program - Use Dynamic programming for O(n) solution in Fibo Calculation''' ''' n -> number to calculate fibonacci for ''' def fibo(n): arr=[0]*(n+1) if n == 1 or n == 0: return 1 arr[1]=1 arr[2]=1 for i in range(3,n+1): arr[i]=arr[i-1]+arr[i-2] return arr[n] '''Driver Program''' if __name__=='__main__': while(True): try: user_input=input('Enter a number: ') if 'exit' not in str(user_input): print(fibo(user_input)) else: break except KeyboardInterrupt: print('\nExiting') break
class Stack: def __init__(self): self.__stackList = [] def getlist(self): return self.__stackList def push(self, val): self.__stackList.append(val) return self.__stackList def pop(self): val = self.__stackList[-1] del self.__stackList[-1] return val class AddingStack(Stack): def __init__(self): Stack.__init__(self) self.__sum = 0 def getSum(self): Stack.getlist(self) return self.__sum, Stack.getlist(self) def push(self, val): self.__sum += val return Stack.push(self, val) def pop(self): val = Stack.pop(self) self.__sum -= val return val obj=Stack() stackObject = AddingStack() for i in range(5): print(stackObject.push(i)) print(stackObject.getSum()) for i in range(5): print(stackObject.pop()) print(stackObject.getSum())
"""Finds the bounding box for D in x and y (The space in D with material)""" import numpy as np def boundingbox(D): D_box = np.nonzero(np.sum(D,axis=0)) D_ybox = np.nonzero(np.sum(D, axis=1)) """ Below example could make it more readable? """ # Creates a region of interest as a slice tuple - easy to pass # RegOfInt = (slice(500, 1100), slice(750, 1250), slice(None)) D = D[D_ybox[0][0]:D_ybox[0][-1]+1, D_box[0][0]:D_box[0][-1]+1,np.min(D_box[1]):np.max(D_box[1]+1)] return D
""" X-ray simulator. Simulates the 2D image generated with x-rays emitted from a point source and penerating a material represented by an 3D array. Generally the coordinate system is right-handed with center in x-ray point source. hat{z} points toward the camera(CCD object) hat{x} (positive right) and hat{y}(inwards) are orthogonal and forms a plane with hat{z} as the normal vector In a 3D-array the direction of the grid is [hat{z}, hat{x}, hat{y}] inputs: d1: The distance from point source to the bottom of the object. d2: The distance from the bottom of the material to the camera (CCD) D: density matrix of size [grid_D[0] X grid_D[1] X grid_D[2]] - defined by the loaded target object grid_D: The amount of voxel in the z, x and y direction size_v_D: The physical size of a single voxel in the Density object (height, length, width) size_ccd_pixel = The physical size of one pixel in the ccd array (lenight, width) grid_ccd: The resolution of the capturing device (n, p) Nsubpixels: The amount of different angled rays hitting one ccd. 1 the camera object and CCD same size if larger one pixel in the image consists of 2 pixels. photonsRay: the amount of photons emitted from the source in direction of any pixel Emin:Estep:Emax: The energy range for sampling the source Nframes: The total amount of image frames generated Nsubframes: The amount of subframes added together to form one frame moveStep: (move_x, move_y) the voxel movement between subframes moveStart: (start_x, start_y) the starting position for the first subframe. """ #%% import numpy as np import matplotlib.pyplot as plt from time import time import cv2 as cv from datetime import datetime from func.produceXray import produceXray from func.calcDiagonal import calcDiagonal from func.generateMuDict import generateMuDict from func.normalize3D import normalize3D from func.normalize2D import normalize2D from func.fieldOfView import fieldOfView from func.projectDtoFOV import projectDtoFOV from func.createDirectories import createDirectories def runXsim( filename, D, spectrum, # 1 m as default, all sizes in centimeters d1 = 100, d2 = 100, # 100 micrometers as default size_v_D = (0.01, 0.01, 0.01), size_ccd_pixel = (0.01, 0.01, 0.01), grid_ccd = (100, 100), Nsubpixels = 1, photonsRay = 1000, Emin = 10, Emax = 80, Estep = 1, saturation = 1000, Nframes = 1, Nsubframes = 1, moveStep = (0,0), moveStart = (0,0), imgName = "ref", keepFOV = False, saveImgs = True ): #%% """ Calculates all relevant constant in the system by the user-defined values """ # physical size of the whole camera object # size_c: the real size of image capturing device. Tuple with two inputs size_c = np.multiply(size_ccd_pixel, grid_ccd) # The finer grid for the camera calculations. grid_c = np.multiply(grid_ccd, Nsubpixels) #Information about the grid definition [m x n x p] # The should all match in size? or grid_D = np.shape(D) size_D = np.multiply(grid_D, size_v_D) """ Information of FOV size and grid. Length and width needs to be bigger than material. For 1 to 1 transposability the amount of voxel per length needs to be the same as in the material. """ size_fov = (size_D[0], (size_c[0]*d1)/(d1+d2), (size_c[1]*d1)/(d1+d2)) #Increases the size of FOV by a maximum of 1. To make pretty numbers and # guarantee that the voxel volumes of D and fov match size_fov = size_fov + (size_v_D-np.mod(size_fov,size_v_D)) """ Define FOV grid so each voxel is same size as in D """ grid_fov = np.round(np.divide(size_fov, size_v_D)).astype(int) size_v_fov = np.divide(size_fov, grid_fov) #%% Creates Directories for all types of files and saves constants """ Set input and output directories """ folder = "results/" if saveImgs == True: """ Save relevant constants """ const_names = ['d1', 'd2', 'size_D', 'grid_D','size_c', 'grid_ccd', 'Nsubpixels', 'moveStep', 'moveStart', 'Nframes', 'Nsubframes', 'photonsRay'] const_vals = [d1, d2, size_D, grid_D, size_c, grid_ccd, Nsubpixels, moveStep, moveStart, Nframes, Nsubframes, photonsRay] createDirectories(filename, folder, const_names, const_vals) #%% Ray spectrum and intensities #For a given spectrum find the energies and the count of photons with each energy ray_energy, ray_counts = produceXray(spectrum, N_points = photonsRay, Emin = Emin, Emax = Emax, Estep = Estep, makePlot=True) #%% Defines the material and its components mu_dict, _ = generateMuDict(ray_energy) #%% Calculates distances and angles # The total height of the system h = d1 + d2 # CCD reshaping to quarter size grid_qc = (int(np.ceil(grid_c[0]/2)),int(np.ceil(grid_c[1]/2))) #The distance to each center point of the CCD(centered in the middle) # nice numbers if shape is half of grid xc = (np.arange(grid_qc[0]) - grid_c[0]/2 + 0.5) * size_c[0] / (grid_c[0]) zc = (np.arange(grid_qc[1]) - grid_c[1]/2 + 0.5) * size_c[1] / (grid_c[1]) # The angles between the center and the midpoint of a given input of the CCD alpha = (np.arctan(xc/h), np.arctan(zc/h)) """Reshaped v_d to a vector and 1/4 of the original content""" v_d = calcDiagonal(size_v_fov, alpha, grid_qc) #%% Generates Field of View list. An list containing all indencies a ray goes # through in the field of view # Only generates a Field of view list if one with those specifics dosen't exist import os fov_name = f'{grid_fov[0]}x{grid_fov[1]}x{grid_fov[2]}_{grid_c[0]}x{grid_c[1]}'+\ f'_{size_v_fov[0]:.3f}x{size_v_fov[1]:.3f}x{size_v_fov[2]:.3f}_'+\ f'{size_fov[0]:.2f}x{size_fov[1]:.3f}x{size_fov[2]:.3f}_'+\ f'{size_c[0]:.3f}x{size_c[1]:.3f}_{d1}_{d2}' if os.path.isfile('fov/'+fov_name+'.npy'): print (f"FOV File exist with name: {fov_name}") fov_list = np.load('fov/'+fov_name+'.npy') FOV_dt = "exits" else: t0 = time() print (f"FOV File with name: {fov_name} does not exist.\n Creates FOV list,") fov_list = fieldOfView(grid_fov, grid_qc, size_v_fov, d1, size_fov, alpha) if keepFOV == True: np.save('fov/'+fov_name,fov_list) else: print('keepFOV = False, did not save FOV file') FOV_dt = time() - t0 print(f'took {FOV_dt:02.2f} seconds\n') #%% """ The main part of the loop which creates the frames""" I_ccd = np.zeros([Nframes, grid_ccd[0], grid_ccd[1]]) mu_d = np.zeros([grid_c[0],grid_c[1], len(ray_energy)]) # Parameter to adjust for the unequal parts of FOV, in the reversed indencies """ Maybe find a better expresions as it seems a little random factor to add """ rev_adjust = (grid_fov[1] - grid_fov[2])//2 y = np.arange(grid_fov[0]) x_points, z_points = fov_list[0, :, :], fov_list[1, :, :] # The necessary points to evaluate # Counter is made to evaluate the loop properly. # Only calculate the upper triangle in the FOV. 1/8 of the whole camera area delta_c = grid_qc[0] - grid_qc[1] count_start = np.arange(0, grid_qc[1]*(delta_c+1), grid_qc[1]) count_end = np.cumsum(np.arange(grid_qc[1], 1, -1))+grid_qc[1]*delta_c counter = np.insert(count_end, 0, count_start) if Nframes == 1 and Nsubframes == 1: move = np.add(moveStart,moveStep) else: move = moveStart # create a background image for i in range(Nframes): t0 = time() I_photon = np.zeros(tuple(grid_c)) for j in range(Nsubframes): t1 = time() #Finds photons from a new distribution. Needs to sample everytime? ray_energy, ray_counts = produceXray(spectrum, N_points=photonsRay, Emin=Emin, Emax=Emax, Estep=Estep) # Calculates all entry and exit points of the rays in the density matrix ref_fov = projectDtoFOV(grid_fov, grid_D, D, move) move = np.add(move, moveStep) #Loops over the part where the indencies cannot be reversed for i2 in range(delta_c): for j2 in range(grid_qc[1]): ind = counter[i2]+j2 x = x_points[ind] z = z_points[ind] """ Upper left quadrant""" mu_d[i2, j2, :] = np.sum(mu_dict[:, ref_fov[y, x, z]]*v_d[ind], axis=1) """ upper right quadrant""" mu_d[i2, grid_c[1]-1-j2, :] = np.sum(mu_dict[:, ref_fov[y, x, grid_fov[2]-1-z]]*v_d[ind], axis=1) """ lower left quadrant""" mu_d[grid_c[0]-1-i2, j2,:] = np.sum(mu_dict[:, ref_fov[y, grid_fov[1] - 1 - x, z]] * v_d[ind], axis=1) """ lower right quadrant""" mu_d[grid_c[0]-1-i2, grid_c[1]-1-j2, :] = np.sum(mu_dict[:, ref_fov[y, grid_fov[1] - 1 - x, grid_fov[2] - 1 - z]] * v_d[ind], axis=1) # Loops over the part where the indencies can be reversed for i2 in range(delta_c, grid_qc[0]): for j2 in range(i2-delta_c, grid_qc[1]): ind = counter[i2]+j2-i2+delta_c x = x_points[ind] z = z_points[ind] """ Upper left quadrant""" mu_d[i2, j2, :] = np.sum( mu_dict[:, ref_fov[y, x, z]] * v_d[ind], axis=1) """ upper right quadrant""" mu_d[i2, grid_c[1]-1-j2,:] = np.sum(mu_dict[:, ref_fov[y, x, grid_fov[2]-1-z]]*v_d[ind], axis=1) """ lower left quadrant""" mu_d[grid_c[0]-1-i2, j2,:] = np.sum(mu_dict[:, ref_fov[y, grid_fov[1] - 1 - x, z]] * v_d[ind], axis=1) """ lower right quadrant""" mu_d[grid_c[0]-1-i2, grid_c[1]-1-j2, :] = np.sum(mu_dict[:, ref_fov[y, grid_fov[1] - 1 - x, grid_fov[2] - 1 - z]] * v_d[ind], axis=1) """Reversed indencies """ i3 = i2 - delta_c j3 = j2 + delta_c """ Upper left quadrant""" mu_d[j3, i3, :] = np.sum(mu_dict[:, ref_fov[y, z+rev_adjust, x-rev_adjust]] * v_d[ind], axis=1) """ upper right quadrant""" mu_d[j3, grid_c[1]-1-i3, :] = np.sum(mu_dict[:, ref_fov[y, z+rev_adjust, grid_fov[2] - 1 - x + rev_adjust]] * v_d[ind], axis=1) """ lower left quadrant""" mu_d[grid_c[0]-1-j3, i3, :] = np.sum(mu_dict[:, ref_fov[y, grid_fov[1] - 1 - z-rev_adjust, x-rev_adjust]] * v_d[ind], axis=1) """ lower right quadrant""" mu_d[grid_c[0]-1-j3, grid_c[1]-1-i3, :] = np.sum(mu_dict[:, ref_fov[y, grid_fov[1] - 1 - z -rev_adjust, grid_fov[2] - 1 - x + rev_adjust]]* v_d[ind], axis=1) # Assuming Poisson ditribution with Poisson varibel photon_count*mu_ray I_photon_temp = np.sum(np.random.poisson( ray_counts * np.exp(-mu_d)), axis=2) if saveImgs == True: # Saves an 8bit image of every subframe I8 = (normalize2D(I_photon_temp)*255.9).astype(np.uint) cv.imwrite(folder+filename+'/'+'subframes/' + filename+imgName + f'{i+1}_{j+1}.png', I8) # Adds all the subframes together I_photon += I_photon_temp #The intensity at the CCD. Adds all the rays hitting the same CCD. #Save as a seperate file I_dummy = np.add.reduceat(I_photon, np.arange(0, I_photon.shape[0], Nsubpixels), axis=0) I_ccd[i,:,:] = np.add.reduceat(I_dummy, np.arange(0, I_photon.shape[1], Nsubpixels), axis=1) # Looks at the thresholdSets everything above threshold to threshold value I_ccd[i,I_ccd[i,:,:] > saturation] = saturation I_ccd[i,:,:] = (normalize2D(I_ccd[i,:,:], A_max = saturation, A_min = 0) *255.9).astype(np.uint8) if saveImgs == True: # Saves the frames as 8bit images cv.imwrite(folder+filename+'/'+'CCDreads/' + filename+imgName+f'{i+1}.png', I_ccd[i, :, :]) frame_dt = time() - t0 print(f'Created Frame {i+1} out of {Nframes}, took {frame_dt:02.2f} seconds\n') print('All Frames created') plt.imshow(I_ccd[0,:,:]) #%% creates movie from func.createMovie import createMovie createMovie(I_ccd, Nframes, grid_ccd, folder, filename) plt.imshow(I_ccd[-1,:,:]) # Image with histogram equalization I_equalizeHist = cv.equalizeHist(I_ccd[-1, :, :].astype('uint8')) plt.imshow(I_equalizeHist) cv.imwrite(folder+filename+'/'+'CCDreads/' + filename+'HistEqualization.png', I_equalizeHist) # %% import os import csv const_names = ['generated FOV in:', 'generated Frame in:'] const_vals = [FOV_dt, frame_dt] if saveImgs: with open(folder+filename+'/runtime.csv', 'w', ) as myfile: wr = csv.writer(myfile) # wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) test = zip(const_names, const_vals) for row in test: wr.writerow([row]) # %%
# PA1: FoxProblem # Jack Keane class FoxProblem: def __init__(self, start_state=(3, 3, 1)): self.start_state = start_state self.goal_state = (0, 0, 0) self.traverses = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] def is_safe(self, state): # determine animals on each bank west_chickens = state[0] west_foxes = state[1] east_chickens = self.start_state[0] - west_chickens east_foxes = self.start_state[1] - west_foxes # check if numbers within correct range [0,num animal] if not (0 <= west_chickens <= self.start_state[0] and 0 <= east_chickens <= self.start_state[0] and 0 <= west_foxes <= self.start_state[1] and 0 <= east_foxes <= self.start_state[1]): return False # check if chickens will get eaten if (west_chickens > 0 and west_foxes > west_chickens): return False if (east_chickens > 0 and east_foxes > east_chickens): return False return True # get successor states for the given state def get_successors(self, state): successors = [] for traverse in self.traverses: # if boat on west bank, animals will be leaving west bank # thus, animals are subtracted from state if state[2] == 1: succ_state = (state[0] - traverse[0], state[1] - traverse[1], 0) # if boat on east bank, animals will be arriving to west bank # thus, animals are added to state else: succ_state = (state[0] + traverse[0], state[1] + traverse[1], 1) if self.is_safe(succ_state): successors.append(succ_state) return successors def goal_test(self, state): return state == self.goal_state def __str__(self): string = "Chickens and foxes problem: " + str(self.start_state) return string # A bit of test code if __name__ == "__main__": test_cp = FoxProblem((5, 4, 1)) print(test_cp.get_successors((5, 4, 1))) print(test_cp)
# 2.1.3 # # Tri de trois réels # # Ecrire un programme faisant saisir trois nombres réels x, y, z à l’utilisateur et qui les trie par ordre croissant # (à la fin du déroulement du programme x ≤ y ≤ z). x = eval(input("Entrez le premier nombre : ")) y = eval(input("Entrez le second nombre : ")) z = eval(input("Entrez le troisième nombre : ")) if x > y: x, y = y, x if y > z: y, z = z, y if x > y: x, y = y, x print(x,"<=",y,"<=",z)
# 2.1.5 # # Somme des premiers carrés # # Ecrire un programme calculant la somme des n premiers carrés d’entiers, où n est un entier naturel # saisi par l’utilisateur. n = None while type(n) is not int: n = eval(input("Entrez un entier : ")) somme = 0 for i in range(n+1): somme += i**2 print("La somme des", n, "premiers entiers est :", somme)
# 2.5.1 # # Nombre d’occurrence d’un élément dans une liste # # Ecrire une fonction calculant le nombre d’occurrences d’un élément dans une liste. def compteOccurrence(l, x): compte = 0 for i in l: if l[i] == x: compte += 1 return compte maListe = [1, 2, 3, 4, 5, 3] print(compteOccurrence(maListe, 2)) print(compteOccurrence(maListe, 3))
# 2.3.2 # # Suite de Syracuse # # Ecrire une procédure affichant les n premiers termes de la suite de Syracuse de base a. def syracuse(n, a): if type(a) is not int or a < 0: print("Erreur : a doit être un entier positif.") return -1 print(a, end=" ") precedent = a for i in range(1, n): if precedent%2 == 0: precedent //= 2 else: precedent = 3*precedent+1 print(precedent, end=" ") print("\n") syracuse(21, 15)
def what_i_want(thing1, thing2): print "I want %s" % thing1 print "I want %s" % thing2 print "That's just awesome!" print "Yay!\n" what_i_want("waffles", "beer") waffles = "waffles" beer = "beer" what_i_want(waffles, beer) what_i_want("waffles" + " beer", "waffles " + beer)
def arrayPrint(A): for i in xrange( len( A) ): print A[i] , print '' def less(a,b): return a < b def greater(a,b): return a > b def insertionSort(A, func = less): """ Insertion sort: - Simple implementation - Efficient for (quite) small data sets - Adaptive (i.e., efficient) for data sets that are already substantially sorted: the time complexity is O(n + d), where d is the number of inversions - More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such as selection sort or bubble sort; the best case (nearly sorted input) is O(n) - Stable; i.e., does not change the relative order of elements with equal keys - In-place; i.e., only requires a constant amount O(1) of additional memory space - Online; i.e., can sort a list as it receives it """ for i in xrange( len(A) ): valueToInsert = A[i] holePos = i while holePos > 0 and func(valueToInsert, A[holePos-1]): A[holePos] = A[holePos - 1] holePos = holePos - 1 A[holePos] = valueToInsert def quickSort(A,p,r,myflag = False): def partition(A,p,r,myflag): print 'partition a=',A,'p=',p,'r=',r x = A[r-1] #pivot i = p - 1 for j in xrange(p,r-2): if A[j] <= x: i = i + 1 A[i],A[j] = A[j],A[i] if myflag: print A if myflag: print (i+1),(r-1) print A[i+1], A[r-1] A[i+1],A[r-1] = A[r-1],A[i+1] if myflag: print A[i+1], A[r-1] print 'return =', (i + 1) print A return i + 1 if p<r-1: q = partition(A,p,r,myflag) quickSort(A,p,q-1,True) quickSort(A,q+1,r,True) ''' X = [1,5,3,2,4] X = [2,8,7,1,3,5,6,4] arrayPrint(X) quickSort(X, 0,len(X),True) arrayPrint(X) ''' import RedBlackTree
def decorator(validate): def result(func): def check_validate(*args, **kwargs): if not validate(*args, **kwargs): return 'error' return func(*args, **kwargs) return check_validate return result def validator(*args, **kwargs): return True pass @decorator(validator) def f(x,y): return x*4 + y d = f(4,3) print(d) #https://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments #python custom decorator with arguments and validation
text = input() stack = [] for i in range(0,len(text)): stack.append(text[i]) if text[i] == "=": stack.pop() if stack: stack.pop() pass print("".join(stack))
n = int(input()) for i in range(n): text = input() print(text.title()) pass """ for i in range(int(input())): print(" ".join([s.capitalize() for s in input().split()])) """
st = {2, 3, 1} print(st) a = set("salam") b = set("ali") print(a | b) print(a & b) print(a - b) print(a ^ b) # ( A - B) U ( A - B ) print({x for x in a if x not in b}) dict = {"ali": 12, "amir": 2.3} print(dict['ali']) print(list(dict)) print({2*x:x/4 for x in range(5)}) d = {'ali': 'A', 'amir': 'B'} for k, v in d.items(): print(k + " got " + v)
"""from datetime import time t = time(17, 21, 20, 2021) print(t , "# ", type(t)) """ """ from datetime import date d = date(2019, 5, 23) print(d.year, d.month, d.day) """ from datetime import datetime dt = datetime(1, 2, 3, 4, 5, 6, 7) print(dt.year, dt.month, dt.day, dt.minute ) print() print(datetime.now())
import csv import globals as g import F03 as c def Exit(): if (not(g.Login_success)): print("Silahkan login terlebih dahulu untuk menggunakan fitur ini.") return; pilih = str(input("Apakah Anda mau melakukan penyimpanan file yang sudah dilakukan (Y/N)? ")) #apabila masukan bukan 'Y', 'y', 'N', atau 'n', pemain diminta untuk menginput ulang while not (pilih == 'y' or pilih == 'Y' or pilih == 'n' or pilih == 'N'): print("Masukan harus berupa Y atau N.") pilih = str(input("Apakah Anda mau melakukan penyimpanan file yang sudah dilakukan (Y/N)? ")) #apabila input berupa 'Y' atau 'y', penyimpanan file dilaksanakan #apabila input berupa 'N' atau 'n', penyimpanan file tidak dilaksanakan #menyimpan file if (pilih == 'Y' or pilih == 'y'): c.Save_File() #pemain keluar dari program g.exit_program = True print() print("Terima kasih telah menggunakan aplikasi kami!")
from time import strftime from tkinter import Label, Tk # ======= Configuração da janela ========= window = Tk() # ======= Cria a janela grafica ========= window.title("Relógio") # ====== Titulo da janela ========= window.geometry("300x100") #======= Proporção da tela ========= window.configure(bg="Black") # =======Tela de fundo(bg = backgroud)===== window.resizable(False, False) # =====Tamanho fixo da tela ======= clock_label = Label(window, bg="black", fg="Red", font=("Red", 30, "bold"), relief="flat") clock_label.place(x=20, y=20) def update_label(): #==========função para atualizar o relogio a cada 80milisegundos=========== current_time = strftime("%H: %M: %S\n %d-%m-%Y ") #tupla na forma do tempo atual clock_label.configure(text=current_time) clock_label.after(80, update_label) #tempo da atualização clock_label.pack(anchor="center") update_label() #atualiza o programa window.mainloop() #faz o programar rodar em looping
# print(1) # print(2) # print(3) # print(4) #print(5) # range(start, end, difference) #range(0, 5, 1) """ for i in range(0, 20, 2): print(i) """ """ #if first and difference value is not set then default irst value is 0 and difference is 1 for j in range(10): print(j) """ """ # print all ood and even for j in range(50): if j%2 == 0: print("even :", j) else: print("Odd :", j) """ # print table of any number """ num = 3 for i in range(1, 11): print(i, "*", num ,": ",i*num) """ ####### # take 5 inputs from user and check they are divide by 5 and 7 or not. # step 1 : take 5 inputs # step 2 : check each number is divide by 5 and 7 or not """ list1 = [] for i in range(1, 6): str1 = "Please enter num "+str(i)+ ":" num = int(input(str1)) list1.append(num) print(list1) for num in list1: if num%5 == 0 or num%7 == 0: print(num, ":",True) else: print(num, ":", False) """ """ for i in range(1, 6): num = int(input("Please enter num"+str(i)+":")) if num%5 ==0 and num%7 == 0: print(num, "it can divide") else: print(num, 'it can not divide') """ ####################################### #Nested Loop condition """ for add in range(3): # i = 0, j = 0, 1, 2 for parcel in range(5): print("address: ", add, "# parcel:", parcel) print("#"*50) """ # Get combination of all two number there sum should be 10 #v1 list1 = [5, 7, 8, 2, 6, 4, 9, 3, 1, 5] #v2, 5, 7, 8, 2, 4, 9, 3, 1 for var1 in list1: #print(var1) var1 = 5, 7, 8 for var2 in list1: # var2 = 5, 7, 8, 2, 6, 4, 9, 3, 1 if var1 == var2: continue else: addition = var1 + var2 print(("var1 :", var1,"|| var2 :", var2)) if addition == 10: print(var1, var2) else: continue print("#"*50)
# lambda arguments:code expression result = lambda x, y: x +y print(result(60, 50)) result2 = lambda x, y: (x +y)*2 print(result2(60, 50)) result3 = lambda x, y: x if x%2 == 0 else y print(result3(21, 30)) # Map : def square(n): return n**2 list1 = [5, 7, 3, 8, 9] output = list(map(square, list1)) print(output) output2 = list(map(lambda x:x//2, list1)) print(output2)
""" When one operator perform multiple task then this is called operator overloading like + , * etc and behind the scene + operator is overloaded by "__add__" method. and * operator is overloaded by "__mul__" method. """ num1 = 50 num2 = 60 print(num1+num2) print(int.__add__(num1, num2)) print(str.__add__('Hello', 'Morning')) print(int.__mul__(4, 5)) print(str.__mul__("#", 50)) print("#"*50)
""" *** * * * * * * * * * * *** * ** *** **** *** ** * """ #1. write a print * at 2,3,4 and space at 1st and 5th position. #2. write code to print * at 1st and 5th position and space at 2,3,4 position # repeat same pattern 5 times """ for i in range(1, 6): if i ==2 or i == 3 or i == 4: print("*", end="") elif i == 1 or i == 5: print(" ", end="") print("\n") for i in range(1, 6): for j in range(1, 6): if j ==2 or j == 3 or j == 4: print(" ", end="") elif j ==1 or j == 5: print("*", end="") print("\n") #print("\n") for i in range(1, 6): if i ==2 or i == 3 or i == 4: print("*", end="") elif i == 1 or i == 5: print(" ", end="") """ """ * ** *** **** *** ** * """ """ #1. write a code to print a increment star from 1 to 5 #2. write a code to print a decremented * pattern from 4 to 1 count = 1 for i in range(1, 6): #i=1, i =2, i = 3 for j in range(1, i): #j= 0, 1, j= 0, 1, 2 | j = 0, 1, 2, 3 print(count, end=" ") count = count+1 print("\n") temp = 1 for i in range(4, 1, -1): # i = 4, i = 3 , i = 2, for j in range(1, i): # j = 1, 2, 3 | j = 1, 2 | j =1 print(temp, end=" ") temp = temp +1 print("\n") """ str1 = "Python" str_len = len(str1) print(str_len) temp = '' #i = -1, -2, -3, -4, -5, -6 for i in range(-1, -str_len-1, -1): print(str1[i],":", temp) temp = temp + str1[i] print(temp)
#1.take user salary and year of experience from user. #-> if exp > 1 year : 10% increament in salary #-> if emp < 1 year : 5% increment in salary # salary = float(input("Please enter emp salary :")) # exp = float(input("Please enter emp experiance :")) # # if exp > 2: # new_salary = salary + salary*10/100 # print(new_salary) # elif exp < 2: # new_salary = salary + salary*5/100 # print(new_salary) # """ list1 = [3, 6, 8, 9] list2 = [6, 7, 8, 2] output = zip(list1, list2) print(output) # for i in output: # print(i) print(dict(output)) """ import json str2 = '{"name": "JOhn", "Age": 45, "Address": "Pune"}' print(type(str2)) result = json.loads(str2) print(type(result)) print(result['name']) with open("data.json","r") as file: data = file.read() print(type(data)) json_data = json.loads(data) print(type(json_data))
""" 1. Class : class is blue print of the object which contains all properties and attribute of the object. 2. Object : object is instance of the class through which we can access class properties. 3. Inheritance 4. Polymorphism 5. Data Hiding and Abstraction """ class Car: # object method/instance method def car_name(self): print("BMW") # object method/instance method def car_prize(self): print("35 Lac") # create a object of the class or instance of the class """ car_obj = Car() car_obj.car_name() car_obj.car_prize() print("_"*50) car_obj2 = Car() car_obj2.car_name() car_obj2.car_prize() """ ################################################### # Constructor : It helps to initilize the object of the class. __init__() # Default Constructor : default constructor call by default while creating the class object, when it does # not have any parameter. # Parametize Constructor : we have to explicitly def __init__ method to create parametize constructor. class student: # class variable school_name = 'International Convent School' # parametize constructor of the class def __init__(self, name, age): self.st_name = name # instance variable self.st_age = age # instance variable # instance method/ object method def show_name(self): print(f"Student Name : {self.st_name}") # instance method/ object method def show_age(self): print(f"Student Age : {self.st_age}") def show_school_name(self): print(f"My school Name :{student.school_name}") """ st_obj = student('John', 40) st_obj.show_name() st_obj.show_age() print("#"*50) st_obj = student('Tejas', 60) st_obj.show_name() st_obj.show_age() st_obj.show_school_name() print(st_obj.school_name) print(student.school_name) """ # self : self is nothing but a object of the class itself, always the first parameter of the instance method. # by default first parameter as object of the class will called along with method, when we tr to access # via object. obj_new = student('Harry', 40) obj_new.show_name() student.show_name(obj_new)
s = input() s = set(list(s)) ans = 'None' for alpha in list('abcdefghijklmnopqrstuvwxyz'): if alpha not in s: ans = alpha break print(ans)
# -*- coding: utf-8 -*- def solve(n): return sum(len(num2char(i)) for i in range(1, n+1)) def num2char(n): num_char_dic = { '0': '', '00': '', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen', '20': 'twenty', '30': 'thirty', '40': 'forty', '50': 'fifty', '60': 'sixty', '70': 'seventy', '80': 'eighty', '90': 'ninety', '100': 'hundred', } """ TODO two-digit numbers (in especially n (greater than 12 and less than 20) can express with thir, four, fif... + teen In other words, if there is stem about num, I can reduce dictionary's size """ result = '' n_str = str(n) niketa = n_str[-2:] yonketa = n_str[:-2] if niketa in num_char_dic.keys(): if yonketa == '': result += num_char_dic[niketa] else: if num_char_dic[niketa] == '': result += num_char_dic[niketa] else: result += 'and' + num_char_dic[niketa] else: if yonketa == '': result += '' + num_char_dic[niketa[0]+'0'] + num_char_dic[niketa[1]] else: result += 'and' + num_char_dic[niketa[0]+'0'] + num_char_dic[niketa[1]] if len(yonketa) == 1: result += num_char_dic[yonketa] + 'hundred' elif len(yonketa) == 2: result = 'onethousand' return result if __name__ == '__main__': print(solve(1000))
# -*- coding: utf-8 -*- def is_palindrome(n): n_str = str(n) return n_str == n_str[::-1] def solve(): return max( i*j for i in range(999, 0, -1) for j in range(999, 0, -1) if is_palindrome(i*j) ) if __name__ == '__main__': print(solve())
# -*- coding: utf-8 -*- S, T, U = map(len, input().split()) if S == U and S == 5 and T == 7: print("valid") else: print("invalid")
s = list(input()) ss = sorted(s) sd = list('yahoo') ssd = sorted(sd) if ss == ssd: print('YES') else: print('NO')
# -*- coding: utf-8 -*- def solve(n): # list comprehension return sum(a_n for a_n in fibnacci(n) if a_n % 2 == 0) def fibnacci(n): a = [1, 2] while 1: a_n = a[-1] + a[-2] if a_n > n: return a a.append(a_n) if __name__ == '__main__': print(solve(4000000))
a, b = 1, 0 for k in range(int(input()) + 1): a, b = b, a + b print("%s %s" % (a, b))
# -*- coding: utf-8 -*- i = int(raw_input()) count = 0 for j in xrange(i): for k in str(j+1): if k == "1": count += 1 print count
# -*- coding: utf-8 -*- Y = int(raw_input()) if Y % 4 == 0: if Y % 100 == 0: if Y % 400 == 0: print "YES" else: print "NO" else: print "YES" else: print "NO"
nome = input("Qual seu nome?") idade = int(input("Qual sua idade?")) # cem_anos = 100 - idade # cem_anos = 2019 + cem_anos repetir_mensagem = int(input("Quantas vezes quer ver esta mensagem ?")) cem_anos = str((2019 - idade)+100) print(("Seu nome é {} e sua idade atual é {}. O ano em que vai fazer 100 anos é {}\n".format(nome,idade, cem_anos)) * repetir_mensagem) # 100 - idade e o resultado somar com idade #duas formas de resolver o mesmo problema, sendo a não comentada transformando a formula em string e jogando dentro da variavel cem_anos.
# import random # # aluno1 = input('Digite o nome do primeiro aluno:') # aluno2 = input('Digite o nome do segundo aluno:') # aluno3 = input('Digite o nome do terceiro aluno:') # aluno4 = input('Digite o nome do quarto aluno:') # # print('Os alunos são \n1- {} \n2- {} \n3- {} \n4- {}'.format(aluno1, aluno2, aluno3, aluno4)) # # print('E o aluno sorteado é o aluno número: {}'.format(random.randrange(1, 5))) # from random import choice n1 = str(input('Primeiro aluno: ')) n2 = str(input('Segundo aluno: ')) n3 = str(input('Terceiro aluno: ')) n4 = str(input('Quarto aluno: ')) lista = [n1, n2, n3, n4] escolhido = choice(lista) print('O aluno escolhido foi {}'.format(escolhido))
salario = float(input('Digite o salário do funcionário: ')) aumento = (salario*15)/100 nsalario = salario + aumento print('O novo salário do Fulano é de {}'.format(nsalario))
import random def busqueda_binaria(lista, comienzo, final, objetivo): print(f' buscando {objetivo} entre {lista[comienzo]} y {lista[final -1]}') if comienzo > final: return False medio = (comienzo + final) // 2 if lista[medio]== objetivo: return True elif lista[medio] < objetivo: return busqueda_binaria(lista, medio+1,final,objetivo) else: return busqueda_binaria(lista, comienzo, medio-1, objetivo) if __name__ == "__main__": tamano_de_lista = int(input('de que tamano sera la lista? ')) objetivo = int(input('Que numero quieres encontrar? ')) lista = sorted([random.randint(0, 100) for i in range(tamano_de_lista) ]) encontrado =busqueda_binaria(lista, 0,len(lista), objetivo) print(lista) print(f'elemento {objetivo} { "esta"if encontrado else "no esta"} enla lista')
x = 3 if x>0: x = x-4 elif x<0: x = x+5 else: x = x+10 print(x)
# Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами # 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка # элементов необходимо использовать функцию input(). string = input("Введи элементы списка через пробел") test_list = string.split() for index, var in enumerate(test_list): if index % 2: test_list[index], test_list[index - 1] = test_list[index - 1], test_list[index] print(test_list)
# Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. # расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия. # Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. from sys import argv script, work_in_h, stavka_in_h, premia = argv print(f"заработная плата составляет:{(float(work_in_h) * float(stavka_in_h)) + float(premia)}")
print('Lottery nimbers') numbers = [] import random def main () : for x in range(9): numbers.append(random.randint(0, 9)) print(numbers) #Задания для написания кода. # 1. Общий объем продаж.Разработайте программу, которая просит пользователя ввести # продажи магазина за каждый день недели. Суммы должны быть сохранены в списке. # Примените цикл, чтобы вычислить общий объем продаж за неделю и показать результат # Константа DAYS содержит количество дней 7, за которые мы соберем данные продаж. DAYS = 7 week =[] def main(): sales = [0] * DAYS # Создать переменную, которая будет содержать индекс. index = 0 print("Введите сумму продажи за день: ") while index < DAYS: print('День № ', index + 1, ': ', sep=' ', end=' ') sales[index] = float(input()) index += 1 print('суммы по дням:') for value in sales: index += value print(value) print(index) main() # 2. Генератор лотерейных чисел.Разработайте программу, которая генерирует семизначную # комбинацию лотерейных чисел. Программа должна сгенерировать семь случайных # чисел, каждое в диапазоне от О до 9, и присвоить каждое число элементу списка. (Случайные # числа рассматривались в главе 5.) Затем напишите еще один цикл, который показывает # содержимое списка. #3. Статистика дождевых осадков. Разработайте программу, которая позволяет пользователю #занести в список общее количество дождевых осадков за каждый из 12 месяцев. #Программа должна вычислить и показать суммарное количество дождевых осадков за #год, среднее ежемесячное количество дождевых осадков и месяцы с самым высоким и #самым низким количеством дождевых осадков. #4. Проrрамма анализа чисел. Разработайте программу, которая просит пользователя ввести #ряд из 20 чисел. Программа должна сохранить числа в списке и затем показать приведенные #ниже данные: #• наименьшее число в списке; #• наибольшее число в списке; #• сумму чисел в списке; #• среднее арифметическое значение чисел в списке. #5.Проверка допустимости номера расходноrо счета. Среди исходного кода главы 7, #а также в подпапке data "Решений задач по программированию" соответствующей главы #вы найдете файл charge_accounts.txt. Этот файл содержит список допустимых номеров #расходных счетов компании. Каждый номер счета представляет собой семизначное число, #в частности 5658845. #Напишите программу, которая считывает содержимое файла в список. Затем эта программа #должна попросить пользователя ввести номер расходного счета. Программа #должна определить, что номер является допустимым, путем его поиска в списке. Если #число в списке имеется, то программа должна вывести сообщение, указывающее на то, #что номер допустимый. Если числа в списке нет, то программа должна вывести сообщение, #указывающее на то, что номер недопустимый #6.Больше числа n. В программе напишите функцию, которая принимает два аргумента: #список и число n. Допустим, что список содержит числа. Функция должна показать все #числа в списке, которые больше n.
# Константа NUМ_DAYS содержит количество дней, # за которые мы соберем данные продаж. NUМ_DAYS = 5 def main(): sales = [0] * NUМ_DAYS # Создать переменную, которая будет содержать индекс. index = 0 print("Введите продажи за каждый день: ") while index < NUМ_DAYS: print('День № ', index + 1, ': ', sep=' ', end=' ') sales[index] = float(input()) index += 1 print('Boт значения, которые были введены:') for value in sales: print(value) main()
#python program to map two list into a dictionary print("enter 2 list of equal length to map into dictionary") a=eval(input("enter a list1 : ")) b=eval(input("enter a list2 : ")) c={} for i in range(len(a)): c[a[i]]=b[i] print(c)
#!/usr/local/bin/python # -*- coding: UTF-8 -*- def name_to_class(key): """ Converts a note name to its pitch-class value. :type key: str """ name2class = {'B#': 0, 'C': 0, 'C#': 1, 'Db': 1, 'D': 2, 'D#': 3, 'Eb': 3, 'E': 4, 'Fb': 4, 'E#': 5, 'F': 5, 'F#': 6, 'Gb': 6, 'G': 7, 'G#': 8, 'Ab': 8, 'A': 9, 'A#': 10, 'Bb': 10, 'B': 11, 'Cb': 11, '??': 12, '-': 12} try: return name2class[key] except KeyError: print('name not defined in dictionary') def mode_to_num(mode): """ Converts a scale type into numeric values (maj = 0, min = 1). :type mode: str """ mode2num = {'major': 0, 'minor': 1, 'maj': 0, 'min': 1, 'M': 0, 'm': 1, '': 0, 'ionian': 2, 'harmonic': 3, 'mixolydian': 4, 'phrygian': 5, 'fifth': 6, 'monotonic': 7, 'difficult': 8, 'peak': 9, 'flat': 10} try: return mode2num[mode] except KeyError: print('mode type not defined in dictionary') def key_to_list(key): """ Converts a key (i.e. C major) type into a numeric list in the form [tonic, mode]. :type key: str """ if len(key) <= 2: key = key.strip() key = [name_to_class(key), 0] return key elif '\t' in key[1:3]: key = key.split('\t') elif ' ' in key[1:3]: key = key.split(' ') key[-1] = key[-1].strip() key = [name_to_class(key[0]), mode_to_num(key[1])] return key def key_to_int(key): """ Converts a key symbol (i.e. C major) type to int :type key: str """ name2class = {'C major': 0, 'C# major': 1, 'Db major': 1, 'D major': 2, 'D# major': 3, 'Eb major': 3, 'E major': 4, 'F major': 5, 'F# major': 6, 'Gb major': 6, 'G major': 7, 'G# major': 8, 'Ab major': 8, 'A major': 9, 'A# major': 10, 'Bb major': 10, 'B major': 11, 'C minor': 12, 'C# minor': 13, 'Db minor': 13, 'D minor': 14, 'D# minor': 15, 'Eb minor': 15, 'E minor': 16, 'F minor': 17, 'F# minor': 18, 'Gb minor': 18, 'G minor': 19, 'G# minor': 20, 'Ab minor': 20, 'A minor': 21, 'A# minor': 22, 'Bb minor': 22, 'B minor': 23, } return name2class[key] def int_to_key(a_number): """ Converts an int onto a key symbol with root and scale. :type a_number: int """ int2key = {0: 'C major', 1: 'C# major', 2: 'D major', 3: 'Eb major', 4: 'E major', 5: 'F major', 6: 'F# major', 7: 'G major', 8: 'Ab major', 9: 'A major', 10: 'Bb major', 11: 'B major', 12: 'C minor', 13: 'C# minor', 14: 'D minor', 15: 'Eb minor', 16: 'E minor', 17: 'F minor', 18: 'F# minor', 19: 'G minor', 20: 'Ab minor', 21: 'A minor', 22: 'Bb minor', 23: 'B minor', } return int2key[a_number] def bin_to_pc(binary, pcp_size=36): """ Returns the pitch-class of the specified pcp vector. It assumes (bin[0] == pc9) as implemeted in Essentia. """ return int((binary / (pcp_size / 12.0)) + 9) % 12 def xls_to_key_annotations(excel_file, sheet_index, export_directory): import xlrd excel_file = xlrd.open_workbook(excel_file) spreadsheet = excel_file.sheet_by_index(sheet_index) for row in range(spreadsheet.nrows): v = spreadsheet.row_values(row) txt = open(export_directory + '/' + v[0] + '.key', 'w') if len(v[1]) > 3: txt.write(v[1] + '\n') else: txt.write(v[1] + ' major\n') txt.close() def matrix_to_excel(my_matrix, label_rows=('C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'), label_cols=('C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'), filename='matrix.xls'): import xlwt wb = xlwt.Workbook() ws = wb.add_sheet('Sheet1') start_row = 1 for label in label_rows: ws.write(start_row, 0, label) start_row += 1 start_col = 1 for label in label_cols: ws.write(0, start_col, label) start_col += 1 next_row = 1 next_col = 1 for row in my_matrix: col = next_col for item in row: ws.write(next_row, col, item) col += 1 next_row += 1 wb.save(filename)
import random import itertools from bisect import bisect def choices(population, weights=None, *, cum_weights=None, k=1): """Copy of source code for random.choices added to random module in 3.6 Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ if len(population) == 0: raise ValueError('Population cannot be empty') if cum_weights is None: if weights is None: total = len(population) return [population[int(random.random() * total)] for i in range(k)] cum_weights = list(itertools.accumulate(weights)) elif weights is not None: raise TypeError('Cannot specify both weights and cumulative weights') if len(cum_weights) != len(population): raise ValueError('The number of weights does not match the population') total = cum_weights[-1] return [population[bisect(cum_weights, random.random() * total)] for i in range(k)] def unbiased_var(label_list): n = len(label_list) if n < 2: return 0 mean = sum(label_list)/n tot = 0 for val in label_list: tot += (mean - val)**2 return tot/(n-1)
""" Author: Mark Arakaki Date: November 24, 2017 Personal Practice Use Create a program that takes in a list from user input and prints out the first and last element from that list. """ def listEnds(list): print "The first element in the list is %s." % list[0] print "The last element in the list is %s." % list[len(list)-1] return; userInput = "default" myList = [] while (userInput != "done"): userInput = raw_input("Please enter in numbers for your list. When you are done type in 'done'.\n"); if userInput != "done": myList.append(userInput); listEnds(myList);
import sqlite3 conn = sqlite3.connect('test_data.db') c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS events (event_ID INTEGER PRIMARY KEY AUTOINCREMENT, event_name TEXT, event_start_date REAL, event_end_date REAL, event_venue TEXT)") c.execute("CREATE TABLE IF NOT EXISTS tickets (ticket_ID INTEGER PRIMARY KEY AUTOINCREMENT, event_ID INTEGER, email_address TEXT, ticket_status BOOLEAN NOT NULL CHECK(ticket_status IN (0,1)), ticket_time_stamp REAL)") ''' def create_table(): c.execute("CREATE TABLE IF NOT EXISTS test_table (textCol TEXT, numCol INT)") def manual_data_entry(): c.execute("INSERT INTO test_table VALUES ('Some Text', 5)") conn.commit() create_table() manual_data_entry()'''
# Counts the occurence of words in a sentence def words(sentence): count_dict = {} for word in sentence.split(): # if key is a integer if word.isdigit(): count_dict.setdefault(int(word),0) count_dict[int(word)] += 1 # otherwise treated as a string else: count_dict.setdefault(word,0) count_dict[word] += 1 return count_dict
# Window Sum # Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, # find the sum of the element inside the window at each moving. # # Example # For array [1,2,7,8,5], moving window size k = 3. # 1 + 2 + 7 = 10 # 2 + 7 + 8 = 17 # 7 + 8 + 5 = 20 # return [10,17,20] ## Solution1: 更直白一点,先建一个长度为n-k+1的list, 这样就能save上一个sum是多少了 ## 分两个loop =》 比 Solution2稍微快一点 ## 极端情况也是O(N) 或 O(K) ## Time O(N) Space O(N) class Solution: """ @param nums: a list of integers. @param k: length of window. @return: the sum of the element inside the window at each moving. """ def winSum(self, nums, k): # write your code here ## corner cases if nums is None or len(nums) == 0: return nums if k >= len(nums): return [sum(nums)] ## initialize resultList with all 0s resultList = (len(nums) - k + 1) * [0] ## get first k sum for i in range(k): resultList[0] += nums[i] ## 规律就是:sum[2] = sum[1] - sum[i - 1] + nums[j] ## j = k + i - 1 for i in range(1, len(nums) - k + 1): # j = k + i - 1 resultList[i] = resultList[i - 1] + nums[k + i - 1] - nums[i - 1] return resultList class Solution: """ @param nums: a list of integers. @param k: length of window. @return: the sum of the element inside the window at each moving. """ ## Solution2. 同向双指针: 和solution 1基本属于一致,复杂度也是,极端的就是O(N)或 O(K) ## Time: O(NK) def winSum(self, nums, k): # write your code here ## corner cases if k == 1 or len(nums) == 0: return nums if k >= len(nums): return [sum(nums)] ## initialize result list/previous sum resultList = [] currentSum = 0 # previousStartIndex = 0 ## initialize j: moving pointer j = 0 for i in range(len(nums) - k + 1): while j <= k + i - 1 and j < len(nums): currentSum += nums[j] j += 1 if i != 0: currentSum -= nums[i - 1] # previousStartIndex = i resultList.append(currentSum) return resultList
""" Given an integer array, find the top k largest numbers in it. Example Example1 Input: [3, 10, 1000, -99, 4, 100] and k = 3 Output: [1000, 100, 10] Example2 Input: [8, 7, 6, 5, 4, 3, 2, 1] and k = 5 Output: [8, 7, 6, 5, 4] """ class Solution: """ @param nums: an integer array @param k: An integer @return: the top k largest numbers in array """ """ 方法一: 用quicksort =>晚点再写 """ """ 方法二:直接sort,但应该不行 Time: O(nlogk), Space: O(1) """ def topk(self, nums, k): # write your code here import heapq heapq.heapify(nums) return heapq.nlargest(k, nums)
""" Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top. Example Given nums = [1, 2, 4, 8, 6, 3] return 8 Given nums = [10, 9, 8, 7], return 10 """ """ 思路过程: increase first, then decrease =>问题是:既然是山并且基于example, 也就是有 可能这个山只有increase array or decrease array? =>觉得是 =>find the max of the list 1) if no time complexity requirement, the easiest way: one pointer => time: O(N), Space: O(1) 2) faster way:binary search => time: O(log(N)), Space: O(1) """ class Solution: """ @param nums: a mountain sequence which increase firstly and then decrease @return: then mountain top """ """ Time: O(log(N)) Space: O(1) """ def mountainSequence(self, nums): # write your code here ## corner cases if nums is None or len(nums) == 0: return None if len(nums) == 1: return nums[0] start, end = 0, len(nums) - 1 while start + 1 < end: mid = (start + end) // 2 ## mid_next = mid + 1 if nums[mid] < nums[mid + 1]: ## 跟后面那个比,没必要前后都比=>跟前面比可能出现没数的情况 start = mid + 1 elif nums[mid] > nums[mid + 1]: end = mid """可以问下有没可能升序或降序里面出现相等的情况 在这里我默认觉得是没有这种情况,所以没有判断==的情况 """ return max(nums[start], nums[end]) ## OR # return nums[start] if nums[start] > nums[end] else nums[end]
""" Given a list of words and an integer k, return the top k frequent words in the list. Example Example 1: Input: [ "yes", "lint", "code", "yes", "code", "baby", "you", "baby", "chrome", "safari", "lint", "code", "body", "lint", "code" ] k = 3 Output: ["code", "lint", "baby"] Example 2: Input: [ "yes", "lint", "code", "yes", "code", "baby", "you", "baby", "chrome", "safari", "lint", "code", "body", "lint", "code" ] k = 4 Output: ["code", "lint", "baby", "yes"] Challenge Do it in O(nlogk) time and O(n) extra space. Notice You should order the words by the frequency of them in the return list, the most frequent one comes first. If two words has the same frequency, the one with lower alphabetical order come first. """ class Solution: """ @param words: an array of string @param k: An integer @return: an array of string """ """ 思路过程: 要求先按cnt排序再按alphabetical 排序 O(N) 时间扫一遍list并存在一个dict{word: cnt} 直接能想到的就是扫一遍sort value in dict, 然后把word一个个 展开并存到heapq里按照value大小以及alphabetical大小, 最后返回nsmallest Time: O(NLOGN), Space:O(M) """ def topKFrequentWords(self, words, k): # write your code here ## corner cases if words is None or len(words) == 0: return [] if len(words) == 1: return words ## scan list and get word count dict word_dict = {} for word in words: if word not in word_dict: word_dict[word] = 1 else: word_dict[word] += 1 ## scan dict values and save into heapq from heapq import nsmallest, heappush, heappop heap = [] for word in word_dict: heappush(heap, (-word_dict[word], word)) # returnlist = [] # for freq, word in nsmallest(k, heap): # returnlist.append(word) # return returnlist """ or we can write as : """ return [word for freq, word in nsmallest(k, heap)]
"""Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example Consider the following matrix: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true. Challenge O(log(n) + log(m)) time """ """ 思路过程: matrix m * n row 1 ... => sorted integers m 1 3 5 7 9 10 13 15 find target return => True/False 如果硬做, Time: O(n * m), Space:O(1) 但如果要优化做,就要用到两次二分: Time: O(log(m) + log(n)), Space: O(1) """ class Solution: """ @param matrix: matrix, a list of lists of integers @param target: An integer @return: a boolean, indicate whether matrix contains target """ """ 方法一: 两次二分: 先确定大概在哪个row, 然后确定column Time: O(log(n) + log(m)), Space: O(1) """ def searchMatrix(self, matrix, target): # write your code here ### corner cases if len(matrix) == 0 or matrix is None: return False m, n = len(matrix), len(matrix[0]) ## compare target with start of medium row and get two rows at the end start_row, end_row = 0, m - 1 while start_row + 1 < end_row: med_row = (start_row + end_row) // 2 ## compare the first value of the row with target value if target == matrix[med_row][0]: return True elif target < matrix[med_row][0]: end_row = med_row - 1 else: ## target > matrix[med_row][0] start_row = med_row ## get two rows and compare with the last value of each rows if matrix[start_row][-1] == target or matrix[end_row][-1] == target: return True if matrix[start_row][-1] < target: target_row = end_row if matrix[start_row][-1] > target: target_row = start_row ## 二分法search target所在的那row的位置, 如果找不到return False start_col, end_col = 0, n - 1 while start_col + 1 < end_col: med_col = (start_col + end_col) // 2 if target == matrix[target_row][med_col]: return True elif target < matrix[target_row][med_col]: end_col = med_col - 1 else: start_col = med_col + 1 if matrix[target_row][start_col] == target: return True if matrix[target_row][end_col] == target: return True return False """ 方法二:直接确定medium position所在的column and row, 和target进行比较 Time: O(log(n * m)) = O(log(n) + log(m)), Space: O(1) """ def searchMatrix2(self, matrix, target): # write your code here ## corner cases if matrix is None or len(matrix) == 0: return False m, n = len(matrix), len(matrix[0]) start, end = 0, n * m - 1 ## 如果把list里元素全展开的index值 while start + 1 < end: mid_pos = (start + end) // 2 mid_row = mid_pos // n mid_col = mid_pos % n if matrix[mid_row][mid_col] == target: return True elif matrix[mid_row][mid_col] < target: start = mid_pos + 1 else: end = mid_pos - 1 start_row, start_col = start // n, start % n end_row, end_col = end // n, end % n if matrix[start_row][start_col] == target: return True if matrix[end_row][end_col] == target: return True return False
# Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. # Example: # # Input: "babad" # # Output: "bab" # # Note: "aba" is also a valid answer. # # # # Example: # # Input: "cbbd" # # Output: "bb" #Solutions Summary: # Solution 1/1.1: 中心点枚举法 # Solution 2: Manachester's algorithm O(n) # Solution 3: Suffix Array O(nlogn) # Solution 3: dynamic programing # Solution 4: brute force ## Solution 1 (中心点枚举法: Recommend) ## 类似前面那个solution, 利用palindrome数长度的奇偶性来选取中心店 class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ ## Corner Cases if s is None: return '' if len(s) == 1 or len(s) == 0: return s maxLen, maxStart = 0, 0 for i in range(len(s)): ## 长度为odd number palindromeLen = self.longestPalindromeLen(s, i, i) if palindromeLen > maxLen: maxLen = palindromeLen start = i - palindromeLen // 2 ## 长度为even number palindromeLen = self.longestPalindromeLen(s, i, i + 1) if palindromeLen > maxLen: maxLen = palindromeLen start = i - palindromeLen // 2 + 1 return s[start: start + maxLen] def longestPalindromeLen(self, s, left, right): palindromeLen = 0 while left >= 0 and right < len(s): if s[left] != s[right]: break if left == right: palindromeLen += 1 else: palindromeLen += 2 left -= 1 right += 1 return palindromeLen ## Solution1.1: loop每个字母并以每个字母为中心,向两端扩散看是否是palindrome并最长 (中心点枚举法: 没有solution 1好, 因为有重复代码) ## Time: O(N^2), Space: O(1) class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ ## corner cases: if len(s) == 1 or len(s) == 0: return s maxStr = '' maxLen = 0 for i in range(len(s) - 1): ## 根据 s[i + 1] 是否和s[i]相等,分奇数长度和偶数长度 ## even len # print "current i:", i if s[i + 1] == s[i]: if i - 1 < 0 or i + 2 >= len(s): if 2 > maxLen: maxStr = s[i: i + 2] maxLen = 2 # print("1: ", maxStr) else: left, right = i - 1, i + 2 while left >= 0 and right < len(s): if s[left] != s[right]: break left -= 1 right += 1 left, right = left + 1, right - 1 if right - left + 1 > maxLen: maxLen = right - left + 1 maxStr = s[left: right + 1] # print('2: ', maxStr) # print ("max string len is ", maxLen) # print ("i is ", i) ## odd len if i - 1 < 0 or i + 1 >= len(s): if 1 > maxLen: maxStr = s[i] maxLen = 1 # print('3: ', maxStr) else: # print ('3: i is ', i) left, right = i - 1, i + 1 # print ("3 : left is %d right is %d " %(left, right)) while left >= 0 and right < len(s): if s[left] != s[right]: break left -= 1 right += 1 left, right = left + 1, right - 1 # print("left is %d right is %d" % (left, right)) if right - left + 1 > maxLen: maxLen = right - left + 1 maxStr = s[left: right + 1] # print('4: ', maxStr) return maxStr # print (maxStr) # print (Solution().longestPalindrome('abcdzdca')) ### Solution 2: Manacher's algorithm:可以背!网上的答案! O(N)时间求字符串的最长回文子串 https://www.felix021.com/blog/read.php?2040 ### ## example # "babad" # "ccc" # "abcdzdcab" # "abcda" ## expected # "bab" # "ccc" # "cdzdc" # "a" ## Solution 3: suffix array ## Solution 4: dynamic programming ## solution 5: 从头开始遍历i = 0, j = i + 1 但小于len(s) =》 类似双指针 => 比较推荐solution 1/1.1 ## Lintcode 过了, leetcode 没过! ## Time O(N^3), Space O(1) class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ ## corner cases if len(s) == 1 or len(s) == 0: return s if self.isPalindrome(s, 0, len(s) - 1): return s maxLen = 0 maxstr = '' for i in range(len(s) - 1): j = i while j < len(s): if self.isPalindrome(string=s, start=i, end=j) and j - i + 1 > maxLen: maxstr = s[i: j + 1] maxLen = j - i + 1 j += 1 return maxstr ## 相向双指针: 判断是否是palindrome=>time: O(end - start) def isPalindrome(self, string, start, end): while start <= end: if string[start] != string[end]: return False start += 1 end -= 1 return True
# Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). # # Example 1: # Input: [3, 2, 1] # # Output: 1 # # Explanation: The third maximum is 1. # Example 2: # Input: [1, 2] # # Output: 2 # # Explanation: The third maximum does not exist, so the maximum (2) is returned instead. # Example 3: # Input: [2, 2, 3, 1] # # Output: 1 # # Explanation: Note that the third maximum here means the third maximum distinct number. # Both numbers with value 2 are both considered as second maximum. ### Solution 1: wrong # Runtime Error Message:# Line 9: IndexError: list index out of range # Last executed input: # [1,1,2] class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 3: return sorted(nums)[-1] return sorted(set(nums),reverse = True)[2] # changed to => 57ms O(1) space, O(n) Time Complexity class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ if len(set(nums)) < 3: return sorted(nums)[-1] return sorted(set(nums),reverse = True)[2] obj = Solution() print(obj.thirdMax([3, 2, 1])) print(obj.thirdMax([1, 2])) print(obj.thirdMax([2, 2, 3, 1])) print(obj.thirdMax([1, 3, 5, 6, 8, 8, 9, 13])) print(obj.thirdMax([1,1,2])) print ("\n") ### Solution 2: third max is to remove the first two max and then max the list is the third one ### Time O(N), space O(1) class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ if len(set(nums)) < 3: return max(nums) iter = 0 num_set = set(nums) while iter < 2: num_set.remove(max(num_set)) iter += 1 return max(num_set) obj = Solution() print(obj.thirdMax([3, 2, 1])) print(obj.thirdMax([1, 2])) print(obj.thirdMax([2, 2, 3, 1])) print(obj.thirdMax([1, 3, 5, 6, 8, 8, 9, 13])) print(obj.thirdMax([1,1,2])) print(obj.thirdMax([2,2,3,1])) print("\n") ### Solution 3: without use any built-in function such as max and sorted ### Time O(N), space O(1) ### Actually it's not kind of fast, but just want to try this method just in case class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ first = list(set(nums))[0] second = third = -float('inf') for num in list(set(nums))[1:]: # print (num) if num > first: third = second second = first first = num # print("first is ", first) elif num > second: third = second second = num # print ("second is ", second ) # print("third is ", third) elif num > third: third = num # print("third is ", third) # print (first, second, third) if third == -float('inf'): return first else: return third obj = Solution() print(obj.thirdMax([3, 2, 1])) print(obj.thirdMax([1, 2])) print(obj.thirdMax([2, 2, 3, 1])) print(obj.thirdMax([1, 3, 5, 6, 8, 8, 9, 13])) print(obj.thirdMax([1,1,2])) print(obj.thirdMax([2,2,3,1]))
# The Hamming distance between two integers is the number of positions at which the corresponding bits are different. # # Given two integers x and y, calculate the Hamming distance. # # Note: # 0 ≤ x, y < 231. # # Example: # # Input: x = 1, y = 4 # # Output: 2 # # Explanation: # 1 (0 0 0 1) # 4 (0 1 0 0) # ↑ ↑ # # The above arrows point to positions where the corresponding bits are different. ### Solution 1: use bit calculation method to compare x % 2 and y % 2, once different, then difference count +1 ### Time Complexity O(logN), Space Complexity O(1) class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ diff_cnt = 0 while x!= 0 or y !=0 : if x % 2 != y % 2: diff_cnt += 1 x = x // 2 y = y // 2 return diff_cnt print(Solution().hammingDistance(1,4)) #2 ### Solution 2: use bit calculation method in python to directly compare diff between binary x and y and count difference ### online solution! but it seems another way to compare ### Time Complexity O(N), Space Complexity O(1) class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x^y).count('1') print(Solution().hammingDistance(1,4)) #2
""" Find top k frequent words in realtime data stream. Implement three methods for Topk Class: TopK(k). The constructor. add(word). Add a new word. topk(). Get the current top k frequent words. Example TopK(2) add("lint") add("code") add("code") topk() >> ["code", "lint"] Notice If two words have the same frequency, rank them by alphabet. """ """ 思路过程: 跟topk 的题差不多只是这里要设计API 用于实际操作 => 可和之前题一样的做法,老是out of time limit! => 要改! 因为题是data stream, 假设数据量很大!!! Time: O(nlogk), Space: O(n) """ class TopK: """ @param: k: An integer """ def __init__(self, k): # do intialization if necessary self.k = k self.wordlist = [] # self.word_dict = {} """ @param: word: A string @return: nothing """ def add(self, word): # write your code here # from heapq import heappush self.wordlist.append(word) # print('wordlist is {}'.format(self.wordlist)) # word_dict = {} # for word in self.wordlist: # if word not in word_dict: # word_dict[word] = 1 # else: # word_dict[word] += 1 # self.heap = [] # for word in word_dict: # # print (word, ":", word_dict[word]) # heappush(self.heap, (-word_dict[word], word)) """ @return: the current top k frequent words. """ def topk(self): # write your code here from heapq import heappush word_dict = {} for word in self.wordlist: if word not in word_dict: word_dict[word] = 1 else: word_dict[word] += 1 heap = [] for word in word_dict: # print (word, ":", word_dict[word]) heappush(heap, (-word_dict[word], word)) from heapq import nsmallest # print ('heap is {}'.format(self.heap)) # for freq, word in nsmallest(self.k, self.heap): # print (word, "-----", freq) return [word for (freq, word) in nsmallest(self.k, heap)] def cmp_words(a, b): if a[1] != b[1]: return b[1] - a[1] return cmp(a[0], b[0]) class HashHeap: def __init__(self): self.heap = [0] self.hash = {} def add(self, key, value): self.heap.append((key, value)) self.hash[key] = self.heap[0] + 1 self.heap[0] += 1 self._siftup(self.heap[0]) def remove(self, key): index = self.hash[key] self._swap(index, self.heap[0]) del self.hash[self.heap[self.heap[0]][0]] self.heap.pop() self.heap[0] -= 1 if index <= self.heap[0]: index = self._siftup(index) self._siftdown(index) def hasKey(self, key): return key in self.hash def min(self): return 0 if self.heap[0] == 0 else self.heap[1][1] def _swap(self, a, b): self.heap[a], self.heap[b] = self.heap[b], self.heap[a] self.hash[self.heap[a][0]] = a self.hash[self.heap[b][0]] = b def _siftup(self, index): while index != 1: if cmp_words(self.heap[index], self.heap[index / 2]) < 0: break self._swap(index, index / 2) index = index / 2 return index def _siftdown(self, index): size = self.heap[0] while index < size: t = index if index * 2 <= size and cmp_words(self.heap[t], self.heap[index * 2]) < 0: t = index * 2 if index * 2 + 1 <= size and cmp_words(self.heap[t], self.heap[index * 2 + 1]) < 0: t = index * 2 + 1 if t == index: break self._swap(index, t) index = t return index def size(self): return self.heap[0] def pop(self): key, value = self.heap[1] self.remove(key) return value class TopK: # @param {int} k an integer def __init__(self, k): # initialize your data structure here self.k = k self.top_k = HashHeap() self.counts = {} # @param {str} word a string def add(self, word): # Write your code here if word not in self.counts: self.counts[word] = 1 else: self.counts[word] += 1 if self.top_k.hasKey(word): self.top_k.remove(word) self.top_k.add(word, self.counts[word]) if self.top_k.size() > self.k: self.top_k.pop() # @return {str[]} the current top k frequent word def topk(self): # Write your code here topk = self.top_k.heap[1:] topk.sort(cmp=cmp_words) return [ele[0] for ele in topk]
"""Corner Cases: better ask interviewer to confirm return value for corner cases""" if list is None or len(list) == 0 or k == 0: return [] """find closest element from target first in list: 利用helper function call binary search first to get closest index make that closet element a centered value and set two pointers i & j to get the k closest """ i = self.findLowerClosest(A, target) j = i + 1 return_list = list # return A to store sorted elemets according to |e.value - target| """这一段找k个element的入list的过程是enhanced的,只是喜欢这个的func design思想,别的没区别""" for index in range(k): if j > len(A) - 1 or (i >= 0 and abs(A[i] - target) <= abs(A[j] - target)): return_list.append(A[i]) i -= 1 else: return_list.append(A[j]) j += 1 return return_list """helper function for binary search""" def findLowerClosest(self, A, target): start, end = 0, len(A) - 1 """Removed closest_index 先定义,因为可以把找到的当成end,然后继续找最小的""" while start < end - 1: mid = (start + end) // 2 if A[mid] == target: end = mid elif A[mid] > target: end = mid else: start = mid return start if abs(A[start] - target) <= abs(A[end] - target) else end
""" Remove adjacent, repeated characters in a given string, leaving only one character for each group of such characters. Assumptions Try to do it in place. Examples “aaaabbbc” is transferred to “abc” Corner Cases If the given string is null, returning null or an empty string are both valid. """ class Solution(object): """ 解题思路:两根指针,一根追踪非重复,另一个动态追踪直到第一个重复结束然后直到结尾; 因为string是immutable=> we can transform to list first; 然后用in place来改变一个list并最后转为string Time: O(n) Space: O(n) """ def deDup(self, input): """ input: string input return: string """ # write your solution here """Corner Cases""" if input is None or len(input) <= 1: return input start = 0 # start index for a in-place list # move = 0 # input_list = list(input) # while move < len(input_list): # if input_list[move] != input_list[start]: # start += 1 # input_list[start] = input_list[move] # # move += 1 # input_list = input_list[: start + 1] # return ''.join(input_list) """ from 33 to 43 can also be re-written as the following""" input_list = list(input) for move in range(len(input_list)): if input_list[move] != input_list[start]: start += 1 input_list[start] = input_list[move] input_list = input_list[: start + 1] return ''.join(input_list) print(Solution().deDup('aaaabbbc')) # 'abc' print(Solution().deDup('')) # '' print(Solution().deDup('a')) # 'a'
""" Given inorder and postorder traversal of a tree, construct the binary tree. Example Example 1: Input: [1,2] [2,1] Output: {1,#,2} Explanation: 1 \ 2 Example 2: Input: [1,2,3] [1,3,2] Output: {2,1,3} Explanation: 2 / \ 1 3 Notice You may assume that duplicates do not exist in the tree. """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ """ 思路过程: given: inorder trasvesal result + postorder trasvesal result => guess original binary tree is 是个逆向的过程 inorder: left->root->right postorder: left->right->root 从已知条件来看,postorder的最后一位肯定是root所对应的值 => 通过确认root,就能 在inorder sequence里找出左子树和右子树distribution => 以此迭代循环 =>所以是recursion eg. 1 / \ 2 3 \ 4 inorder seq: 2->4->1->3 postorder seq: 4->2->3->1 recursions: 1. we know 1 is root => left tree: 2->4, right tree: 3 2. for left tree: inorder seq: 2->4 postorder: 4->2 => we know 2 is the root for left tree1, and 4 is its right tree => sub lefttree is None, sub right tree inorder: 4, postorder: 4 => we know 2.left = None => for sub righttree 4. we know 4 is the root, and no left and right tree => 4.left = None, 4.right = None => 2.right = 4 => 1.left =2 3. 同理, for right tree ** 记得想想如果用iteration试试看以后** """ class Solution: """ @param inorder: A list of integers that inorder traversal of a tree @param postorder: A list of integers that postorder traversal of a tree @return: Root of a tree """ """ Space: O(N), Time: O(N) """ def buildTree(self, inorder, postorder): # write your code here ## recursion end condition if not inorder: # 相当于inorder is None or len(inorder) == 0: return None rootval = postorder[-1] rootindex = inorder.index(rootval) root = TreeNode(rootval) root.left = self.buildTree(inorder[:rootindex], postorder[:rootindex]) root.right = self.buildTree(inorder[rootindex + 1:], postorder[rootindex: -1]) return root
""" Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example Example 1: Input: tree = {1,2,3} Output: true Explanation: This is a balanced binary tree. 1 / \ 2 3 Example 2: Input: tree = {3,9,20,#,#,15,7} Output: true Explanation: This is a balanced binary tree. 3 / \ 9 20 / \ 15 7 Example 3: Input: tree = {1,#,2,3,4} Output: false Explanation: This is not a balanced tree. The height of node 1's right sub-tree is 2 but left sub-tree is 0. 1 \ 2 / \ 3 4 """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ """ 思路过程: 涉及到任何subtree的左右子树高度之差都不能超过1,否则return false=>用divide and conquer的方法 Time: O(N) Space: O(N) 方法一和方法二都是divide and conquer,但第一种方法更适合Industrial """ class Solution: """ @param root: The root of binary tree. @return: True if this Binary tree is Balanced, or false. """ """ 方法一: divide and conquer => return set of int + bool """ def isBalanced(self, root): # write your code here if root is None: return True (height, returntype) = self.traverse(root) return returntype def traverse(self, node): if node is None: return (0, True) (leftH, returntype1) = self.traverse(node.left) (rightH, returntype2) = self.traverse(node.right) height = max(leftH, rightH) + 1 if returntype1 == False or returntype2 == False or abs(leftH - rightH) > 1: return (height, False) return (height, True) """ 方法二:divide and conquer: return值就设为int:看是否 == -1 height = positive int if true or return -1 if not satisfied """ def isBalanced(self, root): return self.traverse(root) != -1 def traverse(self, node): if node is None: return 0 leftH = self.traverse(node.left) if leftH == -1: return -1 rightH = self.traverse(node.right) if rightH == -1: return -1 if abs(leftH - rightH) > 1: return -1 return max(leftH, rightH) + 1