text
stringlengths
37
1.41M
"""Defines the Transform type.""" import math from typing import Optional class Transform: """A mutable object that represents a 2D translation and rotation.""" def __init__(self, parent: Optional["Transform"] = None): self._x = 0 self._y = 0 self._angle = 0 self._parent = parent @property def x(self): """This transform's global X translation.""" if self._parent: parent_angle = self._parent.angle return ( self._parent.x + self._x * math.cos(parent_angle) + self._y * math.sin(parent_angle) ) return self._x def add_x(self, dx): """Adds to this transform's X translation.""" self._x += dx def set_local_x(self, x): """Sets this transform's X translation relative to its parent.""" self._x = x @property def y(self): """This transform's global Y translation.""" if self._parent: parent_angle = self._parent.angle return ( self._parent.y - self._x * math.sin(parent_angle) + self._y * math.cos(parent_angle) ) return self._y def add_y(self, dy): """Adds to this transform's Y translation.""" self._y += dy def set_local_y(self, y): """Sets this transform's Y translation relative to its parent.""" self._y = y @property def angle(self): """This transform's global counterclockwise rotation in radians.""" if self._parent: return self._parent.angle + self._angle return self._angle def rotate(self, radians): """Rotates this transform counterclockwise.""" self._angle += radians def set_local_angle(self, radians): """Sets this transform's counterclockwise rotation relative to its parent. """ self._angle = radians
"""This module defines a factory to spawn collectable heart containers.""" import pygame from collectable_item import make_collectable_item from player import Player _extra_heart_image = pygame.image.load( "images/extra_heart.png" ).convert_alpha() def make_extra_heart(x: float, y: float): """Spawns a collectable heart container that restores the player's hearts at (x, y). """ def player_collect(player: Player): player.increment_hearts() make_collectable_item( x=x, y=y, image=_extra_heart_image, trigger_radius=16, player_collect=player_collect, )
english_to_french = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'} print(english_to_french.keys()) print(list(english_to_french.keys())) print(tuple(english_to_french.keys()))
def decoder(alphabet, letter): if letter == "a": alphabet[0] += 1 elif letter == "b": alphabet[1] += 1 elif letter == "c": alphabet[2] += 1 elif letter == "d": alphabet[3] += 1 elif letter == "e": alphabet[4] += 1 elif letter == "f": alphabet[5] += 1 elif letter == "g": alphabet[6] += 1 elif letter == "h": alphabet[7] += 1 elif letter == "i": alphabet[8] += 1 elif letter == "j": alphabet[9] += 1 elif letter == "k": alphabet[10] += 1 elif letter == "l": alphabet[11] += 1 elif letter == "m": alphabet[12] += 1 elif letter == "n": alphabet[13] += 1 elif letter == "o": alphabet[14] += 1 elif letter == "p": alphabet[15] += 1 elif letter == "q": alphabet[16] += 1 elif letter == "r": alphabet[17] += 1 elif letter == "s": alphabet[18] += 1 elif letter == "t": alphabet[19] += 1 elif letter == "u": alphabet[20] += 1 elif letter == "v": alphabet[21] += 1 elif letter == "w": alphabet[22] += 1 elif letter == "x": alphabet[23] += 1 elif letter == "y": alphabet[24] += 1 elif letter == "z": alphabet[25] += 1 alphabet = [0 for i in range(0, 26)] data = input("") data = list(data) for i in range(0, len(data)): letter = str(data.pop(0)) decoder(alphabet, letter) for i in range(0, alphabet.__len__()): print(alphabet[i], end=" ")
name = input() for i in name: if i.isupper(): print(i, end="")
while True: capital_letter = 0 small_letter = 0 numeric_letter = 0 space = 0 raw_data = input("") if raw_data == "": break for i in range(0, len(raw_data)): if raw_data[i] == " ": space += 1 elif raw_data[i].isnumeric(): numeric_letter += 1 elif raw_data[i].isupper(): capital_letter += 1 else: small_letter += 1 print(str(small_letter) + " " + str(capital_letter) + " " + str(numeric_letter) + " " + str(space))
def calc_time(char): if 'A' <= char < 'D': return 3 elif 'D' <= char < 'G': return 4 elif 'G' <= char < 'J': return 5 elif 'J' <= char < 'M': return 6 elif 'M' <= char < 'P': return 7 elif 'P' <= char < 'T': return 8 elif 'T' <= char < 'W': return 9 elif 'W' <= char <= 'Z': return 10 user_input = input() time_counter = 0 for i in user_input: time_counter += calc_time(i) print(time_counter)
count = input(""); a = list(); for i in range(0, int(count)): raw_data = input(""); a.append(int(raw_data[0]) + int(raw_data[2])); for i in a: print(i);
import requests city=input("Enter your city name:") url='http://api.openweathermap.org/data/2.5/weather?q={}&appid=4e4049498f5fd8ac61f8460d94449a3b'.format(city) res=requests.get(url) data=res.json() print(res) #print(data) Temperature=data['main']['temp'] Latitude=data['coord']['lat'] Longitude=data['coord']['lon'] weather=data['weather'][0]['description'] wind_speed=data['wind']['speed'] print("Temperature: {} " .format(Temperature)) print("Latitude: {}" .format(Latitude)) print("Longitude:{}" .format(Longitude)) print("weather:{} " .format(weather)) print("wind_speed: {}" .format(wind_speed))
numbers=[1,2,3,4,5,6,7,8] for x in numbers: if x % 2==0: print(x)
def raise_both(value1,value2): new_value1=value1**value2 new_value2=value2**value1 new_tuple=(new_value1,new_value2) return new_tuple result=raise_both(2,3) print(result)
import turtle my_turtle=turtle.Turtle() def square(length,angle): my_turtle.forward(length) my_turtle.right(angle) my_turtle.forward(length) my_turtle.right(angle) my_turtle.forward(length) my_turtle.right(angle) my_turtle.forward(length) square(300,90)
# The tic-tac-toe game! # Instructions X = "X" O = "O" EMPTY = " " TIE = "TIE" NUM_SQUARES = 9 def display_instructions(): # Displaying game Instructions. print \ """ Welcome to Tic-Tac-Toe, a showdown between a Human Brain and an Intelligent Computer. Brace yourself, human. The battle is on! Choose the moves like this. 0 | 1 | 2 __________ 3 | 4 | 5 ---------- 6 | 7 | 8 """ def ask_yes_no(question): # Ask a yes or no question response = None while response not in ("y", "n"): response = raw_input(question).lower() return response def ask_number(question, low, high): # Ask for a number withing a range response = None while response not in range(low, high): response = int(raw_input(question)) return response def pieces(): # Determines who goes first go_first = ask_yes_no("Do you want to go first? (y/n)") if go_first == 'y': print "\nThen take the first move. You will need it." human = X computer = O else: print "\nYou are brave! I'll go first." computer = X human = O return computer, human def new_board(): # Create a new empty board board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board def display_board(board): # Display board on screen print "\n\t", board[0], "|", board[1], "|", board[2] print "\t", "__________" print "\t", board[3], "|", board[4], "|", board[5] print "\t", "__________" print "\t", board[6], "|", board[7], "|", board[8], "\n" def legal_moves(board): # If an empty square is found, that is a legal move, otherwise not a legal move moves = [] for square in range(NUM_SQUARES): if board[square] == EMPTY: moves.append(square) return moves def winner(board): WAYS_TO_WIN = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) for row in WAYS_TO_WIN: if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: winner = board[row[0]] return winner if EMPTY not in board: return TIE return None def human_move(board, human): legal = legal_moves(board) move = None while move not in legal: move = ask_number("Where will you move? (0-8): ", 0, NUM_SQUARES) if move not in legal: print "That square is already occupied, foolish human. Choose another.\n" print "Cool." return move def computer_move(board, computer, human): board = board[:] BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) print "I shall take square number ", for move in legal_moves(board): board[move] = computer if winner(board) == computer: print move return move board[move] = EMPTY for move in legal_moves(board): board[move] = human if winner(board) == human: print move return move board[move] = EMPTY for move in BEST_MOVES: if move in legal_moves(board): print move return move def next_turn(turn): if turn == "X": return O else: return X def congrat_winner(the_winner, computer, human): if the_winner != TIE: print the_winner, "won!\n" else: print "It's a tie. \n" if the_winner == computer: print "I triumph once again. It proves that computers are superior to humans!" elif the_winner == human: print "No, no! It cannot be. Somehow you tricked me, human! \n" \ "But never again. I, the computer, so swears it." elif the_winner == TIE: print "Lucky Human. You managed to tie me. Go celebrate for this is the best you will ever achieve." def main(): display_instructions() computer, human = pieces() turn = X board = new_board() display_board(board) while not winner(board): if turn == human: move = human_move(board, human) board[move] = human else: move = computer_move(board, computer, human) board[move] = computer display_board(board) turn = next_turn(turn) the_winner = winner(board) if the_winner == computer or human: congrat_winner(the_winner, computer, human) # START main() raw_input("Press enter to exit")
testu = [1, 2, 3, 4] bla = [num for num in testu if num > 2] print(bla) foo = [ { 'hello': 'world' }, { 'hello': 'bar' }, ] baz = [item['hello'] for item in foo] print(baz)
class student (object): def __init__(self,age,level, name ,grade=None): self.name=name self.age=age self.level=level self.grade=grade or {} def setgrade(self,course, grade): self.grade[course]=grade def getGrade(self,course): return self.grade[course] s1=student(14, 9,"Merl", {"science":9}) s2=student(12, 7,"Bob", {"Math":7}) print (s1.getGrade("science"))
#!/usr/bin/env python3 # Module Docstring """ REST API FUNCTIONS This module would account for all possible functions for REST API testing. """ # Rest API Custom Libraries from rest_api_exception import StringSpaceException # Function for validation of palindrome def is_string_palindrome(string_var): """ Description: This is a function which helps you validate if a passed string is a palindrome. Arguments: string_var (str) :: Mandatory :: Example - hello Return: Type (bool) :: True for success ; False for failure Exception: StringSpaceException - If string passed has spaces Example: >>> is_string_palindrome("kayak") >>> True >>> is_string_palindrome("splunk") >>> False """ # Validate if the user has sent a string as an arg if isinstance(string_var, str): # Validate the string passed has no spaces if len(string_var.split(" ")) > 1: raise StringSpaceException("String can only be a single word without spaces!") # Reverse the string reverse_var = ''.join(reversed(string_var)) # Check if reverse equals string return string_var == reverse_var
from math import sqrt class PrimeNumber(): def __init__(self): super().__init__() def isPrimeNumber(self, num): if num == 1 or num == 0: return 'Not prime' for i in range(2, round(num / 2) + 1): if num % i == 0: return 'Not prime' return 'Prime' T = int(input()) c = PrimeNumber() l = [] for n in range(T): l.append(int(input())) for x in l: print(c.isPrimeNumber(x))
# These are the emails you will be censoring. The open() function is opening the text file that the emails are contained in and the .read() method is allowing us to save their contexts to the following variables: email_one = open("email_one.txt", "r").read() email_two = open("email_two.txt", "r").read() email_three = open("email_three.txt", "r").read() email_four = open("email_four.txt", "r").read() proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"] negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressed", "distressed", "concerning", "horrible", "horribly", "questionable"] def censor_word(text,word): censor = "" # Make the sensor the same length as the original word (incl spaces). for letter in word: if letter == " ": censor += " " else: censor += "#" result = text.replace(word,censor) return result #print(censor_word(email_one,'learning algorithms')) for word in proprietary_terms: email_two = censor_word(email_two,word) #print(email_two) for word in negative_words: words = email_three.split(' ') for i,w in enumerate(words): if w == word: words[i+1]='xx' email_three = ' '.join(words) email_three = censor_word(email_three,word) #print(email_three)
"""Q18 Create a class Building Create Appartment, House and Commercial Building class inheriting Building class. """ class Building: def __init__(self,storey): print("Building") self.storey = storey def storey(self): return f"{self.storey} storey" def greet(self): return f"I got {self.storey} which is the Tallest in my area" class Appartment(Building): def __init__(self,number): print("Appartment") self.number = number def flat_no(self): return f"{self.number} is my flat_no" def greet(self): return f"My flat number {self.number} is lucky to me" class House(Building): def __init__(self,name): print("House") # Ambulatory.__init__(self,name=name) # Aquatic.__init__(self, name=name) buld = Building(34) app = Appartment(3345) house = House("Sweet Home") print(house.storey()) print(app.flat_no()) print(house.greet())
""" Q19 class Progression: 2 ”””Iterator producing a generic progression. 3 4 Default iterator produces the whole numbers 0, 1, 2, ... 5 ””” 6 7 def init (self, start=0): 8 ”””Initialize current to the first value of the progression.””” 9 self. current = start 10 11 def advance(self): 12 ”””Update self. current to a new value. 13 14 This should be overridden by a subclass to customize progression. 15 16 By convention, if current is set to None, this designates the 17 end of a finite progression. 18 ””” 19 self. current += 1 20 21 def next (self): 22 ”””Return the next element, or else raise StopIteration error.””” 23 if self. current is None: # our convention to end a progression 24 raise StopIteration( ) 25 else: 26 answer = self. current # record current value to return 27 self. advance( ) # advance to prepare for next time 28 return answer # return the answer 29 30 def iter (self): 31 ”””By convention, an iterator must return itself as an iterator.””” 32 return self 33 34 def print progression(self, n) 35 ”””Print next n values of the progression.””” 36 print( .join(str(next(self)) for j in range(n))) a. Create implementation of an ArithmeticProgression class, which relies on Progression as its base class. The constructor for this new class accepts both an increment value and a starting value as parameters, although default values for each are provided. By our convention, ArithmeticProgression(4) produces the sequence 0,4, b. Implementation of geometric progression, in which each value is produced by multiplying the preceding value by a fixed constant, known as the base of the geometric progression. The starting point of a geometric progression is traditionally 1, rather than 0, because multiplying 0 by any factor results in 0. As an example, a geometric progression with base 2 proceeds as 1,2,4,8,16,... . c. Implement class FibonacciProgression(Progression): ”””Iterator producing a generalized Fibonacci progression.””” For example, if we start with values 4 and 6, the series proceeds as 4,6,10,16,26,42,. if name == __main__ : print( ‘Default progression: ‘) Progression( ).print progression(10) print(‘Arithmetic progression with increment 5: ‘) ArithmeticProgression(5).print progression(10) print( ‘Arithmetic progression with increment 5 and start 2: ‘) ArithmeticProgression(5, 2).print progression(10) print( ‘Geometric progression with default base: ‘) GeometricProgression( ).print progression(10) print( ‘Geometric progression with base 3: ‘) GeometricProgression(3).print progression(10) print( ‘Fibonacci progression with default start values: ‘) FibonacciProgression( ).print progression(10) print( ‘Fibonacci progression with start values 4 and 6: ‘) FibonacciProgression(4, 6).print progression(10) """ class Progression: """ Iterator producing a generic progression. Default iterator produces the whole numbers 0, 1, 2, ... """ def __init__ (self, start=0): self. current = start def advance(self): self. current += 1 def __next__ (self): if self. current is None: # our convention to end a progression raise StopIteration( ) else: answer = self. current # record current value to return self. advance() # advance to prepare for next time return answer # return the answer def __iter__ (self): return self def print_progression(self, n): #this function simply print out the result that is return from __next__ print(" ,".join(str(next(self)) for j in range(n))) class ArithmeticProgression(Progression): #here class ArithmeticProgresssion is defined and is inherited from base class Progression def __init__(self,increment, value): self.increment = increment self.value = value self.current = value def advance(self): #it replace the property of method advance of base class self.current = self.current + self.increment def __iter__(self): return self def __next__(self): answer = self.current self.advance() return answer def print_progression(self, n): print(" ,".join(str(next(self)) for j in range(n))) class GeometricProgression(Progression): #similarly, we define GeometricProgression and is inherited from baseclass Progression def __init__(self,incrementer): self.incrementer = incrementer self.current = 1 def __iter__(self): return self def advance(self): self.current = self.current * self.incrementer return self.current def __next__(self): answer = self.current self.advance() return answer def print_progression(self, n): """Print next n values of the progression.""" print(" ,".join(str(next(self)) for j in range(n))) class FibonacciProgression: def __init__(self, x, y): self.x = x self.y = y def __iter__(self): return self def __next__(self): self.x , self.y = self.y, self.x+self.y return self.y def print_progression(self, n): print(" ,".join(str(next(self)) for j in range(n))) if __name__ == '__main__': print( "Arithmetic progression with increment 5 and start 2:" ) ArithmeticProgression(5, 2).print_progression(10) print("Geometric progression with base 3: ") GeometricProgression(3).print_progression(10) print("‘Fibonacci progression with start values 4 and 6: ‘") FibonacciProgression(4, 6).print_progression(10)
from ability import Ability from weapon import Weapon from spell import Spell from armor import Armor from hero import Hero from team import Team from random import choice class Arena: def __init__(self): self.previous_winner = None def create_ability(self): name = "" while len(name) < 1: name = input("What is the ability name? ") max_damage = 0 while max_damage < 1: max_damage = input("What is the max damage of the ability? ") try: max_damage = int(max_damage) print(f"{name} has been added.") break except(ValueError, TypeError): max_damage = 0 print("Please enter a number.") return Ability(name, max_damage) def create_weapon(self): name = "" while len(name) < 1: name = input("What is the weapon name? ") max_damage = 0 while max_damage < 1: max_damage = input("What is the max damage of the weapon? ") try: max_damage = int(max_damage) print(f"{name} has been added.") break except(ValueError, TypeError): max_damage = 0 print("Please enter a number.") return Weapon(name, max_damage) def create_spell(self): name = "" while len(name) < 1: name = input("What is the spell name? ") max_damage = 0 while max_damage < 1: max_damage = input("What is the max damage of the spell? ") try: max_damage = int(max_damage) print(f"{name} has been added.") break except(ValueError, TypeError): max_damage = 0 print("Please enter a number.") return Spell(name, max_damage) def create_armor(self): name = "" while len(name) < 1: name = input("What is the armor name? ") max_block = 0 while max_block < 1: max_block = input("What is the max block of the armor? ") try: max_block = int(max_block) print(f"{name} has been added.") break except(ValueError, TypeError): max_block = 0 print("Please enter a number.") return Armor(name, max_block) def create_hero(self): print("\n") hero_name = "" while len(hero_name) < 1: hero_name = input("Hero's name: ") hero = Hero(hero_name) add_item = None while add_item != "5": add_item = input( "\n[1] Add ability\n[2] Add weapon\n[3] Add spell\n[4] Add armor\n[5] Done adding items\n\nYour choice: " ) if add_item == "1": abilty = self.create_ability() hero.add_ability(abilty) elif add_item == "2": weapon = self.create_weapon() hero.add_weapon(weapon) elif add_item == "3": spell = self.create_spell() hero.add_spell(spell) elif add_item == "4": armor = self.create_armor() hero.add_armor(armor) return hero def build_team(self, team): print("{:-^50}".format(team.name).upper()) members = None while not isinstance(members, int): members = input(f"number of members on your team: {team.name}?\n") try: numOfTeamMembers = abs(int(members)) team.remove_all_heros() for i in range(numOfTeamMembers): hero = self.create_hero() team.add_hero(hero) print("\n") print(f"{hero.name} has been added to {team.name}".upper()) break except(ValueError, TypeError): print("Please enter a number.") print("\n") def authorize(self, team): print( "{:-^50}".format(f"{team.name} compleating authorization").upper() ) for hero in team.heroes: if len(hero.abilities) == 0: print(f"{hero.name} is all clear for authorization") for ability in hero.abilities: if ability.max_damage > 100: print( f"{hero.name}'s {ability.name} is unauthorized for use" ) hero.abilities.remove(ability) else: print( f"{hero.name}'s {ability.name} has been authorized for use" ) if len(hero.armors) == 0: print(f"{hero.name} has no armor to authorize") for armor in hero.armors: if armor.max_block > 100: print( f"{hero.name}'s {armor.name} is unauthorized for use" ) hero.armors.remove(armor) else: print( f"{hero.name}'s {armor.name} has been authorized for use" ) print("\n") def team_battle(self, team_one, team_two): self.authorize(team_one) self.authorize(team_two) print("{:-^50}".format("FIGHT!")) team_one.attack(team_two) def surviving_heroes(self, team): survival_count = 0 for hero in team.heroes: if hero.is_alive(): print(f"{hero.name} has made it out of battle!") survival_count += 1 if not survival_count: print("no heroes survived") return survival_count def winning_team(self, team_one, team_one_survival_count, team_two, team_two_survival_count): if team_one_survival_count and team_two_survival_count: print("{:-^50}".format("Draw!No winner could be choosen").upper()) self.previous_winner = None elif team_one_survival_count: p = f"{team_one.name} won" print("{:=^50}".format(p).upper()) self.previous_winner = team_one else: p = f"{team_two.name} won" print("{:=^50}".format(p).upper()) self.previous_winner = team_two def kd_average(self, team): team_kills = 0 team_deaths = 0 for hero in team.heroes: team_kills += hero.kills team_deaths += hero.deaths if team_deaths == 0: team_deaths = 1 print(f"average K/D: {team_kills/team_deaths}") def show_stats(self, team_one, team_two): print("\n") print("{:-^50}".format("STATS")) print("\n") print(f"{team_one.name} stats: ".upper()) team_one_survival_count = self.surviving_heroes(team_one) self.kd_average(team_one) print("\n") print(f"{team_two.name} stats: ".upper()) team_two_survival_count = self.surviving_heroes(team_two) self.kd_average(team_two) print("\n") self.winning_team(team_one, team_one_survival_count, team_two, team_two_survival_count) print("\n") if __name__ == "__main__": game_is_running = True arena = Arena() team_one = Team("Team One") team_two = Team("Team Two") print("\n") print("{:-^50}".format("WELCOME TO THE ARENA")) print("\n") reward_weapons = [ Weapon("Big boots", 80), Weapon("Pillow", 63), Weapon("super bright flash light", 72), Weapon("Water gun", 92) ] arena.build_team(team_one) arena.build_team(team_two) while game_is_running: arena.team_battle(team_one, team_two) arena.show_stats(team_one, team_two) play_again = input("Play Again? Yes or No: ") if play_again.lower() == "n": game_is_running = False elif (play_again.lower() == "y"): team_one.revive_heroes() team_two.revive_heroes() try: chosen_hero = choice(arena.previous_winner.heroes) reward_weapon = choice(reward_weapons) chosen_hero.add_weapon(reward_weapon) print( f"{chosen_hero.name} was rewarded with a {reward_weapon.name}" ) except(AttributeError): pass edit_team = input("Edit your team? Yes or No: ") if edit_team.lower() == "y": arena.build_team(team_one) if __name__ == "__main__": game_is_running = True # Instantiate Game Arena arena = Arena() #Build Teams arena.build_team(team_one) arena.build_team(team_two) while game_is_running: arena.team_battle(team_one,team_two) arena.show_stats(team_one,team_two) play_again = input("Play Again? Y or N: ") #Check for Player Input if play_again.lower() == "n": game_is_running = False else: #Revive heroes to play again team_one.revive_heroes() team_two.revive_heroes()
from random import choice class Team: def __init__(self, name): self.name = name self.heroes = [] def remove_hero(self, name): foundHero = False for hero in self.heroes: if hero.name == name: self.heroes.remove(hero) foundHero = True if not foundHero: return 0 def remove_all_heros(self): self.heroes = [] def view_all_heroes(self): for hero in self.heroes: print(hero.name) def add_hero(self, hero): self.heroes.append(hero) def stats(self): for hero in self.heroes: kd = hero.kills / hero.deaths print(f"{hero.name} Kill/Deaths:{kd}") def revive_heroes(self, health=100): for hero in self.heroes: hero.current_health = hero.starting_health print(f"{hero.name} has been revived.") def attack(self, other_team): living_heroes = [] living_opponents = [] for hero in self.heroes: living_heroes.append(hero) for hero in other_team.heroes: living_opponents.append(hero) while len(living_heroes) > 0 and len(living_opponents) > 0: chosen_hero = choice(living_heroes) chosen_opponent = choice(living_opponents) print(f"{chosen_hero.name} vs {chosen_opponent.name}".upper()) winner = chosen_hero.fight(chosen_opponent) if winner == chosen_hero.name: living_opponents.remove(chosen_opponent) elif winner == chosen_opponent.name: living_heroes.remove(chosen_hero) else: break
""" Tuples are like lists. Tuples are immutable, but you can change lists """ my_list = [1,2,3] print(my_list) my_list[0] = 0 print(my_list) my_tuple = (1,2,3,4,5,6) print(my_tuple) # my_tuple[0] = 0 Assignment not allowed print(my_tuple[0]) print(my_tuple[1:]) print(my_tuple.index(4)) print(my_tuple.count(3)) t = 12345, 54321, 'hello!' print(t) u = t, (1, 2, 3, 4, 5) print(u) # tyhjä tuple ja 1 item tuplessa empty = () single_item = 'hello', # <-- note trailing comma print(len(empty)) print(len(single_item)) print(single_item)
and_output1 = (10==10) and (10 > 9) and_output2 = (10==11) and (10 > 9) and_output3 = (10!=10) and (10 <= 9) or_output1 = (10==10) or (10 < 9) or_output2 = (10==10) or (10 < 9) or_output3 = (10!=10) or (10 < 9) not_true = not(10 == 10) not_false = not (10 > 10) print(and_output1) print(and_output2) print(and_output3) print(or_output1) print(or_output2) print(or_output3) print(not_false) print(not_true) """ order of evaluation 1. not 2. and 3. or """ bool_output = True or not False and False # True print(bool_output) bool_output1 = 10 == 10 or not 10 > 10 and 10 > 10 print(bool_output1) # False bool_output2 = (10 == 10 or not 10 > 10) and 10 > 10 print(bool_output2)
""" == value aquality != not equal to < less than > greater than <= less than or equal to >= greater than or equal to """ bool_one = 10 == 20 not_equal = 10 != 10 greater_than = 10 > 9 less_equal = 10 <= 10 print(bool_one) print(not_equal) print(greater_than) print(less_equal)
mark=int(input("give a positive number:")) if mark > 100 or mark < 0: print("Wrong input") elif mark>=80: print("it is A+") elif mark>=70: print("it is A") elif mark>=60: print("it is A-") elif mark>=50: print("it is B") elif mark >= 40: print("it is C") elif mark >= 33: print("it is D") else: print("it is fail")
if __name__ == '__main__': list= [] n=int(input("enter the number: ")) for i in range(0, n): element=int(input("enter the number the element: ")) list.append(element) print(list)
# Ask the user for a number and determine whether the number is prime or not. def prime_check(a): check = True for i in range(2, a): if a % i == 0: check = False break return check if __name__ == '__main__': num = int(input('Enter the number: ')) check1 = prime_check(num) if check1 is True: print('Number is Prime') else: print('Number is not Prime')
#Functions missing---- #Updating stock #Function to get change from stock def greedy(bal): nickels=25 dimes=25 quarters=25 ones=0 fives=0 while bal>=25: #If money can be converted to quarters print(bal//25,"quarter(s)") quarters=quarters-(bal//25) bal=bal%25 continue while bal>=10:#if money can be converted to dimes print(bal//10,"dime(s)") dimes=dimes-(bal//10) bal=bal%10 continue while bal>=5:#if money can be converted to nickels print(bal//5,"nickel(s)") nickels=nickels-(bal//5) break else:#If person requests refund before inserting money print("0 cents") print(f"Stock contains:\n {nickels} nickels\n {dimes} dimes\n {quarters} quarters") #creating function gives change def change(total_deposit,price1): print("Take the change below.") #giving balance balance=total_deposit-price1 bal=round(balance*100) greedy(bal) #creating function that prints purchase price def purchase_price(price): a=price//1 #Gives number of dollars b=price%1 #Gives number of cents if a==0: payment_due=print(f"Payment due:{b*100:.0f} cents") else: payment_due=print(f"Payment due:{a:.0f} dollars and {b*100:.0f} cents") #creating function to accept deposit def deposit(): ones=0 fives=0 purchase_price(price1) total_deposit=0 while price1>total_deposit: test_price=price1 dep=input("Indicate your deposit:") if dep=="c": #Giving refund change(total_deposit,0) break elif dep=="f": total_deposit=total_deposit+5 test_price=test_price-total_deposit fives=fives+1 if total_deposit<price1: purchase_price(test_price) else: change(total_deposit, price1) continue elif dep=="o": total_deposit=total_deposit+1 test_price=test_price-total_deposit ones=ones+1 if total_deposit<price1: purchase_price(test_price) else: change(total_deposit, price1) continue elif dep=="q": total_deposit=total_deposit+0.25 test_price=test_price-total_deposit if total_deposit<price1: purchase_price(test_price) else: change(total_deposit, price1) continue elif dep=="d": total_deposit=total_deposit+0.1 test_price=test_price-total_deposit if total_deposit<price1: purchase_price(test_price) else: change(total_deposit, price1) continue elif dep=="n": total_deposit=total_deposit+0.05 test_price=test_price-total_deposit if total_deposit<price1: purchase_price(test_price) else: change(total_deposit, price1) continue else: print("Illegal selection:",dep) continue print(f" {ones} ones\n {fives} fives") #creating function for menu of deposit selection def deposit_menu(): print("\nMenu for deposits:\n") print(""" 'n' - deposit a nickel 'd' - deposit a dime 'q' - deposit a quarter 'o' - deposit a one dollar bill 'f' - deposit a five dollar bill 'c' - cancel the purchase """) #main program #initializing money nickels=25 dimes=25 quarters=25 ones=0 fives=0 print("Welcome to the vending machine change maker program") print("Change maker initialized.") print(f"Stock contains:\n {nickels} nickels\n {dimes} dimes\n {quarters} quarters\n {ones} ones\n {fives} fives") while True: try: #requesting for price input price=input("Enter the purchase price (xx.xx) or `q' to quit:") if price=="q": print("Quiting....") break price1=float(price) if (price1>0) and ((price1*100)%5==0): deposit_menu() deposit() else: print("Illegal price: Must be a non-negative multiple of 5 cents.") except: print("Invalid input!!") continue
def computepay(hours,rate): extra=(hours-40)*rate*1.5 if hours>40: pay=extra+(40*rate) else: pay=hours*rate print("Pay:",pay) try: hours=float(input("Enter Hours:")) rate=float(input("Enter Rate:")) except: print("Please enter numeric input:") exit() computepay(hours,rate)
def investment(C,r,n,t): p=C*((1+((r)/n))**(t*n)) return p try: C=float(input("Enter initial amount:")) r=float(input("Enter the yearly rate:")) t=float(input("Enter years till maturation:")) n=float(input("Enter compound interest:")) except: print("Invalid input!!!") exit() print(f"The final value is {investment(C,r,t,n):,.2f}")
from lab_python_oop.Circle import Circle from lab_python_oop.Rectangle import Rectangle from lab_python_oop.Square import Square import pygame # another module loaded using pip def main(): """It's main function that is called after this module is launched.""" variant = 20 # variant number in your group color = ['синий', 'зеленый', 'красный'] # colors of the figures call_my_packet(variant, color) call_other_packet(variant, color) def call_my_packet(variant, color): """Using of my own modules. Variant is number of variant. Color is list of 3rd colors: rectangle, circle, square.""" print('В соответствии со входными данными: ') my_rect = Rectangle(variant, variant, color[0]) print(my_rect) my_circle = Circle(variant, color[1]) print(my_circle) my_square = Square(variant, color[2]) print(my_square) def call_other_packet(variant, color): """Using of another module. Variant is number of variant. Color is list of 3rd colors: rectangle, circle, square.""" flag_error = False # shows if there is incorrect parameters fps = 10 # number of frames per second start_pos_x, start_pos_y = 0, 0 # starting position of print in the window screen_size_x, screen_size_y = 320, 240 # the size of the window if (start_pos_x + 4 * variant) > screen_size_x or (start_pos_y + 4 * variant) > screen_size_y or variant < 1: max_var = min((screen_size_x - start_pos_x) / 4, (screen_size_y - start_pos_y) / 4) while variant < 1 or variant > max_var: flag_error = True print("""При таком значении 'variant' картинка не будет правильно отображаться. Выберите значение от 1 до {}: """.format(max_var), end="") try: variant = int(input()) except ValueError: pass step = {'rect_x': start_pos_x, 'rect_y': start_pos_y, # coordinates for showing in the window 'circle_x': start_pos_x + 2*variant, 'circle_y': start_pos_y + 2*variant, 'square_x': start_pos_x + 3*variant, 'square_y': start_pos_y + 3*variant} color_rgb = {'rect': color[0], 'circle': color[1], 'square': color[2]} # for changing text-color to rgb-color find_rgb(color_rgb) if flag_error: print("-----------Новые данные-----------") call_my_packet(variant, color) pygame.init() sc = pygame.display.set_mode((screen_size_x, screen_size_y)) sc.fill((255, 255, 255)) pygame.draw.rect(sc, color_rgb['rect'], (step['rect_x'], step['rect_y'], variant, variant)) pygame.draw.circle(sc, color_rgb['circle'], (step['circle_x'], step['circle_y']), variant) pygame.draw.rect(sc, color_rgb['square'], (step['square_x'], step['square_y'], variant, variant)) clock = pygame.time.Clock() pygame.display.update() while True: clock.tick(fps) for i in pygame.event.get(): if i.type == pygame.QUIT: return def find_rgb(color_rgb): """Giving of the conformity text-color and rgb-color. Color_rgb is dict that keeps the names of colors. This function changes color_rgb from text to rgb-format""" name = {'rect': 'прямоугольник', 'circle': 'окружность', 'square': 'квадрат'} for i in color_rgb: not_find = True while not_find: if color_rgb[i] == 'красный': color_rgb[i] = (255, 0, 0) not_find = False elif color_rgb[i] == 'зеленый' or color_rgb[i] == 'зелёный': color_rgb[i] = (0, 255, 0) not_find = False elif color_rgb[i] == 'синий': color_rgb[i] = (0, 0, 255) not_find = False else: color_rgb[i] = input("""В программе задан неожиданный цвет для фигуры '{}'. Выберите для нее один из цветов: 'красный', 'зеленый', 'синий': """.format(name[i])) if __name__ == '__main__': main()
import lab_python_oop.Rectangle as Rect class Square(Rect.Rectangle): __name = 'Квадрат' def __init__(self, length, color): self._length = length self._width = length self._color = color @staticmethod def get_name(): return Square.__name def __repr__(self): return '''{} имеет {} цвет, длину {}. Его площадь {}'''.format(Square.get_name(), self._color, self._length, self.space())
from abc import ABC, abstractmethod, abstractproperty class Business_lunch(ABC): """ Интерфейс Строителя объявляет создающие методы для различных частей объектов Продуктов. """ @abstractproperty def lunch(self): """Продуктом является ланч.""" pass @abstractmethod def add_first_dish(self): pass @abstractmethod def add_second_dish(self): pass @abstractmethod def add_salad(self): pass @abstractmethod def add_drink(self): pass class Business_lunch_1(Business_lunch): """Конкретный строитель, строящий ланч первого типа.""" def __init__(self): self.reset() def reset(self): self._lunch = Lunch() @property def lunch(self): lunch = self._lunch return lunch def add_first_dish(self): self._lunch.add("Суп с овощами", 100) def add_second_dish(self): self._lunch.add("Котлета с пюре", 150) def add_salad(self): self._lunch.add("Салат \"Цезарь\"", 125) def add_drink(self): self._lunch.add("Компот вишнёвый", 90) def add_all(self): self.add_first_dish() self.add_second_dish() self.add_salad() self.add_drink() class Business_lunch_2(Business_lunch): """Конкретный строитель, строящий ланч второго типа.""" def __init__(self): self.reset() def reset(self): self._lunch = Lunch() @property def lunch(self): lunch = self._lunch return lunch def add_first_dish(self): self._lunch.add("Солянка", 130) def add_second_dish(self): self._lunch.add("Шашлык из свинины", 225) def add_salad(self): self._lunch.add("Салат \"Овощной\"", 100) def add_drink(self): self._lunch.add("Чай чёрный", 60) def add_all(self): self.add_first_dish() self.add_second_dish() self.add_salad() self.add_drink() class Lunch(): def __init__(self): self.lunch = [] self.sum = 0 def add(self, dish, price): self.lunch.append(dish) self.sum += price def list_lunch(self): return f"{', '.join(self.lunch)}" def get_sum(self): return self.sum if __name__ == '__main__': print('Заказ №1 с первого ланча') order = Business_lunch_1() order.add_first_dish() order.add_second_dish() order.add_drink() print(order.lunch.list_lunch()) print('\nЗаказ №2 с первого ланча') order.reset() order.add_second_dish() order.add_salad() print(order.lunch.list_lunch()) print('\nЗаказ №3 со второго ланча') order = Business_lunch_2() order.add_all() print(order.lunch.list_lunch())
# Import Sqlite3 import sqlite3 as sql # Import de PrettyTable (affichage du tableau dans la console) from prettytable import from_db_cursor CREATE_ARTICLE_TABLE = "CREATE TABLE IF NOT EXISTS Articles(id INTEGER PRIMARY KEY, designation TEXT, prix INTEGER, quantité unitaire TEXT, acheteur TEXT REFERENCES Personne(id))" INSERT_ARTICLE = "INSERT INTO Articles (designation, prix, quantité, acheteur) VALUES (?, ?, ?, ?)" CREATE_PERSON_TABLE = "CREATE TABLE IF NOT EXISTS Personne(id INTEGER PRIMARY KEY, nom TEXT, prénom TEXT, produit TEXT, FOREIGN KEY(produit) REFERENCES Articles(designation))" INSERT_PERSON = "INSERT INTO Personne (nom, prénom, produit) VALUES (?, ?, ?)" '''CREATE TABLE IF NOT EXISTS Personne(id INTEGER PRIMARY KEY, nom TEXT, prénom TEXT, produit TEXT, FOREIGN KEY(produit) REFERENCES Articles(designation))''' MENU_PROMPT = """ # ========================================= # Bienvenu sur l'interface NSI Apéritif : # ========================================= Quelle action souhaitez vous effectuez ? répondre par 1,2,3,4 ou 5: 1 - C - Ajouter un convive, un article. 2 - R - Consulter la liste des articles 3 - U - Modifier la personne apportant tel ou tel article. 4 - D - Supprimer un article ou une personne. 5 - Quitter l'application. Je veux choisir l'option : """ ######################## Application ####################### # Création de table (si non existante) def create_table(): connection = sql.connect("aperitif.db") cursor = connection.cursor() cursor.execute(CREATE_ARTICLE_TABLE) cursor.execute(CREATE_PERSON_TABLE) connection.commit() connection.close() # Afficher une table (avec PrettyTable) def show_table(table): connection = sql.connect("aperitif.db") cursor = connection.cursor() query = ''' SELECT * FROM {}'''.format(table) cursor.execute(query) connection.commit() mytable = from_db_cursor(cursor) print("La table actuellement ⏬\n", mytable) connection.close() # Ajouter une personne dans la table Personne def add_person(last_name, first_name, product): connection = sql.connect("aperitif.db") cursor = connection.cursor() cursor.execute(INSERT_PERSON, (last_name, first_name, product)) connection.commit() connection.close() # Ajouter un produit dans la table Produits def add_product(product_name, price, quantity, buyer): connection = sql.connect("aperitif.db") cursor = connection.cursor() cursor.execute(INSERT_ARTICLE, (product_name, price, quantity, buyer)) connection.commit() connection.close() # Avoir la liste des articles (sous forme de tableau(x)) def get_articles(select): connection = sql.connect("aperitif.db") cursor = connection.cursor() if select == "1": query = ''' SELECT * FROM Articles ''' cursor.execute(query) mytable = from_db_cursor(cursor) print("\n\nTable de la liste complète ⏬\n\n", mytable) elif select == "2": query_2 = ''' SELECT Articles.designation, Articles.prix, Articles.quantité, Personne.nom, Personne.prénom FROM Articles INNER JOIN Personne ON Articles.designation = Personne.produit ''' cursor.execute(query_2) mytable_2 = from_db_cursor(cursor) print("\n\nTable pour les produits dont on connait le nom de l'acheteur ⏬\n\n", mytable_2) elif select == "3": query_3 = ''' SELECT designation, prix, quantité FROM Articles WHERE acheteur = "NULL" ''' cursor.execute(query_3) mytable_3 = from_db_cursor(cursor) print("\n\nTable pour les produits dont on ne connait pas le nom de l'acheteur ⏬\n\n", mytable_3) elif select == "4": query_4 = ''' SELECT id, nom, prénom FROM Personne ''' cursor.execute(query_4) mytable_4 = from_db_cursor(cursor) print("\n\nTable pour savoir la liste des convives ⏬\n\n", mytable_4) else: pass # Mettre à jour un acheteur (convive) def update_buyer(id, last_name, first_name): connection = sql.connect("aperitif.db") cursor = connection.cursor() query = ''' UPDATE Personne SET nom = '{}', prénom = '{}' WHERE id = {}'''.format(last_name, first_name, id) cursor.execute(query) connection.commit() connection.close() # Mettre à jour la quantité def update_quantity(quantity, id): connection = sql.connect("aperitif.db") cursor = connection.cursor() query = ''' UPDATE Articles SET quantité = '{}' WHERE id = {}'''.format(quantity, id) cursor.execute(query) connection.commit() connection.close() # Supprimer un produit def delete_product(id): connection = sql.connect("aperitif.db") cursor = connection.cursor() query = ''' DELETE FROM Articles WHERE id = {} '''.format(id) cursor.execute(query) connection.commit() connection.close() # Supprimer une personne def delete_person(id): connection = sql.connect("aperitif.db") cursor = connection.cursor() query = ''' DELETE FROM Personne WHERE id = {}'''.format(id) cursor.execute(query) connection.commit() connection.close() create_table() ############# Application ############# def app(): while(user_input := input(MENU_PROMPT)) != "5": if user_input == "1": select = input( "Vous souhaitez ajouter un convive ou un article?\nTapez 1 pour un convive. Tapez 2 pour un article ") if select == "1": last_name = input("Entrer le nom du convive ? : ") first_name = input("Entrer le prénom du convive: ") product = input("Entrer le nom du produit qu'elle va amener: ") price = input("Quel est le prix du produit: ") quantity = input("Entrez la quantité du produit: ") add_product(product, price, quantity, last_name) add_person(last_name, first_name, product) elif select == "2": product_name = input("Entrer le nom du produit: ") price_product = input( "Entrer le prix du produit (à l'unité): ") product_qty = input("Entrer la quantité du produit: ") product_buyer_intro = input( "Souhaitez-vous renseignez le nom de l'acheteur ? [Oui / Non]: ") if product_buyer_intro == "Oui": last_name = input("Entrer le nom du convive ? : ") first_name = input("Entrer le prénom du convive: ") add_person(last_name, first_name, product_name) add_product(product_name, price_product, product_qty, last_name) elif product_buyer_intro == "Non": no_buyer = 'NULL' add_product(product_name, price_product, product_qty, no_buyer) pass else: print("Selectionnez 1 ou 2...") elif user_input == "2": select = input('''Tapez 1 ⏩ si vous souhaitez consulter la liste complète des articles\nTapez 2 ⏩ si vous souhaitez la liste des articles dont l'acheteur est connu\nTapez 3 ⏩ si vous souhaitez la liste des articles qui n'ont pas d'acheteur\nTapez 4 ⏩ si vous souhaitez consulter la liste des convives\n''') get_articles(select) elif user_input == "3": select = input( '''Tapez 1 ⏩ si vous souhaitez modifier l"acheteur d'un article\nTapez 2 ⏩ si vous souhaitez modifier la quantité d'un article\n''') if select == "1": show_table("Personne") id = int(input("Entrez l'id: ")) last_name = input("Entrer le nom de famille: ") first_name = input("Entrer le prénom: ") update_buyer(id, last_name, first_name) elif select == "2": show_table("Articles") id = int(input("Entrer l'id: ")) quantity = input("Entrer la quantité souhaitez : ") update_quantity(quantity, id) elif user_input == "4": select = input( '''Tapez 1 si vous souhaitez supprimer un article\nTapez 2 si vous souhaitez supprimer un convive\n''') if select == "1": show_table("Articles") id = int( input("Enter l'id du produit que vous souhaitez supprimer: ")) delete_product(id) print("\nVotre produit a bien été supprimé 😎") elif select == "2": show_table("Personne") id_2 = int( input("Entrer l'id de la personne que vous souhaitez supprimer: ")) delete_person(id_2) delete_product(id_2) print("\nLe convive a bien été supprimé 😎") else: print("Oups... 😥... essayez encore !") app()
# -*- coding: utf-8 -*- """ Created on Tue Jul 20 11:32:28 2021 @author: nitac """ score = input('成績?') score= int(score) if score >= 60: print('及格') else: print('不及格') score=int(input('成績?')) if score>=90: print('A') elif score>=75: print('B') elif score>=60: print('C') else: print('D') math=input('數學成績?') math=int(math) eng=input('英文成績?') eng=int(eng) if math>=90 and eng >=90: print('有獎學金') elif math==100 or eng ==100: print('有獎學金') else: print('沒獎學金') math=input('數學成績?') math=int(math) eng=input('英文成績?') eng=int(eng) if math>=90 and eng>=90: print('有獎品') elif math<60 and eng<60: print('要處罰') else: print('OK')
parrot = "Norwegian Blue" print(parrot[3]) age = 24 print("My age is " + str(age) + " years old") print("My age is {0} years".format(age)) print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6}, and {7}".format(31, "January", "March", "May", "July", "August", "October", "December")) for i in range(1, 12): print("{0:2} squared is {1:<4} and cubed is {2:<4}".format(i, i ** 2, i ** 3)) print("Pi is approximately {0:12.50}".format( 22 / 7 ))
""" Написать функцию odd_sum, которая принимает список, который может состоять из различных элементов. Если все элементы списка целые числа, то функция должна посчитать сумму нечетных чисел. Если хотя бы один элемент не является целым числом, то выкинуть ошибку TypeError с сообщением "Все элементы списка должны быть целыми числами" Задачу стоит выполнить с помощью одного цикла Написать блок if __name__ == '__main__', в котором нужно описать обработку исключения try-except-else-finally """ def odd_sum(int_list: list) -> int: summa = 0 for item in int_list: if type(item) != int: raise TypeError('Все элементы списка должны быть целыми числами') elif item % 2 != 0: summa += item return summa if __name__ == '__main__': some_list = [1, 2, 3, '123'] try: odd_sum(some_list) except TypeError as exc: print(exc) print("Все элементы списка должны быть целыми числами") except ValueError as exc: print(exc) print("Все элементы списка должны быть целыми числами")
def bracket_matcher(my_input): start = ["[","{","("] close = ["]","}",")"] stack = [] for i in my_input: if i in start: stack.append(i) elif i in close: position = close.index(i) if ((len(stack) > 0) and (start[position] == stack[len(stack)-1])): stack.pop() else: return False if len(stack) == 0: return True print(bracket_matcher('abc(123)')) # returns true print(bracket_matcher('a[b]c(123')) # returns false -- missing closing parens print(bracket_matcher('a[bc(123)]')) # returns true print(bracket_matcher('a[bc(12]3)')) # returns false -- improperly nested print(bracket_matcher('a{b}{c(1[2]3)}')) # returns true print(bracket_matcher('a{b}{c(1}[2]3)')) # returns false -- improperly nested print(bracket_matcher('()')) # returns true print(bracket_matcher('[]]')) # returns false - no opening bracket to correspond with last character print(bracket_matcher('abc123yay')) # returns true -- no brackets = correctly matched
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } should_take_the_poll = ('terry', 'simon', 'dave', 'phil') for person in should_take_the_poll: if person in favorite_languages.keys(): print(f'Thanks for responding to the poll, {person.title()}.') else: print(f'{person.title()}, you should take this poll.')
while True: word = input("You're stuck in an infinite loop! Enter the secret word to leave the loop: ") if word == "chupacabra": break print("You've successfully left the loop!")
greeting = 'Hello,' greeting += '\nWhat brand of car are you lokking to rent? ' answer = input(greeting) print(f"Let me see I can find you a {answer.title()}.")
print("+---"*3, end = "+\n") print("| "*3, end = "|")
animals = [ 'lions', 'tigers', 'jaguars' ] for animal in animals: print (animal,"are really cool!") print('all of these animals are really cool!')
"""A Data Provder that reads parallel (aligned) data. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.contrib.slim.python.slim.data import data_provider from tensorflow.contrib.slim.python.slim.data import parallel_reader from tensorflow.python.ops import data_flow_ops from tensorflow.python.training import queue_runner class ParallelDataProvider(data_provider.DataProvider): """Creates a ParallelDataProvider. This data provider reads two datasets in parallel, keeping them aligned. Args: dataset1: The first dataset. An instance of the Dataset class. dataset2: The second dataset. An instance of the Dataset class. Can be None. If None, only `dataset1` is read. num_readers: The number of parallel readers to use. shuffle: Whether to shuffle the data sources and common queue when reading. num_epochs: The number of times each data source is read. If left as None, the data will be cycled through indefinitely. common_queue_capacity: The capacity of the common queue. common_queue_min: The minimum number of elements in the common queue after a dequeue. seed: The seed to use if shuffling. """ def __init__(self, dataset1, dataset2, shuffle=True, num_epochs=None, common_queue_capacity=4096, common_queue_min=1024, seed=None): if seed is None: seed = np.random.randint(10e8) _, data_source = parallel_reader.parallel_read( dataset1.data_sources, reader_class=dataset1.reader, num_epochs=num_epochs, num_readers=1, shuffle=False, capacity=common_queue_capacity, min_after_dequeue=common_queue_min, seed=seed) data_target = "" if dataset2 is not None: _, data_target = parallel_reader.parallel_read( dataset2.data_sources, reader_class=dataset2.reader, num_epochs=num_epochs, num_readers=1, shuffle=False, capacity=common_queue_capacity, min_after_dequeue=common_queue_min, seed=seed) # Optionally shuffle the data if shuffle: shuffle_queue = data_flow_ops.RandomShuffleQueue( capacity=common_queue_capacity, min_after_dequeue=common_queue_min, dtypes=[tf.string, tf.string], seed=seed) enqueue_ops = [] enqueue_ops.append(shuffle_queue.enqueue([data_source, data_target])) queue_runner.add_queue_runner( queue_runner.QueueRunner(shuffle_queue, enqueue_ops)) data_source, data_target = shuffle_queue.dequeue() # Decode source items items = dataset1.decoder.list_items() tensors = dataset1.decoder.decode(data_source, items) if dataset2 is not None: # Decode target items items2 = dataset2.decoder.list_items() tensors2 = dataset2.decoder.decode(data_target, items2) # Merge items and results items = items + items2 tensors = tensors + tensors2 super(ParallelDataProvider, self).__init__( items_to_tensors=dict(zip(items, tensors)), num_samples=dataset1.num_samples)
# scatterplot.py import numpy as np import pylab as pl # Make an array of x values x = [1, 2, 3, 4, 5] # Make an array of y values fro each x value y = [1, 4, 9, 16, 25] # use pylab to plot x and y as cyan circle pl.plot(x, y, 'co') # show the plot on the screen pl.savefig('temp1.png')
def encrypt(text,s): result='' l=len(text) for i in range(l): if (text[i].isupper()): result+= chr((ord(text[i]) + s-65) % 26 + 65) elif(text[i].islower()): result+= chr((ord(text[i]) + s - 97) % 26 + 97) else: result+=text[i] return result text = "ROT13 Algorithm" s = 13 print(encrypt(text,s))
def canSum(targetSum, numbers): arr = [False] * (targetSum + 1) arr[0] = True for i in range(targetSum + 1): if arr[i] == True: for num in numbers: if (i + num <= targetSum): arr[i + num] = True return (arr[targetSum]) print(canSum(7, [2, 3])) print(canSum(7, [5, 3, 4, 7])) print(canSum(7, [2, 4])) print(canSum(8, [2, 3, 5])) print(canSum(300, [7, 14]))
#!/usr/bin/env python # все файли на сервере из файла import requests def request(url): try: return requests.get("http://" + url) except requests.exceptions.ConnectionError: pass target_url = "google.com" with open("/root/subdomains.list", "r") as word_list_file: for line in word_list_file: word = word_list_file.sptrip() test_url = target_url + "/" + word response = request(test_url) if response: print("[+] Discovered URL --> "+test_url)
# Código funcional, aunque aún queda pendiente corregir detalles en cuanto a cómo se guardan los datos requeridos # por el programa. # -*- coding: cp1252 -*- # from Tkinter import Tk, Label, Button, Entry, Text, StringVar from tkinter import Tk, Label, Button, Entry, Text, StringVar colorFondo = "#00F" colorLetra = "#000" ############################################################# lecturaApellido1="xxxxxxxx" lecturaApellido2="xxxxxxxx" lecturaNombre1="xxxxxxxx" lecturaNombre2="xxxxxxxx" lecturaNombre3="xxxxxxxx" lecturaDni="xxxxxxxx" lecturaNivel="xxxxxxxx" lecturaInstitucion="xxxxxxxx" lecturaContacto="xxxxxxxx" lecturaCopiasAnteriores="xxxxxxxx" lecturaAnadirCopias="xxxxxxxx" ############################################################# def crearBecario(): f = open("Base de datos/"+datoDni.get()+".txt","w") f.write(datoApellido1.get()+"\n") f.write(datoApellido2.get()+"\n") f.write(datoNombre1.get()+"\n") f.write(datoNombre2.get()+"\n") f.write(datoNombre3.get()+"\n") f.write(datoDni.get()+"\n") f.write(datoNivel.get()+"\n") f.write(datoInstitucion.get()+"\n") f.write(datoContacto.get()+"\n") f.write(datoCopiasAnteriores.get()+"\n") f.write(datoAnadirCopias.get()+"\n") f.close() ############################################################# def verEstado(): f = open("Base de datos/"+datoDni.get()+".txt","r") # it=(linea for i,linea in enumerate(f) if i>=0) # for linea in it: # print linea it1=(lecturaApellido1 for i,lecturaApellido1 in enumerate(f) if i==0) for lecturaApellido1 in it1: print (lecturaApellido1) lecturaApellido2=(linea for i,linea in enumerate(f) if i==1) lecturaNombre1=(linea for i,linea in enumerate(f) if i==2) lecturaNombre2=(linea for i,linea in enumerate(f) if i==3) lecturaNombre3=(linea for i,linea in enumerate(f) if i==4) lecturaDni=(linea for i,linea in enumerate(f) if i==5) lecturaNivel=(linea for i,linea in enumerate(f) if i==6) lecturaInstitucion=(linea for i,linea in enumerate(f) if i==7) lecturaContacto=(linea for i,linea in enumerate(f) if i==8) lecturaCopiasAnteriores=(linea for i,linea in enumerate(f) if i==9) lecturaAnadirCopias=(linea for i,linea in enumerate(f) if i==10) #lecturaApellido1= #lecturaApellido2= #lecturaNombre1= #lecturaNombre2= #lecturaNombre3= #lecturaDni= #lecturaNivel= #lecturaInstitucion= #lecturaContacto= #lecturaCopiasAnteriores= #lecturaAnadirCopias= ############################################################# ventana = Tk() ventana.title("Base de datos") ventana.resizable(width=False,height=False) ventana.geometry("600x450") ventana.configure(background = colorFondo) ####################################################### boton1 = Button(ventana, text="Agregar becario", width=15, height=1, command=crearBecario).place(x=450,y=40) boton2 = Button(ventana, text="Ver estado", width=15, height=1, command=verEstado).place(x=450,y=80) boton3 = Button(ventana, text="Modificar datos", width=15, height=1).place(x=450,y=120) boton4 = Button(ventana, text="Borrar datos", width=15, height=1).place(x=450,y=160) ####################################################### etiquetaTitulo = Label(ventana, text="Becarios fotocopias", font='bold', bg=colorFondo, fg=colorLetra).place(x=40,y=10) etiquetaApellido1 = Label(ventana, text="Apellido 1", bg=colorFondo, fg=colorLetra).place(x=10,y=40) etiquetaApellido2 = Label(ventana, text="Apellido 2", bg=colorFondo, fg=colorLetra).place(x=10,y=70) etiquetaNombre1 = Label(ventana, text="Nombre 1", bg=colorFondo, fg=colorLetra).place(x=10,y=100) etiquetaNombre2 = Label(ventana, text="Nombre 2", bg=colorFondo, fg=colorLetra).place(x=10,y=130) etiquetaNombre3 = Label(ventana, text="Nombre 3", bg=colorFondo, fg=colorLetra).place(x=10,y=160) etiquetaDni = Label(ventana, text="DNI", bg=colorFondo, fg=colorLetra).place(x=10,y=190) etiquetaNivel = Label(ventana, text="Nivel", bg=colorFondo, fg=colorLetra).place(x=10,y=220) etiquetaInstitucion = Label(ventana, text="Institucion", bg=colorFondo, fg=colorLetra).place(x=10,y=250) etiquetaContacto = Label(ventana, text="Contacto", bg=colorFondo, fg=colorLetra).place(x=10,y=280) etiquetaCopiasAnteriores = Label(ventana, text="Copias anteriores", bg=colorFondo, fg=colorLetra).place(x=10,y=310) etiquetaAnadirCopias = Label(ventana, text="Añadir copias", bg=colorFondo, fg=colorLetra).place(x=10,y=340) datoApellido1=StringVar() datoApellido2=StringVar() datoNombre1=StringVar() datoNombre2=StringVar() datoNombre3=StringVar() datoDni=StringVar() datoNivel=StringVar() datoInstitucion=StringVar() datoContacto=StringVar() datoCopiasAnteriores=StringVar() datoAnadirCopias=StringVar() apellido1Caja = Entry(ventana, textvariable=datoApellido1).place(x=200,y=40) apellido2Caja = Entry(ventana, textvariable=datoApellido2).place(x=200,y=70) nombre1Caja = Entry(ventana, textvariable=datoNombre1).place(x=200,y=100) nombre2Caja = Entry(ventana, textvariable=datoNombre2).place(x=200,y=130) nombre3Caja = Entry(ventana, textvariable=datoNombre3).place(x=200,y=160) dniCaja = Entry(ventana, textvariable=datoDni).place(x=200,y=190) nivelCaja = Entry(ventana, textvariable=datoNivel).place(x=200,y=220) institucionCaja = Entry(ventana, textvariable=datoInstitucion).place(x=200,y=250) contactoCaja = Entry(ventana, textvariable=datoContacto).place(x=200,y=280) copiasAnterioresCaja = Entry(ventana, textvariable=datoCopiasAnteriores).place(x=200,y=310) anadirCopiasCaja = Entry(ventana, textvariable=datoAnadirCopias).place(x=200,y=340) ventana.mainloop() #############################################################
def absolute_value(num): #this function returns the absolute value of entered numbers if num>=0: return num else: return-num #output:2.7 print(absolute_value(2.7)) #output:4 print(absolute_value(4))
from graphs import Graph def validPos(pos, board_size): if pos < 0 or pos >= board_size: return False return True def getNormalizedPos(x, y, board_size): return (x * board_size) + y def getPossiblePositions(posX, posY, board_size): pos_offsets = [(-2,-1), (-1,-2), (1,-2), (2,-1), (2,1), (1,2), (-1, 2), (-2, 1)] newPosList = [] for i in pos_offsets: newX = posX + i[0] newY = posY + i[1] if validPos(newX, board_size) and validPos(newY, board_size): newPosList.append(getNormalizedPos(newX, newY, board_size)) return newPosList def knightsGraph(board_size = 8): g = Graph() for row in range(board_size): for col in range(board_size): currPos = getNormalizedPos(row, col, board_size) newPos = getPossiblePositions(row, col, board_size) for pos in newPos: g.addEdge(currPos, pos) return g def knightsTour(n, v, path, limit): """Solve the knights tour problem Args: n: Depth of the current path v: current vertex to be explored path: path of explored vertices so far limit: number of steps in the knight's tour ex: limit = 63 for a 8x8 board """ if n == limit: return True nlist = v.getNeighbors() v.setColor('gray') path.append(v) done = False i = 0 while i < len(nlist) and not done: nlist_item = nlist[i] if nlist_item.getColor() == 'white': done = knightsTour(n+1, nlist_item, path, limit) i = i + 1 if done is False: # backtrack here path.pop() v.setColor('white') return done if __name__ == '__main__': f = knightsGraph(5) for i in f: print i path = [] knightsTour(0, f.getVertex(0), path, 24) pathstr = '' for i in reversed(path): pathstr = str(i.getKey()) + '->' + pathstr print pathstr.strip('->')
""" Print Odds below n """ def odds_below_n(n): print("______________") for i in range(1, n, 2): print(i) def main(): odds_below_n(40) main()
a = 90 b = 200 if a>b: print("a is greater than b") else : print(" b is greater than a")
""" Printing squares of first 100 numbers """ n = 100 for i in range(n): print(i*i)
"""Factorial""" def factorial(n): """Get the factorial of a given number. Args ---- n : an integer Returns ------ Returns an integer """ fact = 1 i = n while i > 1: fact *= i i -= 1 return fact
# Calculating the Area of Circle # Area of a circle is pi*r*r pi = 3.14 r = float(input(" What is the radius of the circle : ")) Area_Of_The_Circle = pi * r * r print(Area_Of_The_Circle)
value_1 = 20 value_2 = 10 total_sum = (value_1 + value_2) # Printing 20+10 = 30 print(str(value_1) + " + " + str(value_2) + " = " + str(total_sum)) # Printing 20-10 = 10 total_substraction = (value_1 - value_2) print(str(value_1) + " - " + str(value_2) + " = " + str(total_substraction)) # Now Printing in format # 10 * 20 = 120 total_multiplication = (value_1 * value_2) print("{} * {} = {}".format(value_1, value_2, total_multiplication)) #20/10 = 10 print("{x} / {y} = {div}".format(y=value_1, x=value_2, div=value_1/value_2)) # 20 * 10 = 2 print(f"{value_1} // {value_2} = {value_1//value_2}") # 20 // 10 = 2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 23 20:00:48 2019 @author: Ruman https://www.nltk.org/book/ch01.html """ import nltk from nltk.book import * #Nos permite obtener el Titulo del texto cargado print(text2) #Búsquedas de un termino sobre uno de los textos cargados. text1.concordance("monstrous") """ La palabra mostrous aparece en una serie de contextos determinados, podemos buscar palabras que aparecen en contextos similares """ print("\nContexto similar a Mosntuoso:\n") text1.similar("monstrous") text2.similar("monstrous") #Vemos que los dos autores utilizan la palabra con connotaciones difernetes. """ Podemos buscar contextos compartidos por varias palabras """ print("\nContexto compartido:\n") text2.common_contexts(["monstrous", "very"]) """ Podemos ver el número de apariciones y posición en el texto. You can also plot the frequency of word usage through time using https://books.google.com/ngrams """ text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"]) """ Contando Vocavulario """ #Tamaño del texto en Tokens, entendido como una agrupación de caracteres. Por ejemplo Hola, :), o por ejemplo una frase que queramos tratar como un Token. print("Tamaño texto 3:",len(text3)) print("Tamaño texto 2:",len(text2)) #Palabras diferentes en un texto. #print("Palabras diferentes utilizadas en texto2:",sorted(set(text2))) print("Número de palabras diferentes utilizzadas en Texto3:", len(set(text3))) #ocurrencias concretas de una palabra. print("Ocurrencias de la palabra Smote:", text3.count("smote")) """ Estadísticas sencillas """ #Distribución de frecuencia de palabras fdist1 = FreqDist(text3) print("Distribución de frecuencia en Texto1:", fdist1) print("50 mas frecuentes:",fdist1.most_common(50)) print("La palabra god aparece:", fdist1['God']) fdist1.plot(50, cumulative=True) #Palabras que solo aparecen una vez -> "hapaxes" print("Palabras que solo aparecen una vez:",fdist1.hapaxes()) """ Selección de palabras de grano-fino """ #Vamos a buscar palabras que tengan mas de 15 caracteres V = set(text1) long_words = [w for w in V if len(w) > 15] print("\nPalabras con mas de 15 caracteres:",sorted(long_words)) #Palabras/Tokens que aparezcan mas de X veces V = set(text1) number_words = [w for w in V if fdist1[w] > 25] print("\nPalabras que aparecen mas de 25 veces:",sorted(number_words)) #Palabras que aparecen juntas a menudo print("Palabras que aparecen juntas a menudo:") text4.collocations()
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.left.left.left = Node(8) root.left.left.left.left = Node(9) root.left.left.left.right = Node(10) def zigzag_traversal(root): if root: stack1 = [] stack2 = [] ltr = True stack1.append(root) while len(stack1) > 0: item = stack1.pop() print(item.value) if ltr: if item.left: stack2.append(item.left) if item.right: stack2.append(item.right) else: if item.right: stack2.append(item.right) if item.left: stack2.append(item.left) if len(stack1) == 0: ltr = not ltr stack1, stack2 = stack2, stack1 zigzag_traversal(root)
def largest_cnt_subarray(arr): result = 0 tot_sum = 0 beg = 0 end = 0 sub = [] maxlen = 0 for i in range(len(arr)): tot_sum += arr[i] if tot_sum < 0: tot_sum = 0 beg = i+1 if result < tot_sum: result = tot_sum end = i maxlen = end - beg + 1 sub = arr[beg:end + 1] elif result == tot_sum: newend = i if newend - beg + 1 > maxlen: maxlen = newend - beg + 1 sub = arr[beg:newend + 1] end = newend print("beg index = ", beg) print("end index = ", end) print("Max Sub array = ", sub) return result nums1 = [-2, -3, 4, -1, -2, 1, 5, -3] nums2 = [5, -2, -1, 3, -4] nums3 = [-2, -3, 4, -1, -2, 1, 5, -3] nums4 = [6, -4, -2, 5, 1, -6, 2, 4] print("MAX CONT SUM = ", largest_cnt_subarray(nums1)) print("MAX CONT SUM = ", largest_cnt_subarray(nums2)) print("MAX CONT SUM = ", largest_cnt_subarray(nums3)) print("MAX CONT SUM = ", largest_cnt_subarray(nums4))
class vertex: def __init__(self, key): self.id = key self.connTo = {} def addNeighbor(self, nbr, weight = 0): self.connTo[nbr] = weight def getConnenctions(self): return self.connTo.keys() def getId(self): return self.id def getWeight(self, nbr): return self.connTo[nbr] def __str__(self): return str(self.id) + " is connected to" + str([x.id for x in self.connTo]) class graph: def __init__(self): self.vertexList = {} self.noOfvertices = 0 def addVertex(self, key): newV = vertex(key) self.noOfvertices += 1 self.vertexList[key] = newV return newV def getVertex(self, key): if key in self.vertexList: return self.vertexList[key] else: return None def addEdge(self, frm, to, wt=0): if frm not in self.vertexList: newV = self.addVertex(frm) if to not in self.vertexList: newV = self.addVertex(to) self.vertexList[frm].addNeighbor(self.vertexList[to], wt) def getVertices(self): return self.vertexList.keys() def __iter__(self): return iter(self.vertexList.values()) def __contains__(self, key): return key in self.vertexList g = graph() for i in range(1 , 6): g.addVertex(i) g.addEdge(0, 1, 5) g.addEdge(1, 2, 10) g.addEdge(2, 3, 15) g.addEdge(3, 4, 20) g.addEdge(4, 5, 25) g.addEdge(5, 0, 30) for vtx in g: print(vtx) print(vtx.getConnenctions) print('\n')
def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] prev_idx = i - 1 while prev_idx >= 0 and key < arr[prev_idx]: print("key = ", key, end = "\n") print("prev_idx = ", prev_idx, end = "\n") print("i = ", i, end = "\n") print(arr) arr[prev_idx+1] = arr[prev_idx] prev_idx -= 1 arr[prev_idx+1] = key print(arr) arr = [12, 25, 0, 16, 54, 36, 75, 21, 45, 15, 37, 49, 64, 77, 98, 12] insertion_sort(arr) print(arr)
import database import math class Rectangle(object): def __init__(self, pt1, pt2): x1, y1 = pt1 x2, y2 = pt2 self.left = min(x1, x2) self.right = max(x1, x2) self.top = max(y1, y2) self.bottom = min(y1, y2) def contains(self, pt3): x3, y3 = pt3 return self.left <= x3 <= self.right and self.bottom <= y3 <= self.top class Search(object): def __init__(self): self.graph = database.Database.GRAPH #graph of world (dict) self.points = database.Database.POINTS #co-ordinates of all nodes (dict) def get_distance(self,start_node,end_node): start_points = self.points.get(start_node) end_points = self.points.get(end_node) x_dif = end_points[0] - start_points[0] y_dif = end_points[1] - start_points[1] distance = math.hypot(x_dif,y_dif) return distance def get_list(self,string): return string.split() # Gets the neighbour with the lowest f_score def get_lowest_f_score(self,open_set,goal,g_score): lowest_f_cost = 100000000000000000 for node in open_set: current_f_cost = g_score + self.get_distance(node,goal) if len(open_set) == 1: lowest_node = node break elif current_f_cost < lowest_f_cost: lowest_node = node lowest_f_cost = current_f_cost return lowest_node def create_path(self,came_from,current_node): if current_node in came_from: path = self.create_path(came_from, came_from[current_node]) return (path + ' ' + current_node + ' ') else: return ' ' + current_node + ' ' def find_path(self,start,goal): closed_set = [] #evaluated nodes open_set = [start] #nodes waiting to be evaluated came_from = {} g_score = 0 f_score = g_score + self.get_distance(start,goal) while len(open_set) > 0: #find the lowest f_score #itereate through open set and grab lowest f_score current_node = self.get_lowest_f_score(open_set,goal,g_score) #check if current is the goal if current_node == goal: return self.get_list(self.create_path(came_from,goal)) # Mark current node as visited or expanded open_set.remove(current_node) closed_set.append(current_node) #iterate through all neighbours of the current node neighbours = self.graph.get(current_node) for neighbour in neighbours: # if already evaluated, check the next neighbour if neighbour in closed_set: continue neighbour_to_current_dist = self.get_distance(current_node,neighbour) current_g_score = self.get_distance(start,current_node) neighbour_g_score = self.get_distance(start,neighbour) tentative_g_score = current_g_score + neighbour_to_current_dist # if neighbour hasn't been visited yet or has less cost than neighbour if neighbour not in open_set or tentative_g_score < neighbour_g_score: came_from[neighbour] = current_node neighbour_g_score = tentative_g_score neighbour_f_score = neighbour_g_score + self.get_distance(neighbour,goal) #add neighbour to the unvisited list if neighbour not in open_set: open_set.append(neighbour) return None #returns None if failed to find path class Angle(object): def __init__(self, current, target): """ Convert input rads to degrees """ current = math.degrees(current) target = math.degrees(target) self.angle_from = self.normalize(current) self.angle_to = self.normalize(target) def check(self): """ Check which direction is best to rotate based on current heading. """ # -1 is anti-clockwise # 1 is clockwise move_angle = self.angle_to - self.angle_from if (move_angle > 0): if (abs(move_angle) > 180): return -1 else: return 1 else: if (abs(move_angle) > 180): return 1 else: return -1 def normalize(self, input_angle): """ Normalise input angle """ new_angle = int(input_angle) if new_angle < 0: new_angle += 360 return new_angle
''' author: ylavinia String compression Implement a method to perform basic string compression using the counts of repeated characters. Example: Input: aabcccccaa Output: a2b1c5a2 Assume the string has only uppercase and lowercase letters. ''' def compress_string(astring): char_and_freq = create_freq_list(astring) return ''.join(char_and_freq) def create_freq_list(astring): freq_list = [] count = 0 for i in range(len(astring)): # increment count until either the next index is greater than # the string length or the nex letter is not the same as the current count += 1 if ((i + 1) >= len(astring) or (astring[i + 1] != astring[i])): # append the character freq_list.append(astring[i]) # append the current count freq_list.append(str(count)) # count rolls back to zero since we're' moving to the next letter count = 0 return freq_list def main(): print("This program compresses the patterns in a string by replacing the pattern with the count of the repeated characters.") print("Example:") astring = "aaaaaaaaabbbbbbcccccaaaa" print("The string: ", astring) print("Compressed: ", compress_string(astring)) str_input = input("Enter a string with duplicate letters, ex. aboegggguuurryy@@@: ") print("Your string: ", str_input) print("Compressed: ", compress_string(str_input)) if __name__ == "__main__": main()
""" 适配器模式 """ """ 将一个类的接口转换成客户希望的另一个接口,适配器模式使得原本由于接口不兼容而不能一起工作的哪些类可以一起工作 两种实现方式 类适配器:使用多继承 对象适配器:使用组合 """ from abc import ABCMeta,abstractmethod class Payment(metaclass=ABCMeta): @abstractmethod def pay(self,money): pass class Alipay(Payment): def __init__(self,huabei=False): # self.huabei=huabei def pay(self,money): if self.huabei: print("花呗支付了%s元" % money) else: print("支付宝支付了%s元"%money) class WeChat(Payment): #具体产品角色 def pay(self,money): print(" 微信支付了%s元" % money) #跟接口不兼容 class BankPay(object): def cost(self,money): print("银联支付了%s元"%money) class ApplePay(object): def cost(self, money): print("苹果支付了%s元" % money) #类适配器 # class NewBankPay(Payment,BankPay): # def pay(self,money): # self.cost(money) # p=NewBankPay() #对象适配器 class PaymentAdapter(Payment): def __init__(self,payment): self.payment=payment def pay(self,money): self.payment.cost(money) p=PaymentAdapter(ApplePay()) p.pay(20) """ 角色 1、目标接口 2、待适配的类 3、适配器 使用场景 想使用一个已经存在的类,而它的接口不符合你的要求 (对象适配器) 想使用一些已经存在的子类,但不可能对每一个都进行子类化以匹配它们的接口,对象适配器 可以适配它的父类接口 """
from abc import ABCMeta,abstractmethod #接口,定义抽象类和抽象方法(子类必须实现父类的方法) """ 抽象产品角色 """ class Payment(metaclass=ABCMeta): @abstractmethod def pay(self,money): pass #实现Payment接口 #最底层 """ 具体产品角色 """ class Alipay(Payment): #具体产品角色 def __init__(self,huabei=False): #增加花呗支付 self.huabei=huabei def pay(self,money): if self.huabei: print("花呗支付了%s元" % money) else: print("支付宝支付了%s元"%money) class WeChat(Payment): #具体产品角色 def pay(self,money): print(" 微信支付了%s元" % money) class Bank(Payment): def pay(self,money): print(" 银联支付了%s元" % money) #定义工厂接口 """ 抽象工厂角色 """ class PaymentFactory(metaclass=ABCMeta): @abstractmethod def create_payment(self): pass """ 具体工厂角色 """ class AlipayFactory(PaymentFactory): def create_payment(self): return Alipay() class WechatFactory(PaymentFactory): def create_payment(self): return WeChat() class HuabeiFactory(PaymentFactory): def create_payment(self): return Alipay(huabei=True) class BankFactory(PaymentFactory): #新加的 def create_payment(self): return Bank() pf= HuabeiFactory() p=pf.create_payment() p.pay(200) """ 优点: 1、每个具体产品都对应一个具体工厂类,不需要修改工厂代码 2、隐藏了对象创建实现的细节 缺点: 1、每增加一个具体产品类,就必须增加一个相应的具体工厂类 """
#!/usr/bin/env python import numpy as np def sigmoid(x): return 1.0 / (1 + np.exp(-x)) """ def test_sigmoid(): x = 0 print("Input x: {}, the sigmoid value is: {}".format(x, sigmoid(x))) """ def main(): # Prepare dataset train_features = np.array([[1, 0, 26], [0, 1, 25]], dtype=np.float) train_labels = np.array([1, 0], dtype=np.int) test_features = np.array([[1, 0, 26], [0, 1, 25]], dtype=np.float) test_labels = np.array([1, 0], dtype=np.int) feature_size = 3 batch_size = 2 # Define hyperparameters epoch_number = 10 learning_rate = 0.01 weights = np.ones(feature_size) # Start training for epoch_index in range(epoch_number): print("Start the epoch: {}".format(epoch_index)) ''' Implement with batch size # [2, 3] = [3] * [2, 3] multiple_weights_result = weights * train_features # [2] = [2, 3] predict = np.sum(multiple_weights_result, 1) # [2] = [2] sigmoid_predict = sigmoid(predict) # [2] = [2] predict_difference = train_labels - sigmoid_predict # TODO: [2, 3, 1] = [2, 3] * [2] batch_grad = train_features * predict_difference # TODO: fix that grad = batch_grad # [3, 1] = [3, 1] weights += learning_rate * grad ''' # Train with single example train_features = np.array([1, 0, 25], dtype=np.float) train_labels = np.array([0], dtype=np.int) # [3] = [3] * [3] multiple_weights_result = train_features * weights # [1] = [3] predict = np.sum(multiple_weights_result) # [1] = [1] sigmoid_predict = sigmoid(predict) # [1] = [1] predict_difference = train_labels - sigmoid_predict # [3] = [3] * [1] grad = train_features * predict_difference # [3] = [3] weights += learning_rate * grad print("Current weights is: {}".format(weights)) # TODO: Predict with validate dataset predict_true_probability = sigmoid(np.sum(train_features * weights)) print("Current predict true probability is: {}".format( predict_true_probability)) likehood = 1 - predict_true_probability print("Current likehood is: {}\n".format(likehood)) if __name__ == "__main__": main()
import cv2 # for image processing import easygui # to open the filebox import numpy as np # to store image import imageio # to read image stored at particular path import sys import matplotlib.pyplot as plt import os import tkinter as tk from tkinter import filedialog from tkinter import * from PIL import ImageTk, Image 99 top = tk.Tk() top.geometry('400x400') top.title('Cartoonify Your Image !') top.configure(background='white') label = Label(top, background='#CDCDCD', font=('calibri', 20, 'bold')) def upload(): ImagePath = easygui.fileopenbox() cartoonify(ImagePath) def cartoonify(ImagePath): # read the image originalmage = cv2.imread(ImagePath) originalmage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2RGB) # print(image) # image is stored in form of numbers # confirm that image is chosen if originalmage is None: print("Can not find any image. Choose appropriate file") sys.exit() ReSized1 = cv2.resize(originalmage, (960, 540)) #plt.imshow(ReSized1, cmap='gray') LP-III- Machine Learning cartoonify image with machine learning 6 # converting an image to grayscale grayScaleImage = cv2.cvtColor(originalmage, cv2.COLOR_BGR2GRAY) ReSized2 = cv2.resize(grayScaleImage, (960, 540)) #plt.imshow(ReSized2, cmap='gray') # applying median blur to smoothen an image smoothGrayScale = cv2.medianBlur(grayScaleImage, 5) ReSized3 = cv2.resize(smoothGrayScale, (960, 540)) #plt.imshow(ReSized3, cmap='gray') # retrieving the edges for cartoon effect # by using thresholding technique getEdge = cv2.adaptiveThreshold(smoothGrayScale, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) ReSized4 = cv2.resize(getEdge, (960, 540)) #plt.imshow(ReSized4, cmap='gray') # applying bilateral filter to remove noise # and keep edge sharp as required colorImage = cv2.bilateralFilter(originalmage, 9, 300, 300) ReSized5 = cv2.resize(colorImage, (960, 540)) #plt.imshow(ReSized5, cmap='gray') # masking edged image with our "BEAUTIFY" image cartoonImage = cv2.bitwise_and(colorImage, colorImage, mask=getEdge) ReSized6 = cv2.resize(cartoonImage, (960, 540)) #plt.imshow(ReSized6, cmap='gray') # Plotting the whole transition images = [ReSized1, ReSized2, ReSized3, ReSized4, ReSized5, ReSized6] fig, axes = plt.subplots(3, 2, figsize=(8, 8), subplot_kw={ 'xticks': [], 'yticks': []}, gridspec_kw=dict(hspace=0.1, wspace=0.1)) for i, ax in enumerate(axes.flat): ax.imshow(images[i], cmap='gray') save1 = Button(top, text="Save cartoon image", command=lambda: save( ReSized6, ImagePath), padx=30, pady=5) save1.configure(background='#364156', foreground='white', font=('calibri', 10, 'bold')) save1.pack(side=TOP, pady=50) plt.show() def save(ReSized6, ImagePath): # saving an image using imwrite() newName = "cartoonified_Image" path1 = os.path.dirname(ImagePath) extension = os.path.splitext(ImagePath)[1] path = os.path.join(path1, newName+extension) cv2.imwrite(path, cv2.cvtColor(ReSized6, cv2.COLOR_RGB2BGR)) I = "Image saved by name " + newName + " at " + path tk.messagebox.showinfo(title=None, message=I) upload = Button(top, text="Cartoonify an Image", command=upload, padx=10, pady=5) upload.configure(background='#364156', foreground='white', font=('calibri', 10, 'bold')) upload.pack(side=TOP, pady=50) top.mainloop()
from pathlib import Path import urllib.request as url def get_cache_dir() -> Path: """ Returns a cache dir that can be used as a local buffer. Example use cases are intermediate results and downloaded files. At the moment this will be a folder that lies in the root of this package. Reason for this location and against `~/.cache/paderbox` are: - This repo may lie on an faster filesystem. - The user has limited space in the home directory. - You may install paderbox multiple times and do not want to get side effects. - When you delete this repo, also the cache is deleted. Returns: Path to a cache dir >>> get_cache_dir() # doctest: +SKIP PosixPath('.../paderbox/cache') """ dirname = Path(__file__).resolve().absolute().parents[2] path = dirname / "cache" if not path.exists(): path.mkdir() return path def url_to_local_path(fpath, file=None): """ Checks if local cache directory possesses an example named <file>. If not found, loads data from urlpath and stores it under <fpath> Args: fpath: url to the example repository file: name of the testfile Returns: Path to file """ path = get_cache_dir() if file is None: # remove difficult letters file = fpath.replace(':', '_').replace('/', '_') if not (path / file).exists(): datapath = url.urlopen(fpath) data = datapath.read() with open(path / file, "wb") as f: f.write(data) return path / file
import pygame COLORS = { "red" : (255, 0, 0), "white" : (255, 255, 255), "black" : (0, 0, 0), "green" : (0, 255, 0), "grey" : (100, 100, 100), "orange" : (255, 125, 0) } class Game(): def __init__(self): self.running = True self.clock = pygame.time.Clock() def init(self): pygame.init() pygame.display.set_caption("LeapLearner") def handle_event(self): for event in pygame.event.get(): if event.type == pygame.QUIT: print("quit") self.running = False pygame.quit() def run(self, func): self.init() while self.running: self.handle_event() func() #Refresh Screen pygame.display.flip() #Number of frames per secong e.g. 60 self.clock.tick(50) class Canvas(): def __init__(self): self.screen = pygame.display.set_mode((600, 400)) self.w = self.screen.get_rect().width self.h = self.screen.get_rect().height def clear(self): self.screen.fill(COLORS["white"]) #Draw The Road class Rectangle(): #This class represents a car. It derives from the "Sprite" class in Pygame. def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h self.fillStyle = "orange" def draw(self): pygame.draw.rect(canvas.screen, getColor(self.fillStyle), (self.x, self.y, self.w, self.h)) def getColor(color): if(color.lower() in COLORS): return COLORS[color.lower()] else: return (255, 125, 0) canvas = Canvas() game = Game() run = game.run def rectangle(x, y, w, h, c): pygame.draw.rect(canvas.screen, getColor(c), (x, y, w, h))
a=int(input("Enter first number : ")) b=int(input("Enter second number :")) add=a+b sub=a-b mult=a*b div=a/b rem=a%b fd=a//b power=a**b print("Addition of two number is ",add) print("Subtraction of two number is ",sub) print("Multipication of two number is ",mult) print("Division of two number is ",div) print("Remainder of two number is ",rem) print("Addition of two number is ",add) print("Floor Division of two number is ",fd) print("a raise to b is ",power)
k=1 for i in range(int(input())): for j in range(i+1): print(k,end=" ") k+=1 print()
def median(lst): s = sorted(lst) l = len(lst) i = (l-1) // 2 if (l % 2): return s[i] else: return (s[i] + s[i + 1])/2.0 lst=[] n=input("Enter Number Of Input:") for x in range(0,int(n)): x=input("Your Input") lst.append(x) print(median(lst))
# Data import script # Provide the name of a csv file as an argument and your data will be imported into the rollcall database # The CSV should contain three fields: # Participant ID or group number # Participant Name # Day of the week designation # # This is tailored towards different workshops that meet during the week coming together at the end of the month to discuss business. So, for example, participant John Sample runs a Monday night workshop and has an ID number of '01'. from sys import argv import csv import sqlite3 conn = sqlite3.connect('rollcall.db') c = conn.cursor() if len(argv) < 2: print "Please provide a name of a csv file. ex: python import_csv.py myfile.csv" exit(1) else: csvfile = argv[1] # Initialize the table c.execute("CREATE TABLE meeting ( id INTEGER PRIMARY KEY, name TEXT, day TEXT, number INTEGER, present INTEGER, notes TEXT )") meetings = csv.reader(open(csvfile, 'rb'), delimiter=',', quotechar='"') index = 0 for row in meetings: index = index + 1 print "%s %s" % (index, row) c.execute("INSERT INTO meeting VALUES (?, ?, ?, ?, ?, ?)", (index, row[1], row[2], row[0], 0, "No report")) conn.commit() conn.close() exit()
#!/usr/bin/python3 #Modules and Testing #Section 7.4 #See modules_and_testing.py script which this file works in conjunction with. #See which file this function is in print(__name__) #Creating a simple module def first_half(s): return s[:len(s)//2] def last_half(s): return s[len(s)//2:] #Testing Modules #See if we are currently running this script #Using the below if statement simply says, "we are currently running this script what do you want me to do" if __name__ == '__main__': print("Testing string functions") assert first_half("abcd") == "ab", "First half is failing" assert last_half("abcd") == "cd", "Last half is failing"
#!/usr/bin/python3 #Loops and Iterables Section 5 #How to use a for loop #Structure ''' for var in array run code ''' s = "hello world" a = [4, 6, 9] # in keyword print( 5 in a ) print( 4 in a ) print( "ello" in s ) #Ways to iterate over a list(array) #Method 1: Include the array for even_number in [2, 4, 6, 8, 10]: print(even_number) #add more code here... #Method 2: Reference the array odds = [1, 3, 5, 7, 9, 11] for odd_number in odds: print(odd_number) #... #Method 3: Referencing the index of the array (w/ formatting) print(range(len(odds))) for index in range(len(odds)): print("Index: {:d}, odd number: {:d}".format(index, odds[index])) #How to use a while loop #Structure ''' while(condition): run code ''' index = 0 names = ["Josh", "Harry", "Leah", "Micah"] #Use while loop to loop through array "names" #by referencing each element of the array's index while index < len(names): name = names[index] print(name) index = index + 1 #Add all numbers from 1-10 inclusive using while loop total = 0 v = 1 while v <= 10: total = total + v v = v + 1 print(total) #Run a loop forever until a condition is met #Ex. Run program until two added numbers = 20 ''' Uncomment code to run in terminal while True: print("Please make sure a + b = 20") a, b, = int(input("a: ")), int(input("b: ")) #Run until the break condition is met if a + b == 20: print("Stopping Loop") break else: print("Please make sure a + b = 20") ''' #How to use iterables # my_list = [1,2,3,4,5] my_tuple = (2,7,8,9,10) my_string = "Hello World!" print(dir(my_list)) #shows all of the list's properties print('__iter__' in dir (my_list)) #check if list is iterable print('__iter__' in dir (my_tuple)) #check if tuple is iterable print('__iter__' in dir (my_string)) #check if string is iterable #This means each of these can be iterated through #Ex. for element in my_list: print(element) #Spaces for output clarity print() #How a for loop actually works, #First create an iterator for list using built in "iter()" function list_iterator = iter(my_list) while True: #Create a while loop that iterates through elements until it can't iter no-mo! try: #Allows you to test things next_element = next(list_iterator) #"next()" is another built in function print(next_element) except StopIteration: #Catches "StopIteration" from stderr break
#!/usr/bin/python3 #Playing with beautifulSoup import requests from bs4 import BeautifulSoup #Uses requests to get the html of a page url = 'https://newyorktimes.com' r = requests.get(url) r_html = r.text #Saves that html string as a BeautifulSoup object #(Also specifies the parser to be used) soup = BeautifulSoup(r_html, "html.parser") #Prints out all of the links on the page for link in soup.find_all('a'): print(link.get('href'))
# Необходимо написать программу для кулинарной книги. # Список рецептов должен храниться в отдельном файле в следующем формате: # В одном файле может быть произвольное количество блюд. # Читать список рецептов из этого файла. # Соблюдайте кодстайл, разбивайте новую логику на функции и не используйте глобальных переменных. def open_file_dict(arg): # Чтение файла и создание списка "recipes.txt" cook_book_def = {} ingredients = {} list_2 = [] with open(arg, "r", encoding='utf-8') as open_file: for line in open_file: line = line.rstrip("\n") if line != "": if line.isdigit(): line = int(line) for i in range(line): i = open_file.readline() i = i.rstrip("\n") ingred_list = i.split("|") for ingred in ingred_list: if ingred.strip(" ").isdigit(): ingredients["quantity"] = float(ingred.strip(" ")) ingredients["measure"] = ingred_list.pop(-1) else: ingredients["ingredient_name"] = ingred.strip(" ") list_2.append(ingredients) ingredients = {} cook_book_def[name_key] = list_2 list_2 = [] else: name_key = line return cook_book_def cook_book = open_file_dict("recipes.txt") print(cook_book)
import argparse import os import re from translate_html import translate_html def translate_template(filename, target_language): """ Translates the text in an HTML file, including code snippets embedded in that file, from English to another language. :param filename str: the local path to an HTML file :param target_language str: ISO 639-1 code for the natural language to which text should be translated """ path_segments = filename.split("/") page_name = path_segments[-1] # Currently assumes path is to a file in a folder for English versions output_dir = "/".join( [segment if segment != "en" else target_language for segment in path_segments[:-1]] ) if not os.path.isdir(output_dir): os.makedirs(output_dir) with open(filename, "r") as file: page_text = file.read() # Temporarily remove embedded code lines and code blocks in Bottle templates embedded_code_regex = re.compile(r"^\s*(?:%.*$|<%(?:.|\n)*?%>\s*$)", re.MULTILINE) embedded_code_blocks = [] def embedded_code_replace(match): """ Replaces an embedded code block with a placeholder while the surrounding template is being translated. The code block is stored in the captured embedded_code_blocks list at an index indicated in the placeholder. :param match _sre.SRE_Match: regex match for an embedded code block :returns: no-translate tag with the text: "Embedded code $n", where $n is the code block's index in the caller's list """ replacement = '<span translate="no">Embedded code {}</span>'.format(len(embedded_code_blocks)) embedded_code_blocks.append(match.group(0)) return replacement page_text = embedded_code_regex.sub(embedded_code_replace, page_text) # Translate page with temporarily removed embedded code translated_file = translate_html(page_text, target_language) # Re-introduce embedded code for later compilation of templates placeholder_regex = re.compile(r'<span translate="no">Embedded code (\d+)</span>') translated_file = placeholder_regex.sub(lambda match: "\n{}\n".format(embedded_code_blocks[int(match.group(1))]), translated_file) with open(os.path.join(output_dir, page_name), "w") as outfile: outfile.write(translated_file) def main(): parser = argparse.ArgumentParser() parser.add_argument( "language", help="Two-letter (ISO 639-1) code for the target language" ) parser.add_argument( "files", help="File(s) to be translated (use globbing to translate whole directories)", nargs="+", ) args = parser.parse_args() for filename in args.files: print("Translating {}...".format(filename)) translate_template(filename, args.language) print(" done.\n") if __name__ == "__main__": main()
print "\n=Assignment2 Python Program=" def test1(x=26,y=49): return (x*4)+(y%7) # 1. Variable Number of Actual Parameters print "\n1. variable number of actual parameters" print "result : ", test1(3,5) # numbers as parameters # 2. Parameter Correspondence # 2.a Positional print "\n2. parameter correspondency" print "\n2.a positional" print "result : ", test1(5,3) # values of x and y are swapped # 2.b Keyword print "\n2.b keyword" print "result : ", test1(3) # only x input is given, y uses default value # 2.c Combination print "\n2.c combination" print "result : ", test1(3+5,5-3) # expressions as inputs # 3. Formal Parameter Default Values print "\n3. formal parameter default values" print "result : ", test1() # empty inputs to use default x and y # 4. Parameter Passing Methods def test2(x, y): return x , y # returns copy values of inputs def test3(x, y): return x[0] , y[0] # returns values are passed by reference in the addresses print "\n4. parameter passing methods " # 4.1 Pass by value print "\n4.1 pass by value " p = 15 q = 25 print "result (x , y): ", test2(p,q) # value inputs # 4.2 Pass by reference print "\n4.2 pass by reference " a = [15] b = [25] print "result (x , y): ", test3(a,b) # values that are contained in array addresses
#Designed to count phrases of words grouped in 2s def group_text(text, group_size): """ groups a text into text groups set by group_size returns a list of grouped strings """ word_list = text.split() group_list = [] for k in range(len(word_list)): start = k end = k + group_size group_slice = word_list[start: end] # append only groups of proper length/size if len(group_slice) == group_size: group_list.append(" ".join(group_slice)) return group_list text = "test this is test a this is a test" group_size = 2 group_list = group_text(text, group_size) # convert list to set to avoid duplicates group_set = set(group_list) #if wanting to output a text count uncomment the below and remove the group_set print #for group in group_set: # count = text.count(group) # sf = "'%s' appears %d times in the text" # print(sf % (group, count)) print(group_set)
#!/usr/bin/env python3 ''' Determines the tile proportions as a percentage for a given board. ''' import sys,os,re def main(args): if len(args) < 2: print("Usage: %s board boards..." % args[0]) return for fn in args[1:]: with open(fn) as fp: #Skip first 8 lines lines = fp.readlines()[7:] num = [] for line in lines: num += [int(x) for x in re.split("[^0-9]", line) if x] last = -1 cts = 0 maxCts = 0 maxTile = 0 maxCount = 0 count = 0 props = {} for n in num: count += 1 if n == last: cts += 1 else: if cts > maxCts: maxCts = cts maxTile = last maxCount = count cts = 0 last = n if n not in props: props[n] = 1 else: props[n] += 1 print("Tile count: %d" % len(num)) for k in sorted(props): print("%d, %.1f" % (k, (100 * props[k]) / len(num))) print("Max sequence: %d (Tile %d at %d)" % \ (maxCts + 1, maxTile, maxCount - maxCts - 1)) #print(num[maxCount - maxCts - 2 : maxCount + maxCts + 10]) main(sys.argv)
import random list1 = [9, 3, 63, 23, -12, 45, 9, -1, 23, 18, 73, 22, 109, -3, 5, 22] list2 = [] for i in range(0, 15): list2.append(random.randrange(10000)) list3 = [] for i in range(0, 15): list3.append(round(random.uniform(-100.0, 100.0), 2)) def min(the_list): """ Find and return the minimum in a list :param the_list: the input list :return: minimum """ Find the min number def max(the_list): """ Find and return the maximum in a list :param the_list: the input list :return: maximum """ Find the max number min1 = min(list1) max1 = max(list1) min2 = min(list2) max2 = max(list2) min3 = min(list3) max3 = max(list3) message = "List %d : %s \n min is %f and max is %f" print(Print the list, min and max numbers here) print(Print the list, min and max numbers here) print(Print the list, min and max numbers here)
import random list1 = [9, 3, 63, 23, -12, 45, 9, -1, 23, 18, 73, 22, 109, -3, 5, 22] list2 = [] for i in range(0, 15): list2.append(random.randrange(10000)) list3 = [] for i in range(0, 15): list3.append(round(random.uniform(-100.0, 100.0), 2)) def minAndMax(the_list): """ Find and return the minimum and maximum of a list :param the_list: the input list :return: """ Use one function only Using minAndMax() to find min and max numbers of these lists message = "List %d : %s \n min is %f and max is %f" print(message % (1, list1, min1, max1)) print(message % (2, list2, min2, max3)) print(message % (3, list3, min3, max2))
class BST: def __init__(self, initVal=None): self.value=initVal if self.value: self.left= BST() self.right = BST() else: self.left = None self.right = None return def isEmpty(self): return (self.value == None) def isLeaf(self): return (self.left.isEmpty() and self.right.isEmpty()) def insert(self,val): if self.isEmpty(): self.value = val self.left = BST() self.right = BST() if self.value == val: return if val < self.value: self.left.insert(val) return if val > self.value: self.right.insert(val) return def inorder(self): if self.isEmpty(): return('') else: return(self.left.inorder()+'--'+str(self.value)+'--'+self.right.inorder()+'\n') def __str__(self): return str(self.inorder()) def foo(self): if self.isEmpty(): return(0) elif self.isLeaf(): return(self.value) else: return(self.value + max(self.left.foo(), self.right.foo()))
""" 97. Maximum Depth of Binary Tree 中文 English Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example Example 1: Input: tree = {} Output: 0 Explanation: The height of empty tree is 0. Example 2: Input: tree = {1,2,3,#,#,4,5} Output: 3 Explanation: Like this: 1 / \ 2 3 / \ 4 5 it will be serialized {1,2,3,#,#,4,5} """ class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: The root of binary tree. @return: An integer """ def maxDepth(self, root): return self.maxDepthHelper(root, 0) def maxDepthHelper(self, node, max_l): if (node): max_l += 1 return max(self.maxDepthHelper(node.left, max_l), self.maxDepthHelper(node.right, max_l)) return max_l if __name__ == "__main__": s = Solution() t1 = TreeNode(0) assert(s.maxDepth(t1) == 1) assert(s.maxDepth(None) == 0)
""" 184. Largest Number Given a list of non negative integers, arrange them such that they form the largest number. Example Example 1: Input:[1, 20, 23, 4, 8] Output:"8423201" Example 2: Input:[4, 6, 65] Output:"6654" Challenge Do it in O(nlogn) time complexity. Notice The result may be very large, so you need to return a string instead of an integer. """ class Solution: def largestNumber(self, nums): res = "" l = self.helper(list(map(str, nums))) for s in l: res += s return str(int(res)) def helper(self, nums): if len(nums) < 2: return nums mid = (len(nums)-1)//2 return self.merge(self.helper(nums[:mid+1]), self.helper(nums[mid+1:])) def merge(self, n1, n2): if not n1: return n2 elif not n2: return n1 res = [] i = 0 j = 0 while i < len(n1) and j < len(n2): char_i = n1[i] char_j = n2[j] broken = False op1 = char_i + char_j op2 = char_j + char_i if op1 >= op2: res.append(char_i) i += 1 continue else: res.append(char_j) j += 1 continue if i < len(n1): res.extend(n1[i:]) else: res.extend(n2[j:]) return res if __name__ == "__main__": s = Solution() assert(s.largestNumber([0, 0]) == '0') assert(s.largestNumber([25,5,12,97,3,8,79,73,38,88,98,29,84,74,16,2,67,65,41,44,88,75,51,87,95,90,45,40,7,53,5,30,77,5,56,58,41,51,62,88,33,69,81,78,18,63,82,90,21,6,12,92,67,6,81,83,14,6,76,85,79,96,41,44,20,89,59,58,83,58,73,1,41,41,24,55,61,49,10,42,5,1,98,30,91,9,34,5,84,43,73,4,22,11,21,14,1,62,77,41]) == "998989796959291909089888888887858484838382818179797877777767574737373696767666656362626159585858565555555535151494544444434241414141414140383433330302925242222121201816141412121111110") assert(s.largestNumber([3577,9155,9352,7911,1622]) == "93529155791135771622") assert(s.largestNumber([1, 20, 23, 4, 8]) == '8423201') assert(s.largestNumber([4, 6, 65]) == "6654")
class MinStack: def __init__(self): self.stack = [] self.m = 999999999 """ @param: number: An integer @return: nothing """ def push(self, number): self.stack.append(number) if (number < self.m): self.m = number """ @return: An integer """ def pop(self): n = self.stack.pop() if (n == self.m): m = 999999999 for i in range(len(self.stack)): if (self.stack[i] < m): m = self.stack[i] self.m = m return n """ @return: An integer """ def min(self): return self.m
""" 196. Missing Number 中文 English Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array. Example Example 1: Input:[0,1,3] Output:2 Example 2: Input:[1,2,3] Output:0 Challenge Do it in-place with O(1) extra memory and O(n) time. """ class Solution: """ @param nums: An array of integers @return: An integer """ def findMissing(self, nums): for i in range(len(nums)): if nums[i] != i: while nums[i] != i: if nums[i] == len(nums): nums[i] = -1 break if nums[i] == -1: break temp = nums[i] nums[i] = nums[temp] nums[temp] = temp prev = nums[i] i = 0 for j in range(len(nums)): if nums[j] == -1: continue if i != nums[j]: return i i += 1 return i if __name__ == "__main__": s = Solution() assert(s.findMissing([9,8,7,6,2,0,1,5,4]) == 3) assert(s.findMissing([0, 1, 3]) == 2) assert(s.findMissing([1, 2, 3]) == 0)
""" 488. Happy Number 中文 English Write an algorithm to determine if a number is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example Example 1: Input:19 Output:true Explanation: 19 is a happy number 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1 Example 2: Input:5 Output:false Explanation: 5 is not a happy number 25->29->85->89->145->42->20->4->16->37->58->89 89 appears again. """ class Solution: """ @param n: An integer @return: true if this is a happy number or false """ def isHappy(self, n): current = n s = set() while True: m = map(int, str(current)) current = sum([i**2 for i in m]) if current == 1: return True elif current in s: return False s.add(current) if __name__ == "__main__": s = Solution() assert(s.isHappy(19)) assert(not s.isHappy(5)) assert(s.isHappy(152395730))
class Solution: """ @param n: The number of digits @return: All narcissistic numbers with n digits """ def getNarcissisticNumbers(self, n): res = [] if (n == 1): res.append(0) for i in range(10**(n-1), 10**n): if (self.isNarcissisticNumbers(i, n)): res.append(i) return res def isNarcissisticNumbers(self, j, n): digits = list(map(int, str(j))) res = 0 for i in range(len(digits)): res += digits[i] ** n return (res == j) if (__name__ == "__main__"): s = Solution() assert(s.isNarcissisticNumbers(0, 1)) assert(s.getNarcissisticNumbers(1) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) assert(not(s.getNarcissisticNumbers(2)))
""" 76. Longest Increasing Subsequence 中文 English Given a sequence of integers, find the longest increasing subsequence (LIS). You code should return the length of the LIS. Example Example 1: Input: [5,4,1,2,3] Output: 3 Explanation: LIS is [1,2,3] Example 2: Input: [4,2,4,5,3,7] Output: 4 Explanation: LIS is [2,4,5,7] Challenge Time complexity O(n^2) or O(nlogn) Clarification What's the definition of longest increasing subsequence? The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique. https://en.wikipedia.org/wiki/Longest_increasing_subsequence """ class Solution: """ @param nums: An integer array @return: The length of LIS (longest increasing subsequence) """ def longestIncreasingSubsequence(self, nums): if not nums: return 0 res = [1] * len(nums) for i in range(1, len(nums)): for j in range(i): if nums[i] > nums[j] and res[i] <= res[j]: res[i] = res[j] + 1 return max(res) if __name__ == "__main__": s = Solution() assert(s.longestIncreasingSubsequence([5,4,1,2,3]) == 3) assert(s.longestIncreasingSubsequence([4,2,4,5,3,7]) == 4) assert(s.longestIncreasingSubsequence([9,3,6,2,7]) == 3)
""" 142. O(1) Check Power of 2 中文 English Using O(1) time to check whether an integer n is a power of 2. Example Example 1: Input: 4 Output: true Example 2: Input: 5 Output: false Challenge O(1) time """ class Solution: """ @param n: An integer @return: True or false """ def checkPowerOf2(self, n): if n == 0: return False return n & n-1
""" 175. Invert Binary Tree 中文 English Invert a binary tree.Left and right subtrees exchange. Example Example 1: Input: {1,3,#} Output: {1,#,3} Explanation: 1 1 / => \ 3 3 Example 2: Input: {1,2,3,#,#,4} Output: {1,3,2,#,4} Explanation: 1 1 / \ / \ 2 3 => 3 2 / \ 4 4 Challenge Do it in recursion is acceptable, can you do it without recursion? """ class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def invertBinaryTree(self, root): if root: temp = root.left root.left = root.right root.right = temp self.invertBinaryTree(root.left) self.invertBinaryTree(root.right) if __name__ == "__main__": s = Solution() t1 = TreeNode(1) t3 = TreeNode(3) t1.left = t3 s.invertBinaryTree(t1) print (t1.val) print (t1.right.val) print (t1.left) t2 = TreeNode(2) t4 = TreeNode(4) t1.left = t2 t3.left = t4 s.invertBinaryTree(t1) print(t1.val) print(t1.left.val) print(t1.left.right.val) print(t1.right.val)
""" 109. Triangle 中文 English Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. Example Example 1: Input the following triangle: [ [2], [3,4], [6,5,7], [4,1,8,3] ] Output: 11 Explanation: The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Example 2: Input the following triangle: [ [2], [3,2], [6,5,7], [4,4,8,1] ] Output: 12 Explanation: The minimum path sum from top to bottom is 12 (i.e., 2 + 2 + 7 + 1 = 12). Notice Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. """ class Solution: """ @param triangle: a list of lists of integers @return: An integer, minimum path sum """ def minimumTotal(self, triangle): return self.helper(triangle, 0, 0, {}) def helper(self, triangle, level, index, cache): if (level, index) in cache: return cache[(level, index)] if level == len(triangle): return 0 path_sum = min(self.helper(triangle, level+1, index, cache), self.helper(triangle, level+1, index+1, cache)) cache[(level, index)] = path_sum + triangle[level][index] return path_sum + triangle[level][index] if __name__ == "__main__": s = Solution() assert(s.minimumTotal([ [2], [3,4], [6,5,7], [4,1,8,3] ]) == 11) assert(s.minimumTotal([ [2], [3,2], [6,5,7], [4,4,8,1] ]) == 12)
""" 1011. Number of Lines To Write String 中文 English We are to write the letters of a given string S, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is written on the next line. We are given an array widths, an array where widths[0] is the width of 'a', widths[1] is the width of 'b', ..., and widths[25] is the width of 'z'. Now answer two questions: how many lines have at least one character from S, and what is the width used by the last such line? Return your answer as an integer list of length 2. Example Example1 : Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] S = "abcdefghijklmnopqrstuvwxyz" Output: [3, 60] Explanation: All letters have the same length of 10. To write all 26 letters, we need two full lines and one line with 60 units. Example2: Input: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] S = "bbbcccdddaaa" Output: [2, 4] Explanation: All letters except 'a' have the same length of 10, and "bbbcccdddaa" will cover 9 * 10 + 2 * 4 = 98 units. For the last 'a', it is written on the second line because there is only 2 units left in the first line. So the answer is 2 lines, plus 4 units in the second line. Notice The length of S will be in the range [1, 1000]. S will only contain lowercase letters. widths is an array of length 26. widths[i] will be in the range of [2, 10]. """ class Solution: """ @param widths: an array @param S: a string @return: how many lines have at least one character from S, and what is the width used by the last such line """ def numberOfLines(self, widths, S): if not S: return [0, 0] current_line = 0 count_lines = 1 for char in S: c_w = widths[ord(char)-97] if current_line + c_w <= 100: current_line += c_w else: count_lines += 1 current_line = 0 current_line += c_w return [count_lines, current_line] if __name__ == "__main__": s = Solution() assert(s.numberOfLines([10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], "abcdefghijklmnopqrstuvwxyz") == [3, 60]) assert(s.numberOfLines([4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], "bbbcccdddaaa") == [2, 4])
""" 212. Space Replacement 中文 English Write a method to replace all spaces in a string with %20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string. You code should also return the new length of the string after replacement. Example Example 1: Input: string[] = "Mr John Smith" and length = 13 Output: string[] = "Mr%20John%20Smith" and return 17 Explanation: The string after replacement should be "Mr%20John%20Smith", you need to change the string in-place and return the new length 17. Example 2: Input: string[] = "LintCode and Jiuzhang" and length = 21 Output: string[] = "LintCode%20and%20Jiuzhang" and return 25 Explanation: The string after replacement should be "LintCode%20and%20Jiuzhang", you need to change the string in-place and return the new length 25. Challenge Do it in-place. """ class Solution: """ @param: string: An array of Char @param: length: The true length of the string @return: The true length of new string """ def replaceBlank(self, string, length): if not string: return 0 for i in range(len(string)): if string[i] == " ": string[i] = "%20" return len(string)
""" 159. Find Minimum in Rotated Sorted Array 中文 English Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. Example Example 1: Input:[4, 5, 6, 7, 0, 1, 2] Output:0 Explanation: The minimum value in an array is 0. Example 2: Input:[2,1] Output:1 Explanation: The minimum value in an array is 1. Notice You can assume no duplicate exists in the array. """ class Solution: """ @param nums: a rotated sorted array @return: the minimum number in the array """ def findMin(self, nums): start = 0 end = len(nums) -1 minimum = 999999 while start < end: mid = (start + end) // 2 if nums[mid] >= nums[end]: start = mid + 1 if nums[start] < minimum: minimum = nums[start] elif nums[mid] <= nums[end]: end = mid if nums[end] < minimum: minimum = nums[end] return minimum if __name__ == "__main__": s = Solution() print(s.findMin([4, 5, 6, 7, 0, 1, 2])) print(s.findMin([2, 1]))
""" 1143. Minimum Index Sum of Two Lists 中文 English Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. Example Example 1: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] Output: ["Shogun"] Explanation: The only restaurant they both like is "Shogun". Example 2: Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["KFC", "Shogun", "Burger King"] Output: ["Shogun"] Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1). Notice 1.The length of both lists will be in the range of [1, 1000]. 2.The length of strings in both lists will be in the range of [1, 30]. 3.The index is starting from 0 to the list length minus 1. 4.No duplicates in both lists. """ class Solution: """ @param list1: a list of strings @param list2: a list of strings @return: the common interest with the least list index sum """ def findRestaurant(self, list1, list2): minimum = 9999999 res = [] for i in range(len(list1)): for j in range(len(list2)): if list1[i] == list2[j]: if i + j < minimum: minimum = i + j res = [list1[i]] elif i + j == minimum: res.append(list1[i]) return res if __name__ == "__main__": s = Solution() assert(s.findRestaurant(["Shogun", "Tapioca Express", "Burger King", "KFC"], ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]) == ['Shogun']) assert(s.findRestaurant(["Shogun", "Tapioca Express", "Burger King", "KFC"], ["KFC", "Shogun", "Burger King"]) == ['Shogun'])