text
stringlengths
37
1.41M
age = input("What is your current age?") age = int(age) years_remaining = 90 - age days = years_remaining * 365 weeks = years_remaining * 52 months = years_remaining * 12 print(f"You have {years_remaining} years,{days} days, {weeks} weeks, and {months} months left.")
''' This file takes two input files `flicknamn.csv` and `pojknamn.csv` as per the `example_input.csv` format, joins the content and spits out a single normalized file with all the names that have names that can be writen with only katana ''' import csv import jaconv import re ''' normalize an integer string with or without comma to integer ''' def normalize_int(count: str): if ',' in count: return int(count.replace(',', '')) return int(count) ''' takes a swedish name and simplifies patterns in a way that they can be translated to katakana ''' def simplify_swedish_name(name: str): simplified = name.lower().replace('nn', 'n') return simplified ''' checks if a name contains any small characters that makes the name harder to write ''' def is_simple_katakana(name: str): return re.match(u".*[ァィッェゥåäö].*", name) is None ''' return dictionary of all names with katakana ''' def get_names(filename: str, gender: str): with open(filename, newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: name = row['name'] name_simplified = simplify_swedish_name(row['name']) count = normalize_int(row['count']) katakana = jaconv.hira2kata(jaconv.alphabet2kana(name_simplified)) if is_simple_katakana(katakana): yield { 'name': name, 'katakana': katakana, 'count': count, 'gender': gender } all_names = list(get_names('flicknamn.csv', 'girl')) + list(get_names('pojknamn.csv', 'boy')) with open('names.csv', 'w', newline='') as output: writer = csv.writer(output) writer.writerow(['gender','name', 'katakana', 'count']) for row in all_names: writer.writerow([row['gender'], row['name'], row['katakana'], row['count']])
import sys def printSecondHighestAndHighestFunction(listOne): secondLargest = -sys.maxsize-1 largest = -sys.maxsize-1 for value in listOne: if value > secondLargest and value < largest: secondLargest = value if value > largest: secondLargest = largest largest = value print("Second largest number {}".format(secondLargest)) print("Largest number {}".format(largest)) printSecondHighestAndHighestFunction([10, 20, 4, 45, 99, 46, 98, 2, 102, -5])
def get_input(): with open("input.txt") as f: s = f.read().strip() lines = s.split("\n") print(f"num lines = {len(lines)}") total_length = sum(len(line) for line in lines) print(f"avg line length = {round(total_length/len(lines),2)}") return s def grid(s, split = None): if split is None: split = lambda line : list(line) s = s.split("\n") n = len(s) g = [split(line) for line in s] m = len(g[0]) return n, m, g
with open("input.txt") as f: s = f.read().strip().split("\n") # + => + # * => - class P1: def __init__(self, v): self.v = v def __add__(self, o): return P1(self.v + o.v) def __sub__(self, o): return P1(self.v * o.v) ans = 0 for l in s: l = "".join("P1("+x+")" if x.isdigit() else x for x in l) l = l.replace("*","-") ans += eval(l).v print(ans) # + => * # * => + class P2: def __init__(self, v): self.v = v def __add__(self, o): return P2(self.v * o.v) def __mul__(self, o): return P2(self.v + o.v) ans = 0 for l in s: l = "".join("P2("+x+")" if x.isdigit() else x for x in l) l = l.replace("*","?").replace("+","*").replace("?","+") ans += eval(l).v print(ans)
# -*- coding: utf-8 -*- """ Created on Fri Jul 27 15:32:26 2018 @author: shaileeg """ class Animal: def __init__(self, name ="No name"): self._name = name def getName(self): return self._name lion = Animal() monkey = Animal("Tarzan") print(lion.getName()) print(monkey.getName())
import random # Gets the value of a coordinate on the grid. def l(r, c, b): return b[r][c] # Places a bomb in a random location. def placeBomb(b): r = random.randint(0, row-1) c = random.randint(0, column-1) # Checks if there's a bomb in the randomly generated location. If not, it puts one there. If there is, it requests a new location to try. currentRow = b[r] if not currentRow[c] == '*': currentRow[c] = '*' else: placeBomb(b) # Adds 1 to all of the squares around a bomb. def updateValues(rn, c, b): # Row above. if row > (rn - 1) > -1: r = b[rn - 1] if column > (c - 1) > -1: if not r[c - 1] == '*': r[c - 1] += 1 if not r[c] == '*': r[c] += 1 if column > (c + 1) > -1: if not r[c + 1] == '*': r[c + 1] += 1 # Same row. r = b[rn] if column > (c - 1) > -1: if not r[c - 1] == '*': r[c - 1] += 1 if column > (c + 1) > -1: if not r[c + 1] == '*': r[c + 1] += 1 # Row below. if row > (rn + 1) > -1: r = b[rn + 1] if column > (c - 1) > -1: if not r[c - 1] == '*': r[c - 1] += 1 if not r[c] == '*': r[c] += 1 if column > (c + 1) > -1: if not r[c + 1] == '*': r[c + 1] += 1 # Prints the given board. def printBoard(b): for r in range(0, row): list = [] for c in range(0,column): list.append(l(r, c, b)) print(*list, sep='║') if not r == row-1: print('══'*len(b)) def tryAgain(): # This function returns True if the player wants to try again, otherwise it returns False. print('Do you want to try again? (yes or no)') return input().lower().startswith('y') # The solution grid. while True: # Input of dimensions while True: print('Note that columns must be more than rows!!!') row = int(input('Enter rows:')) column = int(input('Enter column:')) if (column > row): break # Input the number of mines while True: mines = int(input('Enter the number of mines:')) if (mines < row * column): break b = [] for j in range(0,column): b.append([]) for i in range(0,row): for j in range(0, column): b[i].append(j) b[i][j] = 0 for n in range(0, mines): placeBomb(b) for r in range(0, row): for c in range(0, column): value = l(r, c, b) if value == '*': updateValues(r, c, b) printBoard(b) if not tryAgain(): break
import unittest class Node: def __init__(self, key): self.key = key self.is_last_sibling = False # indicate if the node is the last sibling self.left_child = None self.next = None # if the node is last sibling, it points to parent, else it points to right sibling def print_children(node): while True: print(node.key) node = node.next if node.is_last_sibling: break def print_parent(node): while not node.is_last_sibling: node = node.next print(node.next.key)
import unittest class Node: def __init__(self, key, p=None, left_child=None, right_sibling=None): self.key = key self.p = p self.left_child = left_child self.right_sibling = right_sibling def print_tree(node): if node is not None: print(node.key) if node.left_child is not None: print_tree(node.left_child) if node.right_sibling is not None: print_tree(node.right_sibling) class ProblemTestCase(unittest.TestCase): def test_case(self): root = Node(3) node1 = Node(1, root, None, Node(2)) root.left_child = node1 print_tree(root) if __name__ == '__main__': unittest.main()
import unittest class Node: def __init__(self, key): self.key = key self.next = None self.prev = None class CircularDoublyLinkedList: def __init__(self): self.nil = Node(None) self.nil.next = self.nil self.nil.prev = self.nil def list_search(L, k): x = L.nil.next while x is not L.nil and x.key != k: x = x.next return x def list_insert(L, x): x.next = L.nil.next L.nil.next.prev = x L.nil.next = x x.prev = L.nil def list_delete(L, x): x.prev.next = x.next x.next.prev = x.prev class ProblemTestCase(unittest.TestCase): @staticmethod def list_to_str(node): keys = [] cur = node while cur.key is not None: keys.append(cur.key) cur = cur.next return ' '.join(map(str, keys)) def test_case(self): L = CircularDoublyLinkedList() list_insert(L, Node(1)) self.assertEqual(self.list_to_str(L.nil.next), '1') list_insert(L, Node(2)) list_insert(L, Node(3)) list_insert(L, Node(4)) list_insert(L, Node(5)) self.assertEqual(self.list_to_str(L.nil.next), '5 4 3 2 1') node_to_del = list_search(L, 3) self.assertEqual(self.list_to_str(node_to_del), '3 2 1') list_delete(L, node_to_del) self.assertEqual(self.list_to_str(L.nil.next), '5 4 2 1') if __name__ == '__main__': unittest.main()
import random import unittest def counting_sort(A, k): B = [0 for _ in range(len(A))] C = [0 for _ in range(k + 1)] for num in A: C[num] = C[num] + 1 # C[i] now contains the number of elements equal to i. for i in range(k): C[i + 1] = C[i + 1] + C[i] # C[i] now contains the number of elements less than or equal to i. for num in A: # reversed(A): B[C[num] - 1] = num # !!! -1 C[num] -= 1 return B class SortTestCase(unittest.TestCase): @staticmethod def random_array(): return [random.randint(0, 100) for _ in range(random.randint(1, 100))] def test_random(self): for _ in range(10000): arr = self.random_array() sorted_arr = sorted(arr) b = counting_sort(arr, 100) self.assertEqual(b, sorted_arr) if __name__ == '__main__': unittest.main()
# references: # https://realpython.com/python3-object-oriented-programming/ used to learn about python OOP # https://levelup.gitconnected.com/writing-tetris-in-python-2a16bddb5318 used and modified this example for core tetris app (IMPORTANT) # https://www.educative.io/edpresso/how-to-generate-a-random-string-in-python used for help with generating code import pygame import random import time from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail import os from dotenv import load_dotenv import string load_dotenv() # initialize set of colors that associate with each piece colors = [ (0, 0, 0), # placeholder; colors[0] not used (0, 255, 255), # Aqua (line piece) (255, 69, 0), # Red (z piece) (0, 205, 102), # Green (s piece) (58, 95, 205), # Royal Blue (reverse L piece) (255, 128, 0), # Orange (L piece) (255, 131, 250), # Purple (T piece) (255, 255, 0), # Yellow (square piece) ] class Figure: """ This class holds all of the figures or "tetris shapes" that the game will randomly choose. Member Variable: Figures (shape of every figure on a 4x4 grid) Member Functions: __init__ (initialize a figure), image (return image of chosen figure), rotation functions (rotate a figure) """ # init x and y to zero x = 0 y = 0 figures = [ [[1, 5, 9, 13], [4, 5, 6, 7]], # line piece [[4, 5, 9, 10], [2, 6, 5, 9]], # z piece [[6, 7, 9, 10], [1, 5, 6, 10]], # s piece [[1, 2, 5, 9], [0, 4, 5, 6], [1, 5, 9, 8], [4, 5, 6, 10]], # reverse L piece [[1, 2, 6, 10], [5, 6, 7, 9], [2, 6, 10, 11], [3, 5, 6, 7]], # L piece [[1, 4, 5, 6], [1, 4, 5, 9], [4, 5, 6, 9], [1, 5, 6, 9]], # T piece [[1, 2, 5, 6]], # square piece ] def __init__(self, x, y): """ Initializes a figure. Params: self, x, y """ # init x and y self.x = x self.y = y # choose a random int between 0 and length of figures list - 1 self.type = random.randint(0, len(self.figures) - 1) # set color to same int as type to make color the same for the same figure self.color = self.type + 1 # init rotation to 0 self.rotation = 0 def image(self): """ Returns the proper rotation of the chosen type of figure. Params: self """ return self.figures[self.type][self.rotation] def rotateLeft(self): """ Rotates the figure left 90 degrees by finding the modulus of the rotation int and the amount of rotation figures that exist for the respective type of figure. """ self.rotation = (self.rotation + 1) % len(self.figures[self.type]) def rotateRight(self): """ Rotates the figure right 90 degrees by finding the modulus of the rotation int - 1 and the amount of rotation figures that exist for the respective type of figure. """ # if rotation = 0, use last rotation figure on the figure list; else, subtract 1 from rotation # (avoids error by disallowing rotation from becoming negative) if self.rotation == 0: self.rotation = len(self.figures[self.type]) - 1 else: self.rotation = (self.rotation - 1) % len(self.figures[self.type]) def rotate180(self): """ Rotates the figure 180 degrees by finding the modulus of the rotation int + 2 and the amount of rotation figures that exist for the respective type of figure. """ self.rotation = (self.rotation + 2) % len(self.figures[self.type]) class Tetris: """ This class holds all the variables of the tetris game. Member Variable: Figures (shape of every figure on a 4x4 grid) Member Functions: __init__ (initializes the game), new_figure (creates new figure) """ level = 2 score = 0 state = "start" field = [] height = 0 width = 0 x = 100 y = 60 zoom = 20 figure = None lines_left = 0 start_time = 0 timer = 0 final_time = 0 def __init__(self, height, width, lines_left): self.height = height self.width = width self.field = [] self.score = 0 self.lines_left = lines_left self.start_time = time.time() self.timer = 0 self.final_time = 0 self.state = "start" for i in range(height): new_line = [] for j in range(width): new_line.append(0) self.field.append(new_line) def new_figure(self): """ Creates new figure object at x=3, y=0 Params: self """ self.figure = Figure(3, 0) def intersects(self): """ Returns whether or not a newly created figure is outside the bounds of the game. If a newly created figure is intersecting, game over. Params: self """ intersection = False # loop through every block in the 4x4 matrix, i*4+j covers every number from 0-15 for i in range(4): for j in range(4): if i * 4 + j in self.figure.image(): if i + self.figure.y > self.height - 1 or \ j + self.figure.x > self.width - 1 or \ j + self.figure.x < 0 or \ self.field[i + self.figure.y][j + self.figure.x] > 0: intersection = True return intersection def break_lines(self): """ Deletes completed lines (given that every block in a line has a value.) """ lines = 0 for i in range(1, self.height): zeros = 0 for j in range(self.width): if self.field[i][j] == 0: zeros += 1 if zeros == 0: lines += 1 for i1 in range(i, 1, -1): for j in range(self.width): self.field[i1][j] = self.field[i1 - 1][j] self.lines_left -= lines if self.lines_left <= 0: self.state = "gameover" def go_space(self): """ Places figure at the bottom of the grid. """ while not self.intersects(): self.figure.y += 1 self.figure.y -= 1 self.freeze() def go_down(self): """ Moves figure down in increments of one y value. """ self.figure.y += 1 if self.intersects(): self.figure.y -= 1 self.freeze() def freeze(self): """ Freezes figure in place so it cannot be moved anymore; "game over" if figure is outside boundaries. """ for i in range(4): for j in range(4): if i * 4 + j in self.figure.image(): self.field[i + self.figure.y][j + self.figure.x] = self.figure.color self.break_lines() self.new_figure() if self.intersects(): self.state = "gameover" def go_side(self, dx): """ Moves figure to the left or to the right by 1 x unit. """ old_x = self.figure.x self.figure.x += dx if self.intersects(): self.figure.x = old_x def rotate(self, direction): """ Rotates the figure left, right, or 180 degrees. Params: Direction (passed into through user input key) """ old_rotation = self.figure.rotation if direction == "left": self.figure.rotateLeft() elif direction == "right": self.figure.rotateRight() elif direction == "180": self.figure.rotate180() if self.intersects(): self.figure.rotation = old_rotation def start_game(gamemode, challenger, challenger_time, challenge_mode): """ Starts a game of CStris. Params: gamemode (10 lines, 20 lines, or 40 lines), challenger (name), challenger_time (what time they got), and challenge mode (used to determine if user is being challenged or not) """ gamemodes = [10, 20, 40] # Initialize the game engine and music engine pygame.init() pygame.mixer.init() # load music and sound effect to play when lines are cleared rootDir = os.path.dirname(os.path.abspath("top_level_file.txt")) music = os.path.join(rootDir + "/sounds/music.mp3") sound_effect = os.path.join(rootDir + "/sounds/clear.wav") # Initialize counter to stop the loop when the game ends stop_loop_count = 0 # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (128, 128, 128) size = (400, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Cstris") # Loop until the user clicks the close button or the game ends. done = False clock = pygame.time.Clock() fps = 25 game = Tetris(20, 10, gamemodes[gamemode - 1]) counter = 0 # play music pygame.mixer.music.load(music) pygame.mixer.music.play(-1) pressing_down = False start_time = time.time() final_time = time.time() while not done: if game.figure is None: game.new_figure() counter += 0.5 if counter > 100000: counter = 0 if fps != 0: if counter % (fps // game.level // 2) == 0 or pressing_down: if game.state == "start": game.go_down() for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: game.rotate("right") if event.key == pygame.K_z: game.rotate("left") if event.key == pygame.K_a: game.rotate("180") if event.key == pygame.K_DOWN: pressing_down = True if event.key == pygame.K_LEFT: game.go_side(-1) if event.key == pygame.K_RIGHT: game.go_side(1) if event.key == pygame.K_SPACE: game.go_space() if event.key == pygame.K_ESCAPE: game.__init__(20, 10, 1) if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: pressing_down = False if event.key == pygame.K_LEFT: pressing_left = False if event.key == pygame.K_RIGHT: pressing_right = False screen.fill(WHITE) for i in range(game.height): for j in range(game.width): pygame.draw.rect(screen, GRAY, [game.x + game.zoom * j, game.y + game.zoom * i, game.zoom, game.zoom], 1) if game.field[i][j] > 0: pygame.draw.rect(screen, colors[game.field[i][j]], [game.x + game.zoom * j + 1, game.y + game.zoom * i + 1, game.zoom - 2, game.zoom - 1]) if game.figure is not None: for i in range(4): for j in range(4): p = i * 4 + j if p in game.figure.image(): pygame.draw.rect(screen, colors[game.figure.color], [game.x + game.zoom * (j + game.figure.x) + 1, game.y + game.zoom * (i + game.figure.y) + 1, game.zoom - 2, game.zoom - 2]) game.timer = round(time.time() - start_time, 2) font = pygame.font.SysFont('Calibri', 25, True, False) font1 = pygame.font.SysFont('Calibri', 65, True, False) lines_left_cap = font.render("Lines Left: ", True, BLACK) lines_left_num = font.render(str(game.lines_left), 25, colors[2]) timer_cap = font.render("Time: " + str(game.timer) + "s", True, BLACK) text_game_over = font1.render("Game Over!", True, BLACK) text_final_time = font1.render("Time: " + str(round(final_time, 2)), True, colors[2]) text_you_win = font1.render("You Win!", True, colors[3]) text_you_lose = font1.render("You Lose!", True, colors[2]) text_challenger_time = font.render(challenger + " Time: " + str(challenger_time), True, BLACK) screen.blit(lines_left_cap, [130, 15]) screen.blit(lines_left_num, [260, 15]) if game.state == "start": screen.blit(timer_cap, [130, 470]) if challenge_mode == False: if game.state == "gameover": stop_loop_count += 1 if stop_loop_count == 1: final_time = time.time() - start_time pygame.mixer.music.stop() screen.blit(text_game_over, [20, 200]) screen.blit(text_final_time, [25, 265]) else: if game.state == "gameover": stop_loop_count += 1 if stop_loop_count == 1: final_time = time.time() - start_time pygame.mixer.music.stop() if final_time <= float(challenger_time): screen.blit(text_you_win, [20, 200]) screen.blit(text_final_time, [20, 265]) screen.blit(text_challenger_time, [20, 330]) else: screen.blit(text_you_lose, [20, 200]) screen.blit(text_final_time, [20, 265]) screen.blit(text_challenger_time, [20, 330]) pygame.display.flip() clock.tick(fps) # pygame.quit() return final_time def display_menu(): """ Displays the menu for the user to use. """ choices = [1,2,3,4,5] choice = 0 while choice not in choices or choice == 4: print("***********************************") print("Please select an option from the menu below: ") print("Play Solo - 1") print("Send Challenge - 2") print("Receive Challenge - 3") print("Instructions - 4") print("Exit - 5") choice = int(input("***********************************\n")) if choice not in choices: print("Please select a valid choice.\n") continue if choice == 4: print("***********************************") print("INSTRUCTIONS:") print("Move left and right: Arrow Keys") print("Place Block: Space Bar") print("Rotate Right 90 Degrees: Up Arrow Key") print("Rotate Left 90 Degrees: 'Z' Key") print("Rotate 180 Degrees: 'A' Key") print("Fast Fall: Down Arrow Key") print("***********************************") continue return choice def display_gamemodes(): """ Displays the 3 gamemode choices: clearing 10 lines, 20 lines, or 40 lines. """ choices = [1,2,3] choice = 0 while choice not in choices: print("***********************************") print("10 Lines - 1") print("20 Lines - 2") print("40 Lines - 3") choice = int(input("***********************************\n")) if choice not in choices: print("Please select a valid choice.\n") continue return choice def generate_code(name, final_time, gamemode): """ Generates a (sort of) encrypted code that stores the Challenger's name, time, and gamemode. Generated when user sends a challenge. Params: name (username), final time(how long user took to complete CStris), gamemode """ nums = string.digits code = ''.join(random.choice(nums) for i in range(50)) final_time_str = str(round(final_time, 2)) code = name + code[:25] + final_time_str + code[25:] + str(gamemode) return code def send_challenge(username, email, final_time, gamemode): """ Sends challenge email to email of user's choice. Includes generated code. Params: username, email(that user sends to), final time, gamemode """ SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY", default="OOPS, please set env var called 'SENDGRID_API_KEY'") SENDER_ADDRESS = os.getenv("SENDER_ADDRESS", default="OOPS, please set env var called 'SENDER_ADDRESS'") client = SendGridAPIClient(SENDGRID_API_KEY) subject = username + " has challenged you to Cstris!" code = generate_code(username, final_time, gamemode) html_content = f""" <h3> You've been challenged to Cstris by {username}! </h3> <ol> Challenge Code: {code} </ol> <ol> Paste the above code into your Cstris and show {username} who's boss! </ol> <ol> (Don't have Cstris? Get it here: https://github.com/connorkeyes/cstris) </ol> """ message = Mail(from_email=SENDER_ADDRESS, to_emails=email, subject=subject, html_content=html_content) try: response = client.send(message) print("Your challenge has been sent. May you conquer all your enemies.") except: print("Unfortunately, something went wrong. Your challenge could not be sent.") print("Double check that the email is valid if you want to send a challenge!") def accept_challenge(code): """ De-encrypts code and returns relevant data for challenge: (gamemode, challenger, and final time) Params: encrypted code """ challenger = "" for char in code: if char.isdigit() == False: challenger += char else: break num_digits = len(code) - len(challenger) - 51 time_start = len(challenger) + 25 time_end = time_start + num_digits final_time = code[time_start:time_end] gamemode = code[len(code) - 1] return [gamemode, challenger, final_time] print("***********************************") print(" CSTRIS ") print("***********************************") name = input("Please enter your name: ") print("***********************************") print("Welcome to Cstris, " + name + "!") choice = display_menu() if choice == 1: print("Please select gamemode: ") gamemode = display_gamemodes() print("Starting game...") final_time = start_game(gamemode, '', 0, False) print(str(round(final_time,2)) + " seconds! Nice job!") elif choice == 2: email = input("Please enter the email address to send a challenge to: ") print("Please select gamemode: ") gamemode = display_gamemodes() print("Starting game...") final_time = start_game(gamemode, '', 0, False) send_challenge(name, email, final_time, gamemode) elif choice == 3: code = input("Please copy and paste the code you received in your email...\n") challenge_info = [] challenge_info = accept_challenge(code) final_time = start_game(int(challenge_info[0]), challenge_info[1], float(challenge_info[2]), True) # choice 4 covered in display_menu(); did to keep instructions within menu display loop else: print("Exiting...") exit()
#This code was made with the intent of testing the board.py module from board import * def run(): rows=int(input('Insert the number of rows: ')) columns=int(input('Insert the number of columns: ')) mainBoard = Board(rows,columns) while True: print('') print('MENU') print('1. print entire board') print('2. add new mark') print('3. remove existing mark') print('4. Show list of current marks') print('5. exit') menu=int(input('What should I do?: ')) if menu == 1: mainBoard.printXYBoard() if menu == 2: xCoordinate = int(input('Enter X: ')) yCoordinate = int(input('Enter Y: ')) symbol = input('Enter symbol (blank for Default): ') markId = input('Enter an ID for this mark (Leave blank for default "None"): ') mainBoard.addNewMark(xCoordinate,yCoordinate,symbol, markId) if menu == 3: mainBoard.showCurrentMarks() index=int(input('Enter mark Index: ')) mainBoard.removeMark(index) if menu == 4: mainBoard.showCurrentMarks() if menu == 5: break print('') wait=input() if __name__=="__main__": run()
cdevfbrb def bigger(a,b): if a>b: return a else: return b def biggest (a,b,c): return bigger(bigger(a,b),c) def median (a,b,c): f = biggest(a,b,c) if f == a: if c>=b: return c else: return b if f == b: if a>=c: return a else: return c if f == c: if a>=b: return a else: return b print(median(1,2,3)) #>>> 2 print(median(9,3,6)) #>>> 6 print(median(7,8,7)) #>>> 7
# Aula 6 - P2 - 12-11-2019 # Estruturas de repetição - FOR <<<<<<< HEAD #--- for simpes usando range com incremento padrão de 1 for i in range (0,10,): print (f'{i}- Padawans HbPy') #--- for simpes usando range com incremento de 2 ======= #--- for simples usando range com incremento padrão de 1 for i in range (0,10,): print (f'{i}- Padawans HbPy') #--- for simples usando range com incremento de 2 >>>>>>> 2d8463416993fc7b9ac4750ff272aa8e9b0ed328 for i in range (0,100,2): print (f' {i}- Pares') #--- For em lista usando range lista = ['Mateus', 'Matheus', 'Marcela', 'Nicole', 'Tonho', 'Pablo'] for i in range (0,6): print (lista[i]) #---Exemplificando o problema do uso de For em lista usando range lista.append ('Natan') for sortudo in lista: print (sortudo) #---For usando os elementos da própria lista (foreach) numero = 10 for i in range(0,10): print (f'{i} x {numero} = {i*numero}')
#--- Exercício 2 - Dicionários #--- Escreva um programa que leia os dados de 11 jogadores #--- Jogador: nome, posição, numero, pernaboa #--- Crie um dicionário para armazenar os dados #--- Imprima todos os joogadores e seus dados lista_jogadores = [] for i in range (1,3): jogador = {} jogadores= {'nome': '', 'posicao': '', 'numero':'', 'pernaboa':''} jogadores['nome'] = input ('digite o nome:') jogadores['posicao'] = input ('digite a posicao:') jogadores['numero'] = int (input ('digite o numero:')) jogadores['pernaboa'] = input ('digite a pernaboa:') lista_jogadores.append(jogadores) print ('\m') # print (lista_jogadores) for i in lista_jogadores: print (i['nome'], i['posicao'], i['numero'], i['pernaboa'])
#Aula 4_2 13-11-2019 #Boleanas #---- Variável booleana simples com True ou False validador = False #---- Substituição do valor inicial validador = True #----- Criação de variável booleana através de expressão de igualdade idade = 18 validador = ( idade == 18 ) print (validador) #----- Criação de variável booleana através de expressão dda diferença validador = ( idade != 18 ) print (validador) #----- Criação de variável booleana através de expressão de maior validador = ( idade > 18 ) print (validador) #----- Criação de variável booleana através de expressão de menor validador = ( idade < 18 ) print (validador) #----- Criação de variável booleana através de expressão de maior e igual validador = ( idade >= 18 ) print (validador) #----- Criação de variável booleana através de expressão de menor e igual validador = ( idade <=18 ) print (validador) #----- Criação de variável booleana através de expressão de negação validador = not True validador = not False sorteado = 'Marcela' #----- Criação de variável booleana através de duas expressões e operador E validador = ( sorteado=='Matheus' and sorteado== 'Marcela' ) #------Criação de variável booleana através de duas expressões e operador OU validador = ( sorteado=='Matheus' or sorteado== 'Marcela')
import funciones as fnMatriz def main(): #Abrimos el archivo uno text1=open("ejemplo1.txt","r") sentences_text1 = text1.read().lower() sentences_text1 = fnMatriz.extract_words(sentences_text1) #Abrimos el archivo dos text2=open("ejemplo2.txt","r") sentences_text2 = text2.read().lower() sentences_text2 = fnMatriz.extract_words(sentences_text2) #Abrimos el archivo tres text3 = open("ejemplo.txt","r") sentences_text3 = text3.read().lower() sentences_text3 = fnMatriz.extract_words(sentences_text3) #Creamos nuestro vocabulario (Diccionario key = palabra : value= idf) vocabulary = fnMatriz.tokenize_sentences([sentences_text1,sentences_text2,sentences_text3]) print("----- Vocabulario -----") print(vocabulary) #Obtenemos los diciconario de cada cada texto (Diccionario key = palabra : value = tf) matrix = fnMatriz.list_dictionary([sentences_text1,sentences_text2,sentences_text3]) print("--- matriz TF ---") fnMatriz.showMatriz(vocabulary,matrix) print("-----Similitud-----") #Calculamos la similitud euclidiana #simEuclidean = euclidean_distance(bagofWords_text1,bagofWords_text2) #print("Distancia euclidiana: " +str(simEuclidean)) #Calculamos la similitud coseno #Enlistamos los valores de los tres diccionarios list_text1 = fnMatriz.create_list(vocabulary,matrix[0]) list_text2 = fnMatriz.create_list(vocabulary,matrix[1]) list_text3 = fnMatriz.create_list(vocabulary,matrix[2]) simCos1_2 = fnMatriz.cosine_similarity(list_text1,list_text2) simCos1_3 = fnMatriz.cosine_similarity(list_text1,list_text3) simCos2_3 = fnMatriz.cosine_similarity(list_text2,list_text3) print ("Similitud coseno texto1-texto2: " + str(simCos1_2)) print ("Similitud coseno texto1-texto3: " + str(simCos1_3)) print ("Similitud coseno texto2-texto3: " + str(simCos2_3)) text1.close() text2.close() text3.close() main()
# Listas meses = ['Enero', 'Febrero', 'Marzo'] # print(meses[1]) # Si usamos posiciones negativas contará de atras hacia adelante # print(meses[-1]) # Para traer elementos con limites, el primero indica desde donde # y el segundo hasta que sea menor que # print(meses[0:2]) # Para agregar elementos a la Lista meses.append(['Abril','Diciembre']) # print(meses[-1][1]) # Para quitar un elemento de la lista meses.remove('Febrero') # print(meses) # Para limpiar toda la lista meses.clear() # print(meses) # Tuplas # colecciones de datos ORDENADAS NO SE PUEDEN MODIFICAR datos_sensibles = (123456, 'Eduardo', 1.87) # print(datos_sensibles[0]) # Para ver cuantos valores repetidos tenemos en la tupla # print(datos_sensibles.count(123456)) # Conjuntos # Coleccion de elementos DESORDENADA, no hay orden para acceder a sus datos colores = {'rojo', 'verde', 'azul', 'morado'} colores.add('blanco') # print(colores) # for color in colores: # print(color) # Diccionarios # coleccion de elementos que estan INDEXADOS, no estan ordenados y se pueden modificar # sus valores. Estan conformados por una CLAVE y un VALOR persona = { 'id':100, 'nomb_per':'Fabian', 'fec_nac':'1992/08/01', 'sex_per': 'M', 'tipo_per':{ 'tiper_id':1, 'tiper_desc':'Employee' } } # Para ver el valor de la clave en especifico print(persona['tipo_per']['tiper_desc']) # Para ver todas sus llaves print(persona.keys()) # Para ver todos sus valores print(persona.values()) # Agregar un item al diccionario persona['per_ubigeo']='04001' # persona['nomb_per']='Julian' print(persona)
from random import choice import sys def open_and_read_file(file_path): """Takes file path as string; returns text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ # your code goes here open_file = open(file_path) input_path = open_file.read() #print input_path return input_path def make_chains(text_string): """Takes input text as string; returns _dictionary_ of markov chains. A chain will be a key that consists of a tuple of (word1, word2) and the value would be a list of the word(s) that follow those two words in the input text. For example: >>> make_chains("hi there mary hi there juanita") {('hi', 'there'): ['mary', 'juanita'], ('there', 'mary'): ['hi'], ('mary', 'hi'): ['there']} """ chains = {} words = text_string.split() for i in (range(len(words) - 2)): two_words = (words[i], words[i+1]) value = words[i+2] if chains.get(two_words): #this means that the key does exist chains.get(two_words).append(value) else: chains[two_words] = [value] return chains def make_text(chains): """Takes dictionary of markov chains; returns random text.""" # text = "" # make a list of punctations that we want to stop our file at. first_key = choice(chains.keys()) # first_value = choice(chains[first_key]) while first_key[0][0].islower(): first_key = choice(chains.keys()) # while the first character of the first item from our tuple key is lowercase, then # select another first key words_to_add_to_string = [first_key[0], first_key[1]] while first_key in chains: # pull the value of the first tuple that we started with, from the list of values that it gives, and then set that value to a variable new_word = choice(chains[first_key]) # append that random value to our words_to_add_to_string list words_to_add_to_string.append(new_word) # set our first_key to first_key[1], and the initial variable that we started off with. first_key = (first_key[1], new_word) if first_key[1][-1] in ['.', '!', '?']: break # if we have a puncuation, we stop. If not, we continue with the loop. # Once out of the while loop, we will join the values in the words_to_add_to_string to the text (which will print) whole_string = " ".join(words_to_add_to_string) return whole_string input_path = sys.argv[1] # Open the file and turn it into one long string input_text = open_and_read_file(input_path) # Get a Markov chain chains = make_chains(input_text) # Produce random text random_text = make_text(chains) print random_text
#mega tezky :( #rozdelit pole A do K casti tak aby v se vratilo co nejmensi nejvetsi soucet hodnot v poli #The large sum is the maximal sum of any block. def blocksNo(A, maxBlock): # Initially set the A[0] being an individual block blocksNumber = 1 # The number of blocks, that A could # be divided to with the restriction # that, the sum of each block is less # than or equal to maxBlock preBlockSum = A[0] for element in A[1:]: # Try to extend the previous block if preBlockSum + element > maxBlock: # Fail to extend the previous block, because # of the sum limitation maxBlock preBlockSum = element blocksNumber += 1 else: preBlockSum += element return blocksNumber def solution(K, M, A): # each block, how many blocks could # the original A be divided to? resultLowerBound = max(A) resultUpperBound = sum(A) result = 0 # Minimal large sum # Handle two special cases if K == 1: return resultUpperBound if K >= len(A): return resultLowerBound # Binary search the result while resultLowerBound <= resultUpperBound: resultMaxMid = (resultLowerBound + resultUpperBound) / 2 blocksNeeded = blocksNo(A, resultMaxMid) if blocksNeeded <= K: # With large sum being resultMaxMid or resultMaxMid-, # we need blocksNeeded/blocksNeeded- blocks. While we # have some unused blocks (K - blocksNeeded), We could # try to use them to decrease the large sum. resultUpperBound = resultMaxMid - 1 result = resultMaxMid else: # With large sum being resultMaxMid or resultMaxMid-, # we need to use more than K blocks. So resultMaxMid # is impossible to be our answer. resultLowerBound = resultMaxMid + 1 return result valK = 3 #pocet bloku valM = 5 arr = [2,1,5,1,2,2,2] print(solution(valK, valM, arr))
def bubble_sort(a): sort_a = a[:] return sort(sort_a) def sort(b): srted = True for idx, i in enumerate(b): if idx + 1 < len(b): #konec pole if i > b[idx+1]: #porovnani bigger = b[idx] b[idx] = b[idx+1] b[idx+1] = bigger srted = False if srted == True: #serazeno return b else: return sort(b) #rekurze arr = [2,5,8,1,3,6,9,7,1,5,6,8] print(bubble_sort(arr))
def day1_split(): with open('day1.txt', 'r') as f: lines = f.read().splitlines() return lines def day1_part1(start=0): freq = start for l in day1_split(): x = int(l) freq += x return freq def day1_part2(start=0): freq = start freqs = set() updates = day1_split() idx = 0 while True: x = int(updates[idx % len(updates)]) freq += x if freq in freqs: return freq else: freqs.add(freq) idx += 1 if __name__ == "__main__": print(f"Solution to day 1 part 1: {day1_part1()}") print(f"Solution to day 1 part 2: {day1_part2()}")
print ('Введите имя:') x = input() x = str(x) if x == 'Вячеслав': print ('Привет, Вячеслав') else: print ('Нет такого имени') input ('Press Enter to exit')
def quickSort(vect): if len(vect) <= 1: return vect element = vect.pop(0) v1 = [x for x in vect if x < element] v2 = [x for x in vect if x >= element] v1 = quickSort(v1) v2 = quickSort(v2) return v1 + [element] + v2 if __name__ == '__main__': print(quickSort([10, 2, 4, 1, -5, 7]))
# 2019-01-24 # Revision of Python Morsels exercises by Trey Hunner # Get the earliest date from a list of dates in a month-day-year format: def get_earliest(*dates): def date_convert(date): m,d,y = date.split('/') return y,m,d return min(dates, key=date_convert) from collections import Counter import re # Count the number of words in a given list. def count_words(words): list_of_words = re.findall(r'[\w\'-]+', words.lower()) return Counter(list_of_words) # Remove adjacent numbers in an iterable def compact(numbers): prior = object() for num in numbers: if num != prior: yield num prior = num # Add matrices def add_2(mat1, mat2): end_mat = [] for row1,row2 in zip(mat1,mat2): end_row = [] for el_1,el_2 in zip(row1,row2): end_row.append(el_1+el_2) end_mat.append(end_row) return end_mat def add(*mats): for mat in mats: if len(mat) != len(mats[0]): raise ValueError("Given matrices are not the same size.") for row in mat: if len(row) != len(mats[0][0]): raise ValueError("Given matrices are not the same size.") end_mat = [] for rows in zip(*mats): end_row = [] for els in zip(*rows): end_row.append(sum(els)) end_mat.append(end_row) return end_mat import math # Create a Circle class class Circle: def __init__(self, radius=1): self.radius = radius def __repr__(self): return 'Circle({})'.format(self.radius) @property def radius(self): return self._radius @property def diameter(self): return self.radius*2 @property def area(self): return math.pi*self.radius**2 @diameter.setter def diameter(self,diameter): self.radius = diameter/2 @radius.setter def radius(self,rad): if rad < 0: raise ValueError("Radius cannot be negative") else: self._radius = rad
# Attempt at solving Python Morsels problem: tail # Return the last 'n' items from a sequence 'seq' def tail(seq, n): tail = [] if n < 0: return tail else: for idx,val in enumerate(seq): tail.append(val) if idx >= n: tail.pop(0) return tail
#!/user/bin/python #Created by Brian Schapp, 19 August 2020 import math, random, sys, os, itertools import tkinter as tk from tkinter import messagebox as mbx root = tk.Tk() root.geometry('300x600') board = tk.Canvas(root, height=600, width=300, bg = 'peru') # CODE GENERATION ############################################################# colors = ['r', 'o' ,'y' ,'g' ,'b' ,'i' ,'p', 'w'] code = [random.choice(colors) for i in range(1,5)] guess = [] print(code) ############################################################################### # KEYS ######################################################################## a = 180 b = 10 c = 190 d = 20 i = 0 while i < 12: coord1 = a, b, c, d key1 = board.create_oval(coord1) coord2 = a + 20, b , c + 20, d key2 = board.create_oval(coord2) coord3 = a, b + 20, 190, d + 20 key3 = board.create_oval(coord3) coord4 = a + 20, b + 20, c + 20, d + 20 key4 = board.create_oval(coord4) b += 40 d += 40 i += 1 ############################################################################### # PEGS ######################################################################## i = tk.IntVar() a = tk.IntVar() b = tk.IntVar() c = tk.IntVar() d = tk.IntVar() i.set(0) a.set(10) b.set(10) c.set(40) d.set(40) e = tk.IntVar() f = tk.IntVar() g = tk.IntVar() h = tk.IntVar() e.set(180) f.set(10) g.set(190) h.set(20) def peg(color): global guess, code guess.append(color[0]) coord = [a.get(), b.get(), c.get(), d.get()] circleA = board.create_oval(coord, fill = color, tags = 'pegs') a.set(a.get() + 40) if a.get() > 130: a.set(10) c.set(c.get() + 40) if c.get() > 160: c.set(40) b.set(b.get() + 40) d.set(d.get() + 40) i.set(i.get() + 1) if i.get() == 4: for button in buttons: button['state'] = 'disabled' blackKey = 0 whiteKey = 0 j = 0 while j < 4: if code[j] == guess[j]: blackKey += 1 elif guess[j] in code and guess[j] != code[j]: whiteKey += 1 j += 1 # KEY POSISTIONING # for key in range(blackKey): if e.get() > 200: f.set(f.get() + 20) h.set(h.get() + 20) e.set(180) if g.get() > 210: g.set(190) coord1 = [e.get(), f.get(), g.get(), h.get()] key = board.create_oval(coord1, fill = 'black', tags = 'keys') e.set(e.get() + 20), g.set(g.get() + 20) for key in range(whiteKey): if e.get() > 200: f.set(f.get() + 20) h.set(h.get() + 20) e.set(180) if g.get() > 210: g.set(190) coord1 = [e.get(), f.get(), g.get(), h.get()] key = board.create_oval(coord1, fill = 'white', tags = 'keys') e.set(e.get() + 20), g.set(g.get() + 20) e.set(180), g.set(190) elif blackKey == 4: mbx.showinfo('Congratulations:', 'Well done! You cracked the code and won the game. ' 'To play again, please exit and run the program again. Otherwise, ' 'click "quit" now. Thanks for playing!') if (blackKey + whiteKey) <= 2: f.set(f.get() + 40) h.set(h.get() + 40) elif (blackKey + whiteKey) >= 3: f.set(f.get() + 20) h.set(h.get() + 20) #################### guess = [] for button in buttons: button['state'] = 'normal' i.set(0) ############################################################################### # INSTRUCTIONS ################################################################ def help(): mbx.showinfo('How to Play:', '''A sequence containing 4 colors ('pegs') is randomly generated and hidden from the player. Colors may repeat. The object is to guess the sequence. Enter your guess using the colored buttons at the bottom of the board. Your guess will be displayed on the board. To the right of your guess will be displayed black and white dots ('keys'). A white key indicates that one peg you chose is in the sequence, but is not in the correct position. A black key indicates that one peg is both in the sequence and in the correct position. Note that the position of the keys is NOT indicative of the position of the peg. All black keys are displayed first, followed by all white keys. You have 12 chances to guess the correct sequence.''') ############################################################################### # OTHER FUNCTIONS ############################################################# def quit(): root.destroy() ############################################################################### # BUTTON ARANGEMENT ########################################################### red = tk.Button(board, bg = 'red', command = lambda: peg('red')) orange = tk.Button(bg = 'orange', command = lambda: peg('orange')) yellow = tk.Button(bg = 'yellow', command = lambda: peg('yellow')) green = tk.Button(bg = 'green', command = lambda: peg('green')) blue = tk.Button(bg = 'blue', command = lambda: peg('blue')) indigo = tk.Button(bg = 'indigo', command = lambda: peg('indigo')) violet = tk.Button(bg = 'plum', command = lambda: peg('plum')) white = tk.Button(bg = 'white', command = lambda: peg('white')) buttons = [red, orange, yellow, green, blue, indigo, violet, white] help = tk.Button(root, text = 'Help', command = help) help.place(x = 10, y = 550, width = 90, height = 30) quit = tk.Button(root, text = 'Quit', command = quit) quit.place(x = 200, y = 550, width = 90, height = 30) red.place(x = 10, y = 500, width = 30, height = 30) orange.place(x = 45, y = 500, width = 30, height = 30) yellow.place(x = 80, y = 500, width = 30, height = 30) green.place(x = 115, y = 500, width = 30, height = 30) blue.place(x = 150, y = 500, width = 30, height = 30) indigo.place(x = 185, y = 500, width = 30, height = 30) violet.place(x = 220, y = 500, width = 30, height = 30) white.place(x = 255, y = 500, width = 30, height = 30) ############################################################################### board.pack() root.mainloop()
#!/usr/bin/env python # coding=utf-8 a = input("请输入一个数字") if a >=50: print a else: print -a
#David Centeno #5001 Intensive Foundations #Spring 2021 ## Version 3.0 ## # A turtle interperter that has been updated to make use of classes. Assigns certain characters to turtle functions import sys import turtle as t import random class TurtleInterpreter: initialized = False def __init__(self, dx = 800 , dy = 800): if TurtleInterpreter.initialized: return TurtleInterpreter.initialized = True t.setup(dx,dy) t.tracer(False) def drawString(self, dstring, distance, angle): """ The distance specifies how far the turtle should move forward for the F character, and the angle specifies the number of degrees the turtle should turn for a + or - character.""" # Character Action # F Move the turtle forward by distance # + Turn the turtle left by angle # - Turn the turtle right by angle # [ Append the turtle's heading and position to a list (e.g. stack) # ] Pop the turtle's heading and position from the list (e.g. stack) and restore the turtle's state #Stack to store the L-System Instructions stack = [] colorStack = [] for c in dstring: #symbol sets F to move turtle forward if c == 'F': t.forward(distance) elif c == 'L': t.color(colorStack[0]) t.begin_fill() t.circle(2) t.end_fill() #symbol sets - to change turtle direction to the right by a certain angle elif c == '-': t.right(angle) #symbol sets + to change turtle direction to the right by a certain angle elif c == '+': t.left(angle) #Appends the turtle postion and heading to the stack list elif c == '[': stack.append(t.pos()) stack.append(t.heading()) #sets the heading and position from popping values from the stack list elif c == ']': t.penup() t.setheading(stack.pop()) t.goto(stack.pop()) t.pendown() #Appends t.color to the colorstack at the 0 position elif c =='<': colorStack.append( t.color()[0] ) #Sets the color elif c =='>': currentColor = colorStack.pop(0) t.color(currentColor) #Sets r to the color red elif c == 'r': t.color((0.7, 0.4, 0.5)) #Sets y tp the color yellow elif c == 'y': t.color((0.8, 0.8, 0.3)) #Sets g to the color green elif c == 'g': t.color((0.1, 0.5, 0.2)) #sets b to the color blue elif c == 'b': t.color((0.1, 0.5, 0.8)) #sets p to the color light pink elif c == 'p': t.color((0.9,0.6,0.6)) #sets 0 to a specific position used for project 8 elif c == '0': self.place(-120,150,270) #sets the width of the branch of a tree elif c == 'w': t.width(4) #Starts the begin fill for coloring an object elif c == '{': t.begin_fill() #Ends the fill ofr coloring an object elif c == '}': t.end_fill() t.update() def hold(self): '''Holds the screen open until user clicks or presses 'q' key''' # Hide the turtle cursor and update the screen t.hideturtle() t.update() # Close the window when users presses the 'q' key t.onkey(t.bye, 'q') # Listen for the q button press event t.listen() # Have the turtle listen for a click t.exitonclick() def place(self, xpos, ypos, angle=None): t.penup() t.goto(xpos,ypos) t.setheading(angle) t.pendown() def orient(self, angle): t.setheading(angle) def goto(self, xpos, ypos): t.penup() t.goto(xpos,ypos) t.pendown() def setColor(self, c): t.color(c) def setWidth(self, w): t.width(w)
#David Centeno #5001 Intensive Foundations import sys import graphicsPlus as gr #Swaps the red and blue values of an image def swapRedBlue( src ): #col gets src's width cols = src.getWidth() #row gets src's height rows = src.getHeight() #iterates through the col and row of srcs pixels. #Its first step sets src's rgb values to a r, g, b var #Its second step switches the values for row in range(rows): for col in range(cols): r, g, b = src.getPixel(col,row) # set the pixel indexed by (j, i) to the value (b, g, r) src.setPixel(col,row, gr.color_rgb(b,g,r)) #Makes a bluer image def increaseBlue ( src ): #col gets src's width cols = src.getWidth() #row gets src's height rows = src.getHeight() for row in range(rows): for col in range(cols): #Grabs the RGB color pixels r, g, b = src.getPixel(col,row) # Reduces R and G pixel colors and leaves blue. Result is a bluer image src.setPixel(col ,row , gr.color_rgb(r//2, g//2, b)) #Creates a grayscale filter def grayscale ( src ): #col gets src's width cols = src.getWidth() #row gets src's height rows = src.getHeight() for row in range(rows): for col in range(cols): #Grabs the RGB value from the pixel r, g, b = src.getPixel(col,row) #Var that adds together rgb value and divides by 3 result is a whole number grayscale = (r+g+b)//3 # sets the pixels to grayscale color src.setPixel(col ,row , gr.color_rgb(grayscale,grayscale,grayscale)) #Creates a cartoon filter def cartoon ( src ): #col gets src's width cols = src.getWidth() #row gets src's height rows = src.getHeight() for row in range(rows): for col in range(cols): #Grabs the R G B values from the pixel r, g, b = src.getPixel(col,row) #Takes the R G B values and divides them by 32 with no float value cR = r //32 cG = g //32 cB = b //32 # sets the pixels to some multiple of 32 which limits the colors to look more cartoon. src.setPixel(col ,row , gr.color_rgb(cR * 32, cG * 32, cB * 32)) def test_Filter (argv): #bring in image file from the command line filename = sys.argv[1] #stores image image = gr.Image(gr.Point(0,0),filename) #determines picture width and height col = image.getWidth() row = image.getHeight() #swaps reds for blue in an image swapRedBlue( image ) #creates the window for the image to be drawn win = gr.GraphWin(filename,col,row) #image.move(col/2,row/2) image.move(col/2,row/2) #draws out the image image.draw( win ) #Save an image of the file to current directory image.save('SavedFilter.ppm') #closes out canvas when mouse is clicked win.getMouse() win.close() if __name__ == "__main__": test_Filter(sys.argv)
#David Centeno #5001 Intensive Foundations #Spring 2021 ## Version 3.0 ## #A shape file that creates classes to be called for use of drawing shapes in other files. import turtle_interpreter class Shape: def __init__(self, distance = 100, angle = 90, color = (0, 0, 0), istring = '' ): # create a field of self called distance and assign it distance self.distance = distance # create a field of self called angle and assign it angle self.angle = angle # create a field of self called color and assign it color self.color = color # create a field of self called string and assign it istring self.string = istring # setColor(self, c) - set the color field to c def setColor(self,c): self.color = c # setDistance(self, d) - set the distance field to d def setDistance(self,d): self.distance = d # setAngle(self, a) - set the angle field to a def setAngle(self,a): self.angle = a # setString(self, s) - set the string field to s def setString(self, s): self.string = s #draw function def draw(self, xpos, ypos, scale=1.0, orientation=0): # Sets ti to use the TurtleInterpreter from the turtle)interpreter.py file ti = turtle_interpreter.TurtleInterpreter() # Uses the turtle interpreter class place method to set the position of this Class ti.place(xpos,ypos,orientation) # Uses the turtle interpreter class setcolor method to set the color of this Class ti.setColor(self.color) # Uses the turtle interpreter class drawstring method to draw the string of this Class ti.drawString(self.string, self.distance * scale ,self.angle) #method that holds up the drawing canvas of the turtle class def hold(self): turtle_interpreter.TurtleInterpreter.hold(self) #Class that makes a square using a set L-System string class Square(Shape): def __init__(self, distance=100, color=(0, 0, 0) ): #Borrowing init function from the parent class shape to set distance, #angle, color and istring Shape.__init__(self,distance,90,color,'F-F-F-F-') #Class that creates a triangle using a set L-system string class Triangle(Shape): #Triangles init function def __init__(self, distance=100, color=(0, 0, 0) ): #Borrowing init function from the parent class shape to set distance, #angle, color and istring Shape.__init__(self,100,120,color,'{F-F-F-}') #Class that creates a Hexagon using a set L-system string class Hexagon(Shape): #Hexagon init function def __init__(self,distance=100, color=(0 , 0, 0)): #Borrowing init function from the parent class shape to set distance, #angle, color and istring Shape.__init__(self,100,60,color, '{F-F-F-F-F-F}') #Class that creates a Star using a set L-system string class Star (Shape): def __init__(self, distance=100, color=(0,0,0)): #Borrowing init function from the parent class shape to set distance #angle, color and istring Shape.__init__(self,distance,216,color,'{F-F-F-F-F-}') #Class that creates a Cross using a set L-system string class Cross (Shape): #Borrowing init function from the parent class shape to set distance, #angle, color and istring def __init__(self, distance=100, color=(0,0,0)): Shape.__init__(self,100,90,color,'{F-F+F-F-F+F-F-F+F-F-F+F-F}') #Class that creates a circle using a set L-system string class Circle (Shape): #Borrowing init function from the parent class shape to set distance, #angle, color and istring def __init__(self, distance=100, color=(0,0,0)): Shape.__init__(self,1,1,color,'{F+F+F+F+F+F+F+F+F+F+F+F+F}'*30) #Function that initiates shape classes def testShape(): #Object creation for shape classes s = Shape() cr = Cross() st = Star() hx = Hexagon() tr = Triangle() sq = Square() cir = Circle() #Cross init function that designates a color to the cross class (Color is Red) cr.__init__(color=(0.8,0.3,0.3)) #Uses draw method to draw Cross cr.draw(-200,-200,.5,0) #Uses draw method to draw Star st.draw(-100,100,1,90) #Hexagon init function that designates a color to the hexagon class (Color is purple) hx.__init__(color=(0.6,0.2,0.6)) #Uses draw method to draw Hexagon hx.draw(0,0,.5,0) #Uses draw method to draw Triangle tr.draw(100,-100,1,60) #Uses draw method to draw Square sq.draw(200,-200,.5,0) #Shape method hold that keeps the canvas open until button is clicked or q is pressed cir.draw(300,300,.2,0) s.hold()
from datetime import datetime, timedelta from calelib import Constants def get_deadline(deadline_string): """ Parse string like to datetime object :param deadline_string: string in format "DAY MONTH" :return: string in datetime format """ if len(deadline_string.split(',')) > 1: date, time = [e.strip() for e in deadline_string.split(',')] else: date = deadline_string time = None input_format = '%d %B%Y' now = datetime.now() curr_year_input = datetime.strptime(date + str(now.year), input_format) if time: hour, minutes = [int(e) for e in time.split(':')] curr_year_input = curr_year_input.replace(hour=hour, minute=minutes) else: curr_year_input += timedelta(days=1) if curr_year_input < now: return curr_year_input.replace(year=now.year + 1) else: return curr_year_input def parse_iso_pretty(date_iso): """ PArse iso-like date to human-like :param date_iso: date in iso-like format :return: human-like formated date like "DAY MONTH" """ return date_iso.strftime('%d %b %Y') def get_first_weekday(month, year): """ Get first weekday of this month :param month: month to show :param year: year to show :return: int value [1..7] """ string_date = str(month) + str(year) date_datetime = datetime.strptime('1' + string_date, '%d%m%Y') return date_datetime.weekday() + 1 def get_month_number(str_month): months = ( 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ) return months.index(str_month[:3].lower()) + 1 def get_month_word(number): months = ( 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' ) return months[number - 1] def get_weekday_number(str_weekday): """ Using name of weekday return its number representation :param str_weekday: weekday from mon - sun :return: integer number [0..7] """ weekdays = ( 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun' ) return weekdays.index(str_weekday[:3].lower()) def get_weekday_word(number): """ Using weekday index return its word representation :param number: number of weekday [0..6] :return: word representation """ weekdays = ( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ) return weekdays[number] def parse_period(period_type, period_value): """ parse entered period in period what can understand "plan" :param period_type: type of periodic :param period_value: date of period :return: dict of readable for plan data for creating tasks """ parsed = {'period': None, 'type': None} if period_type == 'day': parsed['period'] = {'day': int(period_value)} parsed['type'] = Constants.REPEAT_DAY elif period_type == 'week': weekdays_list = period_value.strip().split() weekdays_digits_list = [get_weekday_number(day) for day in weekdays_list] parsed['period'] = {'days': list(set(weekdays_digits_list))} parsed['type'] = Constants.REPEAT_WEEKDAY elif period_type == 'month': period_value = period_value.strip().split() month_list = period_value[1:] month_digits_list = [get_month_number(month) for month in month_list] parsed['period'] = { 'months': list(set(month_digits_list)), 'day': int(period_value[0]) } parsed['type'] = Constants.REPEAT_MONTH elif period_type == 'year': period_value = period_value.strip().split() parsed['type'] = Constants.REPEAT_YEAR parsed['period'] = { 'day': int(period_value[0]), 'month': get_month_number(period_value[1]) } return parsed['type'], parsed['period'] def parse_time(string_time): """ Parse time for plans. :param string_time: time in format HH:MM or only HH :return: depending on param return dict with type and value of time """ hm_time = {'hour': None, 'minutes': None, 'with_minutes': None } if ':' in string_time: hm_time['hour'] = int(string_time.split(':')[0]) hm_time['minutes'] = int(string_time.split(':')[1]) hm_time['with_minutes'] = True if hm_time['hour'] > 24 or hm_time['hour'] < 0 or hm_time['minutes'] > 60 or hm_time['minutes'] < 0: raise ValueError else: hm_time['hour'] = int(string_time) hm_time['with_minutes'] = False return hm_time def parse_remind_type(string_type): if string_type == 'min': return Constants.REMIND_MINUTES elif string_type == 'hour': return Constants.REMIND_HOURS elif string_type == 'day': return Constants.REMIND_DAYS else: return Constants.REMIND_MONTHS
""" A set is an unordered collection of items. Every set element is unique (no duplicates) Creating Python Sets A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function. """ # Different types of sets in Python # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) # set cannot have duplicates # Output: {1, 2, 3, 4} my_set = {1, 2, 3, 4, 3, 2} print(my_set) # we can make set from a list # Output: {1, 2, 3} my_set = set([1, 2, 3, 2]) print(my_set) # initialize a with set() a = set() print(type(a)) # initialize my_set my_set = {1, 3} print(my_set) # my_set[0] # if you uncomment the above line # you will get an error # TypeError: 'set' object does not support indexing # add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) # add multiple elements # Output: {1, 2, 3, 4} my_set.update([2, 3, 4]) print(my_set) # add list and set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4, 5], {1, 6, 8}) print(my_set) # Difference between discard() and remove() # initialize my_set my_set = {1, 3, 4, 5, 6} print(my_set) # discard an element # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # remove an element # Output: {1, 3, 5} my_set.remove(6) print(my_set) # discard an element # not present in my_set # Output: {1, 3, 5} my_set.discard(2) print(my_set) # remove an element # not present in my_set # you will get an error. # Output: KeyError #my_set.remove(2) # initialize my_set # Output: set of unique elements my_set = set("HelloWorld") print(my_set) # pop an element # Output: random element print(my_set.pop()) # pop another element my_set.pop() print(my_set) # clear my_set # Output: set() my_set.clear() print(my_set) print(my_set) # Set union method # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B) # use union function A.union(B) #{1, 2, 3, 4, 5, 6, 7, 8} # use union function on B B.union(A) #{1, 2, 3, 4, 5, 6, 7, 8} # Intersection of sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use & operator # Output: {4, 5} print(A & B) # use intersection function on A print(A.intersection(B)) #{4, 5} # use intersection function on B print(B.intersection(A)) #{4, 5} # Difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A # Output: {1, 2, 3} print(A - B) # use difference function on A print(A.difference(B)) #{1, 2, 3} # use - operator on B print(B - A) #{8, 6, 7} # use difference function on B print(B.difference(A)) #{8, 6, 7} # Symmetric difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use ^ operator # Output: {1, 2, 3, 6, 7, 8} print(A ^ B) # use symmetric_difference function on A print(A.symmetric_difference(B)) #{1, 2, 3, 6, 7, 8} # use symmetric_difference function on B print(B.symmetric_difference(A)) #{1, 2, 3, 6, 7, 8}
my_string = 'Hello' print(my_string) my_string1 = "Hello" print(my_string1) my_string = """ Hello, welcome to the world of Python Thank You """ print(my_string) print('What\'s there') name = "nazmul haque" print(name.title()) print(name.upper()) print(name.lower()) first_name = "Akbar" last_name = "ali" full_name = first_name + " " + last_name print(full_name) print("Hello, " + full_name.title() + "!") favorite_language = ' python ' print(favorite_language.lstrip())
##Decimal to Binary # from collections import deque # s=input() # if(s[::1]==s[::-1]): # print("Palindrome") # else: # print("Not") # def dividBy2(n): # s="" # while(n>0): # s=s+(str(n%2)) # n=n//2 # print(s) # print(s[::-1]) # dividBy2(30) ############################################################# ##TowerOfHanoi # def listsum(numList): # if len(numList) == 1: # return numList[0] # else: # return numList[0] + listsum(numList[1:]) # print(listsum([1,3,5,7,9])) # def moveTower(height,fromT,toT,withT): # if height>=1: # moveTower(height-1,fromT,withT,toT) # moveDisk(fromT,toT) # moveTower(height-1,withT,toT,fromT) # def moveDisk(fp,tp): # print(fp,"->",tp,end="\n") # moveTower(12,"A","B","C") ############################################################# ##MinNumberOfCoinsForGivenDenominations # import sys # def minCoins(coins,V): # if(V==0): # return 0 # res=sys.maxsize # for i in coins: # if(i<=V): # sub_res=minCoins(coins,V-i) # print(sub_res) # if(sub_res + 1 < res): # res=sub_res+1 # #print(res) # return res # coins=[10,20] # V=200 # print(minCoins(coins,V)) ############################################################# # def pascal_triangle(n): # trow = [1] # y = [0] # for x in range(n): # print(trow) # print(list(zip(trow+y,y+trow))) # trow=[l+r for l,r in zip(trow+y, y+trow)] # pascal_triangle(6) ############################################################# ##Knapsack # from collections import deque # weight=[2,3,4,5,9] # value=[3,4,8,8,10] # per_item_val=deque([i/j for i,j in zip(weight,value)]) # print(per_item_val) # w=20 # new_w=0 # val=0 # while(new_w<=w): # i=per_item_val.index(max(per_item_val)) # print(i) # per_item_val[i]=0 # new_w=new_w+weight[i] # if(new_w<=w): # val=val+value[i] # else: # break # print(val) ############################################################# ##BinarySearch # def binarySearch(alist,el): # mid=len(alist)//2 # if len(alist)==0: # return False # else: # if(alist[mid]==el): # return True # if(el>alist[mid]): # return binarySearch(alist[mid:],el) # else: # return binarySearch(alist[:mid],el) # a=[1,2,3,4,6,7,9] # print(binarySearch(a,6)) # print(binarySearch(a,0)) #############################################################
class Sudoku: def __init__(self, grid): self.grid = grid # 9x9 matrix with 0s for empty cells def __init__(self): # 9x9 matrix with 0s for empty cells self.grid = [[0 for c in range(9)] for r in range(9)] def at(self, row, col): res = self.grid[row][col] return res if res > 0 else None def set(self, row, col, value): self.grid[row][col] = value def reset(self, row, col): self.grid[row][col] = 0 def valid_digits(self, row, col): if self.at(row, col): return [self.at(row, col)] from itertools import chain used_digs = chain(self.row(row), self.column(col), self.square(row, col)) used_digs = set(used_digs) return [dig for dig in range(1, 10) if dig not in used_digs] def row(self, row): return self.grid[row] def column(self, col): return (row[col] for row in self.grid) def square(self, row, col): sr = 3 * (row // 3) sc = 3 * (col // 3) return (dig for row in self.grid[sr:sr+3] \ for dig in row[sc:sc+3]) def read_stdin(self): self.grid = [] for i in range(9): row = [int(x) for x in input().split()] self.grid.append(row) def __str__(self): lines = [] sep_row = ('+' + ('-' * (3 + 4)) ) * 3 + '+' lines.append(sep_row) for i, row in enumerate(self.grid): chars = ['|'] for j in range(3): chars.extend(str(d) if d > 0 else ' ' for d in row[3*j:3*j+3]) chars.append('|') lines.append(' '.join(chars)) if i % 3 == 2: lines.append(sep_row) return '\n'.join(lines) def solve(self): return self._solve_at(0, 0) def _solve_at(self, row, col): if row == 9: return True # reached the end done next_row, next_col = self._next_cell(row, col) if self.at(row, col): # skip filled cells return self._solve_at(next_row, next_col) else: valid_digits = self.valid_digits(row, col) if not valid_digits: return False for dig in valid_digits: self.set(row, col, dig) if self._solve_at(next_row, next_col): return True self.reset(row, col) return False @staticmethod def _next_cell(row, col): if col == 8: return row + 1, 0 return row, col + 1
def is_prime(a): if a == 1: return False for d in range(2,a): if a%d == 0: return False return True a = int(input('Число: ')) if is_prime(a) == True: print('Простое') else: print('не простое')
name = 'Jessie' def hop(start, stop, step): """ Creates a list of numbers from start and with steps :param start: starting number of the list :param step: number of steps to the next number in the list :return: list """ return [i for i in range(start,stop,step)]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Implement a single-linked list. Usage: $ python singly_linked_list.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function class Node(object): """Class to implement a node in a singly-linked list.""" def __init__(self, data): self.data = data self.next = None def __repr__(self): """Returns string representation of the node.""" return repr(self.data) class SingleLinkedList(object): """Class to implement a singly-linked list.""" def __init__(self): self.head = None def __repr__(self): """Returns a string representation of the linked list.""" nodes = [] current = self.head while current: nodes.append(repr(current)) current = current.next return '[' + ','.join(nodes) + ']' def append(self, data): """Appends a new node at the end of the linked list. Args: data: element for the new node. """ new_node = Node(data) if not self.head: self.head = new_node return last_node = self.head while last_node.next: last_node = last_node.next last_node.next = new_node def prepend(self, data): """Prepends a new node to the beginning of the linked list. Args: data: element for the new node. """ new_node = Node(data) new_node.next = self.head self.head = new_node def find(self, data): """Returns index of the node in the linked list for the given element. Args: data: element to find in the linked list. Returns: integer index of the node or -1 if the element doesn't exists in the linked list. """ index = 0 current = self.head while current: if current.data == data: return index index += 1 current = current.next return -1 def insert(self, data, index): """Insert a new node in the linked list at the given index. Args: data: element for the new node. index: position of the new node. """ if index == 0: self.prepend(data) return current_index = 0 current = self.head previous = None while current or previous: if current_index == index: new_node = Node(data) new_node.next = current previous.next = new_node break previous = current current = current.next current_index += 1 def delete(self, index): """Deletes the node at the given index. Args: index: index of the node to be removed from the linked list. """ if index == 0 and self.head is not None: self.head = self.head.next return current_index = 0 current = self.head previous = None while current: if current_index == index: previous.next = current.next previous = current current = current.next current_index += 1 if __name__ == '__main__': arr = [3, 5, 7] linked_list = SingleLinkedList() for element in arr: linked_list.append(element) print('After appending:', linked_list) linked_list.prepend(1) print('After prepending', linked_list) print('Find 1:', linked_list.find(1)) print('Find 7:', linked_list.find(7)) print('Find 9:', linked_list.find(9)) linked_list.insert(2, 1) print('After inserting:', linked_list) linked_list.insert(0, 0) print('After inserting:', linked_list) linked_list.insert(9, 6) print('After inserting:', linked_list) linked_list.delete(2) print('After deleting:', linked_list) linked_list.delete(0) print('After deleting:', linked_list) linked_list.delete(4) print('After deleting:', linked_list)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Converts decimal numbers (both integer and real) to binary. Usage: $ python decimal_to_binary.py <decimal_input> Example: $ python decimal_to_binary.py 1901 11101101101 $ python decimal_to_binary.py 3.75 11.11 $ python decimal_to_binary.py 0.6640625 0.10101 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys def convert_integer_with_recursion(decimal): """Converts an integer's representation from decimal to binary. It uses the division method to convert using recursive calls to itself. Args: decimal: integer decimal number. Returns: binary integer as string. """ binary = '' # convert any value greater than 1 to binary. if decimal > 1: # call the current function recursively with the floor division result. binary += convert_integer_with_recursion(decimal // 2) # add denominator of the decimal divided by 2 to the result. # this step comes after the recursive call because while converting # decimal to binary with division method the results are read backwards. binary += str(decimal % 2) return str(binary) # Else return the decimal, since binaries 0 and 1 have the same value in # decimals. return str(decimal) def convert_integer_with_loops(decimal): """Converts a decimal integer to binary. It uses the division method to convert using while loops. Args: decimal: integer decimal number Returns: binary integer as string """ result = '' # iterate until the remaining value is less than the base, 2. while decimal > 1: # the binary value is the denominator of decimal divided by 2. val = decimal % 2 # append the value to the result string. result += str(val) # update the decimal value to the floor division value for next iteration. decimal //= 2 # when the decimal becomes less than 2, append it to the result string. result += str(decimal) # since in the division method the denominators are read in the reverse order # of their generation. # reverse the result string. return result[::-1] def convert_fraction(fraction): """Converts the fractional part of a decimal number to binary. We convert a decimal fraction to binary by iteratively multiplying it by 2 and appending the integer part to the result after taking it out of the multiplication result. The iteration continues until the decimal becomes 1.0 or until we have iterated for a sufficient number of times since not all numbers will lead to 1.0 after continuous multiplication. Args: fraction: a float decimal number. Returns: fractional part of the decimal as string. """ result = '' iteration = 0 # iterate until the fraction becomes 1.0 or we have converted upto 5 decimal # points. while fraction != 1.0 and fraction != 0.0 and iteration < 5: # multiply fraction with the base, 2. fraction *= 2 # append integer part of the fraction to the result. result += str(int(fraction)) # subtract integer part of the fraction. fraction -= int(fraction) iteration += 1 return result if __name__ == '__main__': if len(sys.argv) < 2: raise ValueError('No decimal argument found') # validate if the argument is a valid number by converting it to float. # it will always update the arg to a float string. arg = str(float(sys.argv[1])) # split integer and fractional parts. arg_split = arg.split('.') # convert decimal to binary using loops. result1 = convert_integer_with_loops( int(arg_split[0])) if arg_split[0] else '0' if arg_split[1] and arg_split[1] != '0': result1 += '.' + convert_fraction(float('0.' + arg_split[1])) print(result1) # convert decimal to binary using recursion. result2 = convert_integer_with_recursion( int(arg_split[0])) if arg_split[0] else '0' if arg_split[1] and arg_split[1] != '0': result2 += '.' + convert_fraction(float('0.' + arg_split[1])) print(result2)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Implementing insertion sort. Insertion sort operates this O(n^2) time complexity on worst case. Insertion sort can be divided in two repeatitive steps. 1. Iterating over each element in the array to place it in its proper position. 2. Moving elements to the right while placing the element to its position. Step one will be performed for every element in the array, hence its time complexity is O(n). Worst case for insertion sort in where the array is already sorted in reverse. For worst case, in step two, the number of elements to be moved will increase every time we read a new element. When reading the first element, 0 elements would have to be moved. For the second element, 1 element will me moved and so on. Total number of elements moved in worst case for an array of length n is: 0 + 1 + 2 + 3 + .... + (n-1) = n(n - 1)/2 = (n^2 - n)/2 Since it is a second order polynomial equation, the time complexity is O(n^2). Since we only consider the highest order when calculating complexities, the time complexity in worst case is O(n^2). Best case for insertion sort is where the array is already sorted. In best case, in step two, no movement will ever be needed. So step two can be disregarded. Hence, best case time complexity for insertion sort is O(n). Usage: $ python insertion_sort.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function def insertion_sort(arr): """Sorts an integer array using insertion sort.""" # Read every element in the array to put it in its proper position in the # sorted array on the left. for reader_index in range(len(arr)): reader_value = arr[reader_index] # Loop in reverse in the sorted array on the left. i = reader_index - 1 while i >= 0 and arr[i] >= reader_value: # Move all elements greater than the read element one place to the right. arr[i + 1] = arr[i] i -= 1 # Place the read element at the position of the last element larger than it # or at the beginning of the array if all elements were larger than it. arr[i + 1] = reader_value if __name__ == '__main__': test_cases = [ { 'input': [], 'output': [], }, { 'input': [2], 'output': [2], }, { 'input': [2, 2], 'output': [2, 2], }, { 'input': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'output': [1, 2, 3, 4, 5, 6, 7, 8, 9], }, { 'input': [1, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9], 'output': [1, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9], }, { 'input': [9, 8, 7, 6, 5, 4, 3, 2, 1], 'output': [1, 2, 3, 4, 5, 6, 7, 8, 9], }, { 'input': [9, 8, 7, 6, 5, 4, 3, 3, 2, 2, 1], 'output': [1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9], }, { 'input': [-1, -2, -3, -4, -5, -6, -7, -8, -9], 'output': [-9, -8, -7, -6, -5, -4, -3, -2, -1], }, { 'input': [-1, -2, -3, -3, -4, -5, -6, -7, -8, -9], 'output': [-9, -8, -7, -6, -5, -4, -3, -3, -2, -1], }, { 'input': [9, 7, 5, 3, 1, 2, 4, 6, 8], 'output': [1, 2, 3, 4, 5, 6, 7, 8, 9], }, { 'input': [1, 9, 2, 8, 3, 7, 4, 6, 5], 'output': [1, 2, 3, 4, 5, 6, 7, 8, 9], }, { 'input': [1, 9, 2, -8, 3, 7, -4, 6, -5], 'output': [-8, -5, -4, 1, 2, 3, 6, 7, 9], }, ] for test_case in test_cases: print(test_case) insertion_sort(test_case['input']) assert test_case['input'] == test_case['output']
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """Design a system for a parking lot. Assuming there are four sizes of slots in the parking lot for four different sizes of vehicles. If no empty slot can be found for a vehicle's size, the vehicle can be upgraded to a larger size slot. Even if an instance of ParkingLot class is created at each of the multiple entry/exit point of the parking lot, they should all be looking at the same slot and vehicle data. Usage: $ python parking_lot.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import random import time from enum import Enum class Size(Enum): """Enum to hold sizes in the system.""" small = 1 medium = 2 large = 3 extra_large = 4 class Queue(object): """Class to implement a basic FIFO queue.""" def __init__(self): self.queue = [] def __iter__(self): """Implementing the iter magic method to make Queue iterable.""" return iter(self.queue) def Push(self, ele): """Adds an element to the queue. Args: ele: Element to add to the queue. """ self.queue.append(ele) def Pop(self): """Removes an element from the queue. Returns: The oldest element in the queue or None if the queue is empty. """ if not self.queue: return None ele = self.queue[0] self.queue = self.queue[1:] return ele class Vehicle(object): """Class to encapsulate a vehicle's properties.""" def __init__(self, license_plate, size): self.license_plate = license_plate self.size = size self.slot = None class Slot(object): """Class to encapsulate a parking slot's properties.""" def __init__(self, number, size): self.number = number self.size = size self.occupied = False self.occupied_at = None self.vehicle = None class ParkingLot(object): """Class to encapsulate and implement a parking lot.""" # Flag to signify if the class variables have already been initialized while # creating a previous instance of the class. initialized = False # Holds instances of slots in a dict against their sizes. slots = {} # Dictionary to hold objects of vehicles parked in the parking lot against # license plate numbers. vehicles = {} # Hourly parking charges for each slot size. charges = { Size.small.name: 10, Size.medium.name: 15, Size.large.name: 20, Size.extra_large.name: 25, } # Total money collected from parking charges. collection = 0 def __init__(self): # Do not reinitialize slots if they already have been initialized. if not type(self).initialized: self._InitSlots() def _InitSlots(self): """Initialize parking slots. Creates slot instances for different slot sizes and stores them as a Queue in the slots dictionary class variable against there size. """ type(self).slots[Size.small.name] = Queue() for i in range(50): type(self).slots[Size.small.name].Push(Slot(i, Size.small)) type(self).slots[Size.medium.name] = Queue() for i in range(50, 100): type(self).slots[Size.medium.name].Push(Slot(i, Size.medium)) type(self).slots[Size.large.name] = Queue() for i in range(100, 150): type(self).slots[Size.large.name].Push(Slot(i, Size.large)) type(self).slots[Size.extra_large.name] = Queue() for i in range(150, 200): type(self).slots[Size.extra_large.name].Push(Slot(i, Size.extra_large)) # Set initialized to True once initialization is complete. type(self).initialized = True def _GetEmptySlot(self, size): """Returns an appropriate empty slot for a vehicle size. If no slots of a size are empty, a slot of a higher size is returned. Args: size: Size of the vehicle. Returns: A Slot object or None. """ current_slot_size = size # Fetch Queue of empty slots for the current slot size. slots_queue = type(self).slots[current_slot_size.name] # Keep looping until a queue of slots exist. while slots_queue: # Fetch a slot from the queue and return it. slot = slots_queue.Pop() if slot: return slot # If an empty slot of the required size does not exists, determine a # higher slot size. new_slot_value = current_slot_size.value + 1 # If a queue of empty slots for the higher slot size doesn't exists, # return None. if Size(new_slot_value).name not in self.slots: return None # If a queue of empty slots for the higher slot size exists, set it in a # variable to loop again. slots_queue = type(self).slots[Size(new_slot_value).name] def _CalculateCharges(self, vehicle): """Calculates parking charges to be paid. Args: vehicle: Vehicle object of the vehicle to calculate charges for. Returns: Parking charge to be paid. """ slot = vehicle.slot exit_time = (time.time()) duration_in_seconds = exit_time - slot.occupied_at duration_in_hours = math.ceil(duration_in_seconds / 3600) return type(self).charges[vehicle.size.name] * duration_in_hours def ParkVehicle(self, license_plate, size): """Parks a vehicle in the parking lot. Args: license_plate: License plate number of the vehicle. size: Size enum value for the vehicle's size. Returns: True if the vehicle is parked else False. """ # Return if a vehicle with the given license plate number is already # parked. if license_plate in type(self).vehicles: return False vehicle = Vehicle(license_plate, size) # Search an empty slot for the vehicle. slot = self._GetEmptySlot(vehicle.size) # Return if no slot is found. if not slot: return False # Update slot to mark it occupied. slot.occupied = True slot.occupied_at = int(time.time()) slot.vehicle = vehicle # Add slot to the vehicle object. vehicle.slot = slot # Add vehicle to the vehicles dictionary class variable. type(self).vehicles[vehicle.license_plate] = vehicle return True def ExitVehicle(self, license_plate): """Exits a vehicle from the parking lot. Args: license_plate: License plate number of the vehicle to be exited. Returns: True if the vehicle is exited else False. """ # Check if the vehicle with license plate number is parked in the lot. vehicle = type(self).vehicles.pop(license_plate, None) if not vehicle: return False # Collect parking charges. type(self).collection += self._CalculateCharges(vehicle) # Mark slot as empty. vehicle.slot.occupied_at = None vehicle.slot.vehicle = None vehicle.slot.occupied = False # Add slot to the appropriate empty slots Queue in the class variable. type(self).slots[vehicle.slot.size.name].Push(vehicle.slot) return True def DisplayStats(self): """Prints the current count of empty slots and parking charges collected.""" small = len([ True for slot in type(self).slots[Size.small.name] if not slot.occupied ]) medium = len([ True for slot in type(self).slots[Size.medium.name] if not slot.occupied ]) large = len([ True for slot in type(self).slots[Size.large.name] if not slot.occupied ]) extra_large = len([ True for slot in type(self).slots[Size.extra_large.name] if not slot.occupied ]) print('S:', small, 'M:', medium, 'L:', large, 'XL:', extra_large, 'Total:', small + medium + large + extra_large, 'Collections:', type(self).collection) if __name__ == '__main__': parking_lot = ParkingLot() # Randomly park and exit vehicles. for _ in range(500): if random.randint(0, 1) == 0: # Exit vehicle. exited = parking_lot.ExitVehicle(str(random.randint(1, 50))) if exited: parking_lot.DisplayStats() else: # Park vehicle. parked = parking_lot.ParkVehicle( str(random.randint(1, 50)), Size(random.randint(1, 4))) if parked: parking_lot.DisplayStats()
import re # regular expressions import sqlite3 # This is a base class for objects that represent database items. It # implements # the store() method in terms of fetch_id and do_store, which need to be # implemented in every derived class (see Person below for an example). class DBItem: def __init__(self, conn): self.id = None self.cursor = conn.cursor() def store(self): self.fetch_id() if (self.id is None): self.do_store() self.cursor.execute("select last_insert_rowid()") self.id = self.cursor.fetchone()[0] # Example of a class which represents a single row of a single database table. # This is a very simple example, since it does not contain any references to # other objects. class Person(DBItem): def __init__(self, conn, string): super().__init__(conn) self.born = self.died = None self.name = re.sub('\([0-9/+-]+\)', '', string).strip() # NB. The code below was part of the exercise (extracting years of # birth & death # from the string). m = re.search("([0-9]+)--([0-9]+)", string) if not m is None: self.born = int(m.group(1)) self.died = int(m.group(2)) # TODO: Update born/died if the name is already present but has null values # for # those fields. We assume that names are unique (not entirely true in # practice). def fetch_id(self): self.cursor.execute("select * from person where name = ?", (self.name,)) res = self.cursor.fetchone() # NB. The below lines had a bug in the original version of # scorelib-import.py (which however only becomes relevant when you # start implementing the Score class). res = self.cursor.fetchone() if not res is None: # TODO born/died update should be done inside this if self.id = res[0] mod = False if res[1] is None: mod = True if res[2] is None: mod = True if mod: self.do_update() def do_update(self): self.cursor.execute("update person set born = ?, died = ? where name = ?", (self.born, self.died, self.name)) def do_store(self): print("storing '%s'" % self.name) # NB. Part of the exercise was adding the born/died columns to the # below query. self.cursor.execute("insert into person (name, born, died) values (?, ?, ?)", (self.name, self.born, self.died)) class Score(DBItem): def __init__(self, conn, string): super().__init__(conn) spl = string.split("<->") self.genre = spl[0].strip() self.key = spl[1].strip() self.incipit = spl[2].strip() self.year = spl[3].strip() self.authors = [] for c in spl[4].split(';'): p = Person(conn, c.strip()) p.store() self.authors.append(p.id) def fetch_id(self): self.cursor.execute("select * from score where genre=? and key=? and incipit=? and year=?", (self.genre, self.key, self.incipit, self.year)) res = self.cursor.fetchone() if not res is None: self.id = res[0] def do_update(self): self.cursor.execute("update score set genre = ?, key = ?, incipit = ?, year = ?", (self.genre, self.key, self.incipit, self.year)) def do_store(self): self.cursor.execute("insert into score (genre, key, incipit, year) values (?, ?, ?, ?)", (self.genre, self.key, self.incipit, self.year)) class Voice(DBItem): def __init__(self, conn, string): super().__init__(conn) spl = string.split(",") self.number = spl[0].strip() self.score = spl[1].strip() self.name = spl[2].strip() def fetch_id(self): self.cursor.execute("select * from voice where number = ? and score = ? and name = ?", (self.number, self.score, self.name)) res = self.cursor.fetchone() if not res is None: self.id = res[0] def do_update(self): self.cursor.execute("update voice set number=?, score=?, name=?", (self.number, self.score, self.name)) def do_store(self): self.cursor.execute("insert into voice (number, score, name) values (?, ?, ?)", (self.number, self.score, self.name)) class Edition(DBItem): def __init__(self, conn, string): super().__init__(conn) spl = string.split(",") self.score = spl[0].strip() self.name = spl[1].strip() self.year = spl[2].strip() def fetch_id(self): self.cursor.execute("select id from edition where score = ? and name = ? and year = ?", (self.score, self.name, self.year)) res = self.cursor.fetchone() if not res is None: self.id = res[0] def do_update(self): self.cursor.execute("update edition set score = ?, name = ?, year = ?", (self.score, self.name, self.year)) def do_store(self): self.cursor.execute("insert into edition (score, name, year) values (?, ?, ?)", (self.score, self.name, self.year)) class Score_Author(DBItem): def __init__(self, conn, string): super().__init__(conn) spl = string.split(",") self.score = spl[0].strip() self.composer = spl[1].strip() def fetch_id(self): self.cursor.execute("select * from score_author where score = ? and composer = ?", (self.score, self.composer)) res = self.cursor.fetchone() if not res is None: self.id = res[0] def do_update(self): self.cursor.execute("update score_author set score=?, composer=?", (self.score, self.composer)) def do_store(self): self.cursor.execute("insert into score_author (score, composer) values (?, ?)", (self.score, self.composer)) class Edition_Author(DBItem): def __init__(self, conn, string): super().__init__(conn) spl = string.split(",") self.edition = spl[0].strip() self.editor = spl[1].strip() def fetch_id(self): self.cursor.execute("select * from edition_author where edition = ? and editor = ?", (self.edition, self.editor)) res = self.cursor.fetchone() if not res is None: self.id = res[0] def do_update(self): self.cursor.execute("update edition_author set edition=?, editor=?", (self.edition, self.editor)) def do_store(self): self.cursor.execute("insert into edition_author (edition, editor) values (?, ?)", (self.edition, self.editor)) class Print(DBItem): def __init__(self, conn, string): super().__init__(conn) spl = string.split(",") self.num = spl[0].strip() self.partiture = self.get_partiture(spl[1].strip()) self.edition = spl[2].strip() def get_partiture(self, string): if string == "yes": return 'Y' if string == "no": return 'N' return 'P' def fetch_id(self): self.cursor.execute("select id from print where id=?", (self.num,)) res = self.cursor.fetchone() if not res is None: self.id = res[0] def do_update(self): self.cursor.execute("update print set partiture=?, edition=?", (self.pariture, self.edition)) def do_store(self): self.cursor.execute("insert into print (partiture, edition) values (?, ?)", (self.partiture, self.edition)) # NB. Everything below this line was part of the exercise. # Process a single line of input. def process(k, v): if k == 'Composer': for c in v.split(';'): p = Person(conn, c.strip()) p.store() def processScore(scoredata): scorestring = str(scoredata['Genre']) + "<->" + str(scoredata['Key']) + "<->" + str(scoredata['Incipit']) + "<->" + str(scoredata['Composition Year']) + "<->" + str(scoredata['Composer']) score = Score(conn, scorestring) score.store() for composer in scoredata['Composer'].split(';'): person = Person(conn, composer.strip()) person.store() for author in score.authors: scoreautorstring = str(score.id) + ", " + str(author) scoreauthor = Score_Author(conn, scoreautorstring) scoreauthor.store() if('Editor' in scoredata): editor = Person(conn, scoredata['Editor']) editor.store() editionstring = str(score.id) + ", " + str(scoredata['Edition']) + ", " + str(scoredata['Publication Year']) edition = Edition(conn, editionstring) edition.store() editionauthorstring = str(edition.id) + ", " + str(edition.id) editionauthor = Edition_Author(conn, editionauthorstring) editionauthor.store() vrx = re.compile(r"Voice ([0-9]*)") for k,v in scoredata.items(): if vrx.match(k): voicestr = str(vrx.match(k).group(1)) + ", " + str(score.id) + ", " + str(v) vc = Voice(conn, voicestr) vc.store() printstring = str(scoredata['Print Number'] + ", " + scoredata['Partiture'] + ", " + scoredata['Edition']) print = Print(conn, printstring) print.store() # Database initialisation: sqlite3 scorelib.dat ".read scorelib.sql" conn = sqlite3.connect('scorelib.dat') rx = re.compile(r"([^:]*):(.*)") rxend = re.compile(r"^\s*$") scoredata = {} for line in open('scorelib.txt', 'r', encoding='utf-8'): if rxend.match(line): if(scoredata): processScore(scoredata) scoredata = {} continue m = rx.search(line) if m is None: continue else: scoredata[m.group(1)] = m.group(2) conn.commit()
import tensorflow as tf # A tensor variable with initial value [2.5, 4] b1 = tf.Variable([2.5, 4], tf.float32, name='var_b1') # Placeholders can hold tensors of any shape, if shape is not specified x = tf.placeholder(tf.float32, name='x') b0 = tf.Variable([5.0, 10.0], tf.float32, name='b0') y = b1 * x + b0 # Make the session, explicitly initialize variables # init is another computational node which needs to be executed to initialize variables init = tf.global_variables_initializer() bx = tf.multiply(b1, x, name='bx') y_ = tf.subtract(x, b0, name='y_') with tf.Session() as sess: # to initialize the variables, we will first execute the init node sess.run(init) print("Final result ", sess.run(y, feed_dict={x: [10, 100]})) # Initialize single variable, rather than all the variables in the program # s = b1 * x # init = tf.variable_initializer([W]) # sess.run(init) # Assigning a new value to a variable # result is a computation node just like any other node and can be run using sess.run(result) number = tf.Variable(2) multiplier = tf.Variable(4) result = number.assign(tf.multiply(number, multiplier)) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(10): print("Ans = ", sess.run(result)) print("New multiplier = ", sess.run(multiplier.assign_add(1))) writer = tf.summary.FileWriter('./m3_example3', sess.graph) writer.close()
def quiz(p, q): if p == False: return False elif q == False: return False else: return True print quiz(True, True) print quiz(True, False) print quiz(False, True) print quiz(False, False) print '------------' p, q = True, True print p and q p, q = True, False print p and q p, q = False, True print p and q p, q = False, False print p and q print p, q = True, True print p or q p, q = True, False print p or q p, q = False, True print p or q p, q = False, False print p or q print p, q = True, True print p and (not q) p, q = True, False print p and (not q) p, q = False, True print p and (not q) p, q = False, False print p and (not q) print p, q = True, True print (not p) and (not q) p, q = True, False print (not p) and (not q) p, q = False, True print (not p) and (not q) p, q = False, False print (not p) and (not q)
# "Stopwatch: The Game" # Create an event-driven & interactive # stop-watch game # script author: pk # written 2016/04/16, change line 56 on 04/19 removed one global call in def timer_stop() # -------------------------------------------------- # - import(s) import simplegui # - global binding(s) total_ticks = 0 timer_stopped = True num_stops = 0 num_stops_on_even = 0 # - define helper function(s) def format_time(): ''' formats tenths of seconds into minutes:seconds.tenths, e.g. 15 minutes, 2 seconds and 3-tenths of a second will display as 15:02.3 ''' global tenths_seconds time_in_seconds = total_ticks / 10 minutes = time_in_seconds // 60 seconds = time_in_seconds % 60 tens_seconds = seconds // 10 ones_seconds = seconds % 10 tenths_seconds = str(total_ticks)[-1] return str(minutes) + ':' + str(tens_seconds) + \ str(ones_seconds) + '.' + tenths_seconds def format_stop_compare(): ''' formats the counters for the number of total stops and the number of stops on m:ss.0 ''' global num_stops global num_stops_on_even return str(num_stops_on_even) + '/' + str(num_stops) # - define event handlers for button(s) def timer_start(): ''' starts the timer ''' global timer_stopped timer_stopped = False timer.start() def timer_stop(): ''' stops the timer ''' timer.stop() global num_stops global num_stops_on_even global timer_stopped if timer_stopped == False: timer_stopped = True num_stops +=1 if total_ticks % 10 == 0: num_stops_on_even +=1 def timer_reset(): ''' resets timer to 0:00.0 ''' timer.stop() global total_ticks global num_stops global num_stops_on_even total_ticks = 0 num_stops = 0 num_stops_on_even = 0 # - define event handler for timer(s) def timer_handler(): ''' increments a counter every 1/10th of a second ''' global total_ticks total_ticks +=1 # - define draw handler(s) def draw_handler(canvas): ''' draws formatted time and stop-counter to canvas ''' canvas.draw_text(format_time(), [40, 80], 30, 'green') canvas.draw_text(format_stop_compare(), [110, 25], 20, 'red') # - create frame frame = simplegui.create_frame('Stop Watch!', 150, 150) # - register event handler(s) button_start = frame.add_button('Start', timer_start, 50) button_stop = frame.add_button('Stop', timer_stop, 50) button_reset = frame.add_button('Reset', timer_reset, 50) timer = simplegui.create_timer(100, timer_handler) frame.set_draw_handler(draw_handler) # - start frame frame.start()
""" #- "Zombie Apocalypse" by pdk #- For Coursera: Rice U. Principles of Computing pt.2 #---#----1----#----2----#----3----#----4----#----5----#----6----#----7-2--#----8----#----91234567100 """ import random import poc_grid import poc_queue import poc_zombie_gui EMPTY = 0 FULL = 1 FOUR_WAY = 0 EIGHT_WAY = 1 OBSTACLE = 5 HUMAN = 6 ZOMBIE = 7 class Apocalypse(poc_grid.Grid): """ zombie pursuit of human on grid with obstacles """ def __init__(self, grid_height, grid_width, obstacle_list = None, zombie_list = None, human_list = None): """ Simulation of given size with given obstacles, humans, and zombies """ self._grid_width = grid_width self._grid_height = grid_height poc_grid.Grid.__init__(self, grid_height, grid_width) if obstacle_list is not None: for cell in obstacle_list: self.set_full(cell[0], cell[1]) if zombie_list is not None: self._zombie_list = list(zombie_list) else: self._zombie_list = [] if human_list is not None: self._human_list = list(human_list) else: self._human_list = [] def clear(self): """ Set cells in obstacle grid to be empty Reset zombie and human lists to be empty """ poc_grid.Grid.clear(self) self._zombie_list = [] self._human_list = [] def add_zombie(self, row, col): """ Add zombie to the zombie list """ self._zombie_list.append((row, col)) def num_zombies(self): """ Return number of zombies """ return len(self._zombie_list) def zombies(self): """ Generator that yields the zombies in the order they were added. """ for zombie in self._zombie_list: yield zombie def add_human(self, row, col): """ Add human to the human list """ self._human_list.append((row, col)) def num_humans(self): """ Return number of humans """ return len(self._human_list) def humans(self): """ Generator that yields the humans in the order they were added. """ for human in self._human_list: yield human def compute_distance_field(self, entity_type): """ Function computes and returns a 2D distance field Distance at member of entity_list is zero Shortest paths avoid obstacles and use four-way distances """ visited = poc_grid.Grid(self._grid_height, self._grid_width) max_dist = self._grid_width * self._grid_height distance_field = [[max_dist for dummy_item in row] for row in self._cells] boundary = poc_queue.Queue() if entity_type is ZOMBIE: for item in self._zombie_list: boundary.enqueue(item) elif entity_type is HUMAN: for item in self._human_list: boundary.enqueue(item) else: return for item in boundary: visited.set_full(item[0], item[1]) distance_field[item[0]][item[1]] = 0 while len(boundary) > 0: current_cell = boundary.dequeue() neighbour_cells = self.four_neighbors(current_cell[0], current_cell[1]) for neighbour_cell in neighbour_cells: # check whether the cell has not been visited and is passable if visited.is_empty(neighbour_cell[0], neighbour_cell[1]) and self.cell_is_passible(neighbour_cell): visited.set_full(neighbour_cell[0], neighbour_cell[1]) boundary.enqueue(neighbour_cell) distance_field[neighbour_cell[0]][neighbour_cell[1]] = distance_field[current_cell[0]][current_cell[1]] + 1 return distance_field def move_humans(self, zombie_distance_field): """ Function that moves humans away from zombies, diagonal moves are allowed """ idx = 0 for human in self.humans(): neighbouring_cells = self.eight_neighbors(human[0], human[1]) starting_distance = zombie_distance_field[human[0]][human[1]] best_distance = 0 best_cells = [] for row, distances in enumerate(zombie_distance_field): for col, distance in enumerate(distances): cell = (row, col) if self.cell_is_passible(cell) and cell in neighbouring_cells and distance > best_distance: best_distance = distance if best_distance is starting_distance: continue for cell in neighbouring_cells: if zombie_distance_field[cell[0]][cell[1]] is 0 or self.cell_is_passible(cell) is not True: continue if zombie_distance_field[cell[0]][cell[1]] is best_distance: best_cells.append(cell) if len(best_cells) > 0: self._human_list[idx] = random.choice(best_cells) idx += 1 def move_zombies(self, human_distance_field): """ Function that moves zombies towards humans, no diagonal moves are allowed """ idx = 0 for zombie in self.zombies(): neighbouring_cells = self.four_neighbors(zombie[0], zombie[1]) starting_distance = human_distance_field[zombie[0]][zombie[1]] best_distance = starting_distance best_cells = [] for row, values in enumerate(human_distance_field): for col, distance in enumerate(values): cell = (row, col) if self.cell_is_passible(cell) and cell in neighbouring_cells and distance < best_distance: best_distance = distance if best_distance is starting_distance: continue for cell in neighbouring_cells: if self.cell_is_passible(cell) is not True: continue if human_distance_field[cell[0]][cell[1]] is best_distance: best_cells.append(cell) if len(best_cells) > 0: self._zombie_list[idx] = random.choice(best_cells) idx += 1 def cell_is_passible(self, cell): """ Whether or not a cell is passible. """ return self._cells[cell[0]][cell[1]] is EMPTY poc_zombie_gui.run_gui(Apocalypse(30, 60)) #import user41_l4xt1oBRqy_5 as tests #tests.run_suite(Apocalypse)
#Challenge: Given numbers a, b, and c, #the quadratic equation ax2+bx+c=0 can have #zero, one or two real solutions #(i.e; values for x that satisfy the equation). #The quadratic formula #x=-b +/- sqrt(b2&#8722;4ac)2a #can be used to compute these solutions. #The expression b2 - 4ac is the discriminant #associated with the equation. If the discriminant #is positive, the equation has two solutions. #If the discriminant is zero, the equation has #one solution. Finally, if the discriminant is negative, #the equation has no solutions. #Write a Python function smaller_root that #takes an input the numbers a, b and c and returns #the smaller solution to this equation if one exists. #If the equation has no real solution, print the #message "Error: No real solutions" and simply return. #Note that, in this case, the function will actually #return the special Python value None. # Compute the smaller root of a quadratic equation. ################################################### # Smaller quadratic root formula # Student should enter function on the next lines. def smaller_root(a,b,c): """returns the smaller solution if one exists""" discriminant = b**2 - (4*a*c) if discriminant < 0: print "Error: No real solutions" else: quad_form_pos = (-b + (b**2 - 4*a*c)**.5) / (2*a) quad_form_neg = (-b - (b**2 - 4*a*c)**.5) / (2*a) if quad_form_pos > quad_form_neg: return quad_form_neg else: return quad_form_pos #ALSO # """ # Returns the smaller root of a quadratic equation with the # given coefficients. # """ # # discriminant = b ** 2 - 4 * a * c # if discriminant < 0 or a == 0: # print "Error: No real solutions" # else: # discriminant_sqrt = discriminant ** 0.5 # # Choose the positive or negative square root that leads to a smaller root. # if a > 0: # smaller = - discriminant_sqrt # else: # smaller = discriminant_sqrt # return (-b + smaller) / (2 * a) ################################################### # Tests # Student should not change this code. def test(a, b, c): """Tests the smaller_root function.""" print "The smaller root of " + str(a) + "x^2 + " + str(b) + "x + " + str(c) + " is:" print str(smaller_root(a, b, c)) test(1, 2, 3) test(2, 0, -10) test(6, -3, 5) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #The smaller root of 1x^2 + 2x + 3 is: #Error: No real solutions #None #The smaller root of 2x^2 + 0x + -10 is: #-2.2360679775 #The smaller root of 6x^2 + -3x + 5 is: #Error: No real solutions #None
# "magic 8-ball" import random def number_to_fortune(number): '''convert 0 through 7 to a fortune text''' fortune_list = ['Yes, for sure!','Probably yes.', 'Seems like yes...','Definitely not!', 'Probably not.','I really doubt it...', 'Not sure, check back later!',"I really can't tell"] for i in range(8): if number == i: return fortune_list[i] elif i==7 and number != fortune_list[i]: print "Number out of range, choose 0 - 7" else: continue def mystical_octosphere(question): print question print 'You shake the mystical octosphere.' answer_number = random.randrange(0,7) answer_fortune = number_to_fortune(answer_number) print 'The cloudy liquid swirls, and a reply comes into view...' print'The mystical octosphere says...' print answer_fortune print mystical_octosphere("Will I get rich?") mystical_octosphere("Are the Cubs going to win the World Series?")
# Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем # Об окончании ввода данных свидетельствует пустая строка with open(r'data.txt', encoding='utf-8', mode='w') as my_file: while True: line = input('Введите текст построчно(завершить - пустая срока): ') if my_file.writable(): my_file.writelines('\n' + line) if not line: break my_file = open(r'data.txt', encoding='utf-8', mode='r') print('\n\x1b[34mЧитаем записанные сроки в файл:\x1b[0m', f'{my_file.read()}') my_file.close()
""" Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ lst1 = list(list1) for item in lst1: while lst1.count(item) != 1: lst1.remove(item) return lst1 def intersect(list1, list2): """ Compute the intersection of two sorted lists. Returns a new sorted list containing only elements that are in both list1 and list2. This function can be iterative. """ result = [] for item in list1: if item in list2: result.append(item) return result # Functions to perform merge sort def merge(list1, list2): """ Merge two sorted lists. Returns a new sorted list containing all of the elements that are in either list1 and list2. This function can be iterative. """ result = [] lst1 = list(list1) lst2 = list(list2) while len(lst1) > 0 and len(lst2) >0: temp_min = min(lst1[0], lst2[0]) result.append(temp_min) if lst1[0] == temp_min: lst1.remove(temp_min) else: lst2.remove(temp_min) result.extend(lst1) result.extend(lst2) return result def merge_sort(list1): """ Sort the elements of list1. Return a new sorted list with the same elements as list1. This function should be recursive. """ # split into 2 lists in the middle if len(list1) < 2: return list1 else: if len(list1) == 2: return [min(list1), max(list1)] else: split_idx = int(len(list1)/2) sub_lst1 = list1[ :split_idx] sub_lst2 = list1[split_idx: ] merged_lst1 = merge_sort(sub_lst1) merged_lst2 = merge_sort(sub_lst2) merged_list1 = merge(merged_lst1, merged_lst2) return merged_list1 # Function to generate all strings for the word wrangler game def gen_all_strings(word): """ Generate all strings that can be composed from the letters in word in any order. Returns a list of all strings that can be formed from the letters in word. This function should be recursive. """ if len(word) == 0: return [""] elif len(word) == 1: return ["", word] else: first = word[0] rest = word[1:] rest_strings = gen_all_strings(rest) temp_lst = [] for item in rest_strings: for dummy_i in range(len(item)+1): temp_string = item[:dummy_i] + first + item[dummy_i:] temp_lst.append(temp_string) rest_strings.extend(temp_lst) return rest_strings # Function to load words from a file def load_words(filename): """ Load word list from the file named filename. Returns a list of strings. """ file_url = codeskulptor.file2url(filename) file_opened = urllib2.urlopen(file_url) lst = file_opened.readlines() result = [] for item in lst: result.append(item.rstrip('\n')) return result def run(): """ Run game. """ words = load_words(WORDFILE) wrangler = provided.WordWrangler(words, remove_duplicates, intersect, merge_sort, gen_all_strings) provided.run_game(wrangler) # Uncomment when you are ready to try the game #run()
from multiprocessing import Process, Queue __author__ = 'Horia Mut' def print_progress(iteration, total, prefix='', suffix='', decimals=2, barLength=100): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) @source: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console """ filledLength = int(round(barLength * iteration / float(total))) percents = round(100.00 * (iteration / float(total)), decimals) bar = '#' * filledLength + '-' * (barLength - filledLength) sys.stdout.write('%s [%s] %s%s %s\r' % (prefix, bar, percents, '%', suffix)), sys.stdout.flush() if iteration == total: print("\n") import time import random import sys # a downloading thread def worker(path, total, queue): size = 0 while size < total: dt = random.randint(1, 3) time.sleep(dt) ds = random.randint(1, 5) size = size + ds if size > total: size = total queue.put(("update", path, total, size)) queue.put(("done", path)) # the reporting thread def reporter(queue, number_of_worker_threads): status = {} while number_of_worker_threads > 0: message = queue.get() if message[0] == "update": path, total, size = message[1:] status[path] = (total, size) # update the screen here show_progress(status) elif message[0] == "done": number_of_worker_threads = number_of_worker_threads - 1 print "" def show_progress(status): line = "" for path in status: (total, size) = status[path] line = line + "%s: %3d/%d " % (path, size, total) sys.stdout.write("\r" + line) sys.stdout.flush() def example_usage(): ''' http://stackoverflow.com/questions/28057445/python-threading-multiline-progress-report :return: ''' q = Queue() w1 = Process(target=worker, args=("abc", 30, q)) w2 = Process(target=worker, args=("foobar", 25, q)) w3 = Process(target=worker, args=("bazquux", 16, q)) r = Process(target=reporter, args=(q, 3)) for t in [w1, w2, w3, r]: t.start() for t in [w1, w2, w3, r]: t.join() if __name__ == "__main__": example_usage()
password = 'a123456' x = 3 x = int(x) while x != 0 : word = input('請輸入密碼') if word != password: x = x - 1 if x == 0: break print('密碼錯誤!還剩下',x,'次機會') if word == password: print ('登入成功!') break
Store Let’s say, you have built a store that is filled with different grocery items. You have observed that customers are facing difficulty to find an item. So you have decided to write a program that would make it easy for users to search for items. # Submission Guidelines Create a folder /home/ec2-user/environment/oop/oop_submissions/oop_assignment_005. Make use of the below example command $ mkdir -p /home/ec2-user/environment/oop/oop_submissions/oop_assignment_005/ Copy your code file to the submission folder. Make use of the below example command $ cp store.py /home/ec2-user/environment/oop/oop_submissions/oop_assignment_005 # Coding Guidelines Write all your code in store.py file Write the following classes to complete the assignment # Item An item has the following properties name: Name of the item price: Price of the item > 0 category: Category to which the item belongs to (any string value) Coding Guidelines: Write Item class in store.py file. It should behave as shown below. >>> item = Item(name="Oreo Biscuits", price=30, category="Food") >>> print(item) Oreo Biscuits@30-Food >>> item = Item(name="Oreo Biscuits", price=0, category="Food") ValueError: Invalid value for price, got 0 # Query A query is a request from the customer to the store. It has the following properties field: Properties of Item on which customer is searching . In our case name or price or category value: Value to which the item property is to be matched with operation: Operations mentioned below Coding Guidelines: Write Query class in store.py file. It should behave as shown below. >>> query = Query(field="name", operation="EQ", value="Oreo Biscuits") >>> print(query) name EQ Oreo Biscuits # Store A store is a collection of items. Customers can search for relevant items in the store. It should support the following functionality. # Add item: Adds a new item to the store >>> store = Store() >>> item = Item(name="Oreo Biscuits", price=30, category="Food") >>> store.add_item(item) # Display all items: Displays all the items in the store >>> store = Store() >>> item = Item(name="Oreo Biscuits", price=30, category="Food") >>> store.add_item(item) >>> item = Item(name="Boost Biscuits", price=20, category="Food") >>> store.add_item(item) >>> print(store) Oreo Biscuits@30-Food Boost Biscuits@20-Food # Filter: A filter method should filter the items in a store based on users preference (a Query object) and returns a Store object containing the filtered results. Customers provide thier preference as Query object which represents their needs. You code should be have as below. >>> store = Store() >>> item = Item(name="Oreo Biscuits", price=30, category="Food") >>> store.add_item(item) >>> item = Item(name="Boost Biscuits", price=20, category="Food") >>> store.add_item(item) >>> item = Item(name="Butter", price=10, category="Grocery") >>> store.add_item(item) >>> query = Query(field="category", operation="IN", value=["Food"]) >>> results = store.filter(query) >>> print(results) Oreo Biscuits@30-Food Boost Biscuits@20-Food Equals condition: >>> query = Query(field="name", operation="EQ", value="Oreo Biscuits") >>> results = store.filter(query) >>> print(results) Oreo Biscuits@30-Food Explanation: Query(field="name", operation="EQ", value="Oreo Biscuits") Should filter all the items which have "Oreo Biscuits" as value for the field "name" Greater Than condition: >>> query = Query(field="price", operation="GT", value=20) >>> results = store.filter(query) >>> print(results) Oreo Biscuits@30-Food Explanation: Query(field="price", operation="GT", value=20) Should filter all the items which have value greater than 20 for the field "price" Greater Than or Equal condition: "GTE" >>> query = Query(field="price", operation="GTE", value=20) >>> results = store.filter(query) >>> print(results) Oreo Biscuits@30-Food Boost Biscuits@20-Food Explanation: Query(field="price", operation="GTE", value=20) Should filter all the items which have value greater than or equal to 20 for the field "price" Less Than: "LT" >>> query = Query(field="price", operation="LT", value=20) >>> results = store.filter(query) >>> print(results) Butter@10-Grocery Explanation: Query(field="price", operation="LT", value=20) Should filter all the items which have value less than 20 for the field "price" Less Than or Equal : "LTE" >>> query = Query(field="price", operation="LTE", value=20) >>> results = store.filter(query) >>> print(results) Boost Biscuits@20-Food Butter@10-Grocery Explanation: Query(field="price", operation="LTE", value=20) Should filter all the items which have value less than or equal to 20 for the field "price" StartsWith: "STARTS_WITH" >>> query = Query(field="name", operation="STARTS_WITH", value="Bu") >>> results = store.filter(query) >>> print(results) Butter@10-Grocery Explanation: Query(field="name", operation="STARTS_WITH", value="bu") Should filter all the items which have value that starts with "bu" for the field "name" EndsWith: "ENDS_WITH" - is used to as condition in Query object to filter items with field value that ends with the query value >>> query = Query(field="name", operation="ENDS_WITH", value="cuits") >>> results = store.filter(query) >>> print(results) Oreo Biscuits@30-Food Boost Biscuits@20-Food Explanation: Query(field="name", operation="ENDS_WITH", value="cuits") Should filter all the items which have value that ends with "cuits" for the field "name" Contains: "CONTAINS" >>> query = Query(field="name", operation="CONTAINS", value="uit") >>> results = store.filter(query) >>> print(results) Oreo Biscuits@30-Food Boost Biscuits@20-Food Explanation: Query(field="name", operation="CONTAINS", value="cuits") Should filter all the items which have value that contains "cuits" for the field "name" In: "IN" >>> query = Query(field="name", operation="IN", value=["Oreo Biscuits", "Boost Biscuits" ]) >>> results = store.filter(query) >>> print(results) Oreo Biscuits@30-Food Boost Biscuits@20-Food Explanation: Query(field="name", operation="IN", value=["Oreo Biscuits", "Boost Biscuits" ]) Should filter all the items which have value one of “Oreo Biscuits” or “Boost Biscuits” for the field "name" Filter should return a new store object which has only the selected items. >>> query = Query(field="price", operation="GT", value=15) >>> results = store.filter(query) # filter all items whose price is greater than 15 >>> type(results) # this is to show that results is another store object <class '__main__.Store'> >>> print(results) Oreo Biscuits@30-Food Boost Biscuits@20-Food Incase of empty results. Store should be have as below. >>> query = Query(field="name", operation="STARTS_WITH", value="bu") >>> results = store.filter(query) >>> print(results) No items # Exclude: exclude is very similar to filter but works in an opposite way. Similar to filter, It takes Query as a parameter It returns a new Store object that contains all the items in the store except the ones which match the query. >>> store = Store() >>> item = Item(name="Oreo Biscuits", price=30, category="Food") >>> store.add_item(item) >>> item = Item(name="Boost Biscuits", price=20, category="Food") >>> store.add_item(item) >>> item = Item(name="ParleG Biscuits", price=10, category="Food") >>> store.add_item(item) >>> print(store) Oreo Biscuits@30-Food Boost Biscuits@20-Food ParleG Biscuits@10-Food >>> query = Query(field="price", operation="GT", value=15) >>> results = store.exclude(query) # exclude all items whose price is greater than 15 >>> print(results) ParleG Biscuits@10-Food Exclude should return a new store object which has all the items that doesn’t match the query. >>> query = Query(field="price", operation="GT", value=15) >>> results = store.filter(query) # filter all items whose price is greater than 15 >>> type(results) # this is to show that results is another store object <class '__main__.Store'> >>> print(results) ParleG Biscuits@10-Food # Chaining: Queries can be chained i.e users should be able to perform further queries on the result of a query. Hint: filter and exclude methods should return a new store object with filtered items. >>> store = Store() >>> item = Item(name="Oreo Biscuits", price=30, category="Food") >>> store.add_item(item) >>> item = Item(name="Boost Biscuits", price=20, category="Food") >>> store.add_item(item) >>> item = Item(name="ParleG Biscuits", price=10, category="Food") >>> store.add_item(item) >>> query = Query(field="price", operation="GT", value=15) >>> results = store.filter(query) >>> print(results) Oreo Biscuits@30-Food Boost Biscuits@20-Food >>> new_query = Query(field="name", operation="CONTAINS", value='Boost') >>> updated_results = results.exclude(new_query) >>> print(updated_results) Oreo Biscuits@30-Food # Count: Count of items in the store >>> store = Store() >>> item = Item(name="Oreo Biscuits", price=30, category="Food") >>> store.add_item(item) >>> item = Item(name="Boost Biscuits", price=20, category="Food") >>> store.add_item(item) >>> item = Item(name="ParleG Biscuits", price=10, category="Food") >>> store.add_item(item) >>> store.count() 3 # Query Should allow only the following operations. IN EQ GT GTE LT LTE STARTS_WITH ENDS_WITH CONTAINS Should raise a ValueError incase of invalid input. >>> query = Query(field="name", operation="random", value="Oreo Biscuits") ValueError: Invalid value for operation, got random #upto question class Item: def __init__(self,name=None,price=0,category=None): if price<=0: raise ValueError("Invalid value for price, got {}".format(price)) self.name=name self.price=price self.category=category def __str__(self): return "{}@{}-{}".format(self.name,self.price,self.category) class Query: def __init__(self,field,operation,value): op=['IN','EQ','GT','GTE','LT','LTE','STARTS_WITH','ENDS_WITH','CONTAINS'] if operation not in op: raise ValueError('Invalid value for operation, got {}'.format(operation)) self.field=field self.operation=operation self.value=value def __str__(self): return "{} {} {}".format(self.field,self.operation,self.value) class Store: def __init__(self): self.list1=[] def add_item(self,item): self.list1.append(item) def count(self): return len(self.list1) def __str__(self): if len(self.list1)>0: return "\n".join(map(str,self.list1)) else: return 'No items' def filter(self,query): list2=Store() if query.operation=='EQ': for i in self.list1: if query.value==i.name: list2.add_item((i)) elif query.value==i.price: list2.add_item((i)) elif query.value==i.category: list2.add_item((i)) return list2 if query.operation=='GT': for i in self.list1: if i.price>query.value: list2.add_item((i)) return list2 if query.operation=='GTE': for i in self.list1: if i.price>=query.value: list2.add_item((i)) return list2 if query.operation=='LT': for i in self.list1: if i.price<query.value: list2.add_item((i)) return list2 if query.operation=='LTE': for i in self.list1: if i.price<=query.value: list2.add_item((i)) return list2 if query.operation=='STARTS_WITH': for i in self.list1: if i.name.startswith(query.value): list2.add_item((i)) if i.category.startswith(query.value): list2.add_item((i)) return list2 if query.operation=='ENDS_WITH': for i in self.list1: if i.name.endswith(query.value): list2.add_item((i)) if i.category.endswith(query.value): list2.add_item((i)) return list2 if query.operation=='CONTAINS': for i in self.list1: if query.field == 'name' and i.name.__contains__(query.value): list2.add_item((i)) if query.field=='category' and i.category.__contains__(query.value): list2.add_item((i)) return list2 if query.operation=='IN': for i in self.list1: if i.name in query.value: list2.add_item((i)) elif i.price in query.value: list2.add_item((i)) elif i.category in query.value: list2.add_item((i)) return list2 def exclude(self,query): obj2=Store() if query.operation=='EQ': for i in self.list1: if query.value!=i.name and query.value!=i.price and query.value!=i.category: obj2.add_item(i) return obj2 if query.operation=='GT': for i in self.list1: if query.value>=i.price: obj2.add_item(i) return obj2 if query.operation=='GTE': for i in self.list1: if query.value>i.price: obj2.add_item(i) return obj2 if query.operation=='LT': for i in self.list1: if query.value<=i.price: obj2.add_item(i) return obj2 if query.operation=='LTE': for i in self.list1: if query.value<i.price: obj2.add_item(i) return obj2 if query.operation=='STARTS_WITH': for i in self.list1: if i.name.startswith(query.value) or i.category.startswith(query.value): pass else: obj2.add_item(i) return obj2 if query.operation=='ENDS_WITH': for i in self.list1: if i.name.endswith(query.value) or i.category.endswith(query.value): pass else: obj2.add_item((i)) return obj2 if query.operation=='CONTAINS': for i in self.list1: if query.field == 'name' and i.name.__contains__(query.value): pass elif query.field=='category' and i.category.__contains__(query.value): pass else: obj2.add_item((i)) return obj2 if query.operation=='IN': for i in self.list1: if i.name in query.value: pass elif i.price in query.value: pass elif i.category in query.value: pass else: obj2.add_item((i)) return obj2
Pokemon You might have played or at least heard about the famous Pokemon game. It's based on the popular Pokemon series. In this assignment, lets try to simulate some pokemon and some trainers to "catch 'em all". # Submission Guidelines Exam Duration - 5 hr 30 mins Create a folder /home/ec2-user/environment/oop/oop_submissions/oop_assignment_009. Make use of the below example command $ mkdir -p /home/ec2-user/environment/oop/oop_submissions/oop_assignment_009/ To submit your assignment execute the below code snippet in the assignment folder i.e /home/ec2-user/environment/oop/oop_submissions/oop_assignment_009 cloud9$ ./submit_assignment On submission you will get results.txt in your assignment folder. results.txt gives you the test case results. Coding Guidelines: Write all your code in pokemon.py file All the class, attributes and methods should be same as given in the example # Task1 # Pokemon A pokemon is described by it's name and level. name is any non-empty string & level is a positive integer These two details should be mentioned while creating any pokemon. In case of invalid inputs, raise ValueError as mentioned below: if name is empty - raise ValueError with "name cannot be empty" as error message if level <=0 - raise ValueError with "level should be > 0" as error message In this assignment, you have to simulate the following pokemon. # Pikachu Pikachu is an electric pokemon. Behavior of Pikachu is mentioned below. It can make its unique sound (mentioned below) It can run It can attack - Magnitude of the attack depends on the level of pikachu. It is 10 times the level of the attacking pikachu. (10 x level) >>> my_pikachu = Pikachu(name="Ryan", level=1) >>> my_pikachu.name Ryan >>> my_pikachu.level 1 >>> print(my_pikachu) Ryan - Level 1 >>> my_pikachu.make_sound() # Print Pika Pika >>> my_pikachu.run() # Print Pikachu running... >>> my_pikachu.level 1 >>> my_pikachu.attack() # Print Electric attack with 10 damage >>> another_pikachu.level 2 >>> another_pikachu.attack() # Print Electric attack with 20 damage # Squirtle Squirtle is a water pokemon. Behavior of Squirtle is mentioned below. It can make its unique sound (mentioned below) It can run It can swim It can can attack - Magnitude of the attack depends on the level of Squirtle. It is 9 times the level of the attacking squirtle (9 x level) >>> my_squirtle = Squirtle(name="Ryan") >>> my_squirtle.name Ryan >>> my_squirtle.level 1 >>> print(my_squirtle) Ryan - Level 1 >>> my_squirtle.make_sound() # Print Squirtle...Squirtle >>> my_squirtle.run() # Print Squirtle running... >>> my_squirtle.swim() # Print Squirtle swimming... >>> my_squirtle.level 1 >>> my_squirtle.attack() # Print Water attack with 9 damage >>> another_squirtle.level 2 >>> another_squirtle.attack() # Print Water attack with 18 damage # Pidgey Pidgey is a flying pokemon. Behavior of Pidgey is mentioned below. It can make its unique sound (mentioned below). It can fly It can can attack - Magnitude of the attack is 5 times the level of the attacking pidgey (5 x level) >>> my_pidgey = Pidgey(name="Tom") >>> my_pidgey.name Tom >>> my_pidgey.level 1 >>> print(my_pidgey) Tom - Level 1 >>> my_pidgey.make_sound() # Print Pidgey...Pidgey >>> my_pidgey.fly() # Print Pidgey flying... >>> my_pidgey.level 1 >>> my_pidgey.attack() # Print Air attack with 5 damage >>> another_pidgey.level 2 >>> another_pidgey.attack() # Print Air attack with 10 damage # Swanna Swanna is a water & flying pokemon. Behavior of Swanna is mentioned below. It can make its unique sound (mentioned below). It can fly It can swim It can can attack As it is both water and flying pokemon, Swanna does double damage i.e A water attack with 9 x swanna level and An air attack with 5 x swanna level >>> my_swanna = Swanna(name="Misty") >>> my_swanna.name Misty >>> my_swanna.level 1 >>> print(my_swanna) Misty - Level 1 >>> my_swanna.make_sound() # Print Swanna...Swanna >>> my_swanna.fly() # Print Swanna flying... >>> my_swanna.swim() # Print Swanna swimming... >>> my_swanna.level 1 >>> my_swanna.attack() # Print Water attack with 9 damage Air attack with 5 damage >>> another_swanna.level 2 >>> another_swanna.attack() # Print Water attack with 18 damage Air attack with 10 damage # Zapdos Zapdos is an electic & flying pokemon. Behavior of Zapdos is mentioned below. It can make its unique sound (mentioned below). It can fly It can can attack As it is both electric and flying pokemon, Zapdos does double damage i.e An electric attack with 10 x zapdos level and An air attack with 5 x zapdos level >>> my_zapdos = Zapdos(name="Ryan") >>> my_zapdos.name Ryan >>> my_zapdos.level 1 >>> print(my_zapdos) Ryan - Level 1 >>> my_zapdos.make_sound() # Print Zap...Zap >>> my_zapdos.fly() # Print Zapdos flying... >>> my_zapdos.level 1 >>> my_zapdos.attack() # Print Electric attack with 10 damage Air attack with 5 damage >>> another_zapdos.level 2 >>> another_zapdos.attack() # Print Electric attack with 20 damage Air attack with 10 damage # Task2 # Island An island in the game is described by its name the maximum number of pokemon it can hold total food available on the island number of pokemon left to catch on the island On creating a new island pokemon_left_to_catch should be 0 >>> island = Island(name="Island1", max_no_of_pokemon=5, total_food_available_in_kgs=10000) >>> island.name Island1 >>> island.max_no_of_pokemon 5 >>> island.total_food_available_in_kgs 10000 >>> island.pokemon_left_to_catch 0 >>> print(island) Island1 - 0 pokemon - 10000 food You can add pokemon to an Island. >>> island.pokemon_left_to_catch 0 >>> island.add_pokemon(pokemon) >>> island.pokemon_left_to_catch 1 You can add only a maximum of max_no_of_pokemon pokemon to the Island. >>> island.pokemon_left_to_catch 5 >>> island.max_no_of_pokemon 5 >>> island.add_pokemon(pokemon) # Print Island at its max pokemon capacity >>> island.pokemon_left_to_catch 5 # Task3 # Trainer A Pokemon trainer is described by his/her name: any string with which a trainer is referred, just like a name for humans. experience: represents the experience of the trainer. experience is 100 for a newly created trainer. Every time a trainer catches a pokemon, his/her experience is increased (details are mentioned at catch method below) max_food_in_bag: represents the max amount of food a trainer can carry along with him/her. max_food_in_bag increases with the trainers experience. i.e max_food_in_bag is equal to 10 x experience. food_in_bag: represents the current amount of food a trainer has. >>> trainer = Trainer(name="Bot") >>> trainer.name Bot >>> trainer.experience 100 >>> print(trainer) Bot >>> trainer.max_food_in_bag 1000 >>> trainer.food_in_bag 0 # Task4 Trainers travel from one island to another to catch pokemon and gather food. Trainers should be shown all the available islands. >>> Island.get_all_islands() [Island1 - 100 pokemon - 10000 food, Island2 - 24 pokemon - 12300 food, Island3 - 82 pokemon - 11830 food, Island4 - 192 pokemon - 101238 food] Should return a list of island objects # Task5 Trainer can move from one island to another. >>> trainer.move_to_island(island1) >>> trainer.current_island == island1 True >>> trainer.current_island Island1 - 0 pokemon - 10000 - food If trainer is not on any island current_island should return the message mentioned below. >>> trainer.current_island # Print You are not on any island # Task6 Trainers can collect food from the island and store it in their bag. >>> trainer.move_to_island(island) >>> island.total_food_available_in_kgs 10000 >>> trainer.food_in_bag 0 >>> trainer.collect_food() >>> island.total_food_available_in_kgs 9000 >>> trainer.food_in_bag 1000 Trainer fills his/her bag with food just by calling the collect_food method once. >>> island.total_food_available_in_kgs 9900 >>> trainer.food_in_bag 1000 >>> trainer.max_food_in_bag 1000 >>> trainer.collect_food() >>> trainer.food_in_bag 1000 >>> island.total_food_available_in_kgs 9900 When a trainer collects food from an island, food in the island is decreased by the same amount. If the trainer bag is full i.e., food_in_bag is equal to max_food_in_bag then collect_food doesn't decrease food on the island and also doesn't increase the food_in_bag. If trainer is not on any island collect_food should behave as mentioned below. >>> trainer.current_island # Print You are not on any island >>> trainer.collect_food() # Print Move to an island to collect food If the food on the island is less than the food required by the trainer, then your code should behave as below. >>> island.total_food_available_in_kgs 90 >>> trainer.food_in_bag 0 >>> trainer.experience 100 >>> trainer.max_food_in_bag 1000 >>> trainer.collect_food() >>> trainer.food_in_bag 90 >>> island.total_food_available_in_kgs 0 # Task7 A trainer can catch a pokemon. >>> pokemon.name Pigetto >>> pokemon.level 1 >>> trainer.experience 100 >>> trainer.catch(pokemon) # Print You caught Pigetto Every time a trainer catches a pokemon, their experience increases by the pokemon level x 20 points. >>> pokemon.name Pigetto >>> pokemon.level 1 >>> trainer.experience 100 >>> trainer.catch(pokemon) # Print You caught Pigetto >>> trainer.experience 120 A trainer can catch a pokemon only if his/her experience >= 100 x pokemon.level >>> pokemon.name Pigetto >>> pokemon.level 2 >>> trainer.experience 100 >>> trainer.catch(pokemon) # Print You need more experience to catch Pigetto # Task8 A trainer can see the list of all pokemon he/she has caught. >>> trainer.get_my_pokemon() [Pigetto - Level 1] get_my_pokemon should return a list of pokemon objects the trainer has caught. # Task9 A pokemon remembers its trainer. >>> pokemon.name Pigetto >>> pokemon.level 1 >>> pokemon.master # Print No Master >>> trainer.catch(pokemon) >>> pokemon.master == trainer True
# -*- coding: utf-8 -*- """ Created on Mon Feb 22 17:17:54 2021 @author: uia76912 """ max_value_of_series = int(input("Please enter the final value to be considered in fiboniacci series:")) previous_term = 0 current_term = 1 next_term = 0 fibonacci_series = [0,1] sum_of_even_values = 0 while next_term < max_value_of_series: next_term = previous_term + current_term fibonacci_series.append(next_term) previous_term = current_term current_term = next_term if (next_term % 2) == 0: sum_of_even_values += next_term print("\n Fibonacci values are :\n", fibonacci_series) print("\n Sum of all even values:\n", sum_of_even_values)
#函数img2vector 将图像转化为向量 def img2vextor(filename): returnVect = zeros((1,1024)) fr = open(filename) for i in range(32): lineStr = fr.readline() for j in range(32): returnVect[0,32*i + j] = int(lineStr[j]) return returnVect testVector = kNN.img2vector('testDigits/0_13.txt') print(testVector[0,0:31]) print(testVector[0,32:63]) #手写数字识别系统的测试代码 def handwritingClassTest(): hwlabels = [] trainingFileList = listdir('trainingDigits') #1.获取目录内容 m = len(trainingFileList) trainingMat = zeros((m,1024)) for i in range(m): #2.(以下三行)从文件名解析分类数字 fileNameStr = trainingFileList[i] fileStr = fileNameStr.split('.')[0] classNumStr = int(fileStr.split('-')[0]) hwLabels.append(classNumStr) trainingMat[i,:] = img2vextor('trainingDigits/%s'%fileNameStr) testFileList = listdir('testDigits') errorCount = 0.0 mTest = len(testFileList) for i in range(mTest): fileNameStr = testFileList[i] fileStr = fileNameStr.split('.')[0] classNumStr = int(fileStr.split('-')[0]) vectorUnderTest = img2vector('testDigits/%s'%fileNameStr) classifierResult = classify0(vectorUnderTest,trainingMat,hwLabels,3) print("the classifier came back with:%d,the real answer is :%d"%(classifierResult,vectorUnderTest)) if (classifierResult != classNumStr): errorCount += 1.0 print("\nthe total number of errors is : %d" %errorCount) print("\nthe total error rate is: %f "% (errorCount/float(mTest))) print(kNN.handwritingClassTest())
# 定义一个函数sum_numbers # 能够接受一个num的整数参数 # 计算1+2+...num的结果 def sum_numbers(num): #1.出口 if num == 1: return 1 #2.数字的累加 num + (1...num-1) #假设sun_numbers 能够正确的处理1...num - 1 temp = sum_numbers(num - 1) #两个数字的相加 return num + temp result = sum_numbers(1000) print(result)
name_list = ["张三","李四","王五","王小二"] #len(length 长度)函数可以统计列表中元素的总数 list_len = len(name_list) print("列表中包含 %d 个元素" %list_len) #count 方法可以统计列表中某一个数据出现的次数 count = name_list.count("张三") print("张三出现了 %d 次" % count) #从列表中删除第一次出现的数据,如果数据不存在,程序会报错 name_list.remove("张三"123) print(name_list)
def Quicksort(array): if len(array) < 2: return array quicksort([15,10]) + [33] + quicksort([]) > [10,15,33] #一个有序的数组 #快速排序 def quicksort(array): if len(array) < 2: return array #基线条件:为空或只包含一个元素的数组是“有序”的 else: pivot = array[0] #递归条件 less = [i for i in array[1:] if i <= pivot] #由所有小于基准值的元素组成的子数组 greater = [i for i in array[1:] if i > pivot] #由所有大于基准值的元素组成的子数组 return quicksort(less) + [pivot] + quicksort(greater) print quicksort([10,5,2,3]) def print_items(list): for item in list: print item
class Person: def cry(self): print("I can cry") def speak(self): print("I can speak %s"%(self.word)) tom=Person() tom.cry() tom.word="hahah" tom.speak() class Person1: def __init__(self): self.country="china" self.sex="male" def speak(self): print("I am from %s"%self.country) jack=Person1() jack.speak() print(jack.country,jack.sex) class Person2: def __init__(self,name,age): self.age=age self.name=name self.country="china" def speak(self): print("name=%s,age=%d"%(self.name,self.age)) p1=Person2("jack",19) p2=Person2("Tom",22) p3=p2 p1.speak() p2.speak() print(p3) print(p2)
import string import math from operator import itemgetter alphabet = list(string.ascii_lowercase) def main_menu(): user_word = input("\nWhat word you want to encrypt?\n").lower() while user_word.isalpha() == False: user_word = input("\nType only letters for encryption\n") while True: try: user_chose = int(input("\nWhat type of encryption you want to choose? \n1 - shift, 2 - mirror, 3 - matrix, 4 - rotate right, 5 - square index, 6 - remove odd blocks, 7 - reduce to fixed\n")) while user_chose not in range(1,8): user_chose = int(input("\nChoose the encryption method:\n1 - shift, 2 - mirror, 3 - matrix, 4 - rotate right, 5 - square index, 6 - remove odd blocks, 7 - reduce to fixed\n")) break except ValueError: print("please choose the number between 1 and 7") if user_chose == 1: user_shift = int(input("Type shift number\n")) encrypting_result = shift_characters(user_word, user_shift) elif user_chose == 2: encrypting_result = abc_mirror(user_word) elif user_chose == 3: word2 = input("Type second word for encrypting\n") encrypting_result = create_matrix(user_word, word2) elif user_chose == 4: user_rotate_number = int(input("Type number for rotating\n")) encrypting_result = rotate_right(user_word, n) elif user_chose == 5: encrypting_result = get_square_index_chars(user_word) elif user_chose == 6: block_length = int(input("Type length of the block for encrypting\n")) encrypting_result = remove_odd_blocks(user_word, block_length) elif user_chose == 7: reducing = int(input("Type number for reducing\n")) encrypting_result = reduce_to_fixed(user_word, reducing) return encrypting_result def shift_characters(word, shift): #1 shift_i = [] shift_word = [] while shift>len(alphabet): shift = shift - len(alphabet) for char in word: if char in alphabet: new_char = alphabet.index(char)+shift if new_char<=len(alphabet): shift_i.append(new_char) else: loop_index = len(alphabet) - alphabet.index(char) new_index = shift - loop_index shift_i.append(new_index) shift_word = [alphabet[i] for i in shift_i] new_word = ''.join(shift_word) return new_word #print(shift_characters('ayz', 4)) def abc_mirror(word): #2 mirror = [] for char in word: if char in alphabet: new_index = -alphabet.index(char)-1 mirror.append(new_index) shift_word = [alphabet[i] for i in mirror] return ''.join(shift_word) #abc_mirror("abc") def create_matrix(word1, word2): #3 shift_word = [] shift_index=[] result=[] for char in word2: if char in alphabet: shift_index.append(alphabet.index(char)) for i in shift_index: shift_i = [] for char in word1: if char in alphabet: new_char = alphabet.index(char)+i if new_char<=len(alphabet): shift_i.append(new_char) else: loop_index = len(alphabet) - alphabet.index(char) new_index = i - loop_index shift_i.append(new_index) shift_word = [alphabet[i] for i in shift_i] new_word = ''.join(shift_word) result.append(new_word) return result #create_matrix('mamas', 'papas') def rotate_right(word, n): #4 word_list = list(word) result_list=[] all_char=[] i = 0 while i < n: result_list.insert(0, word_list[-1]) word_list.pop(-1) i+=1 all_char = result_list + word_list print(all_char) result = ''.join(all_char) return result #rotate_right('abcdefgh', 3) def get_square_index_chars(word): #5 result_list=[] list_word = list(word) print(list_word) for i in list_word: root = math.sqrt(list_word.index(i)) if int(root + 0.5) ** 2 == list_word.index(i): result_list.append(i) result_word = ''.join(result_list) return result_word #get_square_index_chars('abcdefghijklm') def remove_odd_blocks(word, block_length): #6 i = 0 slice=[] changed_word = [] result=[] for char in word: if i < block_length-1: slice.append(char) i+=1 elif i == block_length-1: slice.append(char) changed_word.append(''.join(slice)) slice = [] i = 0 if len(slice)>0: changed_word.append(''.join(slice)) for i in changed_word: if changed_word.index(i)%2==0: result.append(i) word_result = ''.join(result) return word_result #remove_odd_blocks('abcdefghijklm', 3) def reduce_to_fixed(word, n): #7 word_list = list(word) word_slice = [] new_word_slice = [] result_word_list = [] i = 0 j = 0 for char in word_list: if i < n: word_slice.append(char) i+=1 rotation_slice = int(n/3) for char in word_slice: while j < rotation_slice: new_word_slice.append(word_slice[0]) word_slice.pop(0) j+=1 result_word_list = word_slice + new_word_slice result_word = ''.join(result_word_list) return result_word #reduce_to_fixed('abcdefghijklm', 6) print(main_menu())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 30 09:18:40 2017 @author: innersme """ #조건이 있을 때, """ for i in range(1,11): if i%2 == 0: print('%d is even'%i) else: print('%d is odd'%i) """ # 조건이 두 개 있을 때? year = 2231 #and or 사용하기 if (year%4==0 and year%100!=0) or year%400==0: print("leap year") else : print("general year")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 3 13:04:18 2017 @author: innersme [야구게임작성] 중복되지 않는 3자리수를 생성한다. 중복되지 않는 임의의 3자리수를 작성한다. 생성된 수와 입력할 수를 비교하여 - 숫자가 같고 자릿수가 틀리면 ball - 숫자가 같고 자릿수가 같으면 strike 비교결과가 3strike이면 종료되는 코드를 작성하시오. """ #num를 입력값으로 받는 import random a = [] #중복되지 않는 n자리수를 생성한다. def makeNumber(num): for i in range(num): temp = int(random.random()*10*num-10**(num-1)) if temp in a: continue a.append(temp) return a #중복되지 않는 임의의 3자리수를 작성한다. def inPut(num): b=input("3자리 입력하세요") return b #비교한다. def Compare(a,b): strike=0 ball=0 for j in range(len(a)): for i in range(len(b)): if a[j]==b[i] and i==j: strike = strike + 1 elif a[j]==b[i] and i!=j: ball = ball + 1 print("%d strike and %d balls"%(strike,ball)) return strike a = makeNumber(3) b = [] while Compare(a,b)!=3: b = inPut(3) #print("print b =",b) #print("%dstrikes and %dballs"%(strike,ball)) """ while : for j in range(3): for i in range(3): if a[j]==b[i] and i==j: strike = strike + 1 elif a[j]==b[i] and i!=j: ball = ball + 1 print("%d strike and %d balls"%(strike,ball)) print("good") """
import sqlite3 def createTables(): connection = sqlite3.connect('AllTables.db') ####################################################################################################################### connection.execute("CREATE TABLE Artists(MemId INTEGER NOT NULL PRIMARY KEY, FullName TEXT NOT NULL, Pincode NUMBER NOT NULL,PhNo NUMBER NOT NULL)") connection.execute("INSERT INTO Artists VALUES(101, 'Robert Gills', '600061', 9792342545)") connection.execute("INSERT INTO Artists VALUES(102, 'Jack Jhonson', '600036', 9863552545)") connection.execute("INSERT INTO Artists VALUES(103, 'Roshini Gourav', '625706', 9734266937)") connection.execute("INSERT INTO Artists VALUES(104, 'Sally Sanders', '600019', 9240778485)") connection.execute("INSERT INTO Artists VALUES(105, 'Darrell Rivers', '132113', 552247092)") connection.execute("INSERT INTO Artists VALUES(106, 'Meena Patel', '825408', 8242147092)") connection.execute("INSERT INTO Artists VALUES(107, 'Neeti Rakesh', '110002', 9249247092)") ####################################################################################################################### connection.execute("CREATE TABLE Artworks(ArtId INTEGER NOT NULL PRIMARY KEY, Title TEXT NOT NULL, Genre TEXT NOT NULL, MemId NUMBER NOT NULL, Price FLOAT NOT NULL)") connection.execute("INSERT INTO Artworks VALUES(1001, 'Taj Mahal', 'Oil Painting', 101, 7000)") connection.execute("INSERT INTO Artworks VALUES(1002, 'Dance', 'Oil Painting', 102, 9000)") connection.execute("INSERT INTO Artworks VALUES(1003, 'The Mind', 'Abstract Art', 103, 10000)") connection.execute("INSERT INTO Artworks VALUES(1004, 'Rainy season', 'Dot Art', 102, 8500)") connection.execute("INSERT INTO Artworks VALUES(1005, 'Rainbow', 'Dot Art', 104, 9000)") connection.execute("INSERT INTO Artworks VALUES(1006, 'Mysteries', 'Abstract Art', 105, 10000)") connection.execute("INSERT INTO Artworks VALUES(1007, 'Waterfalls', '3D Art', 106, 6700)") connection.execute("INSERT INTO Artworks VALUES(1008, 'Surfing', 'Wax Painting', 105, 8900)") ####################################################################################################################### connection.execute("CREATE TABLE Exhibitions(ExCount INTEGER NOT NULL PRIMARY KEY, Theme TEXT NOT NULL, Pincode NUMBER NOT NULL,PhNo NUMBER NOT NULL, FromDate TEXT NOT NULL, ToDate TEXT NOT NULL)") connection.execute("INSERT INTO Exhibitions VALUES(820, 'Tiny Art', '600061', 9799132545, '2018-02-23', '2018-02-27')") connection.execute("INSERT INTO Exhibitions VALUES(821, '3D Art', '600081', 9863142545,'2018-04-26','2018-04-28')") connection.execute("INSERT INTO Exhibitions VALUES(822, 'Famous Landmarks', '600038', 9799112937,'2018-05-26','2018-05-28')") connection.execute("INSERT INTO Exhibitions VALUES(823, 'Local Inspiration', '600019', 9240238485,'2018-06-26','2018-06-29')") connection.execute("INSERT INTO Exhibitions VALUES(824, 'Infinity', '600045', 649247092,'2018-08-23','2018-08-27')") connection.execute("INSERT INTO Exhibitions VALUES(825, 'Universe', '603210', 8249247092,'2018-10-20','2018-10-23')") connection.execute("INSERT INTO Exhibitions VALUES(826, 'Bio Diversity', '603210', 1249247092,'2018-11-24','2018-11-28')") ####################################################################################################################### connection.execute("CREATE TABLE Customers(Cid INTEGER NOT NULL PRIMARY KEY, CName TEXT NOT NULL, Pincode NUMBER NOT NULL,PhNo NUMBER NOT NULL)") connection.execute("INSERT INTO Customers VALUES(1201, 'Raghu Ram', '600061', 9792672545)") connection.execute("INSERT INTO Customers VALUES(1202, 'Jeffrey Ray', '610036', 9863452545)") connection.execute("INSERT INTO Customers VALUES(1203, 'Jack Peters', '635706', 9711266937)") connection.execute("INSERT INTO Customers VALUES(1204, 'Sanya Patel', '600019', 9243378485)") connection.execute("INSERT INTO Customers VALUES(1205, 'Sanjay Suresh', '232113', 551247092)") connection.execute("INSERT INTO Customers VALUES(1206, 'Meena Gautham', '625408', 8242133092)") connection.execute("INSERT INTO Customers VALUES(1207, 'Rita Rakesh', '110002', 9249117092)") ####################################################################################################################### connection.execute("CREATE TABLE Bill(BillId TEXT NOT NULL, Cid INTEGER NOT NULL, ArtId INTEGER NOT NULL, Qty INTEGER NOT NULL, PurchaseDate TEXT NOT NULL, TotalPrice FLOAT NOT NULL)") connection.execute("INSERT INTO Bill VALUES('A12345',1201, 1001, 2, '2018-09-15', 21000)") connection.execute("INSERT INTO Bill VALUES('A12346',1203, 1001, 1, '2018-09-15', 8000)") connection.execute("INSERT INTO Bill VALUES('A12346',1203, 1002, 2, '2018-09-15', 18000)") connection.execute("INSERT INTO Bill VALUES('A12347',1201, 1002, 1, '2018-06-21', 9000)") connection.execute("INSERT INTO Bill VALUES('A12348',1205, 1003, 2, '2018-07-21', 19500)") connection.execute("INSERT INTO Bill VALUES('A12349',1203, 1004, 1, '2018-09-18', 8500)") connection.execute("INSERT INTO Bill VALUES('A12350',1207, 1005, 1, '2018-08-23', 9000)") ####################################################################################################################### connection.commit() connection.close() createTables()
# http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python def all_perms(elements): if len(elements) <=1: yield elements else: for perm in all_perms(elements[1:]): for i in range(len(elements)): #nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] if __name__ == '__main__': n = 6 perms = list() for i in all_perms(range(1,n+1)): perms.append(i) print len(perms) for p in perms: for e in p: print e, print
def noOfStrings( n ): #The number of bit strings of bit size n is the (n + 2)th Fibonacci number a1, a2 = 1, 0 #Setting intial values for num in range( n + 1 ): temp = a1 a1, a2 = a1 + a2, temp #Calculating the (num + 2)th Fibonacci number, and using that along with the previous to calculate the next return (a1 % (1000000007)) t = raw_input() for turns in range( int(t) ): n = raw_input() print noOfStrings( int(n) )
# coding=utf-8 # mache einen string mit einem platzhalter # es ist ein begrüßungstring # der platzhalter wird mit einem namen aufgefüllt # und angezeigt name = "Stepen" print "Welcome {}".format(name) # mache einen string mit einem platzhalter # es ist ein begrüßungstring # mit 2 platzhaltern für vorname und nachname name = "Juia " name2 = "Hein" print "Welcome {}".format(name+name2)
"""单例模式 """ class single(object): issingle = None isfirstinit = False def __new__(cls): if not single.issingle: cls.issingle = object.__new__(cls) # single.issingle = True return cls.issingle def __init__(self): if not single.isfirstinit: print("第一次一定会被初始化,然后就不会再初始化了") single.isfirstinit = True if __name__ == "__main__": # 调试的时候,不能在这里创建对象 s1 = single() s2 = single() print(id(s1)) print(id(s2)) pass # s1 = single() # s2 = single() # print(id(s1)) # print(id(s2))
""" 通过对象和类分别访问私有方法 但类无法访问对象的属性,无论是公有还是私有 """ class Person(): def __init__(self, name): self.name = name self.__age = 18 def __secret(self): print("%s 的年龄是 %d" % (self.name, self.__age)) if __name__ == "__main__": p = Person("xiaofang") print(p._Person__age) p._Person__secret() Person._Person__secret(p)
""" 1.创建子类继承自threading.Thread 2.重写run()方法 3.子类对象调用start()方法 """ import threading import time class myThread(threading.Thread): def __init__(self, num): super().__init__() # 重写父类初始化方法,要先调用父类初始化方法 self.num = num print("我是子类初始化方法", num) def run(self): for i in range(5): print("我是子类,运行第 %d 次" % i) time.sleep(0.5) if __name__ == "__main__": mt = myThread(10) mt.start()
# #helloFunc # def hello(): # print('Howdy!') # print('Howdy!!!') # print('Hello there.') # hello() # hello() # hello() ################################ # #DEF Statements with Parameters # #helloFunc2 # def hello(name): # print('Hello ' + name) # # hello('Alice') # hello('Franky') ############################### # #Return Values and Return Statements # #magic8Ball # import random # def getAnswer(answerNumber): # if answerNumber == 1: # return 'It is certain' # elif answerNumber == 2: # return 'It is decidedly so' # elif answerNumber == 3: # return 'Yes' # elif answerNumber == 4: # return 'Reply hazy, try again' # elif answerNumber == 5: # return 'Ask again later' # elif answerNumber == 6: # return 'Concentrate and ask again' # elif answerNumber == 7: # return 'My reply is no' # elif answerNumber == 8: # return 'Outlook not so good' # elif answerNumber == 9: # return 'Very doubtful' # # r = random.randint(1, 9) # fortune = getAnswer(r) # print(fortune) # #Another way to combine the lines 41 - 43 is print(getAnswer(random.randint(1,9))) ############################# # #Local and Global Scope # # # # #sameName # # def spam(): # # eggs = 'spam local' # # print(eggs) #prints 'spam local' # # # # def bacon(): # # eggs = 'bacon local' # # print(eggs) #prints 'bacon local' # # spam() # # print(eggs) #prints 'bacom local' # # # # eggs = 'global' # # bacon() # # print(eggs) ###################### # #How to modify a global statement within a function # #sameName2 # # def spam(): # global eggs # eggs = 'spam' # # eggs = 'global' # spam() # print(eggs) ##################### # #sameName3 # # def spam(): # global eggs # eggs = 'spam' # this is the global # # def bacon(): # eggs = 'bacon' # this is a local # # def ham(): # print(eggs) # this is global # # eggs = 42 # this is the global # spam() # print(eggs) ####################### # #sameName4 # def spam(): # print(eggs) # Error, because you are asking for a variable that doesn't exist yet # eggs = 'spam local' # # eggs = 'global' # spam()
#!/usr/bin/env python import sys import time # ECS518U # Lab 5 zzz # Have a nap # The snooze time in secs, or forever if no argument is supplied if len(sys.argv) > 1: num_sec = int(sys.argv[1]) inc = 1 else: num_sec = 1 inc = 0 if num_sec % 2: returnCode = 1 else: returnCode = 0 count = 0 # print 'num_sec, inc, count' while count < num_sec: # print 'num_sec, inc, count' print("z ") count += inc # wait for a second time.sleep(1) print("\n") sys.exit(returnCode)
# Initialise maxstep as -1 MAXSTEP = -1 # Function to calculate cycle length def calculate_cycle_length(n): #Initial step as 1 steps = 1 while n != 1: steps += 1 if n % 2 == 0: n //= 2 else: n = 3 * n + 1 return steps # Input values start, end = map(int, input().split()) for num in range(start, end+1): steps = calculate_cycle_length(num) if steps > MAXSTEP: MAXSTEP = steps #Print Result print(start, end, MAXSTEP)
# q1_display_reverse.py # display integer in reverse order # get input integer = input("Enter integers:") while integer.isalpha(): print("Invalid input!") integer = input("Enter integers:") # display results print(integer[::-1])
import random from datetime import datetime now = datetime.now() value = (input('Hi there, what is your name? ')) print() #line break str1 = (' It is your lucky day today, ' 'as we are going to play a cool game ' 'of Rock:Paper:Scissors!') if now.hour < 12: #defines time of day for greeting print(f"Good morning",value,", how are you?" + str1) elif now.hour < 17: print(f"Good Afternoon",value,", how are you?" + str1) elif now.hour < 24: print(f"Good evening", value,", how are you?" + str1) print()#line break print("Here are the rules: " "\n1. You must pick between Rock, Paper or Scissors." "\n2. The computer will, at random, also pick." "\n3. The result will follow after both you and the computer have chosen." "\n4. This is a totally random and fair game, good luck!") print() print("This is how to win:" "\n - Rock beats Paper" "\n - Paper beats Scissors" "\n - Scissors beats Rock") print() # Line break #defining the inputs user_guess = (input("Do you choose Rock, Paper or Scissors? ")) comp_guess = (random.randint(0, 2)) #converting user guess from words to int if user_guess in ('rock','Rock'): user_int = 0 if user_guess in ('paper','Paper'): user_int = 1 if user_guess in ('scissors','Scissors'): user_int = 2 #converting comp guess from int to words to display to user if comp_guess == 0: print('Computer picks Rock') if comp_guess == 1: print('Computer picks Paper') if comp_guess == 2: print('Computer picks Scissors') # printing result to user and determine winner if user_int == comp_guess: print('Wow, it is a Draw!') elif user_int == 0 and comp_guess == 2: print('You win as Rock beats Scissors, congratulations!') elif user_int == 0 and comp_guess == 1: print('Computer wins as Paper beats Rock, sorry!') elif user_int == 2 and comp_guess == 1: print('You win as Scissors beats Paper, congratulations!') elif user_int == 1 and comp_guess == 0: print('You win as Paper beats Rock, congratulations') elif user_int == 1 and comp_guess == 2: print('Computer wins as Scissors beats Paper, sorry!') if user_int == 2 and comp_guess == 0: print('Computer wins as Scissors beats Rock, sorry!')
idade = input("Qual sua idade?") print("Você digitou:", idade) #convertendo a string idade no inteiro idade_int idade_int = int(idade) print("Idade string concatenada com 2") print(idade + "2") print("\n\n") print("Idade numérica somada com 2") print(idade_int + 2)
nome = input("Qual seu nome?") idade = input("Qual sua idade?") print("{} tem {} anos".format(nome, idade)) print(nome, " tem ", idade, " anos") print(nome + " tem " + idade + " anos")
# https://leetcode-cn.com/problems/maximum-subarray/ from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: sub_sum = 0 max_sum = nums[0] for i in range(0, len(nums)): sub_sum = max(sub_sum + nums[i], nums[i]) max_sum = max(sub_sum, max_sum) return max_sum
# https://leetcode-cn.com/problems/longest-consecutive-sequence/ from typing import List class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums: return 0 l = set() for i in range(len(nums)): l.add(nums[i]) sorted_nums = sorted(list(l)) res = [] tmp = [] for i in range(0, len(sorted_nums)-1): tmp.append(sorted_nums[i+1] - sorted_nums[i]) count = 0 for j in range(0, len(tmp)): if tmp[j] == 1: count = count + 1 if tmp[j] != 1: res.append(count) count = 0 res.append(count) return max(res)+1 def longestConsecutiveII(self, nums): longest_streak = 0 num_set = set(nums) for num in num_set: if num - 1 not in num_set: current_num = num current_streak = 1 while current_num + 1 in num_set: current_num += 1 current_streak += 1 longest_streak = max(longest_streak, current_streak) return longest_streak s = Solution() #print(s.longestConsecutive([100, 4, 200, 1, 3, 2])) #s.longestConsecutive([9,1,4,7,3,-1,0,5,8,-1,6]) s.longestConsecutive([1,2,0,1])
# https://leetcode-cn.com/problems/symmetric-tree/ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True return self.isChildSymmetric(root.left, root.right) def isChildSymmetric(self, p, q): if not p or not q: return p == q if p.val != q.val: return False return self.isChildSymmetric(p.left, q.right) and self.isChildSymmetric(p.right, q.left) # 对于此题: 递归的点怎么找?从拿到题的第一时间开始,思路如下: # # 1.怎么判断一棵树是不是对称二叉树? 答案:如果所给根节点,为空,那么是对称。如果不为空的话,当他的左子树与右子树对称时,他对称 # # 2.那么怎么知道左子树与右子树对不对称呢?在这我直接叫为左树和右树 答案:如果左树的左孩子与右树的右孩子对称,左树的右孩子与右树的左孩子对称,那么这个左树和右树就对称。 # # 仔细读这句话,是不是有点绕?怎么感觉有一个功能A我想实现,但我去实现A的时候又要用到A实现后的功能呢? # # 当你思考到这里的时候,递归点已经出现了: 递归点:我在尝试判断左树与右树对称的条件时,发现其跟两树的孩子的对称情况有关系。 # # 想到这里,你不必有太多疑问,上手去按思路写代码,函数A(左树,右树)功能是返回是否对称 # # def 函数A(左树,右树): 左树节点值等于右树节点值 且 函数A(左树的左子树,右树的右子树),函数A(左树的右子树,右树的左子树)均为真 才返回真 # # 实现完毕。。。 # # 写着写着。。。你就发现你写出来了。。。。。。
# https://leetcode-cn.com/contest/weekly-contest-187/problems/destination-city/ from typing import List class Solution: def destCity(self, paths: List[List[str]]) -> str: if not paths: return "" if len(paths) == 1: return paths[0][1] start_city = set() end_city = set() for i in range(0, len(paths)): start_city.add(paths[i][0]) end_city.add(paths[i][1]) return "".join(end_city - start_city) s = Solution() print(s.destCity(paths=[["B","C"],["D","B"],["C","A"]]))
# https://leetcode-cn.com/problems/linked-list-cycle/ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: if head is None: return False if head.next is None: return True p = head q = head.next while q and q.next: p = p.next q = q.next.next if p == q: return True return False
# https://leetcode-cn.com/contest/weekly-contest-191/problems/maximum-product-of-two-elements-in-an-array/ from typing import List class Solution: def maxProduct(self, nums: List[int]) -> int: if not nums: return 0 max_ = max(nums) max_idx = nums.index(max(nums)) ans = [] for i in range(0, len(nums)): if i!=max_idx: ans.append( (max_-1) * (nums[i]-1) ) return max(ans) s = Solution() print(s.maxProduct(nums = [1,5,4,5]))
# https://leetcode-cn.com/contest/weekly-contest-189/problems/rearrange-words-in-a-sentence/ class Solution: def arrangeWords(self, text: str) -> str: if not text: return "" text_list = [] for s in text.lower().split(" "): text_list.append([s, len(s)]) after_sort = sorted(text_list, key=lambda x: x[1]) res = "" for i in range(0, len(after_sort)): if i == 0 : res = res + after_sort[0][0][0].upper() res = res + after_sort[0][0][1:] res = res + " " else: res = res + after_sort[i][0] res = res + " " return res[0:-1] s = Solution() print(s.arrangeWords(text = "Leetcode is cool"))
#https://leetcode-cn.com/problems/valid-parentheses/ class Solution: def isValid(self, s: str) -> bool: if not s: return True if len(s) % 2 == 1: return False s = list(s) tmp_1 = [] flag = False for elem in s: if elem=="(" or elem=="[" or elem=="{": tmp_1.append(elem) if (elem==")" and len(tmp_1)== 0) or (elem=="]" and len(tmp_1)== 0) or (elem=="}" and len(tmp_1)== 0): flag = False break if (elem==")" and tmp_1.pop()!="(") or (elem=="]" and tmp_1.pop()!="[") or (elem=="}" and tmp_1.pop()!="{"): flag = False break flag = True if flag and len(tmp_1) > 0: flag = False return flag def isValidII(self, s: str) -> bool: dic = {')': '(', ']': '[', '}': '{'} stack = [] for i in s: if stack and i in dic: if stack[-1] == dic[i]: stack.pop() else: return False else: stack.append(i) return not stack s = Solution() print(s.isValid(s="{[]}"))
# https://leetcode-cn.com/problems/reverse-linked-list/ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head == None or head.next == None: return head p = self.reverseList(head.next) head.next.next = head head.next = None return p def reverseListii(self, head:ListNode): prev = None curr = head while curr != None: nextTemp = curr.next curr.next = prev prev = curr curr = nextTemp return prev
# https://leetcode-cn.com/problems/decode-string/ class Solution: def decodeString(self, s: str) -> str: stk = [] for ch in s: if ch == ']': sub = '' while stk[-1] != '[': sub = stk.pop() + sub stk.pop() n = '' while stk and stk[-1].isdigit(): n = stk.pop() + n stk.append(int(n) * sub) else: stk.append(ch) return ''.join(stk) s = Solution() s.decodeString(s="3[a]2[bc]")
import socket as s import os # rget -o test1.txt www.w3.org #get users input print "Format: rget -o <output file> http://someurl.domain[:port]/path/to/file" print "Example: rget -o test.txt http://www.google.com/, [:port] is optional" inputCommand = raw_input("Enter command: ") name = inputCommand.split(" ")[2] fileName = name.split(".")[0] fileExt = "." + name.split(".")[1] fileTmpExt = ".tmp" filePath = 'files/' trackerPath = 'tracker/' trackerName = "tracker.txt" serverSocket = s.socket(s.AF_INET, s.SOCK_STREAM) url = inputCommand.split(" ")[3] if url.find(".com") != -1: if url.split(".com")[0].find("//") != -1: host = url.split(".com")[0].split("//")[1] + ".com" else: host = url.split(".com")[0] + ".com" if url.split(".com")[1].find(":") != -1: path = url.split(".com")[1].split(":")[1] serverPort = int(url.split(".com")[1].split(":")[0]) else: path = url.split(".com")[1] serverPort = 80 remote_ip = s.gethostbyname( host ) # Connect to the server serverSocket.connect((remote_ip, serverPort)) elif url.find(".org") != -1: if url.split(".org")[0].find("//") != -1: host = url.split(".org")[0].split("//")[1] + ".org" else: host = url.split(".org")[0] + ".org" if url.split(".org")[1].find(":") != -1: path = url.split(".org")[1].split(":")[1] serverPort = int(url.split(".org")[1].split(":")[0]) else: path = url.split(".org")[1] serverPort = 80 remote_ip = s.gethostbyname( host ) # Connect to the server serverSocket.connect((remote_ip, serverPort)) def getTracker(fileName, host, path, size): f = open(os.path.join(trackerPath, trackerName), 'r') trackFile = f.read() trackList = trackFile.split("\n") trackChecker = fileName + " " + host + " " + path + "_" + size for i in trackList: if i == trackChecker: track = trackChecker.split("_")[1] return int(track) def resume(size): track = getTracker(fileName+fileTmpExt, host, path, size) message = "GET " + path + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Range: bytes=%i-\r\nConnection: close\r\n\r\n" %(track) serverSocket.send(message) def download(): message = "GET " + path + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n" serverSocket.send(message) def tracker(fileName, host, path, size): if os.path.isfile(os.path.join(trackerPath, trackerName)): f = open(os.path.join(trackerPath, trackerName), 'r') trackChecker = fileName + " " + host + " " + path trackFile = f.read() f.close() if trackFile.find(trackChecker) == -1: f = open(os.path.join(trackerPath, trackerName), 'a') f.write(trackChecker + "_" + size) f = open(os.path.join(trackerPath, trackerName), 'r') trackChecker = fileName + " " + host + " " + path trackFile = f.read() f.close() trackList = trackFile.split("\n") open(os.path.join(trackerPath, trackerName), 'w').close() f = open(os.path.join(trackerPath, trackerName), 'w') for line in trackList: if line.split("_")[0] == trackChecker: line = line.replace(line.split("_")[1], str(size)) f.write(line + "\n") elif line != "": if trackFile.find(line) != -1 or trackFile.find(trackChecker) != -1: f.write(line + "\n") else: f.write(fileName + " " + host + " " + path + "_" + size + "\n") f.close else: f = open(os.path.join(trackerPath, trackerName), 'a') f.write(fileName + " " + host + " " + path + "_" + size + "\n") f.close() def resetTracker(): f = open(os.path.join(trackerPath, trackerName), 'r') trackFile = f.read() f.close() trackList = trackFile.split("\n") open(os.path.join(trackerPath, trackerName), 'w').close() f = open(os.path.join(trackerPath, trackerName), 'w') for line in trackList: if line != "": line = line.replace(line.split("_")[1], str(0)) f.write(line + "\n") f.close() def filesWriter(reply): f = open(os.path.join(filePath, fileName+fileTmpExt), 'a') f.write(reply) f.close() def fileStore(): os.rename(os.path.join(filePath, fileName+fileTmpExt), os.path.join(filePath, fileName+fileExt)) resetTracker() if os.path.isfile(os.path.join(filePath, fileName+fileTmpExt)): size = str(os.path.getsize(os.path.join(filePath, fileName+fileTmpExt))) f = open(os.path.join(trackerPath, trackerName), 'r') trackFile = f.read() trackChecker = fileName + fileTmpExt + " " + host + " " + path if trackFile.find(trackChecker) != -1: resume(size) else: os.remove(os.path.join(filePath, fileName+fileTmpExt)) download() else: download() while True: # Recieved Data reply = serverSocket.recv(1024) if len(reply) <= 0: fileStore() break if reply.find('\r\n\r\n') == -1: filesWriter(reply) tracker(fileName+fileTmpExt, host, path, str(os.path.getsize(os.path.join(filePath, fileName+fileTmpExt)))) else: data = reply.split('\r\n\r\n')[1] filesWriter(data) tracker(fileName+fileTmpExt, host, path, str(os.path.getsize(os.path.join(filePath, fileName+fileTmpExt))))
def set_intersection(arr1,arr2): set1 = set(arr1) set2 = set(arr2) print set1,set2 output = [] for element in set1 : if element in set2 : print element print output.append(element) print output arr1 = [1,2,3,4,4] arr2 = [1,4,4] set_intersection(arr1,arr2)
class Node(object): def __init__(self,data): self .data=data self.next = None a1= Node("A") b1= Node("B") c1= Node("C") d1= Node("D") e1= Node("E") f1= Node("F") g1= Node("G") a1.next= b1 b1.next= c1 c1.next= d1 d1.next= e1 e1.next= f1 f1.next= c1 n1= Node("1") n2= Node("2") n3= Node("3") n4= Node("4") n5= Node("5") n6= Node("6") n1.next= n2 n2.next= n3 n3.next= n4 n4.next= n5 n5.next= n6 def traverse1(node): temp = node while(temp !=None): if temp.next != None : print temp.data +">", temp= temp.next else : print temp.data break def cycle_check(node): marker1 = node marker2 = node print marker1.data,marker2.data while marker2 != None and marker2.next.next !=None: marker2 = marker2.next.next marker1= marker1.next print marker1.data,marker2.data if (marker1 == marker2): print marker1.data,marker2.data return True break return False print cycle_check(n1) traverse1(n4)
import operator def odd_occuring(arr): res = arr[0] for i in xrange(1,len(arr)): res =operator.xor(res,arr[i]) print res arr =[2,2,7,6,7,3,3] odd_occuring(arr)
def dup_remove(arr): s1 =set(arr) print s1 dict ={} for i in arr: if dict.has_key(i): s1.remove(i) print s1 else : dict[i]= True print dict print s1 arr = [1,1,2,2,37,4,4,5,5] dup_remove(arr)
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pygame import random import math #initializing the pygame pygame.init() #creating the screen screen = pygame.display.set_mode((800,600)) #adding background background = pygame.image.load('background.png') # whatever we do in the game window is known as event # Quitting the game is also an event # Also hovering mouse also is an event #Title and Icon pygame.display.set_caption("Space Invaders") icon = pygame.image.load('ufo.png') pygame.display.set_icon(icon) #Player playerImg = pygame.image.load('player.png') playerX = 370 playerY = 480 playerX_change = 0 #Enemy enemyImg = pygame.image.load('alien2.png') enemyX = random.randint(0,800) enemyY = random.randint(50,150) enemyX_change = 0.3 enemyY_change = 20 #Bullet bulletImg = pygame.image.load('bullet.png') bulletX = random.randint(0,800) bulletY = 480 bulletX_change = 0 bulletY_change = 4 bullet_state = "ready" score = 0 # Ready state means you can't see the bullet but its # ready to fire # fire state is when the bullet is fired def player(x,y): screen.blit(playerImg, (x,y)) # The following is the game loop def enemy(x,y): screen.blit(enemyImg , (x,y)) def fire_bullet(x,y): global bullet_state bullet_state = "fire" screen.blit(bulletImg,(x+16,y+10)) def isCollision(enemyX , enemyY , bulletX, bulletY): distance = math.sqrt((math.pow((enemyX-bulletX),2))+(math.pow((enemyY-bulletY),2))) if distance < 27: return True else: return False running = True while running: screen.fill((0,0,0)) #background image screen.blit(background, (0,0)) # the following line returns all the events of pygame window for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # if keystroke is pressed check # whether its right or left keystroke if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_change = -2 if event.key == pygame.K_RIGHT: playerX_change = 2 if event.key == pygame.K_SPACE: if bullet_state is "ready": # Get X coordinate of the spaceship bulletX = playerX fire_bullet(bulletX,bulletY) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerX_change = 0 # RGB - Red , Green , Blue # we called the player method in while loop because we want # player to be shown always on the screen. playerX += playerX_change enemyX += enemyX_change #following lines are added to add boundaries to the game. # checking the boundaries of spaceship if playerX < 0: playerX = 0 elif playerX >= 736: playerX = 736 #checking the boundaries of enemy movement if enemyX < 0: enemyX_change = 0.6 enemyY += enemyY_change elif enemyX >= 736: enemyX_change = -0.6 enemyY += enemyY_change # fire bullet if bulletY <= 0: bulletY = 480 bullet_state = "ready" if bullet_state is "fire": fire_bullet(bulletX,bulletY) bulletY -= bulletY_change #collision collision = isCollision(enemyX,enemyY,bulletX , bulletY) if collision: bulletY = 480 bullet_state = "ready" score += 1 print(score) player(playerX,playerY) enemy(enemyX , enemyY) pygame.display.update()
# -*- coding: utf-8 -*- """ Created on Sun Jul 26 19:28:08 2020 @author: Aditi Agrawal """ year=int(input("Enter year you wish: ")) if((year%400==0) or (year%4==0) and (year%100!=0)): print(year," is leap year") else: print(year," is not leap year")
# Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, # and that keeps both safe from outside interference and misuse. # The best example of encapsulation could be a calculator. # Encapsulation is a mechanisme of hiding data implementations # means that instances variables are kept private there is onlyone access method for outside which we can access and change method call getter() and setter() method # instance method can be also kept private and use internally only not from the outside class SoftwareEngineer: def __init__(self, name, age): self.name = name # this is external use self.age = age # this is external use #self.__salary = None private with double underscore self._salary = None # this is private internally use only self._num_bugs_solved = 0 #this is private internally use only #note: _salary: is called a "protected" attribute(one underscore) # __salary: is called a "private" attribute (double underscore) # Here i use the word "private" for internal attributes with only one leading underscore as well # they implement this in order to get a value for _num_bugs_solved def code(self): self._num_bugs_solved += 1 # with += 1 we need for loop to implemet by 1 until we reach 70 # public function is the only way the outside can access the protected attribute #getter def get_salary(self): return self._salary # public function is the only way the outside can access the protected attribute #setter def set_salary(self, base_value): self._salary = self._calculate_salary(base_value) def _calculate_salary(self, base_value): if self._num_bugs_solved < 10: return base_value if self._num_bugs_solved < 100: return base_value * 2 return base_value * 3 se = SoftwareEngineer("Frank", 39) # print(se.age, se.name, se._salary ) for i in range(70): # print(f"the code is {se.code()}") se.set_salary(6000) print(se.get_salary())
"""Text analysis in Python""" import pandas as pd import nltk from nltk.corpus import stopwords stop = stopwords.words('english') df = pd.read_json("/Users/Joel/Desktop/Tweets/final_poke_tweets.json") def transform_data_for_processing(data): #Transforms twiiter data into a list of words #And removes stop words alist = [] temp = "" for x in range(len(data)): temp = str(data[x]).lower() adj_temp = [i for i in temp if i not in stop] alist.append(temp.split()) return alist """Columns 'contributors', 'coordinates', 'created_at', 'entities', 'extended_entities', 'favorite_count', 'favorited', 'filter_level', 'geo', 'id', 'id_str', 'in_reply_to_screen_name', 'in_reply_to_status_id', 'in_reply_to_status_id_str', 'in_reply_to_user_id', 'in_reply_to_user_id_str', 'is_quote_status', 'lang', 'limit', 'place', 'possibly_sensitive', 'quoted_status', 'quoted_status_id', 'quoted_status_id_str', 'retweet_count', 'retweeted', 'retweeted_status', 'scopes', 'source', 'text', 'timestamp_ms', 'truncated', 'user'] """ text_data = df["text"] #print((text_data[1])) transformed_text_data = transform_data_for_processing(text_data) transformed_tokenize_list = tokenize_data(transformed_text_data) for line in transformed_tokenize_list: print(line)
""" This file contains the motion model for a simple differential drive mobile robot. In the robots frame positive x is forward and positive y is to the left. The control commands are forward velocity and angular velocity. Positive angular velocity if considered counterclockwise. """ import numpy as np from params import* def mobile_robot(u, pose, dt, noise=False): """ updates pose of mobile robot with option to add noise Args: u (array): shape 2x1 velocity and angular velocity pose (array): shape 3x1 previous pose containing x, y, and theta Returns pose (array): shape 3x1 new pose containing x, y, and theta """ v = u[0] w = u[1] x = pose[0] y = pose[1] theta = pose[2] # determine the change in pose dx = v*np.cos(theta)*dt dy = v*np.sin(theta)*dt dtheta = w*dt # wrap theta from 0 to 2pi theta = theta + dtheta num_rev = theta/(2*np.pi) rev_frac = num_rev - int(num_rev) theta = rev_frac*2*np.pi # wrap pi to -pi if theta > np.pi: theta -= 2*np.pi elif theta < -np.pi: theta += 2*np.pi if noise: n_dx = np.random.normal(0, std_dx**2) n_dy = np.random.normal(0, std_dy**2) n_dtheta = np.random.normal(0, std_dtheta**2) return [dx + x + n_dx, dy + y + n_dy, theta + n_dtheta] else: return [dx + x, dy + y, theta] #
X = [7.47 , 7.48 , 7.49 , 7.50 , 7.51 , 7.52] Y = [1.93 , 1.95 , 1.98 , 2.01 , 2.03 , 2.06] n = len(X) h = X[1] - X[0] def trapezoidal(X , Y , h): area = (Y[1] + Y[0]) * (h / 2) return area if __name__ == "__main__": i = 0 S = 0 while (i < n - 1): x = [X[i] , X[i + 1]] y = [Y[i] , Y[i + 1]] S += trapezoidal(x , y , h) i += 1 print("\n\nThe integral of curve is " , S)