text
stringlengths
37
1.41M
import sys class Logger(object): """ Logger class. Writes errors and info to the cmd line. """ def __init__(self, verbose=False): """ Initialize a logger object. Args: verbose (boolean): If True, the logger will print all status updates and warnings, in addition to errors """ self.verbose = verbose def log_info(self, text): """ Log an info line, prefixed with an [i]. If verbose is False, this does nothing. Args: text (str): Info text to print. """ if self.verbose: print(" [i] %s" % text) def log_warn(self, text): """ Log a warning, prefixed with an [!]. If verbose is False, this does nothing. Args: text (str): Warning text to print. """ if self.verbose: print(" [!] %s" % text) def program_header(self): """ Print a header ment to separate info from compiler from the output of the resulting program. If verbose is False, this does nothing. """ if self.verbose: print("\n---- OUPUT FROM PROGRAM ----\n") def program_footer(self): """ Print a footer ment to separate the output of the resulting program from the info from compiler. If verbose is False, this does nothing. """ if self.verbose: print("\n---- END OUPUT ----\n") def log_error(self, text): """ Log an error. This will be printed regardless of the status of the verbose variable """ print("\033[91m\033[1mError:\033[0m %s" % text, file=sys.stderr)
class GPA(): def __init__(self): self.gpa = 0.0 def get_gpa(self): return self.gpa def set_gpa(self, value): if value < 0.0: self.gpa = 0.0 elif value > 4.0: self.gpa = 4.0 else: self.gpa = value def get_letter(self): if self.gpa < 1.0: return 'F' elif self.gpa < 2.0: return 'D' elif self.gpa < 3.0: return 'C' elif self.gpa < 4.0: return 'B' else: return 'F' def set_letter(self, letter): if letter == 'A': self.gpa = 4.0 elif letter == 'B': self.gpa = 3.0 elif letter == 'C': self.gpa = 2.0 elif letter == 'D': self.gpa = 1.0 elif letter == 'F': self.gpa = 0.0 def main(): student = GPA() print("Initial values:") print("GPA: {:.2f}".format(student.get_gpa())) print("Letter: {}".format(student.get_letter())) value = float(input("Enter a new GPA: ")) student.set_gpa(value) print("After setting value:") print("GPA: {:.2f}".format(student.get_gpa())) print("Letter: {}".format(student.get_letter())) letter = input("Enter a new letter: ") student.set_letter(letter) print("After setting letter:") print("GPA: {:.2f}".format(student.get_gpa())) print("Letter: {}".format(student.get_letter())) if __name__ == "__main__": main()
""" This file contains psuedocode developed by together by the class one semester... """ # Open the file # Read through it character by character # One way to do this for this program, is to read line by line # and then call line.strip() to get rid of any whitespace # for (line in ...) # If current character is any type of opening brace: (, {, [ # push it (the current character) on to a stack # if current character is any type of closing brace: ), }, ] # compare it to the thing on the top of the stack # If the stack is empty (nothing to compare) # Quit now, it doesn't match # if they match (meaning closing of the same type): # We're good # Pop the opening brace off the stack # If they don't match # Quit now, and tell them the braces don't match # after reading the complete file # If there is anything on the stack, the braces didn't match
""" File: ta03-solution.py Author: Br. Burton This file contains a Rational class to hold fractions and demonstrates their basic functions. """ class Rational: """ The Rational class stores a rational number (i.e., fraction) in the form of a top and bottom number. """ def __init__(self): """ Initializes the number to 0/1 """ self.top = 0 self.bottom = 1 def prompt(self): """ Asks the user for a numerator and denominator and saves them """ # Some error checking here would be nice... self.top = int(input("Enter the numerator: ")) self.bottom = int(input("Enter the denominator: ")) def display(self): """ Displays the number in the format "top/bottom" """ print("{}/{}".format(self.top, self.bottom)) def display_decimal(self): """ Displays the number in the format "0.75" for 3/4 """ # Note that Python 3 by default will do floating point # division instead of integer division like Python 2 or C++ print(self.top/self.bottom) def main(): """ Tests the Rational number class. """ # Create a new rational number fraction = Rational() # Display the default value fraction.display() # Prompt the user for their values fraction.prompt() # Display the new number in both formats fraction.display() fraction.display_decimal() # If this is the file being run, call our main function if __name__ == "__main__": main()
def findBraces(): user = 'stacks06.txt' jOpen = open(user, "r") stack = [] for i in jOpen: k = i.strip() for ch in k: # if current character is an open one just add to the stack if ch == '(' or ch == '[' or ch == '{': stack.append(ch) # if current character is any type of closing brace: ), }, ] if ch == ')' or ch == ']' or ch == '}': # If the stack is empty (nothing to compare) if len(stack) == 0: # Quit now, it doesn't match return "not balance" lastch = stack.pop() # if they match (meaning closing of the same type): # We're good # Pop the opening brace off the stack # If they don't match # Quit now, and tell them the braces don't match if lastch == '(' and (ch != ')'): return "not balanced" if lastch == '[' and (ch != ']'): return "not balanced" if lastch == '{' and (ch != '}'): return "not balanced" # after reading the complete file # If there is anything on the stack, the braces didn't match if len(stack) != 0: return "not balanced" return "Balanced" print(findBraces())
class Point: def __init__(self): self.x = 0 self.y = 0 def prompt_for_point(self): self.x = int(input('Enter x: ')) self.y = int(input('Enter y: ')) def display(self): print('Center:') print('({}, {})'.format(self.x, self.y)) class Circle(Point): def __init__(self): self.radius = 0 super().__init__() def prompt_for_circle(self): super().prompt_for_point() self.radius = int(input("Enter radius: ")) def display(self): super().display() print('Radius: {}'.format(self.radius)) def main(): circle = Circle() circle.prompt_for_circle() print() circle.display() if __name__ == '__main__': main()
""" File: asteroids08.py Original Author: Br. Burton Designed to be completed by others This program implements the asteroids08 game. """ import math from abc import ABC from abc import abstractmethod import random import arcade # These are Global constants to use throughout the game SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 BULLET_RADIUS = 30 BULLET_SPEED = 10 BULLET_LIFE = 60 SHIP_TURN_AMOUNT = 3 SHIP_THRUST_AMOUNT = 0.25 SHIP_RADIUS = 30 INITIAL_ROCK_COUNT = 5 BIG_ROCK_SPIN = 1 BIG_ROCK_SPEED = 1.5 BIG_ROCK_RADIUS = 15 MEDIUM_ROCK_SPIN = -2 MEDIUM_ROCK_RADIUS = 5 SMALL_ROCK_SPIN = 5 SMALL_ROCK_RADIUS = 2 class Point: def __init__(self): self.x_coordinate = 0 self.y_coordinate = 0 class Velocity: def __init__(self): self.dx = 0 self.dy = 0 class FlyingObject(ABC): def __init__(self, img): self.texture = arcade.load_texture(img) self.width = self.texture.width self.height = self.texture.height self.radius = SHIP_RADIUS self.image = img self.center = Point() self.velocity = Velocity() self.angle = 0 self.speed = 0 self.direction = 0 self.alpha = 255 self.alive = True self.velocity.velocity_dx = math.cos(math.radians(self.direction)) * self.speed self.velocity.velocity_dy = math.sin(math.radians(self.direction)) * self.speed def advance(self): self.center.x_coordinate += self.velocity.dx self.center.y_coordinate += self.velocity.dy def is_alive(self): return self.alive def draw(self): arcade.draw_texture_rectangle(self.center.x_coordinate, self.center.y_coordinate, self.width, self.height, self.texture, self.angle, self.alpha) def is_off_screen(self, screen_width, screen_height): return True class Asteroid(FlyingObject): def __init__(self, img): super().__init__(img) self.radius = 0.0 self.velocity.dx = math.cos(math.radians(self.direction)) * self.speed self.velocity.dy = math.sin(math.radians(self.direction)) * self.speed def hit(self): pass class SmallRock(Asteroid): def __init__(self): super().__init__("images/small_rock.png") class MediumRock(Asteroid): def __init__(self): super().__init__("images/medium_rock.png") class BigRock(Asteroid): def __init__(self): super().__init__("images/big_rock.png") self.center.x = random.randint(1, 50) self.center.y = random.randint(1, 150) self.direction = random.randint(1, 50) self.speed = BIG_ROCK_SPEED self.velocity.dx = math.cos(math.radians(self.direction)) * self.speed self.velocity.dy = math.sin(math.radians(self.direction)) * self.speed class Ship(FlyingObject): def __init__(self): super().__init__("images/ship.png") self.angle = 1 self.center.x_coordinate = SCREEN_WIDTH / 2 self.center.y_coordinate = SCREEN_HEIGHT / 2 self.radius = SHIP_RADIUS class Laser(FlyingObject): def __init__(self): super().__init__("images/laser.png") def fire(self, angle): pass def advance(self): pass class Game(arcade.Window): """ This class handles all the game callbacks and interaction This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this class. """ def __init__(self, width, height): """ Sets up the initial conditions of the game :param width: Screen width :param height: Screen height """ super().__init__(width, height) arcade.set_background_color(arcade.color.SMOKY_BLACK) self.held_keys = set() # TODO: declare anything here you need the game class to track #self.ship = Ship() self.laser = [] self.asteroids = [] for item in range(INITIAL_ROCK_COUNT): asteroid = BigRock() self.asteroids.append(asteroid) def on_draw(self): """ Called automatically by the arcade framework. Handles the responsibility of drawing all elements. """ # clear the screen to begin drawing arcade.start_render() # TODO: draw each object # self.ship.draw() for asteroid in self.asteroids: asteroid.draw() def update(self, delta_time): """ Update each object in the game. :param delta_time: tells us how much time has actually elapsed """ self.check_keys() # TODO: Tell everything to advance or move forward one step in time for asteroid in self.asteroids: asteroid.advance() # TODO: Check for collisions def check_keys(self): """ This function checks for keys that are being held down. You will need to put your own method calls in here. """ if arcade.key.LEFT in self.held_keys: pass if arcade.key.RIGHT in self.held_keys: pass if arcade.key.UP in self.held_keys: pass if arcade.key.DOWN in self.held_keys: pass # Machine gun mode... # if arcade.key.SPACE in self.held_keys: # pass def on_key_press(self, key: int, modifiers: int): """ Puts the current key in the set of keys that are being held. You will need to add things here to handle firing the bullet. """ if self.ship.alive: self.held_keys.add(key) if key == arcade.key.SPACE: # TODO: Fire the bullet here! pass def on_key_release(self, key: int, modifiers: int): """ Removes the current key from the set of held keys. """ if key in self.held_keys: self.held_keys.remove(key) # Creates the game and starts it going window = Game(SCREEN_WIDTH, SCREEN_HEIGHT) arcade.run()
""" File: asteroids08.py Original Author: Br. Burton Designed to be completed by others This program implements the asteroids08 game. """ import math from abc import ABC from abc import abstractmethod import random import arcade # These are Global constants to use throughout the game SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCREE_TITLE = 'Asteroids Game, by Carlos W. Mercado, for CS241, Spring Semester 2020 ☺' BULLET_RADIUS = 30 BULLET_SPEED = 10 BULLET_LIFE = 60 BULLET_TIME_NEXTONE = 10.0 SHIP_TURN_AMOUNT = 3 SHIP_THRUST_AMOUNT = 0.25 SHIP_RADIUS = 30 INITIAL_ROCK_COUNT = 5 BIG_ROCK_SPIN = 1 BIG_ROCK_SPEED = 1.5 BIG_ROCK_RADIUS = 15 BIG_ROCK_SCORE = 1 MEDIUM_ROCK_SPIN = -2 MEDIUM_ROCK_RADIUS = 5 MEDIUM_ROCK_SCORE = 2 SMALL_ROCK_SPIN = 5 SMALL_ROCK_RADIUS = 2 SMALL_ROCK_SCORE = 3 # HAS-A section ''' Point and Velocity classes are owned by FlyingObject class and its sub-classes. ''' class Point: def __init__(self): self.x_coordinate = 100 self.y_coordinate = 100 class Velocity: def __init__(self): self.dx = 0 self.dy = 0 # IS-A Section ''' Main parent class: From ABC superclass: FlyingObject 1st child class: Asteroid, Ship, Bullet 2nd child class: From Asteroid: BigRock, MediumRock, SmallRock ''' # This is an abstract class class FlyingObject(ABC): def __init__(self, img): self.texture = arcade.load_texture(img) self.width = self.texture.width self.height = self.texture.height self.image = img self.radius = 0.0 self.center = Point() self.velocity = Velocity() self.angle = 0.0 self.speed = 0.0 self.alpha = 255 self.alive = True def advance(self): self.center.x_coordinate += self.velocity.dx * self.speed self.center.y_coordinate += self.velocity.dy * self.speed def draw(self): arcade.draw_texture_rectangle(self.center.x_coordinate, self.center.y_coordinate, self.width, self.height, self.texture, self.angle, self.alpha) def is_off_screen(self): if self.center.x_coordinate > SCREEN_WIDTH: self.center.x_coordinate -= SCREEN_WIDTH if self.center.x_coordinate < 0: self.center.x_coordinate += SCREEN_WIDTH if self.center.y_coordinate > SCREEN_HEIGHT: self.center.y_coordinate -= SCREEN_HEIGHT if self.center.y_coordinate < 0: self.center.y_coordinate += SCREEN_HEIGHT # This is an abstract class class Asteroid(FlyingObject): def __init__(self, img): super().__init__(img) self.radius = BIG_ROCK_RADIUS def break_apart(self, asteroids): pass # At the beginning of the game there are just 5 rocks, and each one scores 1 point # Every time a BigRock is destroyed, it generates 2 medium rocks and 1 small one. class BigRock(Asteroid): def __init__(self): super().__init__("images/big_rock.png") self.center.x = random.randint(0, SCREEN_WIDTH) self.center.y = random.randint(0, SCREEN_HEIGHT) self.angle = random.randint(1, 360) self.speed = BIG_ROCK_SPEED self.velocity.dx = math.cos(math.radians(self.angle)) * self.speed self.velocity.dy = math.sin(math.radians(self.angle)) * self.speed def advance(self): super().advance() self.angle += BIG_ROCK_SPIN def break_apart(self, asteroids): medium_asteroid = MediumRock(self) medium_asteroid.velocity.dy += 2 asteroids.append(medium_asteroid) medium_asteroid = MediumRock(self) medium_asteroid.velocity.dy -= 2 asteroids.append(medium_asteroid) small_asteroid = SmallRock(self) small_asteroid.velocity.dx += 5 asteroids.append(small_asteroid) # Every destroyed MediumRock scores 2 points # Every time a BigRock is destroyed, it generates 2 small rocks class MediumRock(Asteroid): def __init__(self, asteroid: BigRock): super().__init__("images/medium_rock.png") self.radius = MEDIUM_ROCK_RADIUS self.center.x_coordinate = asteroid.center.x_coordinate self.center.y_coordinate = asteroid.center.y_coordinate self.speed = BIG_ROCK_SPEED self.angle = random.randint(1, 360) self.velocity.dx = math.cos(math.radians(self.angle)) * self.speed self.velocity.dy = math.sin(math.radians(self.angle)) * self.speed def advance(self): super().advance() self.angle += MEDIUM_ROCK_SPIN def break_apart(self, asteroids): small_asteroid = SmallRock(self) small_asteroid.velocity.dy += 1.5 small_asteroid.velocity.dx += 1.5 asteroids.append(small_asteroid) small_asteroid = SmallRock(self) small_asteroid.velocity.dy -= 1.5 small_asteroid.velocity.dx -= 1.5 asteroids.append(small_asteroid) # Every destroyed MediumRock scores 3 points class SmallRock(Asteroid): def __init__(self, asteroid: BigRock): super().__init__("images/small_rock.png") self.radius = SMALL_ROCK_RADIUS self.center.x_coordinate = asteroid.center.x_coordinate self.center.y_coordinate = asteroid.center.y_coordinate self.speed = BIG_ROCK_SPEED self.angle = random.randint(1, 360) self.velocity.dx = math.cos(math.radians(self.angle)) * self.speed self.velocity.dy = math.sin(math.radians(self.angle)) * self.speed def advance(self): super().advance() self.angle += SMALL_ROCK_SPIN class Ship(FlyingObject): def __init__(self): super().__init__("images/ship.png") self.angle = 0 self.center.x_coordinate = SCREEN_WIDTH / 2 self.center.y_coordinate = SCREEN_HEIGHT / 2 self.radius = SHIP_RADIUS self.speed = SHIP_THRUST_AMOUNT def thrust(self): self.velocity.dx += math.cos(math.radians(self.angle)) * self.speed self.velocity.dy += math.sin(math.radians(self.angle)) * self.speed def rotate_right(self): self.angle -= SHIP_TURN_AMOUNT def rotate_left(self): self.angle += SHIP_TURN_AMOUNT def un_thrust(self): self.velocity.dx -= math.cos(math.radians(self.angle)) * self.speed self.velocity.dy -= math.sin(math.radians(self.angle)) * self.speed # Ship's velocity adds to bullet's velocity. For this purpose the bullet's constructor # requires a ship object. Also the ship's position is required. class Bullet(FlyingObject): def __init__(self, ship: Ship): super().__init__("images/laser.png") self.angle = ship.angle self.speed = ship.speed + BULLET_SPEED self.radius = BULLET_RADIUS self.center.x_coordinate = ship.center.x_coordinate + SHIP_RADIUS * math.cos(math.radians(self.angle)) self.center.y_coordinate = ship.center.y_coordinate + SHIP_RADIUS * math.sin(math.radians(self.angle)) self.life = BULLET_LIFE self.ship_velocity_dx = ship.velocity.dx self.ship_velocity_dy = ship.velocity.dy def fire(self, ship): self.velocity.dx = math.cos(math.radians(ship.angle)) * self.speed self.velocity.dy = math.sin(math.radians(ship.angle)) * self.speed # The bullet dies after 60 frames. def advance(self): self.center.x_coordinate += (self.velocity.dx + self.ship_velocity_dx) self.center.y_coordinate += (self.velocity.dy + self.ship_velocity_dy) self.life -= 1 if self.life < 0: self.alive = False def draw(self): arcade.draw_texture_rectangle(self.center.x_coordinate, self.center.y_coordinate, self.width, self.height, self.texture, self.angle, self.alpha) # View Section ''' → FROM main(): window, instance of arcade.Window(), the its view is changed to one of the following classes. Main parent class: arcade.View Children: MenuView, PauseView, GameOverView, YouWinView, GameView GameView contains the whole logic for the main game. Every view changes over different events (keyboard events, or in game events). ''' # Start the game, Close the game class MenuView(arcade.View): def on_show(self): arcade.set_background_color(arcade.color.WHITE) def on_draw(self): arcade.start_render() arcade.draw_text("ASTEROIDS", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 80, arcade.color.BLACK, font_size=50, anchor_x="center") arcade.draw_text("By Carlos W. Mercado, for CS241", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 60, arcade.color.GRAY, font_size=20, anchor_x="center") arcade.draw_text("SPRING Semester, 2020", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 35, arcade.color.GRAY, font_size=20, anchor_x="center") arcade.draw_text("Press ENTER to start", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 5, arcade.color.GRAY, font_size=20, anchor_x="center") arcade.draw_text("ESCAPE to play again", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 30, arcade.color.GRAY, font_size=20, anchor_x="center") arcade.draw_text("Q to quit the game", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 55, arcade.color.GRAY, font_size=20, anchor_x="center") arcade.draw_text("P to pause the game", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 80, arcade.color.GRAY, font_size=20, anchor_x="center") arcade.draw_text("ARROWS to move the ship", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 120, arcade.color.GRAY, font_size=20, anchor_x="center") arcade.draw_text("SPACEBAR to shoot laser", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 145, arcade.color.GRAY, font_size=20, anchor_x="center") arcade.draw_text("Hold SPACEBAR for machine gun mode", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 170, arcade.color.GRAY, font_size=20, anchor_x="center") def on_key_press(self, key: int, modifiers: int): if key == arcade.key.ENTER: # starts the game game = GameView() self.window.show_view(game) if key == arcade.key.Q: # closes the game's main window arcade.close_window() # Pause, GameOver the restart, Close the game class PauseView(arcade.View): def __init__(self, game_view): super().__init__() self.game_view = game_view def on_show(self): arcade.set_background_color(arcade.color.SMOKY_BLACK) def on_draw(self): arcade.start_render() arcade.draw_text("PAUSED", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 50, arcade.color.WHITE, font_size=50, anchor_x="center") arcade.draw_text("P to unpause the game", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, arcade.color.WHITE, font_size=20, anchor_x="center") arcade.draw_text("ESCAPE to play again", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 30, arcade.color.WHITE, font_size=20, anchor_x="center") arcade.draw_text("Q to quit the game", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 60, arcade.color.WHITE, font_size=20, anchor_x="center") def on_key_press(self, key, _modifiers): if key == arcade.key.P: # unpause the game, the game is pause in the GameView class self.window.show_view(self.game_view) if key == arcade.key.ESCAPE: # sends to the game over screen game = GameOverView() self.window.show_view(game) if key == arcade.key.Q: # closes the game arcade.close_window() # Opens main menu, Close the game class GameOverView(arcade.View): def on_show(self): arcade.set_background_color(arcade.color.RED) def on_draw(self): arcade.start_render() arcade.draw_text("GAME OVER", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, arcade.color.WHITE, font_size=50, anchor_x="center") arcade.draw_text("ESCAPE to play again", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 30, arcade.color.WHITE, font_size=20, anchor_x="center") arcade.draw_text("Q to quit game", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 60, arcade.color.WHITE, font_size=20, anchor_x="center") def on_key_press(self, key, _modifiers): if key == arcade.key.ESCAPE: # from game over screen to menu screen game = MenuView() self.window.show_view(game) if key == arcade.key.Q: # closes the game arcade.close_window() # Open main menu, Close the game class YouWinView(arcade.View): def __init__(self, score): super().__init__() self.score = score def on_show(self): arcade.set_background_color(arcade.color.KELLY_GREEN) def on_draw(self): arcade.start_render() arcade.draw_text("YOU WIN", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 30, arcade.color.WHITE, font_size=50, anchor_x="center") arcade.draw_text("Your score was: {}".format(self.score), SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, arcade.color.WHITE, font_size=30, anchor_x="center") arcade.draw_text("ESCAPE to play again", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 30, arcade.color.WHITE, font_size=20, anchor_x="center") arcade.draw_text("Q to quit game", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 60, arcade.color.WHITE, font_size=20, anchor_x="center") def on_key_press(self, key, _modifiers): if key == arcade.key.ESCAPE: # send to the menu screen game = MenuView() self.window.show_view(game) if key == arcade.key.Q: # closes the game arcade.close_window() # MAIN CLASS IN THE PROGRAM # This class handles the game and the event handlers class GameView(arcade.View): """ This class handles all the game callbacks and interaction This class will then call the appropriate functions of each of the above classes. """ def __init__(self): super().__init__() arcade.set_background_color(arcade.color.SMOKY_BLACK) # TODO: declare anything here you need the game class to track self.held_keys = set() self.score = 0 self.lives = 2 self.time_next_bullet = BULLET_TIME_NEXTONE self.bullets = [] self.asteroids = [] self.ships = [] ship = Ship() self.ships.append(ship) self.asteroids.clear() for item in range(INITIAL_ROCK_COUNT): asteroid = BigRock() self.asteroids.append(asteroid) def on_draw(self): """ Called automatically by the arcade framework. Handles the responsibility of drawing all elements. """ # clear the screen to begin drawing arcade.start_render() # TODO: draw each object for asteroid in self.asteroids: asteroid.draw() for bullet in self.bullets: bullet.draw() for ship in self.ships: ship.draw() # Draw score and life counter self.draw_score() def update(self, delta_time): """ Update each object in the game. :param delta_time: tells us how much time has actually elapsed """ # TODO: Tell everything to advance or move forward one step in time # The following loops also keep track of the objects while they move from off the screen. for asteroid in self.asteroids: asteroid.advance() asteroid.is_off_screen() if asteroid.alive is False: self.asteroids.remove(asteroid) for bullet in self.bullets: bullet.advance() bullet.is_off_screen() if bullet.alive is False: self.bullets.remove(bullet) for ship in self.ships: ship.advance() ship.is_off_screen() # The player wins the game when there are no more asteroids left in the game. if len(self.asteroids) == 0: game = YouWinView(self.score) self.window.show_view(game) # For Machine Gun Mode, it is possible to fire a new bullet after BULLET_TIME_NEXTONE self.time_next_bullet -= 1 if self.time_next_bullet < 0: self.time_next_bullet = BULLET_TIME_NEXTONE # TODO: Check for collisions and keys on keyboard, on time self.check_keys() self.check_collisions() def check_keys(self): """ This function checks for keys that are being held down. You will need to put your own method calls in here. """ if arcade.key.UP in self.held_keys: for ship in self.ships: ship.thrust() if arcade.key.DOWN in self.held_keys: for ship in self.ships: ship.un_thrust() if arcade.key.RIGHT in self.held_keys: for ship in self.ships: ship.rotate_right() if arcade.key.LEFT in self.held_keys: for ship in self.ships: ship.rotate_left() # RESTARTING THE GAME while in the GameView if arcade.key.ESCAPE in self.held_keys: game = MenuView() self.window.show_view(game) # Machine gun mode... if arcade.key.SPACE in self.held_keys: # Track of time is kept if self.time_next_bullet == 0: bullet = Bullet(self.ships[0]) bullet.fire(self.ships[0]) self.bullets.append(bullet) def on_key_press(self, key: int, modifiers: int): """ Puts the current key in the set of keys that are being held. You will need to add things here to handle firing the bullet. """ if self.ships[0].alive: self.held_keys.add(key) if key == arcade.key.SPACE: # TODO: Fire the bullet here! bullet = Bullet(self.ships[0]) bullet.fire(self.ships[0]) self.bullets.append(bullet) # PAUSE the game if key == arcade.key.P: game = PauseView(self) self.window.show_view(game) # Game Over because the player wants to if key == arcade.key.Q: game = GameOverView() self.window.show_view(game) # If you want to play again while IN GAME, you lose. No giving up! if key == arcade.key.ESCAPE: game = GameOverView() self.window.show_view(game) def on_key_release(self, key: int, modifiers: int): """ Removes the current key from the set of held keys. Necessary for all keys. """ if key in self.held_keys: self.held_keys.remove(key) def check_collisions(self): """ Checks to see if bullets have hit asteroids. Removes dead items. :return: """ # BULLETS Vs ASTEROIDS for bullet in self.bullets: for asteroid in self.asteroids: if bullet.alive and asteroid.alive: too_close = bullet.radius + asteroid.radius if (abs(bullet.center.x_coordinate - asteroid.center.x_coordinate) < too_close and abs(bullet.center.y_coordinate - asteroid.center.y_coordinate) < too_close): # it's a hit! bullet.alive = False asteroid.alive = False # SCORING if type(asteroid).__name__ == 'BigRock': self.score += BIG_ROCK_SCORE if type(asteroid).__name__ == 'MediumRock': self.score += MEDIUM_ROCK_SCORE if type(asteroid).__name__ == 'SmallRock': self.score += SMALL_ROCK_SCORE # Some asteroids produce more asteroids! asteroid.break_apart(self.asteroids) # SHIP Vs ASTEROIDS for asteroid in self.asteroids: for ship in self.ships: if ship.alive and asteroid.alive: too_close = ship.radius + asteroid.radius if (abs(ship.center.x_coordinate - asteroid.center.x_coordinate) < too_close and abs(ship.center.y_coordinate - asteroid.center.y_coordinate) < too_close): # its a hit! asteroid.alive = False self.lives -= 1 # If the ship is hit 2 times is GAME OVER, babe! if self.lives < 1: ship.alive = False game = GameOverView() self.window.show_view(game) self.cleanup_zombies() def cleanup_zombies(self): """ Removes any dead bullets or asteroids from the list, also the ship. :return: """ for bullet in self.bullets: if not bullet.alive: self.bullets.remove(bullet) for asteroid in self.asteroids: if not asteroid.alive: self.asteroids.remove(asteroid) for ship in self.ships: if not ship.alive: self.ships.remove(ship) def draw_score(self): """ Puts the current score on the screen, and lives """ score_text = "Score: {} \n" \ "Lives: {}".format(self.score, self.lives) start_x = 10 start_y = SCREEN_HEIGHT - 40 arcade.draw_text(score_text, start_x=start_x, start_y=start_y, font_size=15, color=arcade.color.WHITE) # Creates the game and starts it going def main(): window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREE_TITLE) menu = MenuView() window.show_view(menu) arcade.run() if __name__ == '__main__': main()
class Book: def __init__(self): self.title = '' self.author = '' self.publication_year = 0 def prompt_book_info(self): self.title = input('Title: ') self.author = input('Author: ') self.publication_year = input('Publication Year: ') def display_book_info(self): print('{} ({}) by {}'.format(self.title, self.publication_year, self.author)) class TextBook(Book): def __init__(self): self.subject = '' super().__init__() def prompt_subject(self): self.subject = input('Subject: ') def display_subject(self): print('Subject: {}'.format(self.subject)) class PictureBook(Book): def __init__(self): self.illustrator = '' super().__init__() def prompt_illustrator(self): self.subject = input('Illustrator: ') def display_illustrator(self): print('Illustrated by {}'.format(self.subject)) def main(): regular_book = Book() text_book = TextBook() picture_book = PictureBook() regular_book.prompt_book_info() print() regular_book.display_book_info() print() text_book.prompt_book_info() text_book.prompt_subject() print() text_book.display_book_info() text_book.display_subject() print() picture_book.prompt_book_info() picture_book.prompt_illustrator() print() picture_book.display_book_info() picture_book.display_illustrator() if __name__ == '__main__': main()
import time def insert(word, pos, char): if pos == 0: return char + word elif pos == len(word): return word + char return word[:pos] + char + word[pos:] def result(word, letters): start, end = 0, len(letters) max_pos, pos = len(word), 0 while start < end: if pos > max_pos: pos = 0 else: yield insert(word, pos, letters[start]) pos += 1 continue start += 1 word = "A" start = time.clock() for n in result(word, [chr(ord('b') + c) for c in range(2)]): print(n) elapsed = (time.clock() - start) print("Time used:", elapsed) start = time.clock() for i in range(ord('b'), ord('b')+24): new = None for j in range(len(word)): if j == 0: new = chr(i) + word print(new) elif j == len(word)-1: new = word + chr(i) print(new) else: new = word[0:j] + chr(i) + word[j:] print(new) elapsed = (time.clock() - start) print("Time used:", elapsed)
# Time: O(n) # Space: O(n) # Given n processes, each process has a unique PID (process id) # and its PPID (parent process id). # # Each process only has one parent process, but may have one or more children processes. # This is just like a tree structure. Only one process has PPID that is 0, # which means this process has no parent process. All the PIDs will be distinct positive integers. # # We use two list of integers to represent a list of processes, # where the first list contains PID for each process # and the second list contains the corresponding PPID. # # Now given the two lists, and a PID representing a process you want to kill, # return a list of PIDs of processes that will be killed in the end. # You should assume that when a process is killed, # all its children processes will be killed. # No order is required for the final answer. # # Example 1: # Input: # pid = [1, 3, 10, 5] # ppid = [3, 0, 5, 3] # kill = 5 # Output: [5,10] # Explanation: # 3 # / \ # 1 5 # / # 10 # Kill 5 will also kill 10. # Note: # The given kill id is guaranteed to be one of the given PIDs. # n >= 1. # DFS solution. class Solution(object): def killProcess(self, pid, ppid, kill): """ :type pid: List[int] :type ppid: List[int] :type kill: int :rtype: List[int] """ def killAll(pid, children, killed): killed.append(pid) for child in children[pid]: killAll(child, children, killed) result = [] children = collections.defaultdict(set) for i in xrange(len(pid)): children[ppid[i]].add(pid[i]) killAll(kill, children, result) return result # Time: O(n) # Space: O(n) # BFS solution. class Solution2(object): def killProcess(self, pid, ppid, kill): """ :type pid: List[int] :type ppid: List[int] :type kill: int :rtype: List[int] """ def killAll(pid, children, killed): killed.append(pid) for child in children[pid]: killAll(child, children, killed) result = [] children = collections.defaultdict(set) for i in xrange(len(pid)): children[ppid[i]].add(pid[i]) q = collections.deque() q.append(kill) while q: p = q.popleft() result.append(p); for child in children[p]: q.append(child) return result
""" Implements the observer pattern and simulates a simple auction. """ import random class Auctioneer: """ The auctioneer acts as the "core". This class is responsible for tracking the highest bid and notifying the bidders if it changes. """ def __init__(self): """ Initializes auctioneer. """ self.bidders = [] self._highest_bid = 0 self._highest_bidder = None def register_bidder(self, bidder): """ Adds a bidder to the list of tracked bidders. :param bidder: object with __call__(auctioneer) interface. """ self.bidders.append(bidder) def reset_auctioneer(self): """ Resets the auctioneer. Removes all the bidders and resets the highest bid to 0. """ self.bidders.clear() self._highest_bid = 0 self._highest_bidder = None def get_highest_bid(self): """ Return highest bid. :return: float, _highest_bid """ return self._highest_bid def get_highest_bidder(self): """ Return highest bid. :return: str, _highest_bidder """ return self._highest_bidder def _notify_bidders(self): """ Executes all the bidder callbacks. Should only be called if the highest bid has changed. """ for bidder in self.bidders: if self._highest_bidder is not bidder: bidder(self) def accept_bid(self, bid, bidder): """ Accepts a new bid and updates the highest bid. This notifies all the bidders via their callbacks. :param bid: a float. :precondition bid: should be higher than the existing bid. :param bidder: The object with __call__(auctioneer) that placed the bid. """ if bidder != "Starting Bid": print(f"{bidder} bidded {bid} in response to {self._highest_bidder}'s bid of {self._highest_bid}!") self._highest_bid = bid self._highest_bidder = bidder self._notify_bidders() class Bidder: def __init__(self, name, budget=100.00, bid_probability=0.35, bid_increase_perc=1.1): """ Initialize the object with given arguments. :param name: string :param budget: float :param bid_probability: flaot :param bid_increase_perc: flaot :precondition: name must be a string :precondition: budget must be a float :precondition: bid_probability must be a float :precondition: bid_increase_perc must be a float """ self.name = name self.bid_probability = bid_probability self.budget = budget self.bid_increase_perc = bid_increase_perc self.highest_bid = 0 def __call__(self, auctioneer): """ Notifies the bidder to consider bidding. :param auctioneer: Auctioneer :precondition: auctioneer must be an Auctioneer :return: None """ possible_bid = self.bid_increase_perc * auctioneer.get_highest_bid() if possible_bid < self.budget and random.random() <= self.bid_probability: self.highest_bid = possible_bid auctioneer.accept_bid(possible_bid, self) def __str__(self): """ Returns the name of the bidder :return: str, name """ return self.name class Auction: """ Simulates an auction. Is responsible for driving the auctioneer and the bidders. """ def __init__(self, bidders): """ Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder """ self._bidders = bidders self._auctioneer = Auctioneer() for bidder in bidders: self._auctioneer.register_bidder(bidder) def simulate_auction(self, item, start_price): """ Starts the auction for the given item at the given starting price. Drives the auction till completion and prints the results. :param item: string, name of item. :param start_price: float """ print(f"Auctioning {item} starting at {start_price}!") self._auctioneer.accept_bid(start_price, "Starting Bid") summary = {bidder.name: bidder.highest_bid for bidder in self._bidders} print(f"\nThe winner of the auction is: " f"{self._auctioneer.get_highest_bidder()} at ${self._auctioneer.get_highest_bid()}\n") print("Highest Bids Per Bidder") for bidder, highest_bid in summary.items(): print(f"Bidder: {bidder}\tHighest Bid: {highest_bid}") def create_bidder(): name = input("Bidder's name: ") budget = float(input("Bidder's budget: ")) bid_probability = random.random() bid_increase_perc = float(input("Bid increase percentage: ")) return Bidder(name, budget, bid_probability, bid_increase_perc) def main(): auction_item = input("Enter bid item: ") while True: try: starting_price = float(input("Enter starting price: ")) break except ValueError: print("Incorrect input") prompt = "Do you want to use hardcoded bidders or new custom bidders?\n" \ "Enter 1 for hardcoded bidders\n" \ "Enter 2 to begin adding custom bidders\n" bidders = [] if input(prompt).strip() == "1": # Hardcoding the bidders. bidders.append(Bidder("Jojo", 3000, random.random(), 1.2)) bidders.append(Bidder("Melissa", 7000, random.random(), 1.5)) bidders.append(Bidder("Priya", 15000, random.random(), 1.1)) bidders.append(Bidder("Kewei", 800, random.random(), 1.9)) bidders.append(Bidder("Scott", 4000, random.random(), 2)) else: while True: try: bidders.append(create_bidder()) except ValueError: print("Incorrect input") if input("Add bidder(y/n): ").strip().lower() == 'n': break print("\n\nStarting Auction!!") print("------------------") my_auction = Auction(bidders) my_auction.simulate_auction(auction_item, starting_price) if __name__ == '__main__': main()
import abc class Item(abc.ABC): """ Abstract representation of an Item """ def __init__(self, name, description, product_id): """ Initializes variables. :param name: string :param description: string :param product_id: string """ print("Item") self._name = name self._description = description self._product_id = product_id @property def name(self): """ Getter for name. :return: name, string """ return self._name @property def product_id(self): """ Getter for product_id. :return: product_id, string """ return self._product_id
class Order: """ Class that represents an order received. """ def __init__(self, order_number, product_id, item, name, factory_object, **product_details): """ Initializes Order object. :param order_number: int :param product_id: string, combination of alphabet and numbers :param item: string in (toy, candy, stuffed animal) :param name: string, name of the item :param factory_object: ItemFactory :param product_details: dictionary of key/value pairs of product details used to create item """ self._order_number = order_number self._product_id = product_id self._item = item self._name = name self._factory_object = factory_object self._product_details = product_details self._is_valid = True self._error_msg = "" @property def product_id(self): """ Getter for product_id. :return: string """ return self._product_id @property def item(self): """ Getter for item. :return: string """ return self._item @property def name(self): """ Getter for name. :return: string """ return self._name @property def factory_object(self): """ Getter for factory_object :return: ItemFactory """ return self._factory_object @property def product_details(self): """ Getter for product details. :return: dict """ return self._product_details def get_is_valid(self): """ Getter for is_valid. :return: boolean """ return self._is_valid def set_is_valid(self, is_valid): """ Setter for is_valid. :param is_valid: boolean :return: None """ self._is_valid = is_valid is_valid = property(get_is_valid, set_is_valid) def set_error_msg(self, error_msg): """ Setter for error_msg. :param error_msg: string :return: None """ self._error_msg = error_msg def __str__(self): """ String representation of the Order object. :return: the description of the Order object in readable format """ if self._is_valid: quantity = self._product_details.get("quantity") return f"Order {self._order_number}, " \ f"Item {self._item}, " \ f"Product ID {self._product_id}, " \ f"Name \"{self._name}\", " \ f"Quantity {quantity}" else: return f"Order {self._order_number}, " \ f"{self._error_msg}"
from enum import Enum, auto class Colours(Enum): """ Represents colours of particular store items that come in different colours (Robot Bunny, Easter Bunny, Candy Cane). """ ROBOT_BUNNY_BEGIN = ORANGE = auto() EASTER_BUNNY_BEGIN = BLUE = auto() PINK = auto() ROBOT_BUNNY_END = WHITE = auto() GREY = auto() EASTER_BUNNY_END = CHRISTMAS_BEGIN = RED = auto() GREEN = auto()
class User: """ This class represents a FAM user and their user details. """ def __init__(self, name, age, account, budgets, lock_status): """ Initialize user details. :param name: a string :param age: an int :param account: an Account object :param budgets: a tuple of budgets :param lock_status: a boolean :precondition: name must be a string :precondition: age must be an int :precondition: account must be an Account :precondition: budgets must be a tuple :precondition: lock_status must be a bool """ self._name = name self._age = age self._account = account self._budgets = budgets self._lock_status = lock_status def get_transaction_by_date(self): """ Return string consists of transaction details ordered by date. :return: str """ all_transactions = [] for budget in self._budgets: all_transactions += budget.transactions all_transactions.sort(key=lambda x: x.timestamp) transaction_str = "" for transaction in all_transactions: transaction_str += transaction.__str__() + "\n" return transaction_str @property def name(self): """ Display only property for _budget. :return: str """ return self._name @property def budgets(self): """ Display only property for _budget. :return: float """ return self._budgets @property def account(self): """ Display only property for _account. :return: Account """ return self._account
""" (6 Marks) The code below reads a series of strings from data.txt and saves them into file_names list It then does the following using a SINGLE-LINE list comprehension: 1. Determines if the string contains a json or txt extension 2. Creates a list containing the [file name string and FileType enum] and assigns it to the types_list list """ import enum from enum import auto from pathlib import Path class FileType(enum.Enum): JSON = auto() TXT = auto() file_names = [] # List to store file names read from data.txt # TODO - Write code to read data.txt and add the strings to the file_names list file_path = "data.txt" with open(file_path, mode="r", encoding="utf-8") as file: for line in file: file_names.append(line.strip()) # TODO - Replace "???" with a single-line list comprehension that: # - Determines if the string contains a json or txt extension # - Create a list containing the [file name string and FileType enum] and assign it to the types_list list types_list = [[file_name, FileType.JSON] if Path(file_name).suffix == ".json" else [file_name, FileType.TXT] for file_name in file_names] print(types_list) # expected output: [['birds.json', <FileType.JSON: 1>], ['cats.txt', <FileType.TXT: 2>], ['dogs.txt', <FileType.TXT: 2>]]
import json # import json module # with statement with open('result.json', 'rt', encoding='UTF-8-sig') as json_file: json_data = json.load(json_file) print(json_data[0]) print(type(json_data[0])) questions = [] for i in range(len(json_data)): for key in json_data[i].keys(): questions.append(key) print(questions)
from datetime import datetime import time import random odds = [ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59 ] for i in range(3): right_this_minute = datetime.today().minute if right_this_minute in odds: print("This minute seems a little odd.") else: print("Not an odd minute") wait_time = random.randint(1, 30) time.sleep(wait_time) today = datetime.today().strftime("%A") if today == 'Saturday': print('Party') elif today == 'Sunday': print('Rest.') else: print('Work, work, work.') for i in "sleep": print(i) for num in range(3): print('Hello, there!') word = "bottles" for beer_num in range(12, 0, -1): print(beer_num, word, "of beer on the wall.") print(beer_num, word, "of beer.") print("Take one down.") print("Pass it around.") if beer_num == 1: print("No more bottles of beer on the wall.") else: new_num = beer_num - 1 if new_num == 1: word = "bottle" print(new_num, word , "of beer on the wall.") print()
vowels = ['a','e','i','o','u'] word = input("请输入一个英文单词:") found = {} #建立一个空字典 # found['a'] = 0 found['e'] = 0 found['i'] = 0 found['o'] = 0 found['u'] = 0 #found['e'] = found['e'] + 1 #递增e的频度记数 #fouond['e'] += 1 #+=同样能递增e的频度记数,相较上面更为简洁 for letter in word: #利用迭代计算单词中元音字母出现次数 if letter in vowels: found[letter] += 1 #若某个字母在条件内则增加记数 for k, v in sorted(found.items()): #利用循环迭代访问数据 print(k,'出现了',v,'次')
threes = list(range(3,31,3)) for three in threes: print(three)
from users_class import User class Privileges(): '''New prvilege class to be use for admin and possibly more users''' def __init__(self, privileges=['can add post','can delete post','can ban user']): self.privileges = privileges def show_privileges(self): print("The administator: " + str(self.privileges)) '''for privilege in self.privileges: print(privilege)''' class Admin(User): '''Creating an admin class with special ptvileges''' def __init__(self, first_name, last_name): '''Initializing admin with privileges''' super().__init__(first_name, last_name) self.priv = Privileges() #self.privileges = ['can add post','can delete post','can ban user']
languages = { 'tristan' : 'javascript', 'charla' : 'java', 'terrence' : 'ruby', 'andrew' : 'c++', 'taylor' : 'python', 'dreezy' : 'sql', } new_applicants = ['sayi','kim','charla','andrew','matt'] for new_applicant in sorted(new_applicants): for name,language in languages.items(): if new_applicant == name: print("Hi "+new_applicant.title()+", I see you like to code in "+language) break else: print(new_applicant.title() +" please take our poll on your favourite coding language.")
#We're creating a restaurant class with a name and cuisine type class Restaurant(): '''A restaurant with a name and cuisine.''' def __init__(self,name,cuisine): '''Initializing name and cusine''' self.name = name self.cuisine = cuisine self.number_served = 0 def describe_restaurant(self): '''Describing the name and cuisine of the restaurant''' print("Welcome to " + self.name.title() + ", we serve " + self.cuisine.title() + " cuisine.") def open_restaurant(self): print("We're now open!") def served(self): print("The number of customers served at " + self.name.title() + " is " + str(self.number_served)) def set_number_served(self, now_served): self.number_served = now_served def increment_number_served(self): self.number_served += 25
#!/bin/python3 def input_array(): array = [] while True: try: array.append(int(input())) except ValueError as er: print(er) except EOFError: return array def insertion_sort(array): """ insertion sort an array """ for j in range(1, len(array)): key = array[j] i = j - 1 while i >= 0 and array[i] > key: array[i+1] = array[i] i -= 1 array[i+1] = key return array
def aspect_ratio(val, lim): lower = [0, 1] upper = [1, 0] while True: mediant = [lower[0] + upper[0], lower[1] + upper[1]] if (val * mediant[1] > mediant[0]) : if (lim < mediant[1]) : return upper lower = mediant elif (val * mediant[1] == mediant[0]) : if (lim >= mediant[1]) : return mediant if (lower[1] < upper[1]) : return lower return upper else : if (lim < mediant[1]) : return lower upper = mediant print(aspect_ratio(1920/1080,50))
import re import sys if len(sys.argv) is not 3: print("Incorrect usage") sys.exit(0) wordMap = {} textFname = sys.argv[1] #speech.txt outputFname = sys.argv[2] with open(textFname, 'r') as inputs: for line in inputs: line = line.strip() word = re.split('[- \' ; \t "]', line) for singleWord in word: singleWord = singleWord.lower() if singleWord.endswith('.') or singleWord.endswith(':') or singleWord.endswith(','): singleWord = singleWord[:-1] if singleWord not in wordMap: wordMap[singleWord] = 0 wordMap[singleWord] += 1 del wordMap[""] with open(outputFname, "w") as outs: for singleWord in sorted(wordMap.keys()): outs.write(singleWord+" "+str(wordMap[singleWord])+"\n")
# -*- coding:utf-8 -*- # 思路:遍历二叉树的同时交换左右子树的值,直至节点为None # 测试:空子树——返回 # 使用一个栈模拟递归调用 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Mirror(self, pRoot): if pRoot is None: return pRoot.left, pRoot.right = pRoot.right, pRoot.left self.Mirror(pRoot.left) self.Mirror(pRoot.right) def Mirror(self, pRoot): if pRoot is None: return None root = pRoot stack = [] stack.append(root) while stack: cur = stack.pop() cur.left, cur.right = cur.right, cur.left if cur.left: stack.append(cur.left) if cur.right: stack.append(cur.right) return root
class Solution: def rectCover(self, number): if number <= 2: return number a, b = 1, 2 for i in range(1,number): a, b = b, a + b return a
# -*- coding:utf-8 -*- # 思路:迭代 # 测试样例:空链表 class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # 返回 RandomListNode # 迭代: def Clone(self, pHead): if not pHead: return newcode = RandomListNode(pHead.label) newcode.random = pHead.random newcode.next = self.Clone(pHead.next) return newcode # 方法二 def Clone(self, pHead): if not pHead: return # 步骤1:复制节点 dummy = pHead while dummy: copynode = RandomListNode(dummy.label) dummynext = dummy.next dummy.next = copynode copynode.next = dummynext dummy = copynode.next # 步骤2:复制随机指针 dummy = pHead while dummy: copynode = dummy.next if dummy.random: dummyrandom = dummy.random copynode.random = dummyrandom.next dummy = copynode.next # 步骤3:断开链表 dummy = pHead copyhead = dummy.next copynode = copyhead while dummy: dummy.next = copynode.next dummy = dummy.next if dummy: copynode.next = dummy.next copynode = copynode.next else: copynode.next = None return copyhead # 哈希表 class Solution: # 返回 RandomListNode def Clone(self, pHead): # write code here head = pHead p_head = None new_head = None random_dic = {} old_new_dic = {} while head: node = RandomListNode(head.label) node.random = head.random old_new_dic[id(head)] = id(node) random_dic[id(node)] = node head = head.next if new_head: new_head.next = node new_head = new_head.next else: new_head = node p_head = node new_head = p_head while new_head: if new_head.random != None: new_head.random = random_dic[old_new_dic[id(new_head.random)]] new_head = new_head.next return p_head
# 赋值——对象引用 # 例1: print('............赋值例1..............') x = 3.14 y = x print([id(item) for item in [x,y]]) # 输出x和y的地址,地址相同 print(x, y) x = 1.15 print([id(item) for item in [x,y]]) # 此时地址发生了变化,不再相同 print(x, y) # 两值也不再相等(不可变对象) # 例2 print('...........赋值例2...............') a = [1,3,4] a1 = a a2 = a a1[0] = 100 a2[1] = -1 print(a1, a2) # 各自的改变都影响到了对方 print([id(x) for x in a1]) print([id(x) for x in a2]) # 两列表地址均相同,是同一个列表(可变对象) # 浅拷贝 print('.........浅拷贝.................') m = [100,-100] b = [1, 2, 3, m] # 两种浅拷贝的方式 b1 = list(b) b2 = b.copy() print(id(b), id(b1), id(b2)) for x,y,z in zip(b, b1, b2): print(id(x), id(y), id(z)) b1[2] = -10000000 # 仅有b1发生了改变 b2[3][0] = 1 m[1] = 111 # 均发生了改变 print(b, b1, b2) # 其中元素地址相同修改任意元素均引起改变 import copy print('..........深拷贝(可变对象)................') # 可变对象 a = [[1,2],[3,4],[5,6]] b = a.copy() b1 = copy.copy(a) # 浅拷贝得到b c = copy.deepcopy(a) # 深拷贝得到c print('地址:','原始: ', id(a), '浅拷贝: ', id(b), '浅拷贝1: ', id(b1),'深拷贝: ', id(c)) # a和b不同 print('_________________子元素__________________') for x,y,z,d in zip(a,b,b1,c): # a和b的子对象相同 print('子项:','原始: ', id(x), '浅拷贝: ', id(y), '浅拷贝1: ', id(z), '深拷贝: ', id(d)) a[0][0] = 100 b[0][1] = 100 b1[1][0] = 100 c[1][1] = 100 print(a,b,b1,c) # 不可变对象 print('..........深拷贝(不可变对象)................') a = [1,2,3,4] b = a.copy() b1 = copy.copy(a) # 浅拷贝得到b c = copy.deepcopy(a) # 深拷贝得到c print('地址:','原始: ', id(a), '浅拷贝: ', id(b), '浅拷贝1: ', id(b1),'深拷贝: ', id(c)) print('_________________子元素__________________') for x,y,z,d in zip(a,b,b1,c): # 均相同 print('子项:','原始: ', id(x), '浅拷贝: ', id(y), '浅拷贝1: ', id(z), '深拷贝: ', id(d)) a[0] = 100 b[1] = 100 b1[2] = 100 c[3] = 100 print(a,b,b1,c)
# -*- coding:utf-8 -*- # 测试用例:空数组,全部未超过一般 class Solution: def MoreThanHalfNum_Solution(self, numbers): # 哈希表 if len(numbers) == 0: return 0 if len(numbers) == 1: return numbers[0] sign = len(numbers) / 2 data = {} for i in numbers: if i in data.keys(): data[i] += 1 if data[i] > sign: return i else: data[i] = 1 print data return 0 class Solution: def partition(self, numbers, left, right): if left >= right: return left key = numbers[left] while left < right: while numbers[right] >= key and left < right: right -= 1 numbers[left] = numbers[right] while numbers[left] <= key and left < right: left += 1 numbers[right] = numbers[left] numbers[left] = key return left def quickSort(self, numbers, left, right): if left < right: q = self.partition(numbers, left, right) self.quickSort(numbers, left, q) self.quickSort(numbers, q + 1, right) def MoreThanHalfNum_Solution(self, numbers): # 排序 if len(numbers) == 0: return 0 if len(numbers) == 1: return numbers[0] self.quickSort(numbers,0,len(numbers)-1) index = int(len(numbers)/2) # 向上取整:int((A+B-1)/B) = ((A-1)/B + 1) count = 0 for i in range(len(numbers)): if numbers[i] == numbers[index]: count += 1 if count > index+1: return numbers[index] else: return 0 import collections class Solution: def MoreThanHalfNum_Solution(self, numbers): # write code here tmp = collections.Counter(numbers) x = len(numbers)/2 for k, v in tmp.items(): if v > x: return k return 0 class Solution: def MoreThanHalfNum_Solution(self, numbers): if len(numbers) == 0: return 0 if len(numbers) == 1: return numbers[0] key = numbers[0] count = 1 for i in range(1, len(numbers)): if numbers[i] == key: count += 1 else: count -= 1 if count == 0: key = numbers[i] count = 1 time = 0 for i in range(len(numbers)): if key == numbers[i]: time += 1 if 2 * time > len(numbers): return key else: return 0 if __name__ == '__main__': a = [1,2,3,2,4,2,5,2,3] s = Solution() print s.MoreThanHalfNum_Solution(a)
x = input().split() n = int(input()) for i in range(n-1, len(x)): print(x[i], end=" ") for i in range(n): print(x[i], end=" ")
import time from datetime import datetime timings = [] def sort_array(arr): # Bubble sort n = len(arr) start = int(round(time.time() * 1000)) for k in range(n): for j in range(0, n - k - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] finish = int(round(time.time() * 1000)) return finish - start # Random case for i in range(1, 101): nums = [] # Read the input in with open(f"..\\Test files\\Random\\f{i}.txt") as file: for line in file: nums.append(int(line.rstrip())) file.close() # Sort the array timeElapsed = sort_array(nums) # Add timing to array of timings timings.append(timeElapsed) print("PYTHON: Time spent sorting f" + str(i) + ".txt: " + str(timeElapsed)) # Best case nums = [] # Read the input in with open(f"..\\Test files\\Best\\best.txt") as file: for line in file: nums.append(int(line.rstrip())) file.close() # Sort the array timeElapsed = sort_array(nums) # Add timing to array of timings timings.append(timeElapsed) print("PYTHON: Time spent sorting best.txt: " + str(timeElapsed)) # Worst case nums = [] # Read the input in with open(f"..\\Test files\\Worst\\worst.txt") as file: for line in file: nums.append(int(line.rstrip())) file.close() # Sort the array timeElapsed = sort_array(nums) # Add timing to array of timings timings.append(timeElapsed) print("PYTHON: Time spent sorting worst.txt: " + str(timeElapsed)) # Returns a datetime object containing the local date and time current_date_time = datetime.now() # Create the file open(f"results\\{current_date_time.month}-{current_date_time.day}-{current_date_time.year} " f"{current_date_time.hour}-{current_date_time.minute}-{current_date_time.second}.txt", "x") # Open the file and write to it results = open(f"results\\{current_date_time.month}-{current_date_time.day}-{current_date_time.year} " f"{current_date_time.hour}-{current_date_time.minute}-{current_date_time.second}.txt", "w") for time in timings: results.write(f"{time}\n") results.close()
# -*- coding: utf-8 -*- """ Created on Fri Nov 27 19:33:53 2020 @author: Lenovo-PC """ """ def transitive_closure(a): closure = set(a) while True: new_relations = set((x,w) for x,y in closure for q,w in closure ) closure_until_now = closure | new_relations if closure_until_now == closure: break closure = closure_until_now return closure print(transitive_closure([(1, 2),(1, 3),(2, 4),(4, 5)]))""" """ def transitive_closure(a): closure = [] for i in a: b=list(i) closure.append(b) a=closure for i in a: if [i[0],i[0]] not in closure: closure.append([i[0],i[0]]) if [i[1],i[1]] not in closure: closure.append([i[1],i[1]]) for j in range(len(closure)): for i in range(len(closure)): for k in range(len(closure)): if ([a[i][0],a[j][1]] and [a[j][0],a[k][1]] in closure)and not([a[i][0],a[k][1]] in closure): closure.append([a[i][0],a[k][1]]) print(closure)""" def transitive_closure(a): closure = [] for i in a: b=list(i) closure.append(b) a=closure setA=[] for i in a: if [i[0],i[0]] not in closure: closure.append([i[0],i[0]]) if i[0] not in setA: setA.append(i[0]) if [i[1],i[1]] not in closure: closure.append([i[1],i[1]]) if i[1] not in setA: setA.append(i[1]) """" for j in range(len(setA)): for i in range(len(setA)): for k in range(len(setA)): if (([setA[i],setA[j]] in closure) and( [setA[j],setA[k]] in closure))and not([setA[i],setA[k]] in closure): closure.append([setA[i],setA[k]]) """ for i in range(len(setA)): i_tuple=[] i_tuple.append(i for i in range(len(setA))) for j in i_tuple: check=[] for k in range(i) : check.append([i_tuple[k],i_tuple[k+1]]) if i_tuple[k+1]==i_tuple[-1]: break if closure.__contains__(check): closure.append([i_tuple[0],i_tuple[-1]]) closureSet=set() for i in closure: i=tuple(i) closureSet.add(i) print(closureSet) # for i in closure: # for i in closure: transitive_closure([("a","b"),("a","c"),("b","d"),("d","e")]) """ def warshall(a): assert (len(row) == len(a) for row in a) n = len(a) for k in range(n): for i in range(n): for j in range(n): a[i][j] = a[i][j] or (a[i][k] and a[k][j]) return a warshall([[1,2],[1,3],[2,4],[4,5]]) """ """ # Floyd Warshall Algorithm in python # The number of vertices nV = 2 # Algorithm implementation def floyd_warshall(G): distance = list(map(lambda i: list(map(lambda j: j, i)), G)) # Adding vertices individually for k in range(nV): for i in range(nV): for j in range(nV): distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]) print(distance) # Printing the solution def print_solution(distance): for i in range(nV): for j in range(nV): if(distance[i][j] == INF): print("INF", end=" ") else: print(distance[i][j], end=" ") print(" ") G =[[1,2],[1,3],[2,4],[4,5]] floyd_warshall(G) """
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: 1.0 @author: li @license: Apache Licence @contact: [email protected] @site: @software: PyCharm @file: threading_event.py @time: 2018/5/25 17:42 @desc: 用红绿灯来模拟事件 """ import threading from time import sleep event = threading.Event() def lighter(): count = 0 # 默认为绿灯 event.set() while True: if (count > 4) and (count < 10): # 当时间大于20,则更改为红灯 event.clear() # 清除标志,让车辆等待 print("\033[41;1mRed light, please waiting......\033[0m") elif count > 10: event.set() # 设置标志位, 改为绿灯 count = 0 else: print("\033[42;1mGreen light, please cross......\033[0m") sleep(1) count += 1 def car(name): while True: if event.is_set(): # 已设置标志,即为绿灯情况 print("The car [%s] running......" % name) sleep(1) else: print("The car [%s] see the red light, waiting for green light." % name) event.wait() print("The car [%s] see the green light on, start going......." % name) light = threading.Thread(target=lighter) car1 = threading.Thread(target=car, args=("aaa",)) light.start() car1.start()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: 1.0 @author: li @license: Apache Licence @contact: [email protected] @site: @software: PyCharm @file: python反射.py @time: 2018/5/23 23:10 """ class Dog(object): def __init__(self, name): self.name = name def eat(self, food): print("%s is eating %s" % (self.name, food)) def bulk(self): print("%s is bulking......" % self.name) d = Dog("kitty") choice = input(">>>:").strip() if hasattr(d, choice): func = getattr(d, choice) func("shit") else: setattr(d, choice, bulk) d.talk(d)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/19 22:54 # @Author : liping # @File : 二叉树高度.py # @Software: PyCharm\ def get_tree_length(input_list): tree_dict = {} tree_info = [] for node in input_list: k, v = node.split() tree_info.append([k, v]) k_list = [] for k, v in tree_info: print k, v if __name__ == '__main__': node_number = raw_input().split() user_input_node_info = [] user_input = True while user_input: user_input = raw_input() user_input_node_info.append(user_input) user_input_node_info.pop() get_tree_length(user_input_node_info)
'''Write a program that given a text file will create a new text file in which all the lines from the original file are numbered from 1 to n(where n is the number of lines in the file).''' fp=open('test.txt','r+') content=fp.readlines() fp.seek(0) count=0 for line in content: count+=1 line=str(count) + ' ' + line[0:] fp.writelines(line)
def vowel_check(ch): list1=['a','e','i','o','u'] if ch in list1: return'True' return 'False' print vowel_check(raw_input('Enter the Character'))
class proceso: instrucciones= 0 memoria=0 numero=0 def __init__(self, instrucciones, memoria, numero): self.instrucciones= instrucciones self.memoria= memoria self.numero= numero def getNumero(self): return self.numero def setNumero(self, instrucciones): self.numero= numero def getInstrucciones(self): return self.instrucciones def setInstrucciones(self, instrucciones): self.instrucciones= instrucciones def getMemoria(self): return self.memoria def setMemoria(self, memoria): self.memoria= memoria
from Adventure.game_data import World, Item, Location from Adventure.player import Player def do_menu_action(action, location, player, world): ''' (str, Location, Player, World) -> None The function will do all the options in [menu], which includes the following: look inventory score quit back Also, there is another submenu in inventory to let player to drop items in their inventory. ''' # if action is look then print the long description if action == 'look': print('\n' + location.ldescrip) # if action is inventory elif action == 'inventory': print('') # get the inventory list inventory = player.get_inventory() # if list contains something if inventory: # get the items names based on object items_names = [inventory[i].get_name() for i in range(len(inventory))] print("You got " + str(len(items_names)) + "/3 items:") # loop through each item in the list # and print their info for item in inventory: name = 'Name: ' + item.get_name() + '; ' start = 'Starts: ' + str(item.get_starting_location()) + '; ' points = 'Points: ' + str(item.get_target_points()) print(name + start + points + '\n') # ask player if he/she wants to drop print("Do you want to drop something here?") choice = '' while choice not in ['Yes', 'No']: choice = input("Please Choose Yes/No: ") # if drop then ask drop which item if choice == 'Yes': while choice not in items_names + ['back']: choice = input("Please enter the name to drop or back: ") # if player wants to drop one item if choice in items_names: # del item object from inventory list index = items_names.index(choice) item = inventory[index] del inventory[index] # if drop into the correct place # get the points and item disappear if location.num == item.get_target_location(): player.add_score(item.get_target_points()) # otherwise, no points, and player # can still pick them else: location.items.append(item) # count the movement player.count_move() # if list is empty else: print("You got nothing!") # get the score if wants to check elif action == 'score': print('\n' + str(player._score)) # quit the game if player wants elif action == 'quit': player.victory = True def main(): WORLD = World("map.txt", "locations.txt", "items.txt") PLAYER = Player(1, 1) # set starting location of player; # you may change the x, y coordinates here as appropriate # MOVE is the limited movements, the player has to # finish within this num of movements MOVE = 32 menu = ["look", "inventory", "score", "quit", "back"] # ge the total score of all the items total_score = 0 for item in WORLD.items.values(): total_score += item.target_points # to start the game while not PLAYER.victory: location = WORLD.get_location(PLAYER.x, PLAYER.y) location.refresh_points() # ENTER CODE HERE TO PRINT LOCATION DESCRIPTION # depending on whether or not it's been visited before, # print either full description (first time visit) or # brief description (every subsequent visit) # if location has been visited, print short description if location.has_visit: print("Location " + str(location.num)) print(location.bdescrip) # print long one if first visit else: print("Location " + str(location.num)) print(location.ldescrip) location.has_visit = True # print all the action that player can do print("What to do? \n") print("[menu]") # check points in curr location print("[hint]") for action in location.available_actions(): print(action) choice = input("\nEnter action: ") if (choice == "[menu]"): print("Menu Options: \n") for option in menu: print(option) choice = input("\nChoose action: ") # CALL A FUNCTION HERE TO HANDLE WHAT HAPPENS UPON USER'S CHOICE # REMEMBER: the location = w.get_location(p.x, p.y) at the top of # this loop will update the location if the # choice the user made was just a movement, so only updating # player's position is enough to change # the location to the next appropriate location # Possibilities: a helper function do_action(WORLD, PLAYER, # location, choice) # OR A method in World class WORLD.do_action(PLAYER, location, choice) # OR Check what type of action it is, then modify only player # or location accordingly # OR Method in Player class for move or updating inventory # OR Method in Location class for updating location item info, or other # location data # etc.... while choice not in menu: # if action not in the menu print("\nThat is not the verb I recognized.") choice = input("Please choose action: ") # call the helper function do_menu_action(choice, location, PLAYER, WORLD) elif choice == "[hint]": print("\nYou may get", location.target_points, "points from items in current location\n") # if action starts with Go elif choice.startswith('Go'): # get the x and y direction, x, y = choice[3:], PLAYER.x, PLAYER.y right_direction = True # determine which direction the player wants to go if direction == 'north': y -= 1 elif direction == 'south': y += 1 elif direction == 'east': x += 1 elif direction == 'west': x -= 1 else: right_direction = False # if direction is improper if not right_direction: print("\nThat is not the direction I recognized.") # move to the direction elif WORLD.get_location(x, y) is not None: PLAYER.x, PLAYER.y = x, y # count the movement PLAYER.count_move() # if direction does not exist else: print("\nOops... You can not go there.") # if action starts with Check elif choice.startswith('Check'): # get all the items name items = [location.items[i].get_name() for i in range(len(location.items))] # if choice exists if choice[6:] in items: # get the item index item = items.index(choice[6:]) # print name, points and location of that item print("\nName: " + location.items[item].get_name()) print("Target points: " + str(location.items[item].get_target_points())) print("Starts: Location " + str(location.items[item].get_starting_location())) # create a sub menu includes pick and back sub_menu = ["pick", "back"] while choice not in sub_menu: print("Menu Options: \n") # print all the action for sub menu for option in sub_menu: print(option) # ask for next action choice = input("\nPlease choose action: ") # if action is pick, them pick it into inventory # and delete it into current location if choice == 'pick' and not PLAYER.is_too_much_items(): PLAYER.add_item(location.items[item]) del location.items[item] # if item does not exist else: print("\nYou can not check it.") # count movement PLAYER.count_move() # if action is in a improper form else: print("\nThat is not the verb I recognized.") # after each action, check whether wins if PLAYER.get_score() == total_score: PLAYER.victory = True # After the game is finish, we will determine that # whether PLAYER wins or loses. # Since if we can end the game by quit or finish all # steps. We need to determine # whether the player finished in allowed steps # or he/she just quit # if movements are too large if PLAYER.get_move() > MOVE: print("\nYour move has exceed our allowed steps\nGame Over\n") # steps within the movement, then player wins elif PLAYER.get_score() == total_score: print("\nWinning\n") # if player quit, then game over else: print("\nGame Over\n") if __name__ == "__main__": main()
word = input('Enter first text: ') separator = input('Enter second text: ') if separator in word: # with arithmetics # start_index_for_cut = word.index(separator) + len(separator) # result = (word[start_index_for_cut:]).lstrip() # no arithmetics # result = word.partition(separator)[2].lstrip() # no arithmetics 2 result = (word.split(separator, 1))[-1].lstrip() else: result = word print(result)
class Aminal: #默认集成object #类属性 和实例化属性的区别在于类属性不用self,而实例化属性要self, 类属性可以被实例化属性调用,也可以被类属性调用 __eye = 2 b = 10 leg = [] def __init__(self,name,age): #实例化一个方法,在类实例化的时候被调用。 self.name = name self.age = age def run(self): print('在跑------') #调用 a = Aminal('ywy',25) #print(a.run()) #打印的时候会把return None也打印过来 #a.run() print(a.name,a.age) #调用类属性: 以下两种结果都一样。 a.__eye =10 #实例化 print(a.__eye) print(a._Aminal__eye) #双下划线的话就要这样才能访问, #print(Aminal.eye) #设置属性 a.sum = 3 #类实例化的对象创建的属性不可以被类访问,类创建的属性却可以被实例化对象访问 #print(a.sum) #实例化去修改leg(列表), 类属性的leg也会变, 但是实例化去修改eye,类属性的eye不会变 #._eye=10 #print(a.eye) #rint(a._eye) #总结,类就相当于一个模板, 实例化对象就相当于在这个模板上创建的物体, 可以具备模板的属性,也可以增加自己的属性。
import time print(time.time()) #时间戳是从1970 1月1日 零点 print(time.ctime()) #打印 Sat Sep 22 10:32:33 2018 print(time.localtime()) #打印时间元祖,time.struct_time(tm_year=2018, tm_mon=9, tm_mday=22, tm_hour=10, tm_min=34, tm_sec=16, tm_wday=5, tm_yday=265, tm_isdst=0) print(time.localtime(1)) #和上面的格式一样,不过是1970 1-1 零点 print(time.gmtime()) # 和localtime打印的一致 tmp_time = time.localtime() print(tmp_time.tm_year) #会打印2018 print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) #打印2018-09-22 10:42:39 print(time.strptime('2011-11-11 11:11:12','%Y-%m-%d %H:%M:%S')) #datetime from datetime import datetime,time,date,timedelta print(datetime.now()) #打印2018-09-22 10:50:03.044910 tmp_date = datetime(2017,11,11,11,11,11) print(tmp_date) print(date.today()) print()
print('###########################################################') print(' ') print(' Author: Mufaro Simbisayi ') print(' ') print('###########################################################') import os import csv import requests import statistics from purchase import Purchase def get_and_save_csv(): file_name = os.path.abspath("data.csv") if os.path.exists(file_name): return file_name apiUrl = "https://raw.githubusercontent.com/mikeckennedy/python-jumpstart-course-demos/master/apps/09_real_estate_analyzer/you_try/SacramentoRealEstateTransactions2008.csv" chunk_size = 100 response = requests.get( apiUrl ) with open(file_name, 'wb') as fout: for chunk in response.iter_content(chunk_size): fout.write(chunk) return file_name def load_data(file_name): with open(file_name, 'r') as fin: reader = csv.DictReader(fin) return [Purchase(row) for row in reader] def compute_data(purchases): purchases.sort(key = lambda p: p.price) #most expensive house print("The most expensive house: {}-bed, {}-bath house for ${} in {}".format( purchases[-1].beds, purchases[-1].baths, purchases[-1].price, purchases[-1].city )) #least expensive house print("The least expensive house: {}-bed, {}-bath house for ${} in {}".format( purchases[0].beds, purchases[0].baths, purchases[0].price, purchases[0].city )) #average price house print("The average price for a house is ${}".format(round(statistics.mean(( purchase.price for purchase in purchases ))))) #average price of 2 bedroom house print("The average price for a 2 bedroom house is ${}".format(round(statistics.mean(( purchase.price for purchase in purchases if purchase.beds == 2 ))))) def main(): file_name = get_and_save_csv() purchases = load_data(file_name) compute_data(purchases) if __name__ == "__main__": main()
# 高阶函数英文叫Higher-order function # Python内建了map()和reduce()函数 # map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6]) print(list(r)) # map()传入的第一个参数是f,即函数对象本身。由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list L = [] for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: L.append(f(n)) print(L) # map() 会根据提供的函数对指定序列做映射。 # map(function, iterable, ...) # Python 3.x 返回迭代器。 # print(map()) 返回迭代器地址 # 一般和list一起用 才能输出 # reduce() 函数会对参数序列中元素进行累积。先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。 # reduce(function, iterable[, initializer]) from functools import reduce def add(x, y): return x + y count = reduce(add, [1, 2, 3, 4, 5]) print(count) # 计算列表和:1+2+3+4+5 #filter()函数用于过滤序列 def not_empty(s): return s and s.strip() print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))) # 排序算法 sorted print(sorted([36, 5, -12, 9, -21])) print(sorted([36, 5, -12, 9, -21], key=abs)) print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)) L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_name(t): return t[0] L1 = sorted(L, key=by_name) print(L1) def by_score(t): return t[1] L2 = sorted(L, key=by_score,reverse=True) print(L2) #返回函数 #匿名函数 匿名函数有个好处,因为函数没有名字,不必担心函数名冲突 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果 print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) #装饰器 在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator) #简单总结functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单 import functools int2 = functools.partial(int, base=2) print(int2('1000000'))
# File: grid.py # Author: Nathan Robertson # Purpose: Encapsulate a series of points which form a 2D grid. Is a sparse grid so only impasses are stored. class Grid: def __init__(self, impasses, min_point, max_point): self.impasses = impasses self.max_point = max_point self.min_point = min_point def manhattan_neighbors(self, point): """ :param point: A tuple (x, y) :return: Valid neighbors in point that are (up, left, right, and down) from point """ raw_neighbors = [self.up(point), self.down(point), self.left(point), self.right(point)] # Source: https://stackoverflow.com/questions/16096754/remove-none-value-from-a-list-without-removing-the-0-value return list(filter(None.__ne__, raw_neighbors)) def neighbors(self, point): """ Return adjacent points of a point. Excludes out-of-bounds points and impasses """ raw_neighbors = self.manhattan_neighbors(point) + \ [self.lower_right(point), self.lower_left(point), self.upper_right(point), self.upper_left(point)] return list(filter(None.__ne__, raw_neighbors)) def up(self, point): x, y = point return self.make_point((x, y + 1)) def upper_left(self, point): x, y = point return self.make_point((x - 1, y + 1)) def upper_right(self, point): x, y = point return self.make_point((x + 1, y + 1)) def down(self, point): x, y = point return self.make_point((x, y - 1)) def lower_left(self, point): x, y = point return self.make_point((x - 1, y - 1)) def lower_right(self, point): x, y = point return self.make_point((x + 1, y - 1)) def left(self, point): x, y = point return self.make_point((x - 1, y)) def right(self, point): x, y = point return self.make_point((x + 1, y)) def make_point(self, new_point): if self.in_grid_range(new_point) and not self.is_impasse(new_point): return new_point return None def is_impasse(self, point): if point in self.impasses: return True return False def in_grid_range(self, point): return self.min_point <= point < self.max_point
import numpy as np def mundaneMath(first_num, last_num): sum=0 for i in range(first_num, last_num+1): ''' The latter number is last_num+1 bc range function doesn't count the last number. ''' if i%2 == 0: sum = sum + i else: continue print(sum) return sum if __name__ == "__main__": mundaneMath(1, 100)
x=20 y=30 if x<y: print('x is less than 20') #elif a=20 b=20 if a<b: print('a is less than b') elif a==b: print('a is equal to b')
story="my n.\nI live in nepal.\nI am\t a student" print(story) ### a=['1','6','66','6','manoj','ram','rajan'] a[4]='ramesh' print(a) #### name=[1,6,7,3,5,8,9,22,44,5] name.remove(6) print(name) #tuple t=[1,2,3,4,5] t1=(1) print(t1) # m1= int(input("Enter your marks 1:")) m2= int(input("Enter your marks 2:")) m3= int(input("Enter your marks 3:")) m4= int(input("Enter your marks 4:")) mymarks= [m1, m2, m3, m4] mymarks.sort() print(mymarks)
def main(): print("Hello world!") num = int(input("Please enter a number between 1 and 25: ")) while num < 1 or num > 25: num = int(input("Invalid number entered, must be between 1 and 25. Enter again: ")) for n in range(1, num+1): print(f"Number {n} cubed: {n**3}") print(f"Number {n} to the fifth: {n**5}") print("------FACTORIAL TESTING-----") print(fact(8)) comprhensions() def fact(n): if n <= 1: return 1 return n * fact(n-1) # A function that demonstrates list comprehensions def comprhensions(): numbers = [1, 5, 6, 73, 3, 32, 16, 7, 55, 21, 75] altered_numbers = [number ** 2 for number in numbers] print(altered_numbers) new_numbers = [number * 2 for number in numbers if number < 20] print(new_numbers) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # python 2 # program napisal Miro - 4.4.2017 - naloga 8.2 # FIZZBUZZ print "" print "IGRA FIZZBUZZ" print "" izbor = raw_input("Vnesi vrednost med 1 in 100 : ") # vnesemo vrednost med 1 in 100 if int(izbor) < 1 or int(izbor) > 100: print "Števila ni med 1 in 100 !!!" pass elif int(izbor) > 0 or int(izbor) < 101: krog = 1 while krog < (int(izbor)+1): if krog%3==0 and krog%5==0: print "FIZZBUZZ" krog+=1 elif krog%3==0: print "FIZZ" krog+=1 elif krog%5==0: print "BUZZ" krog+=1 elif krog%3!=0 and krog%5!=0: print str(krog) krog += 1
import dices class skill(object): """ Contains a skill. calling is done by skill(bases,value,known=True) bases::string : attributes it depends on. (either ABCx2 or ABC+XYZ format) value: value of the skill. If left empty, standard is calculated. study(learned) --> learned is added to the value of the skill. learn --> teaches the charcter the learned skills """ def __init__(self, bases, value=None, encaffect=True): super(skill, self).__init__() self.encaffect = encaffect self.value = value self.base = ["", ""] self.base[0] = bases[:3] if bases[3] == "x": self.base[1] = self.base[0] else: self.base[1] = bases[-3:] def basevalue(self, inp): self.value = 0 self.value = inp # TODO decide how to do this def study(self, learned): self.value += learned # now the skills as a class is generated # the next step is creating all the skills standardlist = { "Athletics": skill("STR+DEX"), "Boating": skill("STR+CON"), "Brawn": skill("STR+SIZ"), "Conceal": skill("DEX+POW"), "Customs": skill("INTx2", encaffect=False), "Dance": skill("DEX+CHA"), "Deceit": skill("INT+CHA", encaffect=False), "Drive": skill("DEX+POW"), "Endurance": skill("CONx2", encaffect=False), "Evade": skill("DEXx2"), "FirstAid": skill("INT+DEX"), "Influence": skill("CHAx2", encaffect=False), "Insight": skill("INT+POW", encaffect=False), "Locale": skill("INTx2", encaffect=False), "Perception": skill("INT+POW", encaffect=False), "Ride": skill("DEX+POW"), "Sing": skill("CHA+POW", encaffect=False), "Stealth": skill("DEX+INT"), "Swim": skill("STR+CON"), "Unarmed": skill("STR+DEX"), "Willpower": skill("POWx2"), } # standard is used to store the standard skills used in the Mythras franchise professionallist = { "Acrobatics": skill("STR+ DEX"), "Art": skill("POW+CHA"), "Bureaucracy": skill("INTx2"), "Commerce": skill("INT+CHA"), "Courtesy": skill("INT+CHA"), "Craft": skill("DEX+INT"), "Culture": skill("INTx2", encaffect=False), "Devotion": skill("POW+CHA"), "Disguise": skill("INT+CHA"), "Engineering": skill("INTx2"), "Exhort": skill("INT+CHA"), "Folk Magic": skill("POW +CHA"), "Gambling": skill("INT+POW"), "Healing": skill("INT+POW"), "Language": skill("INT+CHA", encaffect=False), "Literacy": skill("INTx2"), "Lockpicking": skill("DEXx2"), "Lore": skill("INTx2"), "Mechanisms": skill("DEX+INT"), "Musicianship": skill("DEX+CHA"), "Navigation": skill("INT+POW"), "Oratory": skill("POW+CHA"), "Seamanship": skill("INT+CON"), "Seduction": skill("INT+CHA"), "Sleight": skill("DEX+CHA"), "Streetwise": skill("POW+CHA"), "Survival": skill("CON+POW"), "Teach": skill("INT+CHA"), "Track": skill("INT+CON"), } # professionallist is used to store the professional skills in Mythras # "Name" : [skill::skill] class knownskills(dict): """ A dictionary with a few special powers """ def __init__(self, *args): super(knownskills, self).__init__() global standardlist global professionallist self.update(standardlist) # creating the Standard skills for element in args: # one shold be capable off adding, this is with the arguments try: self[element] = professionallist[element] except KeyError as hiba: msg = str(hiba) + \ "is not a recognized professional skill in Mythras" print msg print "It was not added to the list of skills" except: print "Something went wrong" print element + " was not added to the list of skills" # this handled the input errors def learn(self, *args): global professionallist for element in args: if element in self: print element, "is already in the learned skills list", \ ", it was not added to protect the value" else: try: self[element] = professionallist[element] except KeyError as hiba: msg = str(hiba) + \ "is not a recognized professional skill in Mythras" print msg print "It was not added to the list of skills" except: print "Something went wrong" print element + " was not added to the list of skills" # this handled the input errors self[element] = professionallist[element] # test = knownskills("Disguise") # test.learn("Lore") # print test["Swim"].base # print test["Disguise"].base # print test["Lore"].base
__author__ = "Lucas Blom" __email__ = "[email protected]" __status__ = "beta" ''' ## UPDATE ME This program gathers movie data from a csv file, creates a pandas data frame with it, and a tkinter application to show all data or iterate through rows individually ''' import tkinter as tk import pandas as pd # define variables and constants frame_data = None df2 = None table = None current_index = None # used for data load into app DATA_FILE = './data/IMDB-Movie-Data.csv' # used in movie options menu UI/UX and on_select function SELECT_ALL_TEXT = 'ALL THE MOVIES' SELECTION_PARAMETER = 'Title' # --- functions --- def get_data(file_name): data = pd.read_csv(file_name, index_col=0) return data # a function we call to display pandas data def show_data(): global table global df2 # destroy old frame with table if table: table.destroy() # create new frame with table table = tk.Frame(frame_data) table.grid(row=1, column=1) # fill frame with table row, column = df2.shape for r in range(row): for c in range(column): e1 = tk.Entry(table) e1.insert(1, df2.iloc[r, c]) e1.grid(row=r, column=c, padx=2, pady=2) e1.config(state='disabled') # function executed when we click the dropdown menu def on_select(val): global df2 global current_index val = selected.get() if val == SELECT_ALL_TEXT: df2 = df next_button.grid_forget() else: df2 = df[df[SELECTION_PARAMETER] == val] # find index current_index = 0 for ind in df.index: if df[SELECTION_PARAMETER][ind] == val: current_index = ind print('current_index', current_index) # put next button on the canvas next_button.grid(row=1, column=0) # DRY show_data() def next_data(): global current_index global df2 if current_index < len(df)-1: current_index = current_index+1 df2 = df.iloc[[current_index]] show_data() # --- main --- # here is the dataframe df = get_data(DATA_FILE) # here we start the GUI root = tk.Tk() root.title("Movie List") root.geometry("1000x800") # prepare list of values for drop down menu # values is a list of unique movie titles and corresponding tuples from csv file values = [SELECT_ALL_TEXT] + list(df[SELECTION_PARAMETER].unique()) # input variable has to be a StringVar, special var for Tkinter to grab user input selected = tk.StringVar(value="Movie Choices") # create drop down menu # we have a function we execute on button click -- on_select from drop down menu options = tk.OptionMenu(root, selected, *values, command=on_select) options.grid(row=0, column=0, padx=15, pady=15) # frame for table and button "Next Data" frame_data = tk.Frame(root) frame_data.grid(row=1, column=0, padx=15, pady=15) # button "Next Data" - inside "frame_data" - without showing it next_button = tk.Button(frame_data, text="Next Data", command=next_data) # table with data - inside "frame_data" - without showing it table = tk.Frame(frame_data) table.grid(row=0, column=0) exit_button = tk.Button(root, text="EXIT", command=root.destroy) exit_button.grid(row=3, column=0, padx=15, pady=15) root.mainloop()
import datetime import calendar class PayrollManagementSystem: def calculate_payroll(self, employees): print("Payroll Management System") print("=========================") for employee in employees: print(f"Employee #:{employee.id}\nEmployee Name :{employee.name}") print(f"Amount :{employee.calculate_payroll()}") print("----------------------------------------") class PartTimePolicy: def __init__(self, total_hours, rate_per_hour): self.total_hours = total_hours self.rate_per_hour = rate_per_hour def calculate_payroll(self): return self.total_hours * self.rate_per_hour class SalaryPolicy: def __init__(self, rate_per_day): self.rate_per_day = rate_per_day def calculate_payroll(self): today = datetime.datetime.now() totalDays = calendar.monthrange(today.year, today.month)[1] return self.rate_per_day * totalDays class CommissionPolicy(SalaryPolicy): def __init__(self, rate_per_day, commission): super().__init__(rate_per_day) self.commission = commission def calculate_payroll(self): salary = super().calculate_payroll() return salary + self.commission
#6 a = int(input('Сколько километров пробежал спортсмен в первый день? ')) b = int(input('Сколько километров пробежал спортсмен в последний день? ')) c = 1 while a < b: a*= 1.1 c+= 1 print("Спортсмен достиг результата в", b, "км на", c, "день")
def computepay(hour, rate): if hour <=40: return hour*rate return 40*rate + (hour-rate)*1.5*rate h = int(input("Enter hours: ")) r = float(input("Enter rate: ")) print("Pay:",computepay(h,r))
numbers = [] while True: try: number = input("Enter a number: ") if number == "done": break number = int(number) numbers.append(number) except ValueError: print("Invalid input") print(sum(numbers), len(numbers), sum(numbers)/len(numbers))
#https://leetcode.com/problems/symmetric-tree/ class Solution: def isSymmetric(self, root: TreeNode) -> bool: return self.Aux(root, root) def Aux(self, t1, t2): if t1 is None and t2 is None: return True elif t1 is None or t2 is None: return False else: p = self.Aux(t1.left, t2.right) q = self.Aux(t1.right, t2.left) return (t1.val == t2.val) and p and q
a = 10 b = 9 # Addition of numbers print(a + b) # Subtraction of numbers print(a - b) # multiplication of numbers print(a * b) # Division operator print( a / b) # floor division print(a // b) # Modulo of both number mod = a % b # Power p = a ** b print(p)
''' A dummy script to test CI ''' import math def circle_area(radius): ''' Returns the area of a circle given its radius circle_area: Float -> Float ''' if radius < 0: raise ValueError("The radius cannot be negative.") if type(radius) not in [int, float]: # pylint: disable=C0123 raise TypeError("The radius must be a non-negative real number.") return math.pi * (radius ** 2)
def pos_neg(a,b,neg): if not neg: if a*b < 0: return True else: return False else: if a < 0 and b < 0: return True else: return False print pos_neg(-1,2,False) print pos_neg(1,-2,False) print pos_neg(-1,-2,True)
# -*- coding: utf-8 -*- """ Created on Sat Jul 24 16:14:24 2021 @author: P Akash """ # importing libraries import pygame import random from enum import Enum from collections import namedtuple import sys # initializing pygame modules pygame.init() # initialize game font font = pygame.font.Font('arial.ttf', 25) # lightweight namedtuple object can be accessible through name or indices Point = namedtuple("Point", ["x", "y"]) # a block size for coordinate reference in game window BLOCK_SIZE = 20 # clock framerate parameters, fps rate SPEED = 10 # RGB colors WHITE = (255, 255, 255) RED = (200, 0, 0) BLUE1 = (0, 0, 255) # color for outer square of snake body BLUE2 = (0, 100, 255) # color for inner square of snake body BLACK = (0, 0, 0) class Direction(Enum): RIGHT = 1 LEFT = 2 UP = 3 DOWN = 4 class SnakeGame(): def __init__(self, window_width = 640, window_height = 480): # initialization of game window properties self.width = window_width self.height = window_height # initialize game window # pygame.display.set_mode(size = (width, height)) : Initialize a window or screen for display self.display = pygame.display.set_mode((self.width, self.height)) pygame.display.set_caption("Snake Game") # pygame.time.Clock() : create an object to help track time. self.clock = pygame.time.Clock() # intial game state # snake direction self.direction = Direction.RIGHT # snake head at the middle of the game window self.head = Point(self.width//2, self.height//2) # snake body # we are going to initial snake of only 2 BLOCK_SIZE self.snake = [self.head, Point(self.head.x - BLOCK_SIZE, self.head.y)] # initialize score self.score = 0 # initialize food and place in game window self.food = None self.place_food() def place_food(self): x = random.randint(0, (self.width - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE y = random.randint(0, (self.height - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE self.food = Point(x, y) if self.food in self.snake: self.place_food() def play_step(self): # 1. Collect user input for event in pygame.event.get(): # pygame.QUIT is equal to when a person clicks on the close button if event.type == pygame.QUIT: pygame.quit() sys.exit() # pygame.KEYDOWN is to check is any key is pressed down if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.direction = Direction.LEFT elif event.key == pygame.K_RIGHT: self.direction = Direction.RIGHT elif event.key == pygame.K_UP: self.direction = Direction.UP elif event.key == pygame.K_DOWN: self.direction = Direction.DOWN # 2. Snake movement # updating snake head based on the user input direction from above self.snake_move(self.direction) self.snake.insert(0, self.head) # 3. check if game over game_over = False if self._is_collision(): game_over = True return game_over, self.score # 4. check if snake has eaten the food # if eaten, place new food or else just move if self.head == self.food: self.score += 1 self.place_food() else: self.snake.pop() # 4. update UI and clock self.update_ui() self.clock.tick(SPEED) return game_over, self.score def snake_move(self, direction): # current snake head position in the game window x = self.head.x y = self.head.y # update snake head coordinates based on input direction if direction == Direction.RIGHT: x += BLOCK_SIZE elif direction == Direction.LEFT: x -= BLOCK_SIZE elif direction == Direction.DOWN: y += BLOCK_SIZE elif direction == Direction.UP: y -= BLOCK_SIZE # update the new head position based on above calculation self.head = Point(x, y) def _is_collision(self): # hits boundary if self.head.x > self.width - BLOCK_SIZE or self.head.x < 0 or self.head.y > self.height - BLOCK_SIZE or self.head.y < 0: print("-- Game over due to boundary collision") return True # hits itself if self.head in self.snake[1:]: print("-- Game over due to self collision") return True return False def update_ui(self): # fill the game display with black color self.display.fill(BLACK) # draws snake on screen for pt in self.snake: pygame.draw.rect(self.display, BLUE1, pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE)) pygame.draw.rect(self.display, BLUE2, pygame.Rect(pt.x + 4, pt.y + 4, 12, 12)) # draws food on the screen pygame.draw.rect(self.display, RED, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE)) # writing score on screen # font.render(text, antialias, color, background = None) # antialias is a boolean argumant, if true the character will have smooth edges text = font.render("Score: " + str(self.score), True, WHITE) # blit or overlap the surface on the canvas at the given position # for more information on blit, please go through the below link: # https://stackoverflow.com/questions/37800894/what-is-the-surface-blit-function-in-pygame-what-does-it-do-how-does-it-work # Inshort we are trying to draw whatever is there in text object in the (0,0) position self.display.blit(text, [0,0]) # updates the components of the entire display pygame.display.flip() if __name__ == "__main__": # SnakeGame class object game = SnakeGame() while True: game_over, score = game.play_step() if game_over == True: break print("Current score : ", score) pygame.quit()
def index_search(i, c): try: return matrix[i].index(c) except: None def word_search_in_matrix(matrix, word, array): w_len = len(word) r_row = True r_column = True for i in array: if i[1] + w_len - 1 <= len(matrix[i[0]]): for x in range(w_len): if word[x] != matrix[i[0]][x]: r_row = False for j in array: if j[1] + w_len - 1 <= len(matrix[j[0]]): for y in range(w_len): if word[y] != matrix[y][j[1]]: r_column = False return r_row or r_column def word_search(matrix, word): w_list = list(word) w_len = len(word) l = [] for i in range(len(matrix)): a = index_search(i, w_list[0]) if a is not None: l.append([i, a]) if word_search_in_matrix(matrix, word, l): return True return False if __name__ == '__main__': matrix = [ ['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S']] print(word_search(matrix, 'FOAM')) # True
class Solution: def intersection(self, nums1, nums2): return list(set(nums1) & set(nums2)) if __name__ == '__main__': print(Solution().intersection([4, 9, 5], [9, 4, 9, 8, 4])) # [9, 4]
class Solution: def reverseWords(self, str): reverse_words = [] for w in str.split(): reverse_words.append(w[::-1]) return " ".join(reverse_words) if __name__ == '__main__': print(Solution().reverseWords("The cat in the hat")) # ehT tac ni eht tah
class Card(object): suits = { 'c': 'clubs', 'd': 'diamonds', 'h': 'hearts', 's': 'spades' } values = { 1: 'Ace', 10: 'Jack', 11: 'Queen', 12: 'King' } def __init__(self, value,suit): self.value = value self.suit = suit def get_value(self): return str(self.value) if self.value not in self.values else self.values[self.value] def get_suit(self): return self.suit def __str__(self): return self.get_value() + ' of ' + str(self.suit) if __name__ == '__main__': my_card = Card(1, "diamonds") print(my_card)
def maximum_product_of_three(lst): len_lst = len(lst) product = [] for i in range(len_lst-2): for j in range(i+1, len_lst-1): for k in range(j+1, len_lst): product.append(lst[i] * lst[j] * lst[k]) return max(product) if __name__ == '__main__': print(maximum_product_of_three([-4, -4, 2, 8])) # 128
d = true while d == true: a = input("enter number 1") b = input("enter what you want to do:,*,/,+ or -") c = input("enter second number") if d = true while d == true: a = int(input("enter number 1")) b = input("enter what you want to do:,*,/,+ or -") c = int(input("enter second number")) if b == "/": a/b
## (1) Import packages import numpy as np import pandas as pd import sys ## (2) Read training data train = pd.read_csv(sys.argv[1], header = None) # Delete column 0 train = train.drop(train.columns[[0]],1) ## (3) Create training feature DataFrame and outcome Series # Split features and outcome y = pd.Series(train.ix[:, train.shape[1]]) del train[58] # Simple 1st-order linear regression ## Normalize train_norm = (train - train.mean()) / train.std() # train_norm = train ## add constant 1 train_norm.insert(loc = 0, column = 0, value = 1) ## (4) Define the sigmoid function def sigmoid(z): return [1.0/(1.0+np.exp(-zi)) for zi in z] ## (5) Define the loss function for logistic regression def computeLoss(X, y, coef): return -sum(np.log(sigmoid(y.multiply(np.dot(X, coef))))) ## (6) Define the loss function for logistic regression with regularization def computeLoss_reg(X, y, coef, lb): return -sum(np.log(sigmoid(y.multiply(np.dot(X, coef))))) + lb * 0.5 * sum(coef[1:]) ## (7) Gradient descent #Set parameters iteration = 200 eta = 0.003 alpha = eta # fixed learning rate loss_history = list() # Initialize coefficients to be all 0 coef = pd.Series(np.repeat(0.0, train_norm.shape[1], axis=0)) # Main loop of gradient descent for ite in range(iteration): loss_history.append(computeLoss(train_norm, y, coef)) temp = list() for i in range(train_norm.shape[1]): temp.append(coef[i] - alpha * sum((sigmoid(np.dot(train_norm, coef)) - y).multiply(train_norm.ix[:,i]))) for i in range(train_norm.shape[1]): coef[i] = temp[i] coef_save = pd.DataFrame(coef) coef_save = pd.concat([coef_save.reset_index(drop = True), train.mean(), train.std()], axis=1) coef_save.to_csv(sys.argv[2], index_label = ['id'], header = ['coef', 'train_mean', 'train_std'])
import Stack import re def postfix(example): t_list = re.split('([^0-9])', example) stack = Stack.Stack() for t in t_list: if t == '' or t == ' ': continue elif t == '+': sum = stack.pop() + stack.pop() stack.puch(sum) elif t == '*': result = stack.pop() * stack.pop() stack.push(result) elif t == '/': result = stack.pop() / stack.pop() stack.push(result) else: stack.push(int(t)) return stack.pop()
class Stack: def __init__(self): self.stack = [] def size(self): return len(self.stack) def pop(self): if len(self.stack) != 0: return self.stack.pop() else: return None def push(self, value): self.stack.append(value) def peek(self): if len(self.stack) != 0: return self.stack[-1] else: return None def is_empty(self): # метод проверки на пустоту return self.stack == [] ''' st = 4. Stack() print(st.is_empty()) st.push(1) st.push('2') st.push(3.14) print(st.size()) print(st.is_empty()) print(st.peek()) while st.size() > 0: st.peek() st.pop() st.pop() print(st.size()) '''
class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class OrderedList: def __init__(self, asc): self.head = None self.tail = None self.ascending = asc def compare(self, v1, v2): # метод сравнения if v1 < v2: return -1 elif v1 == v2: return 0 else: return 1 # -1 если v1 < v2 # 0 если v1 == v2 # +1 если v1 > v2 def add(self, value): new_node = Node(value) if self.head is None: # если список пуст self.head = new_node self.tail = new_node return else: # если в списке есть узлы if self.ascending: # для сортировки по возрастанию # если значение нового узла меньше чем значение головного if self.compare(new_node.value, self.head.value) != 1: new_node.next = self.head self.head.prev = new_node self.head = new_node # если значение нового узла больше чем значение хвостового elif self.compare(new_node.value, self.tail.value) != -1: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node else: # для средних узлов node = self.tail # пока значение нового узла не меньше очередного (перебор от хвоста к голове) while self.compare(new_node.value, node.value) != 1: node = node.prev new_node.prev = node new_node.next = node.next node.next.prev = new_node node.next = new_node return else: # при сортировке по убыванию # если значение нового узла боьше или равно значению головного узла if self.compare(new_node.value, self.head.value) != -1: new_node.next = self.head self.head.prev = new_node self.head = new_node return # если значение нового узла меньше или равно значению хвостового узла elif self.compare(new_node.value, self.tail.value) != 1: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node return else: # для средних узлов node = self.head # пока значение нового узла не меньше очередного (перебор от головы к хвосту) while self.compare(new_node.value, node.value) != -1: node = node.next new_node.prev = node new_node.next = node.next node.next.prev = new_node node.next = new_node return def find(self, val): if self.head is None: return else: node = self.head if self.ascending: while self.compare(node.value, val) != 1: if val > self.tail.value: return elif val == node.value: return node else: if node.next is not None: node = node.next else: while self.compare(node.value, val) != -1: if val < self.tail.value: return elif val == node.value: return node else: if node.next is not None: node = node.next def delete(self, val): if self.head is not None: # если список не пустой if val == self.head.value: # если значение найдено в головном узле if self.head.next is None: # если список состоит из одного узла self.head = None self.tail = None return else: self.head.next.prev = None # если узел в списке не один self.head = self.head.next return elif val == self.tail.value: # если значение найдено в хвостовом узле self.tail.prev.next = None self.tail = self.tail.prev return else: if self.ascending: # если список сортирован по возрастанию if val > self.tail.value or val < self.head.value: return node = self.tail # перебор от хвоста к голове while self.compare(val, node.value) != 1: node = node.prev if val == node.value: node.prev.next = node.next node.next.prev = node.prev return else: # если список сортирован по убыванию if val < self.tail.value or val > self.head.value: return node = self.head # перебор узлов от головы до хвоста while self.compare(val, node.value) != 1: node = node.next if val == node.value: node.prev.next = node.next node.next.prev = node.prev return def clean(self, asc): # очистка списка self.head = None self.tail = None # self.__init__() self.ascending = asc def len(self): if self.head is not None: ln = 0 node = self.head while node is not None: ln += 1 node = node.next return ln else: return 0 def get_all(self): r = [] node = self.head while node != None: r.append(node) node = node.next return r class OrderedStringList(OrderedList): def __init__(self, asc): self.head = None self.tail = None self.ascending = asc def compare(self, v1, v2): if v1.strip() == v2.strip(): return 0 elif v1.strip() > v2.strip(): return 1 else: return -1 # -1 если v1 < v2 # 0 если v1 == v2 # +1 если v1 > v2
# модель построения Графов class Vertex: def __init__(self, val): self.Value = val def __repr__(self): '''Метод упрощенного отображения объектов класса Vertex''' return 'V_{}'.format(self.Value) class SimpleGraph: def __init__(self, size): self.max_vertex = size self.m_adjacency = [[0] * size for _ in range(size)] self.vertex = [None] * size # спаисок вершин def AddVertex(self, value): '''Метод добавления новой вершины с значением Value в свободное место self.vertex''' # ваш код добавления новой вершины # с значением value # в свободное место массива vertex for ind in range(self.max_vertex): if self.vertex[ind] is None: self.vertex[ind] = Vertex(value) break # здесь и далее, параметры v -- индекс вершины # в списке vertex def RemoveVertex(self, v): '''Метод удаления вершины со всеми её ребрами''' # ваш код удаления вершины со всеми её рёбрами if self.is_vertex(v): for i in range(self.max_vertex): # Удаление ребер self.RemoveEdge(i, v) self.vertex[v] = None # удаление вершины pass def IsEdge(self, v1, v2): ''' Метод проверки наличия ребра между вершинами v1 и v2 return True если ребро есть, иначе return False ''' # True если есть ребро между вершинами v1 и v2: if self.is_vertex(v1) and self.is_vertex(v2): return self.m_adjacency[v1][v2] == 1 else: return False def AddEdge(self, v1, v2): '''Метод добавления ребра между вершинами v1 и v2''' # добавление ребра между вершинами v1 и v2 if self.is_vertex(v1) and self.is_vertex(v2): self.m_adjacency[v1][v2] = 1 self.m_adjacency[v2][v1] = 1 return True else: return False def RemoveEdge(self, v1, v2): '''Метод удаления ребра между вершинами v1 и v2''' # удаление ребра между вершинами v1 и v2 if self.is_vertex(v1) and self.is_vertex(v2): self.m_adjacency[v1][v2] = 0 self.m_adjacency[v2][v1] = 0 def is_vertex(self, v): '''Метод проверки вершины в списке vertex''' return v <= self.max_vertex - 1 and self.vertex[v]
import unittest import Linked_List2 class LinkedList2Test(unittest.TestCase): def test_norm2(self): # тесты на создание и заполнение списка link_2 = Linked_List2.LinkedList2() # создание пустого списка self.assertIsNone(link_2.head) # проверка на содержание None в пустом списке link_2.add_in_tail(Linked_List2.Node2(0)) # добавление узла в конец списка self.assertEqual(link_2.head.value, 0) # проверка на равенство значения головного узла self.assertEqual(link_2.tail.value, 0) # проверка на равенство значения хвостового узла def test_find_first(self): # тест метода поиска узла по значению link_2 = Linked_List2.LinkedList2() # создание пустого списка self.assertIsNone(link_2.find_first(0)) # проверка поиска в пустом списке link_2.add_in_tail(Linked_List2.Node2(1)) # заполнение списка link_2.add_in_tail(Linked_List2.Node2(2)) # заполнение списка link_2.add_in_tail(Linked_List2.Node2(-3)) # заполнение списка self.assertEqual(link_2.find_first(2).value, 2) # проверка поиска по значению в пустом списке self.assertEqual(link_2.find_first(-3).value, -3) # проверка поиска отрицательного значения self.assertIsNone(link_2.find_first(0)) # проверка поиска, если в списке нет искомого значения def test_del_first_0(self): # тест удаления узла по значению №1 link_2 = Linked_List2.LinkedList2() # создание пустого списка self.assertIsNone(link_2.del_first(1)) # проверка удаления узла в пустом списке link_2.add_in_tail(Linked_List2.Node2(1)) # заполнение списка link_2.add_in_tail(Linked_List2.Node2(-2)) # заполнение списка link_2.add_in_tail(Linked_List2.Node2(3)) # заполнение списка link_2.del_first(1) # Удаление первого узла self.assertEqual(link_2.head.value, (-2)) # тест соответствия значения первого узла def test_del_first_1(self): # тест удаления узла по значению №2 link_2 = Linked_List2.LinkedList2() # создание пустого списка link_2.add_in_tail(Linked_List2.Node2(1)) # заполнение списка link_2.add_in_tail(Linked_List2.Node2(-2)) # заполнение списка link_2.add_in_tail(Linked_List2.Node2(3)) # заполнение списка link_2.del_first(-2) # удаление среднего узла self.assertEqual(link_2.head.next.value, 3) # тест соответствия значения среднего узла def test_del_first_2(self): # тест удаления узла по значению №3 link_2 = Linked_List2.LinkedList2() # создание пустого списка link_2.add_in_tail(Linked_List2.Node2(1)) # заполнение списка link_2.add_in_tail(Linked_List2.Node2(-2)) # заполнение списка link_2.add_in_tail(Linked_List2.Node2(3)) # заполнение списка link_2.del_first(3) # удаление хвостового узда self.assertEqual(link_2.tail.value, (-2)) # проверка равенства значения хвостового узла def test_insert_next_0(self): # тест вставки нового узла после заданного link_2 = Linked_List2.LinkedList2() # создание пустого списка n_n = Linked_List2.Node2(111) # создание узла link_2.insert_next(None, n_n) # добавление нового узла после заданного self.assertEqual(link_2.head.value, 111) # проверка добавления нового узла после заданного в пустом списке def test_insert_next_1(self): # тест вставки нового узла после заданного link_2 = Linked_List2.LinkedList2() # создание пустого списка n1 = Linked_List2.Node2(1) # создание узла n2 = Linked_List2.Node2(2) # создание узла n3 = Linked_List2.Node2(3) # создание узла n_n = Linked_List2.Node2(111) # создание узла link_2.add_in_tail(n1) # заполнение списка link_2.add_in_tail(n2) # заполнение списка link_2.add_in_tail(n3) # заполнение списка link_2.insert_next(n2, n_n) # добавление нового узла после заданного self.assertEqual(link_2.head.next.next.value, 111) # проверка значения узла, после добавления нового self.assertEqual(link_2.head.next.next.next.value, 3) # проверка значения узла, после добавления нового def test_insert_next_2(self): # тест вставки нового узла после последнего узла link_2 = Linked_List2.LinkedList2() # создание пустого списка n1 = Linked_List2.Node2(1) # создание узла n2 = Linked_List2.Node2(2) # создание узла n_n = Linked_List2.Node2(111) # создание узла link_2.add_in_tail(n1) # заполнение списка link_2.add_in_tail(n2) # заполнение списка link_2.insert_next(n2, n_n) # добавление нового узла после заданного self.assertEqual(link_2.head.next.next.value, 111) # проверка значения узла, после добавления нового self.assertEqual(link_2.tail.value, 111) # проверка значения хвостового узла def test_insert_first(self): link_2 = Linked_List2.LinkedList2() # создание пустого списка link_2.insert_first(11) # добавление в узла в начало пустого списка self.assertEqual(link_2.head.value, 11) # проверка соответствия значения головного узла link_2.add_in_tail(Linked_List2.Node2(100)) # добавление узла в конец списка link_2.insert_first(0) # добавление узла в начало списка self.assertEqual(link_2.head.value, 0) # проверка соответствия значения головного узла self.assertEqual(link_2.tail.value, 100) # проверка соответствия значения хвостового узла if __name__ == "__main__": unittest.main()
#7. Faça um Programa que leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido n1=int(input("Digite um numero de 1 a 7: ")) if n1 == 1: print("1 - Domingo") elif n1 == 2: print("2 - segunda") elif n1 == 3: print("3 - terça") elif n1 == 4: print("4 - quarta") elif n1 == 5: print("5 - quinta") elif n1 == 6: print("6 - sexta") elif n1 == 7: print("7 - sabado") else: print("Valor invalido")
a = [] print(a) a = [1] print(a) a = [1,2,3] print(a) a = [1,"1"] print(a) a.append(4) a.append(5) a.append(6) print(a) a.insert(1,"2") print(a) a = [6,7,8] b= [5,4,3] b.extend(a) print(b) print(a[0:3]) print(a[:3]) print(a[3:]) print(a[:]) a[0] = 7 print(a) ai = [1,2,3] print(ai) # Iterating over list for ele in ai: print(ele) print("same as above") for i in range(len(ai)): print(ai[i]) bi = [4,5,6] for elem_a, elem_b in zip(ai,bi): print("%d,%d"%(elem_a,elem_b)) print(ai) del ai[0] print(ai) ai = [1,2,3,4] # print(ai.pop()) print(ai) print(ai.index(3)) # print(ai.index(5)) try: print(ai.index(5)) except: print("element not in list") # Sorting ai = [4,3,2,1] print(ai) ai.sort() print(ai) def f(x): return x**2 # b = [1,7,4,3,9] # a =[f(x) for x in b] # print(a) a = [f(x) for x in range(10)] print(a) a = [1,2,3,4] print(a) a.reverse() print(a) a = [1,4,3,4] print(a.count(4)) class example: def __init__(self): self.value = 10 a = [] for _ in range(10): new_examaple= example() a.append(new_examaple) print(a)
""" Size of player's hand and the amount of cards on table """ HAND_SIZE = 3 TABLE_SIZE = 4 # suits and values declaration suits = ["CUPS", "COINS", "SWORDS", "CLUBS"] values = {"ACE":1, "TWO":2, "THREE":3, "FOUR":4, \ "FIVE":5, "SIX":6, "SEVEN":7, "FANTE":8, \ "HORSE":9, "KING":10} # String constants HAND_ERROR = "Hand not dealt." ENTER = "Press 's' to start the game!\n" WELCOME = "Welcome to Scopa!\n" NAME = "Please enter your name: " PLAYERS_TURN = "Player's turn: " DEALERS_TURN = "Dealer's turn: " WIN = "You win!" LOSE = "Dealer wins and you lose!" TIE = "Tie Game! What are the odds?" TABLE = "Here's the table \n" PLAYER_INPUT = "Press 't' to make a trick, 'd' to put card on table, press s to try and Scopa!\n" PLAYER_PUT_DOWN = "Select index of card in hand to place on table " PLAYER_TRICK = "You made a trick!" DEALER_TRICK = "Dealer made a trick!" TRICK_SELECTION_ERROR = "This is not a valid trick, please select again " OUT_OF_BOUNDS = "Your selection was out of bounds, please try again\n" D_SCOPA = "Dealer made a scopa! " P_SCOPA = "Player made a scopa! " KNIFE = "THATS IT! You took out the knife from under the table!\n You autmatically win!"
# -*- coding:utf-8 -*- # author : Keekuun """ 斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入, 故又称为“兔子数列”,指的是这样一个数列:1、1、2、3、5、8、13、21、34... """ def fibo1(max): n, a, b = 0, 0, 1 while n < max: yield b # print(b) a, b = b, a + b n += 1 for i in fibo1(9): print(i) print(fibo1(9)) print('*' * 10) def fibo2(n): if n == 1: return [1] elif n == 2: return [1, 1] else: return fibo2(n - 1) + [fibo2(n - 1)[-1] + fibo2(n - 1)[-2]] print(fibo2(9))
#!/usr/bin/python # -*- coding: UTF-8 -*- # author:FunC_ZKK """ 题目:一个标准的科学实验是,抛球并且看它能够弹跳多高。一旦球的“弹跳性”已经确定了, 这个比率值就会给出弹跳性的指数。例如,如果球从10米高落下弹跳到6米高,这个索引就是 0.6,并且球在一次弹跳之后总的运动距离是16米。如果球继续弹跳,两次弹跳后的距离将会 是10米+6米+6米+3.6米=25.6米。注意,每次后续的弹跳运动的距离,都是到地板的距离加上 这个距离的0.6倍,这个0.6倍就是球反弹回来的距离。编一个程序,让用户输入球的一个初始 高度以及允许球持续弹跳的次数。输出球的运动的总距离。 """ #import pdb #pdb.set_trace() def bounce_height_recursion(h, n, rate=0.6): '''递归实现''' sum = h+0.6*h if n == 1: return sum else: sum += sum * 0.6 return sum if __name__ == '__main__': h = int(input('Please enter the height of the ball:\n')) n = int(input('Please enter the bounce times of the ball:\n')) print(bounce_height_recursion(h, n))
# -*- coding:utf-8 -*- # author : Keekuun # 列表生成式,list l1 = [i for i in range(10)] # 或者 l2 = list(range(10)) print(l1, l2) # type(l) list # 打印:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] l3 = [x * x for x in range(1, 11) if x % 2 == 0] print(l3) l4 = [m + n for m in 'ABC' for n in 'XYZ'] print(l4) # 生成器,generator:惰性,可迭代 g = (i for i in range(10)) print(g) # 打印:<generator object <genexpr> at 0x0000027EC76F5F10> for i in g: print(i)
#!/usr/bin/env python3 # # Reads the file 'guardian-puzzlewords-withsees.txt' and removes unwanted # material from it, combines clues when multiple clues for a word are # present, and writes the result to 'guardian-puzzlewords.txt'. # # Words can have one or more clues: # # ACCREDITATION # Granting of recognition (13) # # ACCREDITED # Certified officially (10) # # ACCRUE # Accumulate (6) # Gather (6) # Grow by addition (6) # import codecs import collections import re resee = re.compile(".*See \d") words = collections.defaultdict(set) currentword = "" for line in codecs.open("guardian-puzzlewords-withsees.txt", "rb", "utf8"): line = line.rstrip() if not line: continue if resee.match(line): # Skip clues like "See 1 down" continue if line[0] == " ": clue = line.strip() words[currentword].add(clue) else: currentword = line.strip() with codecs.open("guardian-puzzlewords.txt", "wb", "utf8") as f: for word in sorted(words): f.write(word + "\n") for clue in sorted(words[word]): f.write(" " + clue + "\n") f.write("\n")
from itertools import groupby import re pattern1 = r'([456]\d{3}(-?\d{4}){3}$|\d{16}' card_num = '5644-5567-7878-1121' #def repetition(card_num): # return max(len(list(g)) for _, g in groupby(card_num) if re.match( pattern1, card_num): print("hyphen and string length are correct") num = card_num.replace('-', '') if max(len(list(g)) for _, g in groupby(num)) >= 4: print('more than 4 repetiotions... number Invalid') else: print('Valid') else: print("Invalid. Pattern matching failed")
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ n1 = 0 n2 = 0 d = [0 for _ in range(10)] for n in input_list: d[n] += 1 i = 9 even = 0 cdt = True while cdt: if d[i] > 0: if even == 0: n1 = (n1 * 10) + i even = 1 else: n2 = (n2 * 10) + i even = 0 d[i] -= 1 if d[i] == 0: i -= 1 if i == 0 & d[i] == 0: cdt = False return n1, n2 def test_function(test_case): output = rearrange_digits(test_case[0]) solution = test_case[1] if sum(output) == sum(solution): print("Pass") else: print("Fail") # Provided example test_function([[1, 2, 3, 4, 5], [542, 31]]) test_case = [[4, 6, 2, 5, 9, 8], [964, 852]] test_function(test_case) # Test case 1: Test for empty input # Expected output: empty input test_case = [[], []] test_function(test_case) # Test case 2: Test for 1 input # Expected output: [1] test_case = [[1], [1]] test_function(test_case) # Test case 3: Test for odd number of same digits as input # Expected output: [11, 11] test_case = [[1,1,1], [11, 1]] test_function(test_case)
# rand() function is from random module and random module is also in numpy. # This rand() function is used to create the array of elements near to zero. print() from numpy import random a=random.rand(5) print(a) print() ## 2-D array a1=random.rand(2,3) print(a1) print() ## 3-D array a2=random.rand(1,3,3) print(a2)
# This randint() function is from the random module. This random module is also in numpy. # randint() function create array of random numbers. print() from numpy import random a=random.randint(1,20,10) print(a) print() a1=random.randint(1,10,4) print(a1)
# Linspace function is used to create 1-D evenly spaced array. print() from numpy import linspace,ndim,size,shape a=linspace(1,100,num=10) print(a) print(a.ndim) print(a.size) print(a.shape) print() a1=linspace(1,100,num=20) print(a1) print(a1.ndim) print(a1.size) print(a1.shape) print() a2=linspace(100,200,num=8) print(a2)
# Create categorical graphical analysis - The create_categorical_charts function isolates all the object data type variables in a given data # frame, and generates a bar plot on the count statistics by the target variable def create_categorical_charts(df, target_variable, vars_to_ignore): df = df.select_dtypes(include=['object']).copy() # Remove variables from the dataframe try: df.drop(vars_to_ignore, inplace=True, axis=1) except NameError: print('') except KeyError as e: import sys sys.exit(e) # Prepare the list of columns to be analyzed, and remove the target variable from the list categList = df.columns.to_list() categList.remove(target_variable) # Set the grid structure if len(categList)%3 != 0: row = (len(categList)//3) + 1 plot=1 else: row = (len(categList)//3) plot=1 plt.figure(figsize = (15,10)) # Iterate through all the plots for all categorical variables for i in categList: plt.subplot(row,3,plot) ax=sns.countplot(data=df, x=i, hue=target_variable, linewidth=2, palette=sns.color_palette("tab10")) for p in ax.patches: height = p.get_height() ax.text(p.get_x()+p.get_width()/2., height + 3, '{:1.0f}'.format(height/float(len(df)) * 100)+'%', ha="center") plot = plot + 1 plt.show() # Create numerical graphical analysis - The create_numerical_charts function isolates all the int and float data type variables in a given # data frame, and generates a box plot or histogram by aggregation at the target variable def create_numerical_charts(df, target_variable, plot_type='box', vars_to_ignore=None): target_variable = df[target_variable].to_numpy() no_colors = np.unique(target_variable).size df = df.select_dtypes(include=['float64','int64']).copy() # Remove variables from the dataframe try: while vars_to_ignore != None: df.drop(vars_to_ignore, inplace=True, axis=1) except NameError: print('') except KeyError as e: import sys sys.exit(e) # Prepare the list of columns to be analyzed, and remove the target variable from the list numList = df.columns.to_list() # Set the grid structure if len(numList)%3 != 0: row = (len(numList)//3) + 1 plot=1 else: row = (len(numList)//3) plot=1 plt.figure(figsize = (15,10)) # Iterate through all the plots for all categorical variables for i in numList: plt.subplot(row,3,plot) if plot_type == 'box': sns.boxplot(data=df, x=target_variable, y=i, palette=sns.color_palette("muted")) elif plot_type == 'hist': sns.histplot(data=df, hue=target_variable, palette=sns.color_palette("muted", n_colors=no_colors), x=i) else: print('Plot type can either be box or hist') plot = plot + 1 plt.show()
import coin # The definition of hypothesis F is "p is 0.5" # The following code computes L(E|F) evidence = 140, 110 Likelihood_fair = coin.Likelihood(evidence, 0.5) # If the definition of hypothesis B is "p is either 0.4 or 0.6 with # equal probability, find L(E|B). Likelihood_biased = coin.Likelihood(evidence, 0.4) / 2 + coin.Likelihood(evidence, 0.2) / 2 print Likelihood_fair print Likelihood_biased
#1 scores=[80,75,55] total=0 for score in scores: total+=score average=total/3 print(average) #2 13%2 #3 pin="881120-1068234" yymmdd=pin[:6] num=pin[7:] print(yymmdd) num(pin) #4 pin="881120-1068234" print(pin[7]) #5 a="a:b:c:d" b=a.replace(":","#") print(b) #6 a=[1,3,5,4,2] a.sort() a.reverse() print(a) #7 a=['Life','is','too','short'] result=a.join() print(result) #8 a=(1,2,3) a1=(4,) a+a1 #9 ##3-- 리스트는 dict의 key값으로 쓸 수 없음 #10 a={'A':90,'B':80,'C':70} result=a.pop('B') print(a) print(result) #11 a=[1,1,1,2,2,3,3,3,4,4,5] aSet=set(a) b=list(aSet) print(b) #12 [1,4,3] ##같은 리스트 객체를 가리키고 있기 때문
class InvalidCredentials(Exception): def __init__(self,msg="Invalid Credentials"): Exception.__init__(self,msg) try: names=[ { "name": "Venkat" "password": "849" }, { "name": "Rakesh" "password": "656" } ] a=input("Enter username") b=input("Enter password") userPresent = False for i in names: if a == i["name"] and b == i["password"]: print("Welcome", i["name"], sep=" ") userPresent = True break if not userPresent: raise InvalidCredentials("Invalid Credentials") except InvalidCredentials as e: print(e)
# Python 3 program for Bresenham’s Line Generation # Assumptions : # 1) Line is drawn from left to right. # 2) x1 < x2 and y1 < y2 # 3) Slope of the line is between 0 and 1. # We draw a line from lower left to upper # right. # function for line generation def bresenhamAbajoArriba(x1, y1, x2, y2): m_new = 2 * (y2 - y1) slope_error_new = m_new - (x2 - x1) y = y1 for x in range(x1, x2 + 1): print(slope_error_new) print("(", x, ",", y, ")") # Add slope to increment angle formed slope_error_new = slope_error_new + m_new print("+new "+str(slope_error_new)) # Slope error reached limit, time to # increment y and update slope error. if (slope_error_new >= 0): y = y + 1 slope_error_new = slope_error_new - 2 * (x2 - x1) print("en if "+str(slope_error_new)) def bresenhamXAbajoArriba(x1, y1, x2, y2): m_new = 2 * (x2 - x1) slope_error_new = m_new - (y2 - y1) x = x1 for y in range(y1, y2 + 1): print(slope_error_new) print("(", x, ",", y, ")") # Add slope to increment angle formed slope_error_new = slope_error_new + m_new print("+new "+str(slope_error_new)) # Slope error reached limit, time to # increment y and update slope error. if (slope_error_new >= 0): x = x + 1 slope_error_new = slope_error_new - 2 * (y2 - y1) print("en if "+str(slope_error_new)) def bresenhamArribaAbajo(x1, y1, x2, y2): m_new = 2 * (y1 - y2) slope_error_new = m_new - (x2 - x1) y = y1 for x in range(x1, x2 + 1): print("(", x, ",", y, ")") # Add slope to increment angle formed slope_error_new = slope_error_new + m_new # Slope error reached limit, time to # increment y and update slope error. if ( 0 > slope_error_new): print("no") else: y = y - 1 slope_error_new = slope_error_new - 2 * (x2 - x1) x1 = 0 y1 = 0 x2 = 4 y2 = 2 bresenhamAbajoArriba(x1, y1, x2, y2) x1 = 0 y1 = 0 x2 = 2 y2 = 4 bresenhamXAbajoArriba(x1, y1, x2, y2) #bresenhamArribaAbajo(x1, y2, x2, y1) # This code is contributed by ash264 def drawCircle(xc, yc, x, y): print(xc + x, yc + y) print(xc - x, yc + y) print(xc + x, yc - y) print(xc - x, yc - y) print(xc + y, yc + x) print(xc - y, yc + x) print(xc + y, yc - x) print(xc - y, yc - x) def circleBres(xc, yc, r): x = 0 y = r d = 3 - 2 * r drawCircle(xc, yc, x, y) while (y >= x): x += 1 if (d > 0): y -= 1 d = d + 4 * (x - y) + 10 else: d = d + 4 * x + 6 drawCircle(xc, yc, x, y) xc = 2 yc = 2 r = 2 #circleBres(xc, yc, r)
import random class Game: def __init__(self, decks_count, reset_on_dealer_blackjack): self.deck = Deck(decks_count) self.reset_on_dealer_blackjack = reset_on_dealer_blackjack def start_round(self): self.deck.reset() game_round = Round(self.deck) return game_round def run_managed_game(self, round_callback): game_round = self.start_round() if self.reset_on_dealer_blackjack: while game_round.dealer_has_blackjack(): game_round = self.start_round() while game_round.is_player_alive(): action = round_callback(game_round.player_sum, game_round.dealer_sum) if action == 'HIT': game_round.draw_for_player() elif action == 'STAND': return game_round.resolve_round() else: raise ValueError(f"Invalid player action: {action}") return 'LOSE' class Deck: def __init__(self, decks_count=1): self.deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] * 4 * decks_count # 4 suits. All 10-valued cards are identical in behavior self.drawn_cards_indices = set() self.reset() def reset(self): self.drawn_cards_indices = set() # Draw a card by picking a random one until we pick one we've not chosen before. # Since we pick such a low fraction of the deck each game, this is much faster than shuffling or removing from the deck # There's a time and place for functional programming; this isn't it. def draw(self): if len(self.drawn_cards_indices) >= len(self.deck): raise RuntimeError("Tried to pick a card from an empty deck") while True: drawn_card_index = random.randrange(len(self.deck)) if drawn_card_index not in self.drawn_cards_indices: self.drawn_cards_indices.add(drawn_card_index) return self.deck[drawn_card_index] class Round: def __init__(self, deck): self.deck = deck self.dealer_cards_visible = [self.deck.draw()] self.dealer_cards_hidden = [self.deck.draw()] self.player_cards = [self.deck.draw(), self.deck.draw()] def sum_cards(self, cards): current_sum = sum([c for c in cards if c != 1]) aces = [11 for c in cards if c == 1] # Treat aces as 11. If the score busts 21, downgrade aces from 11 to 1 one at a time while current_sum + sum(aces) > 21 and 11 in aces: aces[aces.index(11)] = 1 return current_sum + sum(aces) @property def dealer_sum(self): return self.sum_cards(self.dealer_cards_visible) @property def player_sum(self): return self.sum_cards(self.player_cards) def dealer_has_blackjack(self): # Dealer blackjack requires a visible 10 and hidden Ace, or vice-versa if len(self.dealer_cards_hidden) == 1 and len(self.dealer_cards_visible) == 1 and ( (self.dealer_cards_visible[0] == 1 and self.dealer_cards_hidden[0] == 10) or (self.dealer_cards_visible[0] == 10 and self.dealer_cards_hidden[0] == 1)): return True else: return False def is_player_alive(self): return self.player_sum <= 21 and self.dealer_has_blackjack() is False def draw_for_player(self): self.player_cards.append(self.deck.draw()) def start_round(self): self.dealer_cards_visible.append(self.deck.draw()) self.dealer_cards_hidden.append(self.deck.draw()) self.player_cards.extend([self.deck.draw(), self.deck.draw()]) def resolve_round(self): self.dealer_cards_visible.extend(self.dealer_cards_hidden) self.dealer_cards_hidden = [] # Dealer had first turn blackjack. Instant loss. if self.dealer_sum == 21: return 'LOSE' if self.player_sum > 21: return 'LOSE' while self.dealer_sum < 17: self.dealer_cards_visible.append(self.deck.draw()) if self.dealer_sum > 21: return 'WIN' if self.dealer_sum == self.player_sum: return 'DRAW' elif self.player_sum > self.dealer_sum: return 'WIN' else: return 'LOSE'
#!/usr/bin/env python3 """ Threads that waste CPU cycles """ import os import threading # a simple function that wastes CPU cycles forever def cpu_waster(): while True: pass # display information about this process print('\n Process ID: ', os.getpid()) print('Thread Count: ', threading.active_count()) for thread in threading.enumerate(): print(thread) print('\nStarting 12 CPU Wasters...') for i in range(12): threading.Thread(target=cpu_waster).start() # display information about this process print('\n Process ID: ', os.getpid()) print('Thread Count: ', threading.active_count()) for thread in threading.enumerate(): print(thread)
# first_name = input("What is your first name?") # last_name = input("What is your last name?") # print(last_name, first_name) # first_name = input('What is your first name?') # last_name = input('What is your last name?') # # # def reverse_order(first_name, last_name): # print("%s %s" % (last_name, first_name)) # """Warm up #2 # Write a function called "happy_bday" # that "sings" (prints) # the Happy Birthday Song # # It must take on parameter called "name" # """ # # # def happy_bday(name): # print("Happy birthday to you,") # print("Happy birthday to you,") # print("Happy birthday dear %s" % name) # print("Happy birthday dear " + name) works # print("Happy birthday to you!") """ Write a function called add_py that takes one parameter called "name" and prints out name.py example: add_py("I_ate_some") == "I_ate_some.py" """ def add_py(name): print("%s.py" % name) # Solution 1 # print(name + ".py") # Solution 2 """Write a function called "add" which takes three parameters and prints the sum of the numbers """ def add(num1, num2, num3): print(num1 + num2 + num3) # add(90, 900, 9000) def repeat(string): print(string) print(string) print(string) # repeat("string") for x in range(3): print("string") # prints string three times def date(month, day, year): print(str(month) + "/" + str(day) + "/" + str(year)) date(12, 8, 17)
# print("Hello World") # # # # # print() # Creates a blank line # # # # print("See if you can figure this out") # # # # print(10 % 3) # # # # # # # # Variables # # # # car_name = "Lamborguieapig" # # # # car_type = "Beast" # # # # car_cylinders = 8 # # # # car_mpg = 9000.1 # # # # # # # # # Inline Printing # # # # print("My car is the %s." % car_name) # # # # print("My car is the %s. It is a %s" % (car_name, car_type)) # # # # Taking input # # # # name = input("What is your name? ") # # # # print("Hello %s." % name) # # # # # print(name) # # # # # # # # age = input("How old are you? ") # # # # print("Oh, so you're %s years old." % age) # # # # # print(age) # # # # # # # Change to the file # # # # # # # # # <<<<<<< HEAD # # # def print_hw(): # # # print("Hello World") # # # print_hw() # # # # # # def say_hi(name): # name is a "parameter # # # print("Hello %s." % name) # # # print("I hope you have a fantastic day.") # # # say_hi("John") # # # def birthday(age): # # # age += 1 # age = age + 1 # # # print(age) # # # # # # # # # say_hi("John") # # # print("John is 15. Next year:") # # # birthday(15) # # # # # # age = input("How old are you? ") # # # print("Oh, so you're %s years old." % age) # # # # print(age) # # # # # # Press Ctrl-A and Ctrl-/ # # # to comment old code # # # # # # # def f(x): # # # return x**5 + 4 * x **4 - 17*x**2 + 4 # # # # # # # # # print(f(3)) # # # print(f(3) + f(5)) # # # # # # # If statements # # # # # # # # # def grade_calc(percentage): # # # if percentage >= 90: # # # return "A" # # # elif percentage >= 80: # Else if # # # return "B" # # # elif percentage >= 70: # # # return "C" # # # elif percentage >= 60: # # # return "D" # # # else: # # # return "F" # # # # # Loops # # # # # # # for num in range(5): # # # print(num + 1) # # a = 1 # # while a < 10: # # print(a) # # a += 1 # # # # # response = "" # # # while response != "Hello": # # # response = input("Say \"Hello\"") # # # # print("Hello \nWorld") # \n means newline # # # # # # import random # imports should be at the top # # print(random.randint(0, 6)) # # # Comparisons # print(1 == 1) # Two equal signs to compare # print(1 != 2) # One is not equal to 2 # print(not False) # This prints True # print(1 == 1 and 4 <= 5) # print(1 < 0 or 5 > 1) # # # Recasting # c = '1' # print(c == 1) # False - C is a string, 1 is an int # print(int(c) == 1) # True - Compares two ints # print(c == str(1)) # True - Compares two strings # Lists the_count = [1, 2, 3, 4, 5] characters = ["Graves", "Dory", "Boots", "Dora", "Shrek", "Obi-wan", "Carl"] print(characters[0]) print(characters[4]) print(len(characters)) # Gives you the length of the list # Going through lists for char in characters: print(char) for num in the_count: print(num ** 2) len(characters) range(3) # Makes a list of the numbers from 0 to 2 range(len(characters)) # Makes a list of ALL INDICES for num in range(len(characters)): char = characters[num] print("The character at index %d is %s" % (num, char)) str1 = "Hello World!" listOne = list(str1) print(listOne) listOne[11] = '.' print(listOne) newStr = "".join(listOne) print(newStr) print(listOne[-2]) # Goes backwards # adding stuff to a list characters.append("Ironman/Batman/whomever you want") print(characters) characters.append("Pepe") # removing things from a list characters.remove("Carl") print(characters) characters.pop(6) print(characters) # the string class import string # has to be at the top print(string.ascii_letters) print(string.ascii_lowercase) print(string.digits) print(string.punctuation) # start hangman off with the player already having guessed all the punctuations and space strTwo = 'ThIs sEntENcE iS uNuSuAL' lowercase = strTwo.lower() print(lowercase) # Dictionaries - Make up a key: value pair dictionary = {'name': 'Lance', 'age': 18, 'height': 6 * 12 + 2} # Accessing from a dictionary print(dictionary['name']) print(dictionary['age']) print(dictionary['height']) # Adding to a dictionary dictionary["eye color"] = "blue" dictionary["toilet paper"] = True print(dictionary) large_dictionary = { "California": "CA", "Washington": "WA", "Illinois": "IL" } print(large_dictionary['Washington']) larger_dictionary = { "California": [ 'Fresno', 'Sacremento', 'Los Angeles' ], "Washington": [ "Seattle", "Tacoma", "Olympia", "Spokane" ], "Illinois": [ "Chicago", "Naperville", "Peoria" ] } print(larger_dictionary['Illinois']) print(larger_dictionary['Illinois'][0]) print(larger_dictionary['Washington'][3]) largest_dictionary = { "CA": { 'NAME': "California", 'POPULATION': 39250000, 'BORDER ST': [ 'Oregon', 'Nevada', "Arizona" ] }, "MI": { "NAME": "Michigan", "POPULATION": 99280000, "BORDER ST": [ 'Wisconsin', 'Ohio', 'Indiana' ] }, "FL": { "NAME": "Florida", "POPULATION": 20610000, "BORDER ST": [ 'Georgia', 'Alabama' ] } } print(largest_dictionary["MI"]["BORDER ST"][1]) print(largest_dictionary["FL"]["NAME"]) print('░░░░░░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░░░░░' '\n░░░░░░█░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░█░░░░░' '\n░░░░░░█░█░░░░░░░░▄▀▀▄░▀░█░█▄▀▀▄░' '\n█▀▀█▄░█░█░░▀░░░░░█░░░▀▄▄█▄▀░░░█░' '\n▀▄▄░▀██░█▄░▀░░░▄▄▀░░░░░░░░░░░░▀▄' '\n░░▀█▄▄█░█░░░░▄░░█░░░▄█░░░▄░▄█░░█' '\n░░░░░▀█░▀▄▀░░░░░█░██░▄░░▄░░▄░███' '\n░░░░░▄█▄░░▀▀▀▀▀▀▀▀▄░░▀▀▀▀▀▀▀░▄▀░' '\n░░░░█░░▄█▀█▀▀█▀▀▀▀▀▀█▀▀█▀█▀▀█░░░' '\n░░░░▀▀▀▀░░▀▀▀░░░░░░░░▀▀▀░░▀▀░░░░')
class Graphics(): size=0 m_list=[] def __init__(self): print("What SIZE of broad you want to choose :- \n") self.size=int(input("Example:- (For 3x3 , Enter 3)\n")) for i in range(self.size): print(" ---"*(self.size)) print("| "*(self.size+1)) if(i == self.size-1): print(" ---"*(self.size)) def setboard(self): for i in range(0,self.size*self.size): boundlist =[ i*self.size-1 for i in range(1,self.size+1)] if i not in boundlist: self.m_list.insert(i,"| ") else: self.m_list.insert(i,"| |") for i in range(0,self.size): print("") print(" ---"*(self.size)) for j in range(0,self.size): print(self.m_list[i*self.size+j],end="") if(i == self.size-1): print("") print(" ---"*(self.size)) def showboard(self): for i in range(0,self.size): print("") print(" ---"*(self.size)) for j in range(0,self.size): print(self.m_list[i*self.size+j],end="") if(i == self.size-1): print("") print(" ---"*(self.size)) class Back_End(): def user_input(self,graphics,sign): s_coord =input("Enter the coordinate , where you want enter:-\n") coord = s_coord.split(",") x_coord =int(coord[0])-1 y_coord =int(coord[1])-1 s_fetch = graphics.m_list[x_coord*graphics.size+y_coord] test =[*s_fetch] if(not test[2]=="X"or test[2]=="O"): test[2]=sign graphics.m_list[x_coord*graphics.size+y_coord]="".join(test) else: self.user_input(graphics,sign) def check(self,graphics): #leftdigonal checklist=[ i*(graphics.size+1) for i in range(0,graphics.size)] self.sub_check(graphics,checklist) #rightdigonal checklist = [ (graphics.size-1)*(i+1) for i in range (0, graphics.size)] self.sub_check(graphics,checklist) #up-horizentally checklist =[ i for i in range(0,graphics.size)] self.sub_check(graphics,checklist) #left-veritcally checklist = [ i*graphics.size for i in range(0 ,graphics.size) ] self.sub_check(graphics,checklist) #down-horizentally checklist = [ (graphics.size*(graphics.size-1))+i for i in range(0 ,graphics.size) ] self.sub_check(graphics,checklist) #right-vertically checklist=[ (graphics.size*(i+1))-1 for i in range(0 , graphics.size)] self.sub_check(graphics,checklist) #bettwen-vertically if(graphics.size>2): for x in range(1 ,graphics.size-1): checklist = [(graphics.size*i)+x for i in range(0,graphics.size)] self.sub_check(graphics,checklist) #bettween horizentally if(graphics.size>2): for x in range(1 ,graphics.size-1): checklist = [((graphics.size*x)+i) for i in range(0,graphics.size)] print(checklist) self.sub_check(graphics,checklist) def sub_check(self,graphics,checklist): x_gamepoint=0 o_gamepoint=0 for i in checklist: string=graphics.m_list[i] if string[2] =="X": x_gamepoint= x_gamepoint+1 elif string[2] =="O": o_gamepoint= o_gamepoint+1 else: break if(x_gamepoint==graphics.size): print("X has won the game") graphics.showboard() exit() if(o_gamepoint==graphics.size): print("O has won the game") graphics.showboard() exit() class Game(): graphics = Graphics() graphics.setboard() backend = Back_End() for i in range(0,graphics.size*graphics.size): if(i%2==0): print("PLAYER X:-") backend.user_input(graphics,"X") backend.check(graphics) graphics.showboard() else: print("PLAYER O:-") backend.user_input(graphics,"O") backend.check(graphics) graphics.showboard()
"""Dylan Valmadre""" def main(): min_length = 10 valid_pw = False get_password(min_length, valid_pw) def get_password(min_length, valid_pw): while not valid_pw: password = input(str("Enter password: ")) if len(password) < min_length: valid_pw = False print("Password must contain at least 10 digits.") else: valid_pw = True display_asterisk(password) def display_asterisk(string): for char in string: print("*", end=" ") main()
list1=[None]*5 i=0 while i<5: a=input("Enter the list items %d:"%i) list1[i]=a i+=1 print "List1 is ",list1