text
stringlengths
37
1.41M
#writes False if any one of them is greater than or equal to the sum of the other two and True #otherwise. # (Note: This computation tests whether the three numbers could be the lengths of the sides of # some triangle.) #---------------------------------------------------------------------------------------------------- #if_side_of_trngl.py #---------------------------------------------------------------------------------------------------- import stdio import sys side1 = int(sys.argv[1]) side2 = int(sys.argv[2]) side3 = int(sys.argv[3]) #Sum three sides #find out the greater sides #determine the shorter side # greater side >= compute sum of shorter two sides - false else true #Sum three sides total=side1+side2+side3 greatest = side1 #compute greatest among three if greatest < side2 : greatest = side2 elif greatest < side3 : greatest = side3 #compute greatest among three smallest = side1 if smallest > side2: smallest = side2 elif smallest > side3: smallest = side3 smaller = total - ( greatest + smallest ) stdio.writeln(smallest) stdio.writeln(smaller) stdio.writeln(greatest) if greatest >= smallest + smaller : stdio.writeln("False,cannot form a triangle") else : stdio.writeln("True,can form a triangle")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 19 09:23:33 2018 @author: joykumardas program.py """ def main(): folder = get_folder_from_user() if not folder: print("Sorry we cant search that location.") return text = get_search_text_from_user() if not text: print("we can't search for nothing.") return search_folders( folder , text ) def print_header(): print('-----------------------------------') print(' File Search App ') print('-----------------------------------') def get_folder_from_user(): pass def get_search_text_from_user(): pass def search_folders ( folder , text ): pass if __name__ == '__main__': main()
import tkinter as tk import requests from bs4 import BeautifulSoup url = 'https://weather.com/en-IN/weather/today/l/32355ced66b7ce3ab7ccafb0a4f45f12e7c915bcf8454f712efa57474ba8d6c8' root = tk.Tk() root.title("Weather") root.config(bg = 'white') def getWeather(): page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') location = soup.find('h1',class_="_1Ayv3").text temperature = soup.find('span',class_="_3KcTQ").text airquality = soup.find('text',class_='k2Z7I').text airqualitytitle = soup.find('span',class_='_1VMr2').text sunrise = soup.find('div',class_='_2ATeV').text sunset = soup.find('div',class_='_2_gJb _2ATeV').text humidity = soup.find('div',class_='_23DP5').text wind = soup.find('span',class_='_1Va1P undefined').text pressure = soup.find('span',class_='_3olKd undefined').text locationlabel.config(text=(location)) templabel.config(text = temperature+"C") WeatherText = "Sunrise : "+sunrise+"\n"+"SunSet : "+sunset+"\n"+"Pressure : "+pressure+"\n"+"Wind : "+wind+"\n" weatherPrediction.config(text=WeatherText) airqualityText = airquality + " "*5 + airqualitytitle + "\n" airqualitylabel.config(text = airqualityText) weatherPrediction.after(120000,getWeather) root.update() locationlabel= tk.Label(root, font = ('Calibri bold',20), bg = 'white') locationlabel.grid(row = 0,column = 1, sticky='N',padx=20,pady=40) templabel = tk.Label(root, font = ('Caliber bold', 40), bg="white") templabel.grid(row=0,column = 0,sticky="W",padx=17) weatherPrediction = tk.Label(root, font = ('Caliber', 15), bg="white") weatherPrediction.grid(row=2,column=1,sticky="W",padx=40) tk.Label(root,text = "Air Quality", font = ('Calibri bold',20), bg = 'white').grid(row = 1,column = 2, sticky='W',padx=20) airqualitylabel = tk.Label(root, font = ('Caliber bold', 20), bg="white") airqualitylabel.grid(row=2,column=2,sticky="W") getWeather() root.mainloop()
num=int(input("enter any Number")) rev =0 while num>0 : Rem = num% 10 num = num//10 rev=rev*10+Rem print("The Reverse of the number",rev)
#this code gives the numbers of integers, floats, and strings present in the list a= ['Hello',35,'b',45.5,'world',60] i=f=s=0 for j in a: if isinstance(j,int): i=i+1 elif isinstance(j,float): f=f+1 else: s=s+1 print('Number of integers are:',i) print('Number of Floats are:',f) print("numbers of strings are:",s)
# Decision Tree Regression tutorial from Machine Learning A-Z - SuperDataScience # Input by Ryan L Buchanan 23SEP20 # Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:-1].values y = dataset.iloc[:, -1].values print(X) print(y) # Train the Decision Tree Regression model from sklearn.tree import DecisionTreeRegressor regressor = DecisionTreeRegressor(random_state=0) regressor.fit(X, y) # Predict new result print("The predicted salary is $" + str(int(regressor.predict([[6.5]])))) # Visualize the Decision Tree Regression results (higher resolution) X_grid = np.arange(min(X), max(X), 0.1) X_grid = X_grid.reshape(len(X_grid), 1) ax = plt.gca() ax.set_facecolor('grey') plt.scatter(X, y, color = 'red') plt.plot(X_grid, regressor.predict(X_grid), color = 'blue') plt.title("Truth or Bluff (Design Tree Regression)") plt.xlabel("Years of Experience") plt.ylabel("Salary in $US") plt.show()
import pygame from pygame.locals import * WIDTH = 600 HEIGHT = 300 WINDOW_DIMENSIONS = (WIDTH, HEIGHT) WHITE = pygame.Color('white') BLACK = pygame.Color('black') # some variables to define an oscillating circle RADIUS = 50 # circle radius, pixels LINEWIDTH = 1 # circle line width, pixels XMIN = RADIUS # minimum x position XMAX = WIDTH - RADIUS # maximum x position YMIN = RADIUS YMAX = HEIGHT - RADIUS FPS = 100 # how many frames per second do we want? position = [XMIN, YMIN] # define a starting x,y velocity = [240, 60] # pick some numbers, pixels/second # start setting up Pygame pygame.init() displaysurface = pygame.display.set_mode(WINDOW_DIMENSIONS) pygame.display.set_caption('Pygame Animate 1') clock = pygame.time.Clock() # make a clock object to manage a frame rate done = False while not done: # main game loop elapsedms = clock.tick(FPS) # forces WAIT to maintain FPS # compute a new position for the circle based on old position and velocity position = [p + v/FPS for p,v in zip(position, velocity)] # v/FPS computes pixels/frame instead of pixels/second # resulting position is a tuple of floats! # check to see if the circle is outside the margin if ((position[0] > XMAX and velocity[0] > 0) or (position[0] < XMIN and velocity[0] < 0)): # outside left/right margin? velocity[0] *= -1 # reverse the x velocity if ((position[1] > YMAX and velocity[1] > 0) or (position[1] < YMIN and velocity[1] < 0)): # outside top/bottom margin? velocity[1] *= -1 # reverse the x velocity displaysurface.fill(BLACK) # erase the entire display surface pygame.draw.circle(displaysurface, WHITE, [int(x) for x in position], # position must be passed with integer parts RADIUS, LINEWIDTH) # draw a circle directly to the display surface pygame.display.update() # refresh the display screen (display what we have done) for event in pygame.event.get(): # check for events if event.type == QUIT: done = True else: print(event) # see the variety of events that pygame knows about
#! /usr/bin/python # # Simple Roman Merels engine (to be used in a pygame application) # http://gwydir.demon.co.uk/jo/games/romgame/index.htm # __author__ = 'ericdennison' import random import re from consoletictactoe import TTTPosition class MerelsPosition(TTTPosition): """ Representation of a Merels board play position (where pieces are and whose turn it is) Internally, the board is represented as a tuple of 9 integers that represent positions on the circular grid, thus: ( 0, 0, 0, 0, 0, 0, 0, 0, 0) Winning positions: X ~ ~ ~ ~ X ~ X ~ ~ ~ ~ ~ X ~ ~ X ~ ~ X ~ X X X ~ ~ X X ~ ~ ~ X ~ ~ ~ ~ X is represented by +1 O is represented by -1 In addition to the board position, the object also knows which player is to move NEXT (-1 or +1) See http://gwydir.demon.co.uk/jo/games/romgame/index.htm """ # Coordinates for three in a row. Each tuple represents the indexes of three # positions on the board that represent a win if they all hold the same # non-zero value (i.e. all +1 or all -1). We will use this to "automate" the # process of checking for a winning position. threes = [ (3,4,5), # horizontal (1,4,7), # vertical (0,4,8), # diagonal slope -1 (2,4,6)] # diagonal slope +1 # Coordinates for neighbors of each position on the board. This is used # to find candidate positions for sliding neighbors = [ (1,3,4), # neighbors from 0 (0,2,4), # neighbors from 1 (1,4,5), # and so on... (0,4,6), (0,1,2,3,5,6,7,8), # lots of places to go from 4 (2,4,8), (3,4,7), (4,6,8), (4,5,7)] searchdepth = 7 def __init__(self, statelist = [0,0,0,0,0,0,0,0,0], nextplayer = 1): super(MerelsPosition, self).__init__(statelist, nextplayer) def _possiblemoves(self): """ Return a list of new MerelsPosition objects representing all possible next moves. The method walks through every spot on the grid, looking for empty ones. Each empty spot is used to define a new MerelsPosition object with that spot filled. The list of new MerelsPosition objects is returned. If player hasn't played all his pieces yet, he must play one. If all have been played, a piece may be slid one position Note: the method sets a property: nextmoves with the result of this call. If it is called a second time in the future, it just returns the previously computed version. """ # utility function for adding new positions appendposition = lambda pos, player=self.nextplayer * -1: self.nextmoves.append(MerelsPosition(pos,player)) if not len(self.nextmoves): if self.mustslide(): for i in range(9): # for each spot on the board if self.board[i] == self.nextplayer: # if our piece is there for n in self.neighbors[i]: # consider its neighbors if not self.board[n]: # that are empty newboard = list(self.board[:]) newboard[n] = self.nextplayer # move here newboard[i] = 0 # from here appendposition(newboard) else: for i in range(9): if not self.board[i]: newboard = list(self.board[:]) newboard[i] = self.nextplayer appendposition(newboard) #self.nextmoves.append(MerelsPosition(newboard, self.nextplayer * -1)) return self.nextmoves def mustslide(self): """ Return True if the nextplayer has played all his positions and must begin sliding. """ return self.board.count(self.nextplayer) == 3 def setslide(self, frcoords, tocoords): """ Play a slide on the board """ boardlist = list(self.board) boardlist[self._ifromxy(tocoords)] = self.nextplayer boardlist[self._ifromxy(frcoords)] = 0 return self._newinstance(boardlist, self.nextplayer * -1) def inputnextmove(self): """ Solicit next move from the user. Loop until the entered move is one of the possible next moves known for the current position. """ possibles = self._possiblemoves() next = None if len(possibles): while not next in possibles: # ensure valid moves are taken by the human print ("Current board position is: ") print (self) if self.mustslide(): movetext = input("Slide a piece using > char - enter from > to: eg. 0,2 > 1,1: ") movecoords = re.search("(\d+).*,.*(\d+).*>.*(\d+).*,.*(\d+)", movetext) if movecoords: frmove = [int(x) for x in movecoords.groups()[:2]] tomove = [int(x) for x in movecoords.groups()[2:4]] next = self.setslide(frmove, tomove) else: movetext = input("Your move - enter location coordinate pair: e.g. 0,2: ") coords = re.search("(\d+).*,.*(\d+)", movetext) if coords: move = [int(x) for x in coords.groups()] next = self.setmove(move) return next else: return None # no more moves possible # Play the game! # Set an initial, blank position, next player is X if __name__ == '__main__': g = MerelsPosition([0,0,0,0,0,0,0,0,0],1) g.playconsole()
import pygame from pygame.locals import * from pygameapp import PygameApp from circle import Circle class MyApp(PygameApp): """ Custom version of PygameApp, to display moving circle """ def __init__(self, screensize = (400,400)): """ Application initialization is executed only ONCE! """ super().__init__(screensize = screensize, title="My Test Application") # call base class initializer pygame.key.set_repeat(100) # allow keys to repeat when held 100 msec self.setbackgroundcolor((220,220,220)) # set a new background color self.circ = Circle(self.spritegroup) # create a default circle def handle_event(self, event): """ Override the base class event handler. Based on mouse and keyboard input make adjustments to the Circle object or make copies of it. """ if event.type == MOUSEMOTION: self.circ.setpos(event.pos) elif event.type == MOUSEBUTTONDOWN: if event.button == 4: # scroll UP "button" self.circ.setradius(self.circ.radius+1) elif event.button == 5: # scroll DOWN "button" self.circ.setradius(self.circ.radius-1) elif event.button == 1: newcirc = self.circ.copy() # "drop" a copy of the current circle newcirc.setcolor((255,0,0,200)) newcirc.setthickness(1) newcirc.update() # force update and display elif event.type == KEYDOWN: # keyboard circpos = self.circ.pos if event.key == K_UP: # cursor up circpos = (circpos[0],circpos[1]-1) # calculate a new position elif event.key == K_DOWN: # cursor down circpos = (circpos[0],circpos[1]+1) # calculate a new position self.circ.setpos(circpos) # update the position else: print (pygame.event.event_name(event.type)) # view unhandled events on the console return True # Keep going! def quit(self): """ Override default quit behavior here, if desired """ pass def poll(self): """ Override default poll behavior here, if desired """ pass # Run an instance of MyApp! if __name__ == '__main__': myapp = MyApp() myapp.run(100) # 100 frames per second!
def ContientE(mot): if "e" in mot : return True return False def NbE(mot): nbE=0 for i in mot: if i=="e": nbE+=1 return nbE def ContientLettre(mot, lettre): for i in range(len(mot)) : if mot[i]==lettre: print("La lettre",lettre,"se trouve la position",str(i+1)) def IndicesPaires(mot): carPaires="" for i in range (len(mot)): if i%2==0:carPaires+=mot[i] print(carPaires) def ContientMaj(mot): for i in mot: if i.isupper():return(True) return(False) print(ContientMaj("ab3j")) def InsererAsterix(mot): motAsterix="" for i in mot: motAsterix +=i motAsterix+="*" return(motAsterix) def InverserChaine(mot): motInverse = "" for i in reversed(range(len(mot))): motInverse += mot[i] return motInverse def InverserChaine2(mot): motInverse = "" for i in range(len(mot)): motInverse += mot[len(mot)-i-1] return motInverse def Palindrome(mot): motInverse = "" palindrome = False for i in reversed(range(len(mot))): motInverse += mot[i] if(mot==motInverse): palindrome = True return (motInverse,palindrome)
# Name: Ryan Menow # Date: 12/06/2020 # Course: CSCI 330 - Programming Languages # Professor: William Killian # Assignment: MU Calculator # Description: Implement a calculator using Python! # This includes implementing the lexical analyszer, expression parser and evalutor. import ply.lex as lex import ply.yacc as yacc from calclex import tokens import sys #=====================Lexical Analyser============================== # List of tokens tokens = [ 'PLUS', 'MINUS', 'TIMES', 'DIVIDES', 'POWER', 'LPAREN', 'RPAREN', 'NUMBER', 'PI', 'E', ] # Rules for tokens t_PLUS = r'\+' t_MINUS = r'\-' t_TIMES = r'\*' t_DIVIDES = r'\/' t_POWER = r'\^' t_LPAREN = r'\(' t_RPAREN = r'\)' # Ignore whitespace t_ignore = r' ' # Define what NUMBER is def t_NUMBER(t): r'\d+(\.\d*)?' t.value = float(t.value) return t # Define what PI is def t_PI(t): r'[p][i]' t.value = 3.14159265358979 return t # Define what E is def t_E(t): r'[e]' t.value = 2.71828182845904 return t # Error for illegal characters def t_error(t): print("You have an illegal character(s)!") t.lexer.skip(1) # Creates lexer lexer = lex.lex() #=====================Expression Parser & Evaluator============================= # Sets precedence for operators precedence = ( ('left', 'PLUS', 'MINUS'), ('left', 'TIMES', 'DIVIDES'), ('right', 'POWER'), ) # Displays solution to calculation def p_calc(p): ''' calc : Exp | empty ''' print(run(p[1])) # Calculates the given expression(s) def run(p): # If p is a tuple compute the appropriate calculation if type(p) == tuple: # Calculation for addition if p[0] == '+': return run(p[1]) + run(p[2]) # Calculation for subtraction elif p[0] == '-': return run(p[1]) - run(p[2]) # Calculation for multiplication elif p[0] == '*': return run(p[1]) * run(p[2]) # Calculation for division elif p[0] == '/': return run(p[1]) / run(p[2]) # Calculation for exponation elif p[0] == '^': return run(p[1]) ** run(p[2]) # If p is not a tuple, then return p else: return p # Handles Expression grammars and sets up AST using tuples def p_exp(p): ''' Exp : Exp PLUS Exp | Exp MINUS Exp | Exp TIMES Exp | Exp DIVIDES Exp | Exp POWER Exp ''' p[0] = (p[2], p[1], p[3]) def p_exp_term(p): ''' Exp : Term ''' p[0] = p[1] # Handles Term grammars def p_term_paren(p): ''' Term : LPAREN Exp RPAREN ''' p[0] = p[2] def p_term_num(p): ''' Term : Num ''' p[0] = p[1] # Handles Num grammars def p_num(p): ''' Num : NUMBER | PI | E ''' p[0] = p[1] # Handles empty input def p_empty(p): ''' empty : ''' p[0] = None # Handles Syntax error def p_error(p): print("There is a syntax error in your input!") # Creates parser parser = yacc.yacc() # Allows user to give input to the parser while True: try: s = input('>>> ') except EOFError: break parser.parse(s)
string = input("Enter sentence to encrypt: ") shift = int(input("Enter value to shift characters by: ")) stringl = string.split() wordList = [] i = 0 for word in stringl: wordList.append([]) for letter in word: x = ord(letter) if x in range(97, 123): x += shift if x > 122: x = 96 + (x - 122) elif x in range(65, 91): x += shift if x > 90: x = 64 + (x - 90) wordList[i].append(chr(x)) i += 1 print(wordList) for word in wordList: for letter in word: print(letter.strip(), end = "") print(" ", end = "") print()
bDay = input("Enter your birthdate (dd/mm/yyyy): ").split("/") b = int(bDay[0]) a = int(bDay[1]) c = int(bDay[2]) % 100 d = int(bDay[2]) // 100 if a <= 10: a -= 2 else: a += 10 c -= 1 w = (13 * a - 1)//5 x = c // 4 y = d // 4 z = w + x + y + b + c - 2 * d r = z % 7 dayList = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] if r < 0: r += 7 print(dayList[r])
n = int(input("Enter your number: ")); a = 1; x = 0; y = 1; def getFibo(x, y, a, n): z = 0 if a <= n: z = x + y; a += 1; return getFibo(y, z, a, n); else: return x; print(getFibo(x, y, a, n));
while True: num = int(input("Enter your integer: ")) if num **0.5 > 998537: print("Number entered is out of range (max is 9900000000000)") #Actually limit can be higher but eh... else: break f = open("primes1000000.txt", "r") primes = f.read().split() f.close() def checkPrime(num, primes): if str(num) in primes: return True for i in primes: if num % int(i) == 0: return False return True print(checkPrime(num, primes))
# -*- coding: utf-8 -*- """ Created on Mon Apr 22 10:13:21 2019 @author: Administrator """ ## CODE FOR MINES IMPLEMENTATION def dump(game): """Print a human-readable representation of game. Arguments: game (dict): Game state >>> dump({'dimensions': [1, 2], 'mask': [[False, False]], 'board': [['.', 1]], 'state': 'ongoing'}) dimensions: [1, 2] board: ['.', 1] mask: [False, False] state: ongoing """ lines = ["dimensions: %s" % (game["dimensions"], ), "board: %s" % ("\n ".join(map(str, game["board"])), ), "mask: %s" % ("\n ".join(map(str, game["mask"])), ), "state: %s" % (game["state"], ), ] print("\n".join(lines)) # Helper function def fill_entry(rows, cols, value): """Return a rows*cols nested list. input: rows (int) : number of rows cols (int) : number of columns value (float) : value to be filled in each cell """ ans = [] for i in range(rows): r = [] for j in range(cols): r.append(value) ans.append(r) return ans def neibour_idx(num_rows, num_cols, r, c): """Return a list of index for neibours of (r,c). """ ans = [] for x in [r-1, r, r+1]: for y in [c-1, c, c+1]: if 0 <= x < num_rows: if 0 <= y < num_cols: ans.append((x, y)) return ans def calcu_squares(game): """Return : bombs (int) : number of bombs have been found covered_squares (int) : numbers of covered squares """ bombs = 0 covered_squares = 0 for r in range(game["dimensions"][0]): for c in range(game["dimensions"][1]): if game["board"][r][c] == ".": if game["mask"][r][c] == True: bombs += 1 elif game["mask"][r][c] == False: covered_squares += 1 return bombs, covered_squares # End helper function def new_game(num_rows, num_cols, bombs): """Start a new game. Return a game state dictionary, with the "dimensions", "state", "board" and "mask" fields adequately initialized. Parameters: num_rows (int): Number of rows num_cols (int): Number of columns bombs (list): List of bombs, given in (row, column) pairs, which can be either tuples or lists Returns: A game state dictionary >>> dump(new_game(2, 4, [(0, 0), (1, 0), (1, 1)])) dimensions: [2, 4] board: ['.', 3, 1, 0] ['.', '.', 1, 0] mask: [False, False, False, False] [False, False, False, False] state: ongoing """ # fill entry (revise 2) board = fill_entry(num_rows, num_cols, 0) for b in bombs: board[b[0]][b[1]] = '.' mask = fill_entry(num_rows, num_cols, False) # revise 2 for r in range(num_rows): for c in range(num_cols): if board[r][c] == 0: neighbor_bombs = 0 for x, y in neibour_idx(num_rows, num_cols, r, c): # revise 4 if board[x][y] == '.': neighbor_bombs += 1 board[r][c] = neighbor_bombs return {"dimensions": [num_rows, num_cols], "board" : board, "mask" : mask, "state": "ongoing"} def reveal_squares(game, row, col): """Helper function: recursively reveal squares on the board, and return the number of squares that were revealed.""" if game["board"][row][col] != 0: if game["mask"][row][col]: return 0 else: game["mask"][row][col] = True return 1 else: revealed = set() # conditions (revise 3) (revise 5) num_rows, num_cols = game["dimensions"] for r, c in neibour_idx(num_rows, num_cols, row, col): if game["board"][r][c] != '.' and not game["mask"][r][c]: game["mask"][r][c] = True revealed.add((r, c)) total = len(revealed) for r,c in revealed: if game["board"][r][c] != "." : total += reveal_squares(game, r, c) return total def dig(game, row, col): """Recursively dig up (row, col) and neighboring squares. Update game["mask"] to reveal (row, col); then recursively reveal (dig up) its neighbors, as long as (row, col) does not contain and is not adjacent to a bomb. Return an integer indicating how many new squares were revealed. The state of the game should be changed to "defeat" when at least one bomb is visible on the board after digging (i.e. game["mask"][bomb_location] == True), "victory" when all safe squares (squares that do not contain a bomb) and no bombs are visible, and "ongoing" otherwise. Parameters: game (dict): Game state row (int): Where to start digging (row) col (int): Where to start digging (col) Returns: int: the number of new squares revealed >>> game = {"dimensions": [2, 4], ... "board": [[".", 3, 1, 0], ... [".", ".", 1, 0]], ... "mask": [[False, True, False, False], ... [False, False, False, False]], ... "state": "ongoing"} >>> dig(game, 0, 3) 4 >>> dump(game) dimensions: [2, 4] board: ['.', 3, 1, 0] ['.', '.', 1, 0] mask: [False, True, True, True] [False, False, True, True] state: victory >>> game = {"dimensions": [2, 4], ... "board": [[".", 3, 1, 0], ... [".", ".", 1, 0]], ... "mask": [[False, True, False, False], ... [False, False, False, False]], ... "state": "ongoing"} >>> dig(game, 0, 0) 1 >>> dump(game) dimensions: [2, 4] board: ['.', 3, 1, 0] ['.', '.', 1, 0] mask: [True, True, False, False] [False, False, False, False] state: defeat """ state = game["state"] if state == "defeat" or state == "victory": game["state"] = state return 0 if game["board"][row][col] == '.': game["mask"][row][col] = True game["state"] = "defeat" return 1 bombs, covered_squares = calcu_squares(game) # (revise 4) if bombs != 0: game["state"] = "defeat" return 0 if covered_squares == 0: game["state"] = "victory" return 0 revealed = reveal_squares(game, row, col) bombs, covered_squares = calcu_squares(game) # (revise 4) bad_squares = bombs + covered_squares if bad_squares > 0: game["state"] = "ongoing" return revealed else: game["state"] = "victory" return revealed def render(game, xray=False): """Prepare a game for display. Returns a two-dimensional array (list of lists) of "_" (hidden squares), "." (bombs), " " (empty squares), or "1", "2", etc. (squares neighboring bombs). game["mask"] indicates which squares should be visible. If xray is True (the default is False), game["mask"] is ignored and all cells are shown. Parameters: game (dict): Game state xray (bool): Whether to reveal all tiles or just the ones allowed by game["mask"] Returns: A 2D array (list of lists) >>> render({"dimensions": [2, 4], ... "state": "ongoing", ... "board": [[".", 3, 1, 0], ... [".", ".", 1, 0]], ... "mask": [[False, True, True, False], ... [False, False, True, False]]}, False) [['_', '3', '1', '_'], ['_', '_', '1', '_']] >>> render({"dimensions": [2, 4], ... "state": "ongoing", ... "board": [[".", 3, 1, 0], ... [".", ".", 1, 0]], ... "mask": [[False, True, False, True], ... [False, False, False, True]]}, True) [['.', '3', '1', ' '], ['.', '.', '1', ' ']] """ x, y = game['dimensions'] result = [[0]*y for i in range(x)] if xray : for i in range(x): for j in range(y): if game['board'][i][j] == 0: result[i][j] = ' ' else: result[i][j] = str(game['board'][i][j]) else: for i in range(x): for j in range(y): reveal = game['mask'][i][j] value = game['board'][i][j] if not reveal: result[i][j] = '_' elif value == 0: result[i][j] = ' ' else: result[i][j] = str(value) return result def render_ascii(game, xray=False): """Render a game as ASCII art. Returns a string-based representation of argument "game". Each tile of the game board should be rendered as in the function "render(game)". Parameters: game (dict): Game state xray (bool): Whether to reveal all tiles or just the ones allowed by game["mask"] Returns: A string-based representation of game >>> print(render_ascii({"dimensions": [2, 4], ... "state": "ongoing", ... "board": [[".", 3, 1, 0], ... [".", ".", 1, 0]], ... "mask": [[True, True, True, False], ... [False, False, True, False]]})) .31_ __1_ """ x, y = game['dimensions'] after_ren = render(game, xray) ans = '' for i in range(x): for j in range(y): ans = ans + after_ren[i][j] ans = ans + '\n' return ans[:-1]
from typing import ByteString, Dict, Iterable, Mapping, Text def decode_dict(data: Dict[bytes, bytes]) -> Dict[str, str]: """ Recursively decode all byte-strings found in a dictionary """ ret = {} for key, value in data.items(): if isinstance(key, ByteString): key = key.decode() if isinstance(value, (Mapping, Dict)): ret[key] = decode_dict(value) elif isinstance(value, ByteString): ret[key] = value.decode() elif isinstance(value, Iterable) and not isinstance(value, Text): ret[key] = value.__new__( x.decode() if isinstance(x, ByteString) else x for x in value ) else: ret[key] = value return ret
#!/usr/bin/python import Tkinter as tki import os import tkMessageBox # http://stackoverflow.com/questions/14771380/how-do-i-make-the-program-wait-for-an-input-using-an-entry-box-in-python-gui # Frame for displaying abstract and evaluation class Questionnarie(tki.Frame): def __init__(self, parent, readings, ratings_fp): tki.Frame.__init__(self, parent) self._setup_gui() self._readings = readings.keys()[:] self._text = readings self._current = "" self._ratings_fp = ratings_fp self._next_abstract() def _setup_gui(self): self._label_var = tki.StringVar() self._label = tki.Label(textvariable=self._label_var) self._label_var.set("Please Rate the following passage from 1 to 10 on difficulty. \nWith 1 being completely understandable and 10 being completely foreign.") self._label.pack() self._textbox = tki.Text(wrap=tki.WORD, padx=15) self._textbox.pack(padx=10) self._scale = tki.Scale(orient=tki.HORIZONTAL, length=200, sliderlength=10, to=10) self._scale.pack(anchor=tki.S) self._button = tki.Button(text="Next", command=self._move_next) self._button.pack(anchor=tki.SE, padx=10, pady=10) def _next_abstract(self): self._textbox.config(state=tki.NORMAL) self._textbox.delete("1.0", tki.END) self._current = self._readings.pop(0) self._textbox.insert(tki.INSERT, self._text[self._current]) self._textbox.config(state=tki.DISABLED) self._scale.set(0) def _move_next(self): if self._get_rating(): if len(self._readings) > 0: self._next_abstract() else: self._ratings_fp.close() self.quit() self.destroy() else: tkMessageBox.showinfo(title="Error", message="Please give a rating greater than 0.") def _get_rating(self): rating = str(self._scale.get()) if rating != "0": result = '{:<50} {:>3}'.format(self._current, rating) self._ratings_fp.write(result + "\n") return True else: return False def fetchExistingRating(name): rating_fp = open(name + "_rating.txt", "a+") rating_fp.seek(0) rating_dict = {} l = rating_fp.readlines() for s in l: words = s.split() rating_dict[' '.join(words[:-1])] = words[-1] rating_fp.close() return rating_dict # start evaluation based on which user selected def setDirectory(frame, name): seperator = os.sep directory = os.getcwd() + seperator + name file_dict = {} rating_dict = fetchExistingRating(name) for filename in os.listdir(directory): f = open(directory + seperator + filename, "r") if filename not in rating_dict: file_dict[filename] = f.read() for widget in frame.winfo_children(): widget.destroy() if file_dict: rating_fp = open(name + "_rating.txt", "a") evalPage = Questionnarie(frame, file_dict, rating_fp) evalPage.pack() else: tki.Button(frame, text="Done!", command=lambda: quit()).pack() def createStart(frame): frame = tki.Frame(top) nen = tki.Button( frame, text="Professor Nenkova", command=lambda: setDirectory(frame, "nenkova")) a = tki.Button( frame, text="Omar", command=lambda: setDirectory(frame, "omar")) b = tki.Button( frame, text="Spencer", command=lambda: setDirectory(frame, "spencer")) c = tki.Button( frame, text="Zack", command=lambda: setDirectory(frame, "zack")) d = tki.Button( frame, text="Zhi", command=lambda: setDirectory(frame, "zhi")) frame.pack() nen.pack(pady=10) a.pack(pady=10) b.pack(pady=10) c.pack(pady=10) d.pack(pady=10) top = tki.Tk() top.minsize(width=200, height=250) createStart(top) top.mainloop()
def solution(expression): answer = 0 # 연산자 우선 순위 모든 경우의 수 operators_all = [ ('+','-','*'),('+','*','-'), ('-','+','*'),('-','*','+'), ('*','+','-'),('*','-','+') ] # 배열로 변환 expression = expression.replace("*",',*,') expression = expression.replace("+",',+,') expression = expression.replace("-",',-,') expression = expression.split(",") # 모든 경우의 수에서 하나씩 for operators in operators_all: # 입력 받은 수식 복사 _ex = expression[:] # 연산자 우선순위 받아온 것 중 하나 for operator in operators: # 복사한 수식 배열에 연산자가 있을 때 while operator in _ex: # 해당 연산자의 index i = _ex.index(operator) if operator == "*": _ex[i-1] = int(_ex[i-1]) * int(_ex[i+1]) # 복사한 배열에서 계산한 수식 빼고 재배열 _ex = _ex[:i]+_ex[i+2:] if operator == "+": _ex[i-1] = int(_ex[i-1]) + int(_ex[i+1]) _ex = _ex[:i]+_ex[i+2:] if operator == "-": _ex[i-1] = int(_ex[i-1]) - int(_ex[i+1]) _ex = _ex[:i]+_ex[i+2:] # 절대값이 가장 큰 결과값 반환 answer = max(answer,abs(_ex[-1])) return answer
from DB.connection import DataBase import funtions def menu(): print('-' * 20 + ' MENU ' + '-' * 20) print('1 - Registrar nueva tienda') print('2 - Crear nueva categoría') print('3 - Agregar producto') print('4 - Mostrar todos los productos por país') print('5 - Mostrar el valor total de los productos') print('6 - Mostrar la cantidad total de productos') print('7 - Mostrar cantidad de productos ordenados por categoría') print('8 - Salir') print('-' * 50) option = int(input('Selecciona una opción: ')) if option < 1 or option > 8: print('Opción inválida') elif option == 8: print('Adiosin') else: run_option(option) def run_option(option): db = DataBase() if option == 1: store = funtions.insert_store() try: db.insert_store(store) print('\nTienda registrada') except: print('Ocurrió un error') elif option == 2: category = funtions.insert_category() try: db.insert_category(category) print('\nCategoría agregada') except: print('Ocurrió un error') elif option == 3: product = funtions.insert_product() try: db.insert_product(product) print('\nProducto agregado') except: print('Ocurrió un error') elif option == 4: country = input('Ingresa un país: ') try: products = db.products_by_country(country) if len(products) > 0: funtions.products_by_country(products) else: print('No se encontraron productos') except: print('Ocurrió un error') elif option == 5: try: total = db.total_value() if len(total) > 0: funtions.total_value(total) else: print('No se encontraron productos') except: print('Ocurrió un error') elif option == 6: try: total = db.total_products() if len(total) > 0: funtions.total_products(total) else: print('No se encontraron productos') except: print('Ocurrió un error') elif option == 7: try: total = db.order_by_category() if len(total) > 0: funtions.order_by_category(total) else: print('No se encontraron categorías') except: print('Ocurrió un error') else: print('Opción inválida') if __name__ == '__main__': menu()
# Ανάδραση σε επιλογή κύκλου ''' Να ζωγραφήσετε 100 τυχαίους κόκκινους κύκλους ακτίνας 10 pixel. Όταν επιλέγεται ένας από τους κύκους να αντιδρά αλλάζοντας χρώμα. ''' import tkinter as tk import random class App(): def __init__(self, root): self.root = root self.root.title('canvas_1') self.canvas = tk.Canvas(self.root, width=600, height=600, bg='lightblue') self.canvas.pack() radius=10 for i in range(100): #100 κύκλοι διάμετρου radius x, y = random.randint(radius, 600 - radius), random.randint(radius, 600 - radius) self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, fill="red") self.canvas.bind('<1>', self.click) self.canvas.bind('', self.back) def click(self, event): if self.canvas.find_withtag('current'): self.canvas.itemconfig('current', fill="blue") def back(self, event): if self.canvas.find_withtag('current'): self.canvas.itemconfig('current', fill="red") root = tk.Tk() App(root) root.mainloop()
# εφαρμογή contacts v.0 χωρίς μόνιμη αποθήκευση import os import random class Contact(): ''' κλάση επαφών με όνομα και τηλέφωνο μια μεταβλητή κλάσης theContacts''' theContacts = {} def list_contacts(term = ''): for c in sorted(Contact.theContacts, key=lambda x : x.split()[-1]): if term: if term.lower() in c.lower(): print(Contact.theContacts[c]) else: print(Contact.theContacts[c]) def __init__(self, name, number=''): # μέθοδος δημιουργός επαφών self.name = name.strip() self.number = number.strip() Contact.theContacts[self.name] = self def __repr__(self): # μέθοδος εκτύπωσης επαφών return self.name + ': ' + self.number class Main(): ''' κλάση επικοινωνίας με τον χρήστη - δημιουργία - διαγραφή επαφών''' def __init__(self): while True: command = input('\nΕπαφές:{}. \n[+]εισαγωγή [-]διαγραφή [?]επισκόπηση [enter] Έξοδος.:'.\ format(len(Contact.theContacts))) if command == '': break elif command[0] == '?': Contact.list_contacts(command[1:]) elif command[0] == '-': name = input('ΔΙΑΓΡΑΦΗ. Δώσε Όνομα επαφής >>>') try: del Contact.theContacts[name.strip()] except KeyError : print('Επαφή με όνομα {} δεν υπάρχει'.format(name)) elif command[0] == '+': contact_details = input('ΕΙΣΑΓΩΓΗ Όνομα επαφής: τηλέφωνο >>>') if ':' in contact_details: try: Contact(*contact_details.split(':')) except IndexError: print('Σφάλμα εισαγωγής επαφής') else: print('Προσοχή δώσε το όνομα, άνω-κάτω τελεία (:) τηλέφωνο') if __name__ == '__main__': Main()
# Animation show 1 import tkinter as tk import time import random class ball(object): def __init__(self, canvas, *args, **kwargs): self.canvas = canvas self.id = canvas.create_oval(*args, **kwargs) self.vx = random.randint(1,5) self.vy = random.randint(1,5) def move(self): x1, y1, x2, y2 = self.canvas.bbox(self.id) if x2 > app.width: self.vx = -self.vx if y2 > app.height: self.vy = -self.vy if x1 < 0: self.vx = -self.vx if y1 < 0: self.vy = -self.vy self.canvas.move(self.id, self.vx, self.vy) class App(object): def __init__(self, master, **kwargs): self.master = master self.width = 400 self.height = 400 self.canvas = tk.Canvas(self.master, width=self.width, height=self.height) self.canvas.pack() self.balls = [ #ball(self.canvas, 20, 260, 120, 360, outline='white', fill='blue'), ball(self.canvas, 2, 2, 40, 40, outline='white', fill='red')] self.canvas.pack() self.master.after(0, self.animation) def animation(self): for alien in self.balls: alien.move() self.master.after(12, self.animation) root = tk.Tk() app = App(root) root.mainloop()
'''Find the largest palindrome made from the product of two 3-digit numbers. ''' numlist = [] # want the largest just go the other way to find the largest def checkPalindrome(word): ##checks if its palindrome word = str(word) word = list(word) length=len(word) half = length//2 for k in range(half): if word[k] != word[length-k-1]: return False return True for i in range(100, 1000): # thankfully timesing commutative for j in range(100, 1000): # goes throught every number and times all 3 digit numbers x2 = i * j if checkPalindrome(x2) == True: # if its true it will append it to a list numlist.append(x2) print(max(numlist))
""" Example demonstrating lazy evaluation. """ import time from flexx import react class DataProcessor(react.HasSignals): @react.input def raw1(n=0): return float(n) @react.input def raw2(n=0): return float(n) @react.lazy('raw1') def processed1(data): print('processing 1 (slow)') time.sleep(1) return data + 10 @react.lazy('raw2') def processed2(data): print('processing 2 (fast)') time.sleep(0.1) return data + 1 @react.lazy('processed1', 'processed2') def result(data1, data2): return data1 + data2 p = DataProcessor() # Get result, first time, we need to wait, next time is instant print(p.result()) print(p.result()) # We can change the input, but nothing happens until we request a result p.raw1(10) p.raw1(50) p.raw1(100) print(p.result()) # Dito, but now we change raw2, so getting the result is fast p.raw2(10) p.raw2(50) p.raw2(100) print(p.result())
import os import math os.system('cls') def get_average(data_list): total_sum = 0 size = len(data_list) for i in range(size): total_sum += data_list[i] return total_sum / size def get_min(data_list): return min(data_list) def get_max(data_list): return max(data_list) def get_deviation(data_list): average = get_average(data_list) total_sum = 0 size = len(data_list) for i in range(size): total_sum += (data_list[i] - average)**2 return math.sqrt(total_sum / (size - 1)) def collect_data(): data_list = [] user_input = input("Enter a number: ") while True: if user_input == "done" and len(data_list) > 2: return data_list break elif user_input == "done" and len(data_list) <= 1: print("Not enough data") else: data_list.append(int(user_input)) user_input = input("Enter a number: ") return data_list #Main Program user_input = collect_data() print("\nNumbers: ") print(*user_input,sep=",") print(f"The average is {get_average(user_input):.0f}.") print(f"The minimum is {get_min(user_input)}.") print(f"The maximum is {get_max(user_input)}.") print(f"The Standard deviation is {get_deviation(user_input):.2f}.") """ Computing Statistics Statistics is important in our field. When measuring response times or rendering times, it’s helpful to collect data so you can easily spot abnormalities. For example, the standard deviation helps you determine which values are outliers and which values are within normal ranges. Write a program that prompts for response times from a website in milliseconds. It should keep asking for values until the user enters “done.” The program should print the average time (mean), the minimum time, the maximum time, and the standard deviation. To compute the average (mean) 1. Compute the sum of all values. 2. Divide the sum by the number of values. To compute the standard deviation 1. Calculate the difference from the mean for each number and square it. 2. Compute the mean of the squared values. 3. Take the square root of the mean. Example Output Enter a number: 100 Enter a number: 200 Enter a number: 1000 Enter a number: 300 Enter a number: done Numbers: 100, 200, 1000, 300 The average is 400. The minimum is 100. The maximum is 1000. The standard deviation is 400.25(error in book actual value is 408.25). Constraints • Use loops and arrays to perform the input and mathematical operations. Chapter 7. Data Structures • 68 report erratum • discuss • Be sure to exclude the “done” entry from the array of inputs. • Be sure to properly convert numeric values to strings. • Keep the input separate from the processing and the output. """
import os os.system('cls') #Python doesn't have a switch-case so a solution is to use a dict either in a function or class def month(i): switcher = { 1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 6:"June", 7:"July", 8:"August", 9:"September", 10:"October", 11:"November", 12:"December" } return switcher.get(i ,"Invalid Month") #Testing if the input is valid month input while True: try: input = int(input("Please enter the number of the month: ")) if input > 12: print("Not a valid month") else: print(f"The name of the month is {month(input)}.") break except ValueError: print("Only intergers") continue """ Numbers to Names Many programs display information to the end user in one form but use a different form inside the program. For example, you may show the word Blue on the screen, but behind the scenes you’ll have a numerical value for that color or an internal value because you may need to represent the textual description in another language for Spanishspeaking visitors. Write a program that converts a number from 1 to 12 to the corresponding month. Prompt for a number and display the corresponding calendar month, with 1 being January and 12 being December. For any value outside that range, display an appropriate error message. Example Output Please enter the number of the month: 3 The name of the month is March. Constraints • Use a switch or case statement for this program. • Use a single output statement for this program. """
import os os.system('cls') quote = input("What is the quote?") person = input("Who said it?") print(f"{person} says, \"{quote} \"")
import os from sys import argv os.system('cls') script, filename = argv def read_datafile(filename): txt = open(filename) names_list = [] names_list = txt.read().split("\n") names_sorted = sorted(names_list) print(f"Last First Salary") print("--------------------------------------") #Splits invidual columns of data in a list within a list split_list = [row.split(",") for row in names_sorted] for i in split_list: print('{0[0]:<15}{0[1]:<15}{0[2]:<5}'.format(i)) read_datafile(filename) """ Parsing a Data File Sometimes data comes in as a structured format that you have to break down and turn into records so you can process them. CSV, or comma-separated values, is a common standard for doing this. Construct a program that reads in the following data file: Ling,Mai,55900 Johnson,Jim,56500 Jones,Aaron,46000 Jones,Chris,34500 Swift,Geoffrey,14200 Xiong,Fong,65000 Zarnecki,Sabrina,51500 Process the records and display the results formatted as a table, evenly spaced, as shown in the example output. Example Output Last First Salary ------------------------- Ling Mai 55900 Johnson Jim 56500 Jones Aaron 46000 Jones Chris 34500 Swift Geoffrey 14200 Xiong Fong 65000 Zarnecki Sabrina 51500 Constraints • Write your own code to parse the data. Don’t use a CSV parser. • Use spaces to align the columns. • Make each column one space longer than the longest value in the column. """
import os import json from urllib.request import urlopen os.system('cls') city = input("Where city are you in? ") with urlopen(f"http://api.openweathermap.org/data/2.5/weather?q={city}&APPID=a7c64bcd3a79ce72e2f62695d35b7eed") as response: source = response.read() data = json.loads(source) #JSON data is in Kelvin fahrenheit = data['main']['temp'] weather = 9/5 * (fahrenheit - 273) + 32 print(f"{city} weather: {weather:.0f} degrees Fahrenheit") """" Is it nice out today? Or should I grab my coat? Using the OpenWeatherMap API at http://openweathermap.org/ current, create a program that prompts for a city name and returns the current temperature for the city. Example Output Where are you? Chicago IL Chicago weather: 65 degrees Fahrenheit Constraint • Keep the processing of the weather feed separate from the part of your program that displays the results. """"
import math import os os.system('cls') length = int(input("What is the length of the room in feet?")) width = int(input("What is the width of the room in feet?")) print(f"You entered dimensions of {length} feet by {width} feet") area = length * width print(f"The area is {area} square feet") conversion_factor = 0.09290304 square_meters = area * conversion_factor print(f"{square_meters:.3f} square meters") """ Area of a Rectangular Room When working in a global environment, you’ll have to present information in both metric and Imperial units. And you’ll need to know when to do the conversion to ensure the most accurate results. Create a program that calculates the area of a room. Prompt the user for the length and width of the room in feet. Then display the area in both square feet and square meters. Example Output What is the length of the room in feet? 15 What is the width of the room in feet? 20 You entered dimensions of 15 feet by 20 feet. The area is 300 square feet 27.871 square meters The formula for this conversion is m2 = f2 × 0.09290304 Constraints • Keep the calculations separate from the output. • Use a constant to hold the conversion factor. """
#%% import datetime import math #%% class Pessoa: def __init__(self, nome:str, sobrenome:str, data_de_nascimento:datetime.date): self.nome = nome self.sobrenome = sobrenome self.data_de_nascimento = data_de_nascimento @property def idade(self) -> int: return math.floor((datetime.date.today() - self.data_de_nascimento).days / 365.2425) def __str__(self) -> str: return f"{self.nome} {self.sobrenome} tem {self.idade} anos" #%% vinicius = Pessoa(nome='Vinicius', sobrenome='Nascimento', data_de_nascimento=datetime.date(year=1993, month=1, day=6)) print(vinicius) print(vinicius.nome) print(vinicius.idade)
#%% import datetime import math from typing import List #%% class Pessoa: def __init__(self, nome:str, sobrenome:str, data_de_nascimento:datetime.date): self.nome = nome self.sobrenome = sobrenome self.data_de_nascimento = data_de_nascimento @property def idade(self) -> int: return math.floor((datetime.date.today() - self.data_de_nascimento).days / 365.2425) def __str__(self) -> str: return f"{self.nome} {self.sobrenome} tem {self.idade} anos" #%% class Curriculo: def __init__(self, pessoa: Pessoa, experiencias: List[str]): self.pessoa = pessoa self.experiencias = experiencias @property def quantidade_de_experiencias(self) -> int: return len(self.experiencias) @property def empresa_atual(self) -> str: return self.experiencias[-1] def adiciona_experiencia(self, experiencia: str) -> None: self.experiencias.append(experiencia) def __str__(self) -> str: return f"{self.pessoa.nome} {self.pessoa.sobrenome} tem {self.pessoa.idade} anos e " \ f"já trabalhou em {self.quantidade_de_experiencias} empresas e atualmente trabalha na " \ f"empresa {self.empresa_atual}" # %% vinicius = Pessoa(nome='Vinicius', sobrenome='Nascimento', data_de_nascimento=datetime.date(1993,1,6)) print(vinicius) curriculo_vinicius = Curriculo( pessoa = vinicius, experiencias=['Iteris', 'Cignify', 'S4R', 'Bradesco', 'Carrefour', 'Distrito']) # %% print(curriculo_vinicius.pessoa) print(curriculo_vinicius) # %% curriculo_vinicius.adiciona_experiencia('Facebook') print(curriculo_vinicius) #%% class Vivente: def __init__(self, nome:str, data_de_nascimento:datetime.date) -> None: self.nome = nome self.data_de_nascimento = data_de_nascimento @property def idade(self) -> int: return math.floor((datetime.date.today() - self.data_de_nascimento).days / 365.2425) def emite_ruido(self, ruido: str): print(f"{self.nome} fez ruido: {ruido}") # %% class PessoaHeranca(Vivente): def __str__(self) -> str: return f"{self.nome} tem {self.idade} anos" def fala(self, frase): return self.emite_ruido(frase) class Cachorro(Vivente): def __init__(self, nome: str, data_de_nascimento: datetime.date, raca: str) -> None: super().__init__(nome, data_de_nascimento) self.raca = raca def __str__(self) -> str: return f"{self.nome} é da raça {self.raca} e tem {self.idade} anos" def late(self): return self.emite_ruido("Au Au!") # %% vinicius2 = PessoaHeranca(nome="Vinicius", data_de_nascimento=datetime.date(1993,1,6)) print(vinicius2) # %% duke = Cachorro("Duke", datetime.date(2015,12,25), "Vira-Lata") print(duke) # %% duke.late() duke.late() vinicius2.fala("Cala a boca!") duke.late()
# 17) Definir una clase padre llamada Vehiculo y dos clases hijas llamadas Coche y Bicicleta, # las cuales heredan de la clase Padre Vehiculo. # La clase padre debe tener los siguientes atributos y métodos # Vehiculo (Clase Padre): # -Atributos (color, ruedas) # -Métodos ( __init__() y __str__ ) # Coche (Clase Hija de Vehículo) (Además de los atributos y métodos heradados de Vehículo): # -Atributos ( velocidad (km/hr) ) # -Métodos ( __init__() y __str__() ) # Bicicleta (Clase Hija de Vehículo) (Además de los atributos y métodos heradados de Vehículo): # -Atributos ( tipo (urbana/montaña/etc ) # -Métodos ( __init__() y __str__() ) class Vehiculo: def __init__(self, color, ruedas): self.color = color self.ruedas = ruedas def __str__(self): return f'Vehiculo[Color: {self.color}. Ruedas: {self.ruedas}]' class Coche(Vehiculo): def __init__(self, color, ruedas, velocidad): super().__init__(color, ruedas) self.velocidad = velocidad def __str__(self): return f'Coche[Velocidad: {self.velocidad} km/h], {super().__str__()}' class Bicicleta(Vehiculo): def __init__(self, color, ruedas, tipo): super().__init__(color, ruedas) self.tipo = tipo def __str__(self): return f'Bicicleta[Tipo: {self.tipo}], {super().__str__()}' vehiculo1 = Vehiculo('Rojo', 3) print(vehiculo1) coche1 = Coche('Verde', 4, 120) print(coche1) bicicleta1 = Bicicleta('Blanco', 2, 'Montaña') print(bicicleta1)
# 10) Tarea: Iterar un rango de 0 a 10 e imprimir números divisibles entre 3 for i in range(10): if i % 3 == 0: print(f'Número divisible por 3: {i}')
def count_distance(start, end, speed): #semua perhitungan diubah kedetik start = ((start[1] + (start[0] * 60)) * 60) + start[2] end = ((end[1] + (end[0] * 60)) * 60) + end[2] time = end - start #10 menit pertama distance = (10*60) * speed time -= (10*60) speed += 1 while time != 0: #setiap 7 menit berikutnya if time % (7*60) == 0: speed += 1 distance += speed time -= 1 print( 'Durasi perjalanan:', end - start, 'detik \n'+ 'Kecepatan saat ini:', speed, 'm/s \n'+ 'Jarak yang telah ditempuh:', distance, 'm \n' ) start = [5, 25, 15] end = [9, 0, 0] speed = 3 count_distance(start, end, speed) #output: #Durasi perjalanan: 12885 detik #Kecepatan saat ini: 33 m/s #Jarak yang telah ditempuh: 233640 m
money = input("请输入红包金额") num = money.count(".") if num <= 1: for i in money: if i not in "1234567890.": print("请输入数字!!") exit() if num == 1: xsws = len(money) - (money.index(".")+1) if xsws <=2: money = float(money) if money >= 0.01 and money <= 200: print("发送红包成功!金额:",money) else: print("红包的金额必须在0.01-200的范围内") else: print("只能输入两位小数") else: money = float(money) if money >= 0.01 and money <= 200: print("发送红包成功!金额",money) else: print("红包金额必须在0.01-200的范围内!") else: print("请输入正确的数字")
import random item_list = ['Rock', 'Paper', 'Scissor'] com_point = 0 player_point = 0 while True: com_player = random.choice(item_list).lower() player = input(' \n enter your choice: Rock, Paper, Scissor, Quit: ').lower() if player == com_player: print(' Tie') print(' Point table: \n Computer:{} Player:{}'.format(com_point, player_point)) elif player == 'rock' and com_player == 'paper': print('', com_player) print(' com win') com_point += 1 print(' Point table: \n Computer:{} Player:{}'.format(com_point, player_point)) elif player == 'rock' and com_player == 'scissor': print('', com_player) print(' player win') player_point += 1 print(' Point table: \n Computer:{} Player:{}'.format(com_point, player_point)) elif player == 'paper' and com_player == 'rock': print('', com_player) print(' player win') player_point += 1 print(' Point table: \n Computer:{} Player:{}'.format(com_point, player_point)) elif player == 'paper' and com_player == 'scissor': print('', com_player) print(' com win') com_point += 1 print(' Point table: \n Computer:{} Player:{}'.format(com_point, player_point)) elif player == 'scissor' and com_player == 'rock': print('', com_player) print(' com win') com_point += 1 print(' Point table: \n Computer:{} Player:{}'.format(com_point, player_point)) elif player == 'scissor' and com_player == "paper": print('', com_player) print(' player win') player_point += 1 print(' Point table: \n Computer:{} Player:{}'.format(com_point, player_point)) elif player == 'quit': quit() else: print(' invalid input')
#!/usr/bin/python3 import struct import sys def main(): if len(sys.argv) != 2: print("error: missing argument", file=sys.stderr) return 1 with open(sys.argv[1]) as file: addr = 0 for line in file: line = line.strip() if line.startswith('//'): continue data, = struct.unpack('>h', bytes.fromhex(line)) print('{}: {}'.format(addr, data)) addr += 1 if __name__ == '__main__': sys.exit(main());
import pygame class Snake: def __init__(self, width, height, display, difficulty): self.w = 12 self.h = 12 self.x = width / 2 self.y = height / 2 self.name = 'Hossein' self.color = (0, 255, 255) self.speed = 1.5 * difficulty self.score = 0 self.display = display self.x_change = -1 self.y_change = 0 self.alive = True self.body = [] def show(self): pygame.draw.rect(self.display, self.color, [self.x, self.y, self.w, self.h]) for i in range(0, len(self.body)): if i % 2 == 0: pygame.draw.rect(self.display, (0, 0, 255), [self.body[i].x, self.body[i].y, self.w, self.h]) else: pygame.draw.rect(self.display, self.color, [self.body[i].x, self.body[i].y, self.w, self.h]) def move(self, fruit): head_old_x = self.x head_old_y = self.y if self.x_change == -1: self.x -= self.speed elif self.x_change == 1: self.x += self.speed if self.y_change == -1: self.y += self.speed elif self.y_change == 1: self.y -= self.speed # move body if body exists if len(self.body) > 0: self.body[0].x = head_old_x self.body[0].y = head_old_y for i in range(0, len(self.body)): # save old positions if i == 0: self.body[i].old_x = self.body[i].x self.body[i].old_y = self.body[i].y else: self.body[i].old_x = self.body[i].x self.body[i].old_y = self.body[i].y # move if i == 0: self.body[i].x = head_old_x self.body[i].y = head_old_y else: self.body[i].x = self.body[i - 1].old_x self.body[i].y = self.body[i - 1].old_y self.check_next_move(fruit) def check_next_move(self, fruit): # check is wall # Speed Here Means Difficulty if self.speed / 1.5 == 1: if self.x < 0: self.x = self.display.get_width() elif self.x > self.display.get_width(): self.x = 0 elif self.y < 0: self.y = self.display.get_height() elif self.y > self.display.get_height(): self.y = 0 else: if self.x < 0 or self.x > self.display.get_width() or self.y > self.display.get_height() or self.y < 0: self.alive = False # check is itself for i in range(1, len(self.body)): if (self.x == self.body[i].x) and (self.y == self.body[i].y): self.alive = False break # check is fruit if (fruit.x - fruit.r <= self.x + self.w and self.x - self.w <= fruit.x + fruit.r) and ( fruit.y - fruit.r <= self.y + self.h and self.y - self.h <= fruit.y + fruit.r) and (self.alive == True): self.score += fruit.point # add to body if len(self.body) == 0: self.body.append(Body(self.x, self.y)) else: self.body.append(Body(self.body[-1].x, self.body[-1].y)) fruit.recreate(self) class Body: def __init__(self, new_x, new_y): self.x = new_x self.y = new_y self.old_x = 0 self.old_y = 0
#from items import * from map import rooms from gameparser import * current_room = rooms["lobby"] def age_verification(name): while True: try: print("How old are you?") player_age = int(input("...")) if player_age < 0 or player_age > 100: print("Please enter age between 1-100") continue elif player_age >= 13: print_welcome(name) else: print("You are too young to play this game.") quit() break except ValueError: print("You did not enter a valid number.") def print_welcome(name): print() print('''Please choose a difficulty level. 1) Easy 2) Medium 3) Hard ''')
import turtle import os BORDER_RIGHT = 600 BORDER_LEFT = 90 def setup_screen(): """Create a main screen.""" window = turtle.Screen() window.bgcolor("black") window.title("Space Invaders") _draw_border() def _draw_border(): """Draw border on the main window.""" border_pen = turtle.Turtle() border_pen.speed(0) border_pen.color("white") border_pen.penup() border_pen.setposition(-300, -300) border_pen.pendown() border_pen.pensize(3) for side in range(4): border_pen.fd(BORDER_RIGHT) border_pen.lt(BORDER_LEFT) border_pen.hideturtle()
# 3.3 Organizing Lists #3.3.1 Using sort() to sorting the list permenantly 使用方法sort() 对列表进行永久性排序 cars = ["bmw", "audi", "toyota", "subaru"] cars.sort() print(cars) # 你还可以按与字母顺序相反的顺序排列列表元素,为此,只需向sort() 方法传递参数reverse=True cars = ["bmw", "audi", "toyota", "subaru"] cars.sort(reverse = True) print(cars) # 3.3.2 Using sorted() to sort the list temporary cars = ['bmw', 'audi', 'toyota', 'subaru'] print("Here is the original list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the original list again:") print(cars) # 注意,调用函数sorted() 后,列表元素的排列顺序并没有变。如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted() 传递参数reverse=True #3.3.3 Printing the list reversely cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.reverse() print(cars) # reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序 #3.3.4 The length of the list cars = ['bmw', 'audi', 'toyota', 'subaru'] print(len(cars))
python2.7 print "Hello Python 2.7 world!" Hello Python 2.7 world! # 在Python 2中,无需将要打印的内容放在括号内。从技术上说,Python 3中的print 是一个函数,因此括号必不可少。有些Python 2 print 语句也包含括号,但其行为与Python 3中 稍有不同。简单地说,在Python 2代码中,有些print 语句包含括号,有些不包含。 python2.7 >>> 3 / 2 1 # 在Python 2中,整数除法的结果只包含整数部分,小数部分被删除。请注意,计算整数结果时,采取的方式不是四舍五入,而是将小数部分直接删除。 在Python 2中,若要避免这种情况,务必确保至少有一个操作数为浮点数,这样结果也将为浮点数 >>> 3 / 2 1 >>> 3.0 /2 1.5 >>> 3 / 2.0 1.5 >>> 3.0 / 2.0 1.5
#5.2 Condition test #5.2.1 car = 'bmw' car == 'bmw' #5.2.2 car = 'Audi' car == 'audi' car = 'Audi' car.lower() == 'audi' #5.2.3 requested_topping = 'mushrooms' if requested_topping != 'anchovies': print("Hold the anchovies!") #5.2.4 age = 18 age == 18 answer = 17 if answer != 42: print("That is not the correct answer. Please try again!") #5.2.5 #1 AND age_0 = 22 age_1 = 18 age_0 >= 21 and age_1 >=21 age_1 = 22 age_0 >= 21 and age_1 >=21 (age_0 >=21) and (age_1 >=21) #2 OR age_0 = 22 age_1 = 18 age_0 >= 21 or age_1 >= 21 age_0 =18 age_0 >= 21 or age_1 >= 21 #5.2.6 requested_topping = ['mushrooms', 'onions', 'pineapple'] 'mushrooms' in requested_topping 'pepperoni' in requested_topping #5.2.7 banned_users = ['andrew', 'carolina', 'david'] user = 'marie' if user not in banned_users: print(user.title() + ", you can post a response if you wish.")
#5-3 practice #5-3 alien color #1 alien_color = 'green' if alien_color == 'green': print("You just received 5 points!") alien_color = 'red' if alien_color == 'green': print("You just received 5 points!") #5-4 alien color #2 alien_color = 'green' if alien_color == 'green': print("You just received 5 points!") else: print("You just received 10 points!") alien_color = 'red' if alien_color == 'green': print("You just received 5 points!") else: print("You just received 10 points!") #5-5 alien color #3 alien_color = 'green' if alien_color == 'green': point = 5 elif alien_color == 'yellow': point = 10 else: point = 15 print("You just received " + str(point) + " points.") alien_color = 'yellow' if alien_color == 'green': point = 5 elif alien_color == 'yellow': point = 10 else: point = 15 print("You just received " + str(point) + " points.") alien_color = 'red' if alien_color == 'green': point = 5 elif alien_color == 'yellow': point = 10 else: point = 15 print("You just received " + str(point) + " points.") #5-6 Different life stage age = 17 if age < 2: print("He is still a baby.") elif age < 4: print("He's a toddler.") elif age < 13: print("He's a child.") elif age < 20: print("He's a teenager.") elif age < 65: print("He's an adult.") else: print("He is an elder.") #5-7 favorite_fruits = ['pineapple', 'kiwi', 'watermelon'] if 'apple' in favorite_fruits: print("You really like apple!") if 'blueberry' in favorite_fruits: print("You really like blueberry!") if 'pineapple' in favorite_fruits: print("You really like pineapple!") if 'kiwi' in favorite_fruits: print("You really like kiwi!") if 'watermelon' in favorite_fruits: print("You really like watermelon!")
import re '''Step 1: create the big occurences list''' def occurenceslist_creator(): alfabet = 'abcdefghijklmnopqrstuvwxyz $' occurenceslist = dict([(letter, []) for letter in alfabet]) #to create a dictionary with empty values with first letters as keys for firstletter in occurenceslist.keys(): occurenceslist[firstletter].append(dict([(letter, 0) for letter in alfabet])) return occurenceslist occurencesdic = occurenceslist_creator() print("Empty Dictionary:", occurencesdic) '''Step 2: open up the files needed as test values/sentences''' #manual made test sentence: sentence = "Appels rijpen* beHAlve het$ wormpje ''/?" alicefile = open('alice.txt', 'r') aliceLines = alicefile.readlines() '''Step 3: replace any unvalid value with a invalid sign''' def remover(sentence =""): #source: https://stackoverflow.com/questions/55902042/python-keep-only-alphanumeric-and-space-and-ignore-non-ascii/55902074 valid_values = list("abcdefghijklmnopqrstuvwxyz ") captilized_values = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") for item in sentence: if item in captilized_values: sentence = sentence.replace(item, item.lower()) elif item not in valid_values: sentence = sentence.replace(item, "$") return sentence '''Step 4: cut the characters and the next letter/value of it and place them in a list''' def sentence_cutter(removed_sentence = ""): cutted_sentence = [removed_sentence[i:i+2] for i in range(0, len(removed_sentence)-1)] return cutted_sentence '''Step 5: Add the occurences of the cutted sentence to the big occurences dictionary''' def addto_occurences_dic(cutted_sentence): for cutted_characters in cutted_sentence: first_character = cutted_characters[0] second_character = cutted_characters[1] occurencesdic[first_character][0][second_character] += 1 return occurencesdic '''Extra Step: Run the functions''' for aliceline in aliceLines: valid_sentence = remover(aliceline) cutted_sentence = sentence_cutter(valid_sentence) occurencesdic = addto_occurences_dic(cutted_sentence) print("After Alice's Text: ", occurencesdic) valid_sentence = remover(sentence) cutted_sentence = sentence_cutter(valid_sentence) occurencesdic = addto_occurences_dic(cutted_sentence) print("After Manual Text: ", occurencesdic) '''Step 6: Percent of times that a certain ''' for i in 'abcdefghijklmnopqrstuvwxyz $': tot = sum(list(occurencesdic[i][0].values())) for j in 'abcdefghijklmnopqrstuvwxyz $': if tot > 0 and occurencesdic[i][0][j] > 0: occurencesdic[i][0][j] = round((occurencesdic[i][0][j]/tot)*100, 1) print("Percentage Occurences: ", occurencesdic)
""" Module utility to define some utilities functions, like read data, divide data in training and test set and so on. """ import csv import numpy as np def read_monk_data(file_path, train_dim=1.0, shuffle=False): """ Read data from Monk dataset to put as input in ML algorithms Param: file_path (string): Path of Monk dataset train_dim (float): number between 0.0 to 1.0 to use as partition between training and test set. Semantics of Monk Dataset: 1° Row: label of data with value 0, 1 2° Row: has value 1, 2, 3 3° Row: has value 1, 2, 3 4° Row: has value 1, 2 5° Row: has value 1, 2, 3 6° Row: has value 1, 2, 3, 4 7° Row: has value 1, 2 """ with open(file_path, "r") as monk_file: string_data = [line.split() for line in monk_file] label = [0.1 if int(row[0]) == 0 else 0.9 for row in string_data] #label = [int(row[0]) for row in string_data] data = [] for row in string_data: data_row = np.zeros(17) data_row[int(row[1]) - 1] = 1 data_row[int(row[2]) + 2] = 1 data_row[int(row[3]) + 5] = 1 data_row[int(row[4]) + 7] = 1 data_row[int(row[5]) + 10] = 1 data_row[int(row[6]) + 14] = 1 data.append(data_row) if 0 < train_dim < 1: dim_data = int(train_dim * len(data)) return data[:dim_data], label[:dim_data], data[dim_data:], label[dim_data:] return data, label, [], [] def read_cup_data(file_path, train_dim=1.0): """ Read data from ML Cup dataset to put as input in ML algorithms Param: file_path (string): Path of ML Cup dataset train_dim (float): number between 0.0 to 1.0 to use as partition between training and test set. """ with open(file_path, "r") as cup_file: reader = csv.reader(cup_file, delimiter=",") labels = [] data = [] for row in reader: if row[0][0] != '#': # Id, 10 data, 2 label labels.append([float(row[11]), float(row[12])]) data.append([float(x) for x in row[1:11]]) if 0 < train_dim < 1: dim_data = int(train_dim * len(data)) return np.array(data[:dim_data]), np.array(labels[:dim_data]), \ np.array(data[dim_data:]), np.array(labels[dim_data:]) return np.array(data), np.array(labels), [], [] def read_blind_data(file_path): """ Read blind data from ML Cup dataset to set ML algorithms Param: file_path (string): Path of ML Cup blind dataset """ with open(file_path, "r") as cup_file: reader = csv.reader(cup_file, delimiter=",") id_name = [] data = [] for row in reader: if row[0][0] != '#': # Id, 10 data, 2 label id_name.append(int(row[0])) data.append([float(x) for x in row[1:11]]) return id_name, np.array(data) def normalize_data(features = [], targets = [], den_features = None, den_targets = None): """used to normalize features or/and targets Args: features (list, optional): features to be normalized. Defaults to []. targets (list, optional): targets to be normalized. Defaults to []. den_f ((float64,float64), optional): (mean,variance) for feature normalization. Defaults to None. den_t ((float64,float64): (mean,variance) for target normalization. Defaults to None. Returns: (nparray, nparray, (mean,variance)): [description] """ features = np.array(features) targets = np.array(targets) if den_features == None: den_features = (np.mean(features), np.std(features)) if den_targets == None: den_targets = (np.mean(targets), np.std(targets)) if len(features) > 0: features = (features - den_features[0])/den_features[1] if len(targets) > 0: targets = (targets - den_targets[0])/den_targets[1] return np.array(features), np.array(targets), den_features, den_targets def denormalize_data(dataset, den_tupla): dataset = np.array(dataset) return dataset * den_tupla[1] + den_tupla[0]
""" Layer Module used to represent a layer of a NN """ import numpy as np from activation_function import ActivationFunction from learning_rate import LearningRate import copy class Layer: """ Layer class represent a layer in a NN """ def __init__(self, weights, learning_rates, activation): """This function initialize an instance of the layer class Parameters: weights (numpy.ndarray): matrix, of num_unit * num_input + 1 elements, that contain the weights of the units in the layer (including the biases) learning_rates (numpy.ndarray): matrix, of unitNumber * inputNumber elements, that contain the learning rates of the units in the layer (including the biases) activation (ActivationFunction): each unit of this layer use this function as activation function """ # checking parameters ------------------- if not isinstance(weights, np.ndarray): raise ValueError('weights must be a np.ndarray object') if not isinstance(learning_rates, LearningRate): raise ValueError('learning_rates must be a np.ndarray object') if not isinstance(activation, ActivationFunction): raise ValueError('activation must be an activation function') if weights.shape != learning_rates.value().shape: raise ValueError( 'weights and learning_rates must have the same shape') # --------------------------------------- self.weights = weights self.transposedWeights = np.transpose(weights) self.learning_rates = learning_rates self.activation = activation # num_unit = number of weights'/learning_rates' rows # num_input = number of weights'/learning_rates' columns self.num_unit, self.num_input = weights.shape # removing 1, because in weights there is also the bias column self.num_input -= 1 self.net = 0 # delta calculated in the last error signal execution self.errors = np.empty([self.num_unit]) # contains the last input the layer has processed self.inputs = 0 self.old_delta_w = np.zeros(weights.shape) self.current_delta_w = np.zeros(weights.shape) def get_num_unit(self): """To get the number of unit in the layer Returns: int: the number of units in the layer """ return self.num_unit def get_num_input(self): """To get the number of input for the layer Returns: int: the number of input for the layer (included the bias input) """ return self.num_input def get_errors(self): """To get the array of errors obtained once you have executed the error signal Returns: np.array: an array of floating-point. In particular, the i-th element of the returned array is the error of the i-th unit in the layer """ return self.errors def get_weights(self): """To get the weights of each unit of the level. Returns: np.array: a matrix W of dimension self.get_num_unit * ( self.get_num_input + 1). W[i][j] is the j-th weight of the i-th unit. """ return self.weights def update_learning_rate(self, epoch): """Update the learning rate according to the epoch Args: epoch (int): current training epoch """ self.learning_rates.update(epoch) def function_signal(self, input_values): """ Calculate the propagated values of a layer using an activation function Parameters: input_values(list of patterns): values used as input in a Layer (it is the output of predicing layer) Return: output values of Layer units """ # checking that the input is the right dimension if input_values.shape[1] != self.num_input: raise ValueError # adding bias input to input_values input_values = np.c_[np.ones(len(input_values)), input_values] # updating the value of inputs self.inputs = input_values # calculating the value of the net. The value calculated is an array # whose i-th element is the net value of the i-th unit. self.net = np.matmul(input_values, self.transposedWeights) # returnig the value obtained applying the activation function # of the layer to the new nets result. return np.array(self.activation.output(self.net)) def error_signal(self, target, output): """abstract class implementation in output layer and input layer """ def deepcopy(self): """Create a deep copy of the layer object Returns: Layer: deep copy of the layer """ if isinstance(self, HiddenLayer): return HiddenLayer(copy.deepcopy(self.weights), self.learning_rates.deepcopy(), self.activation) elif isinstance(self, OutputLayer): return OutputLayer(copy.deepcopy(self.weights), self.learning_rates.deepcopy(), self.activation) else: return Layer(copy.deepcopy(self.weights), self.learning_rates.deepcopy(), self.activation) class OutputLayer(Layer): """ Represent an Output Layer in NN model It is a subclass of Layer object """ def __init__(self, weights, learning_rates, activation): """This function initialize an instance of the layer class Parameters: weights (numpy.ndarray): matrix, of num_unit * num_input + 1 elements, that contain the weights of the units in the layer (including the biases) learning_rates (numpy.ndarray): matrix, of unitNumber * inputNumber elements, that contain the learning rates of the units in the layer (including the biases) activation (ActivationFunction): each unit of this layer use this function as activation function """ super().__init__(weights, learning_rates, activation) def error_signal(self, targets, outputs, loss): """implement the calculation of the error signal for an output layer Parameters: target (np.array): target for a specific pattern x output (np.array): the output of the layer for a specific pattern x loss (Loss): the loss object used to compute the derivative of Loss function Formula: for each unit i errors[i] = f'(net[i]) * loss'(target, output) """ difference = loss.derivative(outputs, targets) self.errors = np.multiply(self.activation.derivative(self.net), difference) self.current_delta_w = np.sum([np.einsum('i,j', error, input) for error, input in zip(self.errors, self.inputs)], axis=0) class HiddenLayer(Layer): """ Represent an Hidden Layer in our NN model and it is a subclass of Layer object """ def __init__(self, weights, learning_rates, activation): """This function initialize an instance of the layer class Parameters: weights (numpy.ndarray): matrix, of num_unit * num_input + 1 elements, that contain the weights of the units in the layer (including the biases) learning_rates (numpy.ndarray): matrix, of unitNumber * inputNumber elements, that contain the learning rates of the units in the layer (including the biases) activation (ActivationFunction): each unit of this layer use this function as activation function """ super().__init__(weights, learning_rates, activation) def error_signal(self, downStreamErrors, downStreamWeights): """implement the calculation of the error signal for an hidden layer Parameters: downStreamErrors (np.array): error signals of the layer above downStreamWeights (np.array): weights of the layer above Formula: for each unit i, assuming the layer above has k units: errors[i] = f'(net[i]) * (downStreamWeights[0][i] * downStreamErrors[0] + ... + downStreamWeights[k][i] * downStreamErrors[k]) """ self.errors = (self.activation.derivative(self.net) * np.matmul(downStreamErrors, downStreamWeights[0:, 1:])) self.current_delta_w = np.sum([np.einsum('i,j', error, input) for error, input in zip(self.errors, self.inputs)], axis=0)
import random HANGMAN_PICS = [''' +---+ | | | ===''', ''' +---+ O | | | ===''', ''' +---+ O | | | | ===''', ''' +---+ O | /| | | ===''', ''' +---+ O | /|\ | | ===''', ''' +---+ O | /|\ | / | ===''', ''' +---+ O | /|\ | / \ | ==='''] words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra' def getRandomWord(wordList): wordList_Split = wordList.split() word_index = random.randint(0, len(wordList_Split) - 1) return wordList_Split[word_index] def displayBoard(missedLetters, correctLetters, secretWord): # based on the number of missed letters, display approriate hangman pic print(HANGMAN_PICS[len(missedLetters)], "\n") print('Missed letters:', end=' ') for letter in missedLetters: print(letter, end=' ') print() blanks = '_' * len(secretWord) for i in range(len(secretWord)): if secretWord[i] in correctLetters: # Trick is here blanks = blanks[:i] + secretWord[i] + blanks[i+1:] for letter in blanks: print(letter, end=' ') print() def getGuess(alreadyGuessed): while True: print("Guess a letter") guess = input() guess = guess.lower() if len(guess) != 1: print("Please enter a single letter.") elif guess in alreadyGuessed: print("You have already guessed that letter") elif guess not in 'abcdefghijklmnopqrstuvwxyz': print("Please enter a letter") else: return guess def playAgain(): print("Do you want to play again? Y or N") return input().lower().startswith("y") print("H A N G M A N") missedLetters = '' correctLetters = '' secretWord = getRandomWord(words) gameIsDone = False while True: displayBoard(missedLetters, correctLetters, secretWord) # Let the player enter a letter guess = getGuess(missedLetters + correctLetters) if guess in secretWord: correctLetters = correctLetters + guess # Check if the player has won foundAllLetters = True for i in range(len(secretWord)): if secretWord[i] not in correctLetters: foundAllLetters = False break if foundAllLetters: print("Correct, the word is {}. You've won!".format(secretWord)) gameIsDone = True else: missedLetters = missedLetters + guess # Check if player has guessed too many times and lost if len(missedLetters) == len(HANGMAN_PICS) - 1: displayBoard(missedLetters, correctLetters, secretWord) print("You have run out of guesses!\nAfter {} missed guesses and {} correct guesses, the word was {}".format( str(len(missedLetters)), str(len(correctLetters)), secretWord)) gameIsDone = True # Ask the player if they want to play again if the game is ended if gameIsDone: if playAgain(): missedLetters = '' correctLetters = '' secretWord = getRandomWord(words) gameIsDone = False else: print("Thanks for playing Hangman")
import turtle def draw_anyshape(): window = turtle.Screen() window.bgcolor("red") draw_square() # draw_circle() # draw_triangle() window.exitonclick() def draw_square(): brad = turtle.Turtle() brad.shape("turtle") brad.color("green") brad.speed(2) count = 0 while count < 50: brad.forward(100) brad.right(90) brad.right(10) count = count + 1 def draw_circle(): angie = turtle.Turtle() angie.circle(100) angie.color("yellow") angie.shape("turtle") def draw_triangle(): triang = turtle.Turtle() triang.forward(300) triang.left(120) triang.forward(300) triang.left(120) triang.forward(300) triang.color("yellow") triang.shape("turtle") draw_anyshape()
import math import pandas as pd # x is defined as a list of data points or the mean depending on the defenition it's provided. # z is the z-score primarly they z-score for the 95 or 98% (CI) # x_bar is a sample mean withint the normal distribution # n is the sample size for the normal distribution, excpet in the midpoint function where it is the length. def make_a_list(): #Make x """Easier way to copy an excel column and make it into a list.""" df = pd.read_clipboard(header=None) x = [i for i in df[0]] return x def mode(x): #x is a list """the left hand side is the count of numbers and the right is the greatest number in the histogram.""" mode_list = [] for number in x: mode_list.append((x.count(number),number)) return max(mode_list) def mean(x): #x is a list sum = 0 average = 0 for i in x: sum += i average = sum/float(len(x)) return average def variance(x,n): sum = 0 for i in x: summation += (i-mean(x))**2 variance = summation / (n-1) return sum def pooled_variance(x_1,x_2): ss_1 = variance(x_1) ss_2 = variance(x_2) df_1 = len(x_1)-1 df_2 = len(x_2)-1 return (ss_1 + ss_2)/(df_1 + df_2) def std(x): #x is a list sum = 0 variance = 0 std = 0 for i in x: sum += (i-mean(x))**2 variance = sum/len(x) std = math.sqrt(variance) return std def std_indy(x_1,x_2): s_1 = std(x_1) s_2 = std(x_2) return math.sqrt(s_1**2 + s_2**2) def midpoint(x): #x is a list n = len(x) if n % 2 == 0: median = (x[n/2] + x[n/2 + 1])/float(2) return median else: median = x[(n-1)/2] return median def standard_error(x,n): #x is a list and n is a sample sigma = std(x) n = math.sqrt(n) return sigma/float(n) def standard_sample_error(x,n): sigma = bessels_correction(x) n = math.sqrt(n) return sigma/float(n) def independent_standard_error(x_1,x_2,n_1,n_2): s_1 = bessels_correction(x_1) s_2 = bessels_correction(x_2) return math.sqrt(s_1**2/float(n_1) + s_2**2/float(n_2)) def corrected_standard_error(x_1,x_2,n_1,n_2): """Corrected standard error using the pooled variance""" s_p = pooled_variance(x_1,x_2) df_1 = n_1 - 1 df_2 = n_2 - 1 SE = math.sqrt(s_p/n_1 + s_p/n_2) return SE def margin_error(z,s,n): """always calculate the the margin of error on a two-tailed test.""" return z*(s/float(math.sqrt(n))) def confidence_interval(x_bar,z,s,n): #x_bar is a sample mean, z or t is the margin of error score, s is the standard deviation # and n is the sample size SE = s/float(math.sqrt(n)) return(x_bar-(z*SE),x_bar+(z*SE)) def confidence_interval_indy(x_bar_1,x_bar_2,z,s_1,s_2,n_1,n_2): SE = math.sqrt(s_1**2/float(n_1) + s_2**2/float(n_2)) diff = (x_bar_1 - x_bar_2) return(diff-(z*SE), diff + (z*SE)) def z_score(x_bar,x,sigma): #x_bar is a sample mean, x is a mean and sigma is the standard deviation return(x_bar-x)/float(sigma) def t_stat(x_bar,x,s,n): #x_bar is a sample mean, x is a mean, s is the standard deviation and n is the sample size SE = s/float(math.sqrt(n)) return(x_bar-x)/SE def t_stat_indy(x_bar_1,x_bar_2,x_1,x_2,s_1,s_2,n_1,n_2): SE = math.sqrt(s_1**2/float(n_1) + s_2**2/float(n_2)) return(((x_bar_1-x_bar_2)-(x_1-x_2))/SE) def t_stat_indy_pool(x_bar_1,x_bar_2,x_1,x_2,SE): """pooled variance for the t_test. Normally we use thsi one.""" return(((x_bar_1-x_bar_2)-(x_1-x_2))/SE) def cohens_d(x_bar,x,s): #s := as the standard deviation of the sample mean x_bar. d = (x_bar-x)/float(s) return d def difference(x,y): """this function takes two lists x and y respectively and outputs the difference as a list.""" diff = [] for i,j in zip(x,y): diff.append(i-j) return diff def bessels_correction(x): #x is a list sum = 0 variance = 0 S = 0 for i in x: sum += (i-mean(x))**2 variance = sum/float(len(x)-1) S = math.sqrt(variance) return S def degrees_of_freedom(x): #x is a list """the left hand side is the sample and the right is the DOF.""" return (len(x),len(x)-1) def degrees_of_freedom_indy(x_1,x_2): n_1 = len(x_1) n_2 = len(x_2) df = n_1 + n_2 - 2 return (((n_1,n_2), df)) def r_squared(x_bar,x,s,n): """this is for the t-test r squared were we look at the degrees of freedom""" t = t_stat(x_bar,x,s,n) #this is the t-statistic df = (n-1) #this is the degrees of freed of the sample size. r_squared = t**2/(t**2 + df) #this is r^2 return r_squared
class planet: planets = dict() def __init__(self, name, orbiter): self.orbiters = [] self.orbits = None if orbiter != None: self.orbiters.append(orbiter) orbiter.addOrbits(self) self.planets[name] = self self.name = name def addOrbiter(self, orbiter): self.orbiters.append(orbiter) orbiter.addOrbits(self) def addOrbits(self, orbits): self.orbits = orbits def printPlanet(self, depth): print(self.name.rjust(depth, '#')) for p in self.orbiters: p.printPlanet(depth + 1) def countOrbits(self, depth): #print(self.name.rjust(depth, '#')) #print("counting orbits for: " + self.name) orbitCount = 0 if self.orbits != None: orbitCount = self.orbits.countOrbits(depth+1) else: #print("Nonea pukkaa") return depth #print(" there are orbits: " + str(orbitCount)) return orbitCount def findPathToRoot(self): path = [] tmpPlanet = None if self.name == "COM": return None if self.orbits.name == "COM": return None tmpPlanet = self.orbits while True: if tmpPlanet.name == "COM": return path path.append(tmpPlanet) tmpPlanet = tmpPlanet.orbits def printInfo(self): print("name: " + self.name + " orbiters: " + str(self.orbiters) + " orbits: " + str(self.orbits)) path = "input.txt" with open(path) as fl: for line in fl: line = line.strip() pl = line.split(')') #print(pl) if pl[0] in planet.planets and pl[1] in planet.planets: planet.planets[pl[0]].addOrbiter(planet.planets[pl[1]]) #print("both existed:") #planet.planets[pl[0]].printPlanet(1) #planet.planets[pl[1]].printPlanet(1) elif pl[0] in planet.planets: newPlanet = planet(pl[1], None) planet.planets[pl[0]].addOrbiter(newPlanet) #print("0 existed:") #newPlanet.printPlanet(1) elif pl[1] in planet.planets: newPlanet = planet(pl[0], planet.planets[pl[1]]) else: newPlanet = planet(pl[1], None) #print("none existet new planet:") #newPlanet.printPlanet(1) newPlanet2 = planet(pl[0], newPlanet) #print("none existet new planet 2:") #newPlanet2.printPlanet(1) planet.planets["COM"].printPlanet(1) totalDepth = 0 for key in planet.planets: #planet.planets[key].printInfo() totalDepth += planet.planets[key].countOrbits(0) print("syvyydet: " + str(totalDepth)) print("Pukki juurest: " + str(planet.planets["SAN"].countOrbits(0))) print("minä juurest: " + str(planet.planets["YOU"].countOrbits(0))) pathToYou = planet.planets["YOU"].findPathToRoot() print("path to you: ") print(pathToYou) pathToSanta = planet.planets["SAN"].findPathToRoot() print("path to santa: ") print(pathToSanta) partOfSantaPath = None partOfYouPath = None partOfSantaPath = pathToSanta.pop() partOfYouPath = pathToYou.pop() common = partOfYouPath while True: if partOfSantaPath == partOfYouPath: common = partOfSantaPath partOfSantaPath = pathToSanta.pop() partOfYouPath = pathToYou.pop() else: break print("yhteinen isä on: " + common.name) santaDis = planet.planets["SAN"].countOrbits(0) - 1 youDis = planet.planets["YOU"].countOrbits(0) - 1 commonDis = common.countOrbits(0) pathDis = santaDis + youDis - 2*commonDis print(pathDis)
#!/usr/bin/env python3 import sys import ast import re #input_file = "test.txt" #input_file = "test2.txt" input_file = "input.txt" with open(input_file) as f: data = f.read() kws = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"] ecls = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] def checkInput(input): if int(input["byr"]) > 2002: #print("invalid byr") return False if int(input["byr"]) < 1920: #print("invalid byr") return False if int(input["iyr"]) < 2010: #print("invalid iyr") return False if int(input["iyr"]) > 2020: #print("invalid iyr") return False if int(input["eyr"]) > 2030: #print("invalid eyr") return False if int(input["eyr"]) < 2020: #print("invalid eyr") return False if input["hgt"][-2:] == "cm": if int(input["hgt"][:-2]) < 150: #print("invalid hgt") return False if int(input["hgt"][:-2]) > 193: #print("invalid hgt") return False elif input["hgt"][-2:] == "in": if int(input["hgt"][:-2]) < 59: #print("invalid hgt") return False if int(input["hgt"][:-2]) > 76: #print("invalid hgt") return False else: #print("invalid hgt") return False if re.match(r"(#\w{6}$)", input["hcl"]) is None: #print("HCL kusee") return False if input["ecl"] not in ecls: #print("ecl kusee") return False if re.match(r"\d{9}$", input["pid"]) is None: #print("Pid kusee") return False return True okCount = 0 data = data.split("\n\n") #print(len(data)) for d in data: dd = d.replace(" ", " , ") dd = dd.replace(":", " : ") ds = set(dd.split()) & set(kws) #print(dd) #print(ds) if len(ds) == 8: #print("Is okay, all in") okCount += 1 if len(ds) == 7: if ("cid") not in ds: #print("Is okay, only cid is missing") okCount += 1 print("PART1: a'ok passports {}".format(okCount)) ## PART 2 okCount = 0 for d in data: if len(d) > 0: dd = d.replace(" ", ", ") dd = dd.replace(":", " : ") dd = dd.replace("\n", " , ") dd = dd.strip(",") #print(dd) di = dict((x.strip(), y.strip()) for x,y in (element.split(':') for element in dd.split(','))) #print(di) ds = set(dd.split()) & set(kws) #print(dd) #print(ds) if len(ds) == 8: validated = checkInput(di) if validated: #print("Is all ok") okCount += 1 if len(ds) == 7: if ("cid") not in ds: validated = checkInput(di) if validated: #print("Is all ok") okCount += 1 print("PART2: a'ok passports {}".format(okCount))
#!/usr/bin/env python3 import sys input_file = 'test_input.txt' input_file = 'input.txt' #input_file = "test2.txt" if len(sys.argv) > 1 : input_file = sys.argv[1] with open(input_file) as f: data = f.readlines() data = [d.strip() for d in data] data = [d.split("->") for d in data] cave = {} def addCoord(x, y): return [x[0]+y[0], x[1]+y[1]] miny, minx = 700, 700 maxy, maxx = 0, 0 for d in data: for i in range(1, len(d)): start = d[i-1].split(",") end = d[i].split(",") start = [int(s) for s in start] end = [int(e) for e in end] #print("27 s:{}, e:{}".format(start, end)) minx = min(minx, start[0], end[0]) miny = min(miny, start[1], end[1]) maxx = max(maxx, start[0], end[0]) maxy = max(maxy, start[1], end[1]) if start[1] == end[1]: #print("eka kasvaa") if start[0] < end[0]: for j in range(start[0], end[0]+1): cave[(j, start[1])] = '#' else: for j in range(end[0], start[0]+1): cave[(j, start[1])] = '#' elif start[0] == end[0]: #print("Toka kasvaa") if start[1] < end[1]: for j in range(start[1], end[1]+1): cave[(start[0], j)] = '#' else: for j in range(end[1], start[1]+1): cave[(start[0], j)] = '#' #print(max(start[1], end[1])) #print(min(start[1], end[1])) for j in range(max(start[1], end[1]), min(start[1], end[1])+dir, dir): #print("37:",j) cave[(start[0], j)] = '#' #print(cave) sand = [500, 0] lasts = (500,0) rested = True falls = [[0,1], [-1,1], [1,1]] sands = 0 part1 = 0 part1done = False while rested: stillFalling = False for f in falls: toTest = addCoord(sand, f) toTest = (toTest[0], toTest[1]) if toTest not in cave: stillFalling = True sand = toTest break if not stillFalling or sand[1] == maxy+1: if part1done == False and sand[1] == maxy+1: part1done = True part1 = sands cave[sand] = "x" cave[lasts] = "o" lasts = sand sands += 1 sand = (500, 0) if cave.get((500,0))== "x": break if sand[1] > 200: break cave[(500,0)] = "S" print() for i in range(0, maxy+10): print(str(i).zfill(3), end=" ") for j in range(minx-10, maxx+10): if cave.get((j, i)) == None: print(".", end="") else: print(cave.get((j,i)), end="") print() print("Part1:") print("It dropped {} before going to void".format(part1)) print("Part2:") print("It dropped {} before blocking start".format(sands)) print(miny, maxy, minx, maxx)
#!/usr/bin/env python3 import sys input_file = 'test_input.txt' input_file = 'input.txt' if len(sys.argv) > 1 : input_file = sys.argv[1] with open(input_file) as f: data = f.readlines() data = [d.strip() for d in data] var='a' alphabets=[] # starting from the ASCII value of 'a' and keep increasing the # value by i. alphabets=[(chr(ord(var)+i)) for i in range(26)] var='A' for i in range(26): alphabets.append(chr(ord(var)+i)) # PART one sum = 0 for d in data: ind = int(len(d)/2) firstCom = d[:ind] secondCom = d[ind:] commonChar = set(firstCom).intersection(secondCom).pop() value = alphabets.index(commonChar) +1 sum += value print("PART1:") print("Sum of priorities: {}".format(sum)) # PART two i = 0 sum = 0 while i < len(data): elf1 = data[i] elf2 = data[i+1] elf3 = data[i+2] auth = set(elf1).intersection(elf2).intersection(elf3).pop() i += 3 value = alphabets.index(auth) +1 sum += value print("PART2:") print("Sum of priorities: {}".format(sum))
#!/usr/bin/env python3 import sys input_file = 'test_input.txt' input_file = 'input.txt' if len(sys.argv) > 1 : input_file = sys.argv[1] with open(input_file) as f: data = f.readlines() data = [d.strip() for d in data] # PART one pointsDict = { "A X": 4, "A Y": 8, "A Z": 3, "B X": 1, "B Y": 5, "B Z": 9, "C X": 7, "C Y": 2, "C Z": 6, } points = 0 for d in data: points += pointsDict[d] print("PART1: ") print(points) # x = häviö # y = tasuri # z = voitto templist = ['C', 'A', 'B', 'C', 'A'] valueDict = { 'A': 1, 'B': 2, 'C': 3 } toDoDict = { 'X': -1, 'Y': 0, 'Z': 1 } resultPointDict = { 'X': 0, 'Y': 3, 'Z': 6 } points = 0 rndPoints = 0 whatToDo = 'A' index = 0 for d in data: index = valueDict[d[0]] + toDoDict[d[2]] whatToDo = templist[index] rndPoints = resultPointDict[d[2]] + valueDict[whatToDo] points += rndPoints print("Part2: ") print(points)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019/11/4 15:52 # @Author : YangYusheng # @File : 前馈神经网络.py # @Software: PyCharm # coding:utf-8 import numpy as np import pandas as pd class NeuralNetwork(): # 随机初始化权重 def __init__(self): np.random.seed(1) self.synaptic_weights = 2 * np.random.random((400, 1)) - 1 # 定义激活函数:这里使用sigmoid def sigmoid(self, x): return 1 / (1 + np.exp(-x)) # 计算Sigmoid函数的偏导数 def sigmoid_derivative(self, x): return x * (1 - x) # 训练模型 def train(self, training_inputs, training_outputs, learn_rate, training_iterations): # 迭代训练 for iteration in range(training_iterations): # 前向计算 output = self.think(training_inputs) # 计算误差 error = training_outputs - output adjustments = np.dot(training_inputs.T, error * self.sigmoid_derivative(output)) self.synaptic_weights += learn_rate * adjustments def think(self, inputs): # 输入通过网络得到输出 # 转化为浮点型数据类型 inputs = inputs.astype(float) output = self.sigmoid(np.dot(inputs, self.synaptic_weights)) return output if __name__ == "__main__": X = pd.read_csv("X_data.csv", header=None) y = pd.read_csv("y_label.csv", header=None) neural_network = NeuralNetwork() train_data = X training_inputs = np.array(train_data) training_outputs = np.array(y) # 参数学习率 learn_rate = 0.1 # 模型迭代的次数 epoch = 1500 neural_network.train(training_inputs, training_outputs, learn_rate, epoch) print("迭代计算之后权重矩阵W: ") print(neural_network.synaptic_weights)
class cell(): """A cell is a single unit of a sudoku puzzle. A sudoku puzzle is composed of 81 cells. Initialize a cell with a list of possible answers that can be put in an answer (if one exists), position in the sudoku puzzle, and whether or not the answer has been selected for the box""" def __init__(self, position): self.possibleAnswers = [1,2,3,4,5,6,7,8,9] self.answer = None self.position = position self.solved = False """Removes a value from the list of possible answers for a cell""" def remove(self, num): if num in self.possibleAnswers and self.solved == False: self.possibleAnswers.remove(num) if len(self.possibleAnswers) == 1: self.answer = self.possibleAnswers[0] self.solved = True else: raise(ValueError) """Returns whether or not a cell has been solved""" def solvedMethod(self): return self.solved """Returns the position of the cell in the sudoku puzzle""" def checkPosition(self): return self.position """Returns a list of possible answers that can be filled into the cell""" def returnPossible(self): return self.possibleAnswers """Returns the length of the possible answers list as an integer""" def lenOfPossible(self): return len(self.possibleAnswers) """Returns the value if the cell has been solved, otherwise it returns false""" def returnSolved(self): if self.solved == True: return self.possibleAnswers[0] else: return False """Sets the state of the cell to solved, sets the answer to a num, and eliminates all other possible answers from the possible answer list except for the given number""" def setAnswer(self, num): if num in [1,2,3,4,5,6,7,8,9]: self.solved = True self.answer = num self.possibleAnswers = [num] else: raise(ValueError) def emptySudoku(): ans = [] for x in range(1,10): if x in [7,8,9]: z = 3 if x in [4,5,6]: z = 2 if x in [1,2,3]: z = 1 for y in range(1,10): if y in [7,8,9]: z += 2 if y in [4,5,6]: z += 1 if y in [1,2,3]: z += 0 c = cell((x,y,z)) ans.append(c) return ans
#!/usr/bin/env python import math import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", type=int, help = "total number of items to choose from") parser.add_argument("-k", type=int, help = "number of items to choose") parser.add_argument("-l", "--log", action="store_true", help = "returns the log binomial coefficient") parser.add_argument("-t", "--test", action="store_true", help="tests the module and quits") args = parser.parse_args() def logfactorial(n, k = 0): '''Takes an integer n and calculates log(n!) = log(1) + log(2) + ... + log(n) >>> logfactorial(1) 0.0 >>> round(logfactorial(10),5) 15.10441 ''' assert int(n) == n, 'Error: input should be an integer -- it is not!' assert n > 0, 'Error: input should be positive!' if k != None: assert int(k) == k, 'Error: input k should be an integer' assert k >= 0, 'Error: input k should be positive' result=0 for i in range(k+1, n+1): result += math.log(i) return(result) def choose(n,k, log = False): '''Takes two positive integers, n and k, and calculates n choose k. >>> choose(5,1) 5 >>> choose(5,3) 10 >>> choose(5,10) 0 ''' assert int(n) == n, 'Error: inputs should be an integer -- n it is not!' assert n > 0, 'Error: inputs should be positive -- n is not' assert int(k) == k, 'Error: inputs should be an integer -- k is not!' assert k > 0, 'Error: input should be positive -- k is not' if n < k: return(0) else: result = logfactorial(n,k) - logfactorial(n-k) if not log: ## Note: use int(round(...)) to force round to nearest integer, and return integer. ## Using only round will return float, using only integer, will return only integer part of number. ## For example, int(8.9) = 8 result = int(round(math.exp(result))) return(result) ## If run as script (i.e. not imported)... if __name__ == '__main__': ## ... and --test not specified: if not args.test: ## - check n if args.n<=0: raise Exception("argument -n must be positive") ## - check k elif args.k<0: raise Exception("argument -k must be 0 positive") ## if both n and k pass, run and print choose with user specified values else: print(choose(args.n, args.k, args.log)) else: ## ... if --test is specified, run tests. print("Testing the module...") import doctest doctest.testmod() print("DONE!")
import json import os import time import random def main(): # TODO: allow them to choose from multiple JSON files? for file in os.listdir(): if file.endswith(".json"): print (file) json_file = input("Which file will you open? ") with open("theGlassHouse1.json") as fp: game = json.load(fp) print_instructions() print("You are about to play '{}'! Good luck!".format(game['__metadata__']['title'])) print("") play(game) def play(rooms): current_time= time.time() # Where are we? Look in __metadata__ for the room we should start in first. current_place = rooms['__metadata__']['start'] # The things the player has collected. stuff = ['Cell Phone; no signal or battery...'] visited = {} while True: # Figure out what room we're in -- current_place is a name. times= int(time.time() - current_time) here = rooms[current_place] # Print the description. print(here["description"]) print ("You have been here for " + str(times) +" seconds") if here ["items"] == []: print ("There is nothing here for you to take.") else: print ("You can take" + str(here["items"])) cat_s = "not seen" cat = random.randint(0, 7) if cat_s == "seen": if cat == 1: print ("You spot the cat again! So pretty!") if cat == 2: print ("You see some lonely fur.") else: if cat == 1: print ("You spot a black cat!") cat_s = "seen" if here.get("visited", False): print ("You've been in this room before.") here ['visited'] = True # TODO: print any available items in the room... # e.g., There is a Mansion Key. # Is this a game-over? if here.get("ends_game", False): break # Allow the user to choose an exit: usable_exits = find_usable_exits(here, stuff) # unlocked_exits = usable_exits[0] # locked_exits = usable_exits [1] # Print out numbers for them to choose: for i, exit in enumerate(usable_exits): print(" {}. {}".format(i+1, exit['description'])) # See what they typed: action = input("> ").lower().strip() if action == "help": print_instructions () continue # If they type any variant of quit; exit the game. if action in ["quit", "escape", "exit", "q"]: print("You quit. Better luck next time!") break # TODO: if they type "stuff", print any items they have (check the stuff list!) if action == "stuff": if stuff == []: print ("You have nothing.") else: print(stuff) continue # TODO: if they type "take", grab any items in the room. if action == "take": if here ["items"] == []: print ("There is nothing here for you to take.") else: print ("You picked up", + here ["items"]) stuff.extend(here["items"]) here["items"].clear() continue #TODO: If they type "drop", drop specific item and attach it to current location if action == "drop": drop = -1 while drop != 0: print ("Which item do you want to drop?") for i, item in enumerate (stuff): print (" {}. {}".format (i+1, item)) drop= input(">").lower().strip() if int (drop) > len(stuff) or int(drop) < 0: print ("That's not an item.") else: drop = int(drop) here ["items"].append(stuff [drop -1]) stuff.pop(drop - 1) drop = 0 continue # TODO: if they type "search", or "find", look through any exits in the room that might be hidden, and make them not hidden anymore! # Try to turn their action into an exit, by number. try: num = int(action) - 1 selected = usable_exits[num] current_place = selected['destination'] print("...") except: print("I don't understand '{}'...".format(action)) print("") print("") print("=== GAME OVER ===") def find_usable_exits(room, stuff): """ Given a room, and the player's stuff, find a list of exits that they can use right now. That means the exits must not be hidden, and if they require a key, the player has it. RETURNS - a list of exits that are visible (not hidden) and don't require a key! """ usable = [] locked = [] unlocked = [] for exit in room['exits']: if exit.get("hidden", False): continue if "required_key" in exit: if exit["required_key"] in stuff: usable.append(exit) continue usable.append(exit) return usable def print_instructions(): print("=== Instructions ===") print(" - Type a number to select an exit.") print(" - Type 'stuff' to see what you're carrying.") print(" - Type 'take' to pick up an item.") print(" - Type 'quit' to exit the game.") print(" - Type 'search' to take a deeper look at a room.") print("=== Instructions ===") print("") if __name__ == '__main__': main()
/** Plays song when it's time to wake up. Input required hour and minute from user and keeps the loop running until its time for alaram. It requires path to any song or music file in computer system in order to play music. **/ import time import os not_executed = 1 try: hour = int(input("At what hour? ")) minute = int (input("At what minute? ")) except ValueError: print ("It's not an integer") while(not_executed): dt = list(time.localtime()) dthour = dt[3] dtminute = dt[4] if dthour == hour and dtminute == minute: print ("Wake UP! It's",hour,":",minute) os.startfile("C:\\Users\\XYZ\\Music\\Songs\\Ed Sheeran - Shape of You.mp3") not_executed = 0
''' Matteo Gisondi, 1730913, Samuel Park, 1732027, Ali Tahmasebi, 1730131 Friday, May 24 R. Vincent, instructor Final Project ''' from Piece import Piece import numpy as np class Player(): '''keep track of piece positions and color of pieces''' DIM = 8 # dimensions of a standard board def __init__(self, positions, color, direction): self.positions = positions # set of piece positions self.pieces = {i:Piece(i, color) for i in self.positions} # dict of piece objects associated to position self.direction = direction # direction of moves self.crowned() # update crowned pieces def color(self): return self.pieces[list(self.positions)[0]].color def legalMoves(self, other): '''set of all legal moves''' legal_moves = set() for i, j in self.positions: if self.pieces[(i, j)].state == 2: # piece is promoted rows = (i - 1, i + 1) # check above and below elif self.direction == 'down': rows = (i + 1,) # check below elif self.direction == 'up': rows = (i - 1,) # check above else: raise('No direction specified') for next_row in rows: # check up, down, or both for next_col in (j - 1, j + 1): # check left and right try: assert 0 <= next_row < Player.DIM assert 0 <= next_col < Player.DIM # move square exists assert (next_row, next_col) not in self.positions assert (next_row, next_col) not in other.positions # destination space is not occupied legal_moves.add((self.pieces[(i, j)], (next_row, next_col))) except: pass return legal_moves def crowned(self): """ Added by Ali return an array of uncrowned and crowned pieces as tuple in repsective orded """ # numpy arrays fro crowned and uncrowned self.crowned = [] self.uncrowned = [] for piece in self.pieces.values(): # iterate over all the pieces # check state if piece.state == 2: # append to proper array self.crowned.append(piece) else: self.uncrowned.append(piece) # numpy acts weird when you try to append a user defined object to an array # so i turn the lists into arrays at the end self.crowned, self.uncrowned = np.array(self.crowned), np.array(self.uncrowned) return (self.crowned.copy(), self.uncrowned.copy()) def legalCaptures(self, other): '''set of all legal captures''' legal_captures = set() for i, j in self.positions: if self.pieces[(i, j)].state == 2: # piece is promoted rows = ((i - 1, i - 2), (i + 1, i + 2)) # check above and below elif self.direction == 'down': rows = ((i + 1, i + 2),) # check below elif self.direction == 'up': rows = ((i - 1, i - 2),) # check above else: raise('No direction specified: down = player1, up = player2') for next_row, next_row2 in rows: for next_col, next_col2 in ((j - 1, j - 2), (j + 1, j + 2)): try: assert 0 <= next_row2 < Player.DIM assert 0 <= next_col2 < Player.DIM # move square exists assert (next_row, next_col) not in self.positions assert (next_row, next_col) in other.positions assert (next_row2, next_col2) not in self.positions assert (next_row2, next_col2) not in other.positions # intermediate space is occupied by enemy piece, not by friendly # destination space is not occupied legal_captures.add((self.pieces[(i, j)], (next_row2, next_col2))) except: pass return legal_captures def move(self, other, piece, destination): '''update self and other positions for piece move must make move based on list of legal moves''' self.positions.remove(piece.pos) # remove current position del_piece = self.pieces.pop(piece.pos) # remove current piece self.pieces[destination] = Piece(destination, del_piece.color, del_piece.state) self.positions.add(destination) self.promote(self.pieces[destination]) # add new piece and check for promotion self.crowned() # update the crowned pieces return (piece, destination) def removePiece(self, piece): self.positions.remove(piece.pos) self.pieces.pop(piece.pos) self.crowned() # update the crowned pieces def capture(self, other, piece, destination): '''update self and other positions for piece capture must capture based on list of legal captures''' self.positions.remove(piece.pos) # remove current position inter_x = (piece.pos[0] + destination[0]) // 2 inter_y = (piece.pos[1] + destination[1]) // 2 other.removePiece(other.pieces[(inter_x, inter_y)]) # remove intermediate piece del_piece = self.pieces.pop(piece.pos) # remove current piece self.pieces[destination] = Piece(destination, del_piece.color, del_piece.state) self.positions.add(destination) self.promote(self.pieces[destination]) # add new piece and check for promotion self.crowned() # update the crowned pieces return (piece, destination) def promote(self, piece): if self.direction == 'down': limit = 7 elif self.direction == 'up': limit = 0 if piece.pos[0] == limit: self.pieces[piece.pos].state = 2 self.crowned() # update the crowned pieces def __repr__(self): return 'Player({}, {})'.format(self.positions, self.color(), self.direction)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res, tmp = [], [] while root or len(tmp)>0: while root: tmp.append(root) root=root.left res.append(tmp[-1].val) root=tmp[-1].right del tmp[-1] return res
#!/usr/bin/python # -*- coding: utf-8 -*- # Date 2015/10/31 # By Charlotte.HonG # unix_mid_test_05 import random # 演算法 # def insertion_sort(lst, start, end): # if len(lst) == 1: # return # for i in xrange(start + 1, end + 1): # temp = lst[i] # j = i - 1 # while j >= start and temp < lst[j]: # lst[j + 1] = lst[j] # j -= 1 # lst[j + 1] = temp # 使用內建函數 def sortsl(lst, start, end): temp_list = lst[start:end + 1] temp_list.sort() temp_list = lst[:start] + temp_list + lst[end + 1:] return temp_list def main(): random_list = range(0, 10) random.shuffle(random_list) print 'Original= ', random_list print 'Limit_Order=', sortsl(random_list, 1, 8) print 'Original= ', random_list if __name__ == '__main__': main()
# 0 - 4 for i in range(5): print("i = ", i) # 2 - 4 for i in range(2, 5): print("i = ", i)
# > : Greater than # > : Less than # >= : Greater than or equal to # <= : Less than or equal to # == : Equal to # != : Not equal to drink = input("Pick one (Coke or Pepsi) : ") if drink == "Coke": print("Here is your Coke") elif drink == "Pepsi": print("Here is your Pepsi") else: print("Here is your water")
# print(type("3")) # print(type('3')) # print(type('''3''')) samp_string = "This is a very important string" print("Length: ", len(samp_string)) print(samp_string[0]) print(samp_string[-1]) print(samp_string[0:4]) #till 4th non inclusive print(samp_string[8:]) print("Every other", samp_string[0:-1:2]) # Start from the beginning, until the end, stepping by 2 characters print("Reverse", samp_string[::-1]) print("Green " + "Eggs") print("Hello" * 5) num_string = str(4) for char in samp_string: print(char) for i in range(0, len(samp_string)-1, 2): print(samp_string[i] + samp_string[i+1]) # A - Z : 65 - 90 # a - z : 97 - 122 print("A = ", ord("A")) print("65 = ", chr(65))
# Import the os and reading CSV modules import os import csv # Path to CSV file csvpath = os.path.join('Resources', 'budget_data.csv') # Reading using CSV module with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') # Skip the header header = next(csvreader) # Initialize variables countMonths = 0 totalRevenue = 0 rowRevenue = 0 firstRow = True # Read each row of data after the header for row in csvreader: # Add to the months counter countMonths = countMonths + 1 # Add to the total revenue variable totalRevenue = totalRevenue + float(row[1]) # Check whether it is the first row with value so to skip increase/decrease calculation if(firstRow == True): # If is it the first row, then change the boolean to false for next execution and initialize the variables calculated in the conditional below firstRow = False totalChange = 0 maxIncrease = -1000000 maxDecrease = 1000000 else: # If it is not the first row, then calculate the total of changes and check for maximum and minimum changes totalChange = totalChange + (float(row[1]) - rowRevenue) if((float(row[1]) - rowRevenue) > maxIncrease): maxIncrease = float(row[1]) - rowRevenue maxIncreaseMonth = row[0] if((float(row[1]) - rowRevenue) < maxDecrease): maxDecrease = float(row[1]) - rowRevenue maxDecreaseMonth = row[0] # Save the current revenue value for the next row iteraction, so to calculate the changes in the conditional above rowRevenue = float(row[1]) # Output summary to terminal print("Financial Analysis") print("------------------") print("Total Months: " + str(countMonths)) print("Total: $" + str(totalRevenue)) print("Average Change: $" + str(totalChange/(countMonths-1))) print("Greatest Increase in Profits: " + maxIncreaseMonth + " ($" + str(maxIncrease) + ")") print("Greatest Decrease in Profits: " + maxDecreaseMonth + " ($" + str(maxDecrease) + ")") # Open a txt file and write the same output f = open("output.txt","w") f.write("Financial Analysis" + "\n") f.write("------------------" + "\n") f.write("Total Months: " + str(countMonths) + "\n") f.write("Total: $" + str(totalRevenue) + "\n") f.write("Average Change: $" + str(totalChange/(countMonths-1)) + "\n") f.write("Greatest Increase in Profits: " + maxIncreaseMonth + " ($" + str(maxIncrease) + ")" + "\n") f.write("Greatest Decrease in Profits: " + maxDecreaseMonth + " ($" + str(maxDecrease) + ")") f.close()
import csv import os raw_data = open('budget_data.csv') csv_reader = csv.reader(raw_data, delimiter=',') file_heders = next(csv_reader) print(F"Hearder: {file_heders} ") count_months = 0 total = 0 previousvalue = 867884 total_changes = 0 G_increase = 0 G_decrease = 0 for row in csv_reader: count_months += 1 total = total + int(row[1]) change = int(row[1])-previousvalue total_changes += change previousvalue = int(row[1]) if change > G_increase: G_increase = change m_increase = row[0] if change <G_decrease: G_decrease = change m_decrease = row[0] average = total_changes/ (count_months - 1) average = str(round(average, 2)) print(F" Total Months: {count_months}, \n Total: {total}, \n Average: {average},\n Greatest Increase in Profits: {m_increase} {G_increase},\n Greatest Decrease in Profits: {m_decrease} {G_decrease}") with open("out.txt", "w") as f: f.write(F" Total Months: {count_months}, \n Total: {total}, \n Average: {average},\n Greatest Increase in Profits: {m_increase} {G_increase},\n Greatest Decrease in Profits: {m_decrease} {G_decrease}")
######################################################################## # USER STORY: # When you take a pic of your signature # but the background is not entirely white # you can "python Set_Background_White YOUR_SIGNATURE_FILE" to turn the background white # GIVEN that your signature is somewhat black or dark color ######################################################################## import sys from PIL import Image # ORIGINAL_IMAGE_NAME is the original image file ORIGINAL_IMAGE_NAME = sys.argv[1] # # assume jpg file original_image = Image.open(ORIGINAL_IMAGE_NAME) # #load image to pixel original_pix = original_image.load() for i in range(original_image.size[0]): for j in range(original_image.size[1]): # sum of background pixel's rbg # NOTE: user can CUSTOMIZE this background_color = 600 if original_pix[i,j][0]+original_pix[i,j][1]+original_pix[i,j][2]> background_color: # turn the it to white original_pix[i,j] = (255,255,255) # save file original_image.save("output_"+ORIGINAL_IMAGE_NAME)
""" 简易计算器 """ class Count: result_msg = '' ''' 加法运算 ''' def add(self, value: int): self.result_msg += '+' + value.__str__() ''' 减法运算 ''' def subtract(self, value: int): self.result_msg += '-' + value.__str__() ''' 乘法运算 ''' def multiply(self, value: int): self.result_msg += '*' + value.__str__() ''' 除法运算 ''' def divide(self, value: int): self.result_msg += '/' + value.__str__() ''' 利用eval进行运算,并返回结果 ''' def result(self): return eval(self.result_msg)
def mas_repetido(matriz): pass def condensa(cadena): if cadena: ocurrencias = 0 i = 0 lista = [] while len(cadena) > 0: ocurrencias += 1 while i + 1 < len(cadena) and cadena[i + 1] == cadena[i]: ocurrencias += 1 i += 1 i = 0 lista.append((cadena[0], ocurrencias)) cadena = cadena.replace(cadena[0], "", ocurrencias) ocurrencias = 0 for i in range(len(lista)): print (lista[i]) else: print([]) def triangulo_pascal(niveles): if niveles > 0: if niveles == 0: return [] elif niveles == 1: return [[1]] else: lista_1 = [1] resultado = triangulo_pascal(niveles-1) lista_2 = resultado[-1] for i in range(len(lista_2)-1): lista_1.append(lista_2[i] + lista_2[i+1]) lista_1 += [1] resultado.append(lista_1) for i in range(len(resultado)): print (resultado[i]) else: print("No existen niveles negativos") def subcadenas(cadena): if cadena == []: return [[]] ll = lattice(cadena[1:]) a =([e+[cadena[0]] for e in ll] + ll) print(a) return a def mas_repetido_s(): print("Por favor ingresa la matriz") y = input() mas_repetido(y) main_aux() def condensa_s(): print("Por favor ingresa la cadena") n = input() condensa(n) main_aux() def triangulo_s(): print("Por favor ingresa el nivel al que quieres llegar") m = input() triangulo_pascal(m) main_aux() def subcadenas_s(): print("dame la cadena con esta estructura ['caracter','caracter','caracter']" + " con tantos caracteres como desees separados por comas u entre comillas simples") x = input() subcadenas(x) main_aux() def checar_funcion(n): switcher = { 1: mas_repetido_s, 2: condensa_s, 3: triangulo_s, 4: subcadenas_s } funcion = switcher.get(n, "Por favor ingresa un número válido") funcion() main() def main_aux(): print("¿Deseas continuar? S/n") z = input() z.lower() if z == "s": main() elif z == "n": sys.exit() else: "Por favor elige una opción válida" main_aux() def main(): print("\n¡Bienvenido al programa!") print("Por favor ingresa el número que corresponda a la función que quieres utilizar\n\n") print("1. Más repetido: esta función encuentra el valor que más repeticiones tiene en una matriz. Si dos números aparecen la misma cantidad de veces, devuelve el que aparece primero\n\n") print("2. Condensa: Esta función devuelve una lista con la letra y la cantidad de veces que aparece\n\n") print("3. Triangulo de pascal: esta función delvuelve una lista con los niveles del triangulo de pascal\n\n") print("4. subcadenas: Esta función devuelve una lista con la cadena dividida en subcadenas de tamaño i\n\n") z = int(input()) checar_funcion(z) if __name__ == "__main__": main()
#imports everything from the random module. This allows program to select random integers. from random import * #Creates min and max variables. Min variable will be between 0 and 10 (not including 10). Max variable will be between 11 and 21 (not including 21). min = randrange(10) max = randrange(11,21) #Creates a random number variable that selects a random integer between the range of the min and max created earlier. The min and max integers are included. rand_num = randint(min,max) #Prints welcome message and asks an input for name. Name is saved in variable called user_name. print("Hello! Welcome to Kharee's Guessing Game \n") user_name = input("Input your name: ") #Sets a variable for number of guesses to 0. number_of_guesses = 0 #Checks if name entered by user is "Kharee". If so, displays message regarding the program having chosen a random number and also what that random number is. If the name is not "Kharee", the program displays the same message about the random number but doesn't display contents. if (user_name == "Kharee"): print("Greetings " + user_name + "! The secret number is " + str(rand_num) + ". ;)\n\nI'm thinking of a number between " + str(min) + " and " + str(max) + ".\n") else: print("\nGreetings " + user_name + "!\n\nI'm thinking of a number between " + str(min) + " and " + str(max) + ".\n") #"While" statement that allows code to run while the number of guesses is less than or equal to 5. while number_of_guesses <= 5: #Checks if the number of guesses is equal to 5 and if so, displays a message about what the random number. was. if(number_of_guesses == 5): print("Sorry, you're out of guesses! The number was: " + str(rand_num)) break #Prints message about how many guesses are remaining by subtracting the number of guesses variable from 5. print("You have " + str(5 - (number_of_guesses)) + " guesses!") #Displays prompt for user's guess of the random number and formats it into an integer. user_guess = int(input("Input a number: ")) #If the user's number is lower than the random number, a message is displayed about it and the number of guesses increases by 1. if (user_guess < rand_num): print("You are too low!") number_of_guesses+=1 #If the user's number is higher than the random number, a message is displayed about it and the number of guesses increases by 1. elif(user_guess > rand_num): print("Oops too high!") number_of_guesses+=1 #If the user's number is the same as the random number, a message is displayed that the number was guessed and how many tries it took. elif(user_guess == rand_num): print("You guessed correctly! Only took " + str(number_of_guesses + 1) + " tries!") break
#!/usr/bin/python from random import * x = 0 i = 0 while True: x = randint (1, 6) print (x) i = i+1 if x == 3: print ('salio 3! en el intento', i) break
if __name__ == '__main__': T = int(input()) alphabet_dict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20, 'u':21, 'v':22, 'w':23, 'x':24, 'y':25, 'z':26} for _ in range(T): s = str(input()) len_ = len(s) mid = len_ // 2 palindrome = 0 if len_ % 2 == 0: if s[:mid] + s[mid-1::-1] == s: palindrome = 1 else: if s[:mid] + s[mid] + s[mid-1::-1] == s: palindrome = 1 if palindrome == 1: print("Palindrome") else: prod = 1 for letter in s: prod *= alphabet_dict[letter] print(prod)
if __name__ == '__main__': N = int(input()) S = str(input()) count_a, count_e, count_h, count_r = S.count('a'), S.count('e'), S.count('h'), S.count('r') count_c, count_k, count_t = S.count('c'), S.count('k'), S.count('t') min2x = min(count_a, count_e, count_h, count_r) minx = min(count_c, count_k, count_t) double_down = min2x // 2 if double_down >= minx: print(minx) if double_down < minx: print(double_down)
# -*- coding: utf-8 -*- """ Created on Mon Oct 5 18:15:36 2020 @author: huybv1998 """ n = int(input("nhap 1 so n : ")) sum1 = 0 for i in range(1, n): if (n % i == 0): sum1 += i if (sum1 == n): print("so n la so hoan hao") else: print("so n la so ko hoan hao")
# -*- coding: utf-8 -*- """ Created on Thu Oct 22 23:22:39 2020 @author: huy """ A = [] B = [] n = int(input("Nhập 1 số n: ")) for i in range(0, n): if (i % 2 == 0): A.append(i) if (i%2): B.append(i) print(A)
# -*- coding: utf-8 -*- """ Created on Wed Oct 28 23:59:37 2020 @author: huybv1998 """ import random N = int(input("Nhập số N: ")) A = list(range(N)) random.shuffle(A) print(A)
# -*- coding: utf-8 -*- """ Created on Sat Oct 31 01:22:37 2020 @author: huybv1998 """ import math def calculateArea(a, b, c): p = (a + b + c)/2 S = math.sqrt(p*(p-a)*(p-b)*(p-c)) ha = S/(0.5*a) #Chỗ này đề bài bị sai hb = S/(0.5*b) #Không phải là 2*a mà là 0.5*a hc = S/(0.5*c) return ha, hb, hc while True: x = (input("Nhập 3 số a, b ,c : ").split()) a = int(x[0]) b = int(x[1]) c = int(x[2]) if ((a + b <= c) or (a + c <= b) or (b + c <= a)): print("Oops, xin hãy nhập lại") continue break print(calculateArea(a, b, c))
import sys from math import sin, cos, sqrt, atan2, radians def Distance(lat1, lon1, lat2, lon2): R = 6371.0 lat1 = radians(lat1) lon1 = radians(lon1) lat2 = radians(lat2) lon2 = radians(lon2) dlon = lon2 - lon1 dlat = lat2 - lat1 a = abs(sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2) c = 2 * atan2(sqrt(a), sqrt(1-a)) return(R*c) def pathToStrng(graph, path): pred = len(path)-1 answer = "" while pred != 0: city = graph[pred][2] pred = path[pred] answer = city + ", "+ answer answer = graph[0][2] + ", " + answer return(answer.rstrip(", ")) def Dijkstra(matrix, length, DicGraph): priorityQ = [] path = [0]*length colour = ["WHITE"]*length dist = [0]*length colour[0] = "GREY" priorityQ.append([0,0]) while priorityQ != []: priorityQ.sort(key = lambda x: x[1]) t1 = priorityQ[0][1] #value to city u = priorityQ[0][0] #pointer to city priorityQ.pop(0) for x in range(0, length): t2 = t1 + matrix[u][x] if colour[x] == "WHITE": colour[x] = "GREY" path[x] = u priorityQ.append([x, t2]) elif colour[x] == "GREY": for item in priorityQ: # need to make this more efficient "edit: added break" if item[0] == x: if item[1] > t2: item[1] = t2 path[x] = u break colour[u] = "BLACK" dist[u] = t1 if dist[-1] == float('inf'): return("Not possible") else: return(pathToStrng(DicGraph, path)) def AdjacencyMatrix(length, gass, DicGraph): adjMatrix = [] for m in range(0, length): adjMatrix.append([0]*length) # populate the matrix for y in range(0, length): lat1 = DicGraph[y][0] lng1 = DicGraph[y][1] for x in range(0, length): lat2 = DicGraph[x][0] lng2 = DicGraph[x][1] if adjMatrix[y][x] == 0: dist = (float(Distance(lat1, lng1, lat2, lng2))) if dist == 0 or dist > gass: adjMatrix[y][x] = float('inf') adjMatrix[x][y] = float('inf') else: adjMatrix[y][x] = dist adjMatrix[x][y] = dist return adjMatrix def createDic(): DicGraph = {} for x in range(cities): line = sys.stdin.readline().split() tempName = line[2:] name = "" for i in tempName: name = name + i + " " arr = [float(line[0]), float(line[1]), name.rstrip()] DicGraph.update({x: arr}) return(DicGraph) cases = int(sys.stdin.readline()) #number of tests case_index = 0 while case_index != cases: cities = int(sys.stdin.readline()) #number of cities DicGraph = createDic() gass = float(sys.stdin.readline()) adjMatrix = AdjacencyMatrix(cities, gass, DicGraph) distance = Dijkstra(adjMatrix, cities, DicGraph) print(distance) #send it off to shortest path algorithm case_index += 1
import sys for row_column in sys.stdin: row, column = row_column.split() row = int(row) column = int(column) element = [[None]*column for i in range(row)] answer = [[None]*row for i in range(column)] # print(element) for row_number in range(0, row): element[row_number] = sys.stdin.readline().split() # print(element) for j in range(0, row): for k in range(0, column): answer[k][j] = element[j][k] # print(element[j][k]) for l in range(0, column): for m in range(0, row): print(answer[l][m], end=" ") print("") print("")
#!/usr/bin/env python # coding: utf-8 # <H1>WATER JUG PROBLEM USING BFS & DFS<H1> # Given Problem: You are given a m liter jug and a n liter jug where $0 < m < n$. Both the jugs are initially empty. The jugs don't have markings to allow measuring smaller quantities. You have to use the jugs to measure $d$ liters of water where $d < n$. Determine the minimum no of operations to be performed to obtain $d$ liters of water in one of jug. # <b>States:</b> Amount of water in each respective jug, where the states are represented by [S(J1), S(J2)] and S(J1) is the amount in the first jug and S(J2) is the amount in the second jug # # <b>Capacity of Jug1 (J1):</b> 3 litres # # <b>Capacity of Jug1 (J2):</b> 4 litres # # <b>Initial State:</b> [0,0] # # <b>Goal state:</b> The user give the input the amount of water required in the jug (J2) i.e. [2,y] or [2,0] # # These are the initial operators used: # # <b>Operators:</b> # 1. Fill the first jug # 2. Fill the second jug # 3. Empty the first jug # 4. Empty the second jug # 5. Pour the first jug into the second jug # 6. Pour the second jug into the second jug # # <b>Branching Factor:</b> 6 (because we have 6 operators) # In[1]: import collections # In[2]: #This method return a key value for a given node. #Node is a list of two integers representing current state of the jugs def get_index(node): return pow(7, node[0]) * pow(5, node[1]) # In[3]: #This method accepts an input for asking the choice for type of searching required i.e. BFS or DFS. #Method return True for BFS, False otherwise def get_search_type(): s = input("Enter 'b' for BFS, 'd' for DFS: ") s = s[0].lower() while s != 'd' and s != 'b': s = input("The input is not valid! Enter 'b' for BFS, 'd' for DFS: ") s = s[0].lower() return s == 'd' # In[4]: #This method accept volumes of the jugs as an input from the user. #Returns a list of two integeres representing volumes of the jugs. def get_jugs(): print("Receiving the volume of the jugs...") jugs = [] temp = int(input("Enter first jug volume (>1): ")) while temp < 1: temp = int(input("Enter a valid amount (>1): ")) jugs.append(temp) temp = int(input("Enter second jug volume (>1): ")) while temp < 1: temp = int(input("Enter a valid amount (>1): ")) jugs.append(temp) return jugs # In[5]: #This method accepts the desired amount of water as an input from the user whereas #the parameter jugs is a list of two integers representing volumes of the jugs #Returns the desired amount of water as goal def get_goal(jugs): print("Receiving the desired amount of the water...") max_amount = max(jugs[0], jugs[1]) s = "Enter the desired amount of water (1 - {0}): ".format(max_amount) goal_amount = int(input(s)) while goal_amount < 1 or goal_amount > max_amount: goal_amount = int(input("Enter a valid amount (1 - {0}): ".format(max_amount))) return goal_amount # In[6]: #This method checks whether the given path matches the goal node. #The path parameter is a list of nodes representing the path to be checked #The goal_amount parameter is an integer representing the desired amount of water def is_goal(path, goal_amount): print("Checking if the gaol is achieved...") return path[-1][0] == goal_amount or path[-1][1] == goal_amount # In[7]: #This method validates whether the given node is already visited. #The parameter node is a list of two integers representing current state of the jugs #The parameter check_dict is a dictionary storing visited nodes def been_there(node, check_dict): print("Checking if {0} is visited before...".format(node)) return check_dict.get(get_index(node), False) # In[8]: #This method returns the list of all possible transitions #The parameter jugs is a list of two integers representing volumes of the jugs #The parameter path is a list of nodes represeting the current path #The parameter check_dict is a dictionary storing visited nodes def next_transitions(jugs, path, check_dict): print("Finding next transitions and checking for the loops...") result = [] next_nodes = [] node = [] a_max = jugs[0] b_max = jugs[1] a = path[-1][0] # initial amount in the first jug b = path[-1][1] # initial amount in the second jug # 1. fill in the first jug node.append(a_max) node.append(b) if not been_there(node, check_dict): next_nodes.append(node) node = [] # 2. fill in the second jug node.append(a) node.append(b_max) if not been_there(node, check_dict): next_nodes.append(node) node = [] # 3. second jug to first jug node.append(min(a_max, a + b)) node.append(b - (node[0] - a)) # b - ( a' - a) if not been_there(node, check_dict): next_nodes.append(node) node = [] # 4. first jug to second jug node.append(min(a + b, b_max)) node.insert(0, a - (node[0] - b)) if not been_there(node, check_dict): next_nodes.append(node) node = [] # 5. empty first jug node.append(0) node.append(b) if not been_there(node, check_dict): next_nodes.append(node) node = [] # 6. empty second jug node.append(a) node.append(0) if not been_there(node, check_dict): next_nodes.append(node) # create a list of next paths for i in range(0, len(next_nodes)): temp = list(path) temp.append(next_nodes[i]) result.append(temp) if len(next_nodes) == 0: print("No more unvisited nodes...\nBacktracking...") else: print("Possible transitions: ") for nnode in next_nodes: print(nnode) return result # In[9]: # This method returns a string explaining the transition from old state/node to new state/node # The parameter old is a list representing old state/node # The parameter new is a list representing new state/node # The parameter jugs is a list of two integers representing volumes of the jugs def transition(old, new, jugs): a = old[0] b = old[1] a_prime = new[0] b_prime = new[1] a_max = jugs[0] b_max = jugs[1] if a > a_prime: if b == b_prime: return "Clear {0}-liter jug:\t\t\t".format(a_max) else: return "Pour {0}-liter jug into {1}-liter jug:\t".format(a_max, b_max) else: if b > b_prime: if a == a_prime: return "Clear {0}-liter jug:\t\t\t".format(b_max) else: return "Pour {0}-liter jug into {1}-liter jug:\t".format(b_max, a_max) else: if a == a_prime: return "Fill {0}-liter jug:\t\t\t".format(b_max) else: return "Fill {0}-liter jug:\t\t\t".format(a_max) # In[10]: #This method prints the goal path #The path is a list of nodes representing the goal path #The jugs is a list of two integers representing volumes of the jugs def print_path(path, jugs): print("Starting from:\t\t\t\t", path[0]) for i in range(0, len(path) - 1): print(i+1,":", transition(path[i], path[i+1], jugs), path[i+1]) # In[11]: #This method searches for a path between starting node and goal node # The parameter starting_node is a list of list of two integers representing initial state of the jugs #The parameter jugs a list of two integers representing volumes of the jugs #The parameter goal_amount is an integer represting the desired amount #The parameter check_dict is a dictionary storing visited nodes #The parameter is_breadth is implements BFS, if True; DFS otherwise def search(starting_node, jugs, goal_amount, check_dict, is_breadth): if is_breadth: print("Implementing DFS...") else: print("Implementing BFS...") goal = [] accomplished = False q = collections.deque() q.appendleft(starting_node) while len(q) != 0: path = q.popleft() check_dict[get_index(path[-1])] = True if len(path) >= 2: print(transition(path[-2], path[-1], jugs), path[-1]) if is_goal(path, goal_amount): accomplished = True goal = path break next_moves = next_transitions(jugs, path, check_dict) for i in next_moves: if is_breadth: q.append(i) else: q.appendleft(i) if accomplished: print("The goal is achieved\nPrinting the sequence of the moves...\n") print_path(goal, jugs) else: print("Problem cannot be solved.") # In[12]: if __name__ == '__main__': starting_node = [[0, 0]] jugs = get_jugs() goal_amount = get_goal(jugs) check_dict = {} is_breadth = get_search_type() search(starting_node, jugs, goal_amount, check_dict, is_breadth)
### neural network model for predicting handwritten digits ### using MNIST datasets ### tutorials from tensorflow.org # load the datasets from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('../data/', one_hot=True) # import tensorflow library import tensorflow as tf # graph input definition # the placeholder for images, the 784-dimensional vector X = tf.placeholder(tf.float32, [None, 784]) # variables definition # for weights W and biases b W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) # define the model using softmax y = tf.nn.softmax(tf.matmul(X, W) + b) # implement the cross-entropy y_ = tf.placeholder(tf.float32, [None, 10]) # for the labels cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=y) # gradient descent learning_rate = 0.5 train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) # get the session sess = tf.InteractiveSession() # initialize the variables tf.global_variables_initializer().run() # train the neural network model # but, instead one epoch for all training sets # we do one epoch for a mini-batch training_epochs = 1000 batch_size = 100 for i in range(training_epochs): batch_xs, batch_ys = mnist.train.next_batch(batch_size) sess.run(train_step, feed_dict={X: batch_xs, y_: batch_ys}) # evaluate the model correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print('The accuracy:', sess.run(accuracy, feed_dict={X:mnist.test.images, y_:mnist.test.labels}))
""" This module contains helper functions for text processing """ import sys import re def preprocess_human(text): """ Adds new lines before all headers in order to make the text more readable """ text = re.sub('\n', '', text) # Get rid of the old new lines that I'd put in header_patterns = [r'Review of Systems:', r'Physical Exam(ination)?:', r'(Patient )?(Active )?Problem List', r'Risks and benefits:', r'Time out:', r'Chief Complaint:', r'Marital Status:', 'Attending Physician:', 'Events of last 24 hours:', 'Current Medications:', 'Years of Education:', 'Current Unit:', 'Cardio Rate:', 'Assessment (and|&) Plan:', 'Plan:','Patient Instructions:', 'Patient Education:', 'General:', ] default_header = r'([\s]{2,}([a-z ]*){1,2}:)' # Simple default header pattern that will grab words followed by colons header_patterns.append(default_header) #header = re.compile(default_header, flags=re.IGNORECASE) header = re.compile('({})'.format('|'.join(header_patterns)), flags=re.IGNORECASE) # Put a period and two lines before every header text = header.sub(r'.\n\n\1', text) #list_element = re.compile(r'(-[(),a-z/\s]*\?:\s+(yes|no|unsure))', flags=re.IGNORECASE) list_element = re.compile(r'(-[^-?:]*\?:\s+(yes|no|unsure))', flags=re.IGNORECASE) # Put a period and a new line before every list element text = list_element.sub(r'.\n\1', text) return text def find_headers_and_lists(text): """ Finds headers and lists in the text and returns starting points for each of them. This allows us to properly split sentences before headers and bullet-point lists. """ header_and_list_points = [] header = re.compile(r'[\s]{2,}([a-z ]*){1,2}:', flags=re.IGNORECASE) header_points = list(header.finditer(text)) header_and_list_points.extend(header_points) list_elements = re.compile(r'-[a-z\s]*\?:\s+(yes|no)', flags=re.IGNORECASE) list_points = list(list_elements.finditer(text)) header_and_list_points.extend(list_points) return header_and_list_points if __name__ == '__main__': infile = sys.argv[1] string = open(infile).read() #print(find_headers_and_lists(string)) #string = "Review of Systems: this. Chief complaint: that. Problem List: -Pneumonia. Physical Exam: okay. Physical Examination: that, that." #print(string) preprocessed = preprocess_human(string) print('Preprocessed:') print(preprocessed) exit() string = " Impression: We examined the patient yesterday. He shows signs of pneumonia.\ The wound is CDI. He has not developed a urinary tract infection\ However, there is a wound infection near the abdomen. There is no surgical site infection. There is an abscess Surgical Sites: There is a surgical site infection. Signed, Dr.Doctor MD."
#Nand gate class Gate(object): """ class representing a gate. It can be any gate. """ def __init__(self, *args): """ initialise the class """ self.input = args self.output = None def logic(self): """ the intelligence to be performed """ raise NotImplementedError def output(self): """ the output of the gate """ self.logic() return self.output class AndGate(Gate): """ class representing AND gate """ def logic(self): self.output = self.input[0] and self.input[1] return self.output class OrGate(Gate): """ class representing OR gate """ def logic(self): self.output = self.input[0] and self.input[1] return self.output class NotGate(Gate): """ class representing NOT gate """ def logic(self): self.output = not self.input[0] return self.output class NandGate(AndGate,NotGate): #class representing Nand Gate def logic(self): self.temp = AndGate.logic(self) Gate.__init__(self,self.temp) self.output = NotGate.logic(self) return self.output n = NandGate(1,1).logic() print(int(n))
phone = input('Phone: ') numbers = { #defining dictionary '1': 'one', #dont forget the commas at the end '2': 'two', '3': 'three', '4': 'four', '5': 'five', } phone_number = '' for x in phone: numbers.get(x) phone_number = phone_number + ' ' + numbers.get(x, '!!') # added '!' value not to have 'NONE error' print(phone_number)
my_name = 'Python' #문자열 (사람을 위한 텍스트를 프로그래머가 부르는 방법) my_age = 2019 - 1994 #숫자 print(my_name, '응 어제', my_age, '살') my_next_age = my_age + 1 print('내년에는', my_next_age, '살') multiply = 9 * 9 # = 81 divide = 30 / 5 # = 6 power = 2 ** 10 # = 1024 reminder = 15 % 4 # = 3 print(multiply, divide, power, reminder) text = '2015' + '1999' number = 2015 + 1999 print(text, number)
# Get Starbucks from cities ''' This file retrieves latitude/longitude pairs for all Starbucks in each of the cities available in the data, and saves to a csv. This data is used to construct the "Starbucks index" of average minimum distance necessary to find another Starbucks in each city. Usage: Call get_all_starbucks with either the default parameters or custom locations. Note that ingest_data.py must be in the same folder (or the import path must be changed) This is cutting edge technology for caffeine addicts everywhere ''' # Retrieve necessary imports from aggregate_city_data import find_all_cities import glob from yelp.api.v3 import Yelp import pandas as pd import numpy as np import csv # Load Yelp Credentials. Details explained in find_yelp_data.py app_id = '######################' app_secret = '################################################################' yelp = Yelp( app_id, app_secret, ) def get_all_starbucks(filepath = '*.csv', filename = "starbucks_locations.csv"): ''' Create a csv of all the lat/long pairs for all Starbucks in each city Inputs: - filepath: The folder to search for city data files - filename: The name of the csv to hold Starbucks data Returns: - df: A pandas dataframe (a csv is also saved) ''' # Construct a list of all cities used for the data city_list = find_all_cities(filepath) # Construct a blank list info_list = [] for city in city_list: # Find total number of Starbucks in a city return_dict = yelp.search(term = "Starbucks", location = city, limit = 50) # Chunk results, as described in find_yelp_data.py chunk_count = (return_dict["total"] // 50) + 1 if chunk_count > 19: chunk_count = 19 # Creates necessary sub-searches for i in range(chunk_count): return_dict = yelp.search(term = "Starbucks", location = city, limit = 50, offset = 50 * i) info_list = append_location_info(city, return_dict, info_list) # Convert to pandas dataframe headers = (["City", "Latitude", "Longitude", "Review Count"]) df = pd.DataFrame(info_list, columns = headers) # Use "Review Count" to check for duplicates, then drop the column # Lat/Long tuples alone cannot be used for duplciate checking, because some # Starbucks repeat lat/long pairs (i.e, they are in the same building) df_unique = df.drop_duplicates() del df_unique["Review Count"] # Save to csv df_unique.to_csv(filename) return df_unique def append_location_info(city, return_dict, info_list): ''' Use results from a search to retrieve latitude and longitude information for Starbucks returned by the search. Inputs: - city: The city being searched (used for labelling the eventual csv) - return_dict: The dictionary returned by the Yelp API call - info_list: The list to add location tuples to Returns: - info_list: An updated list of Starbucks locations ''' for i in range(len(return_dict["businesses"])): # Create holding list info_holding = [city] # Check for latitude and longitude if return_dict["businesses"][i]["coordinates"]["longitude"] != "": info_holding.append(return_dict["businesses"][i]["coordinates"]["latitude"]) info_holding.append(return_dict["businesses"][i]["coordinates"]["longitude"]) # Review Count is used to check for duplicates info_holding.append(return_dict["businesses"][i]["review_count"]) info_list.append(info_holding) # Update on progress print('Finished {} Starbucks'.format(len(info_list))) return info_list
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 27 09:53:12 2017 @author: pesu """ ''' Python program that outputs a list of n-grams represented as string and a dictionary containing n-gram and its count as key-value pairs. ''' from nltk import word_tokenize file_content = open("in1.txt").read() wordlist = word_tokenize(file_content) print('\nTokens List:\n') print(wordlist) def getNGrams(input_list, n): print('\n',n,'_Grams:\n') return [input_list[i:i+n] for i in range(len(input_list)-(n-1))] list =getNGrams(wordlist, 1) di=dict() for i in list: d="" for j in i: d=d + j + " " print(d) if(d in di): di[d]=di[d]+1 else: di[d]=1 print(di)
# Programming Exercise 15 # 15 Find a sudoku puzzle. Write a program to solve it. class Block: def __init__(self, data): self.block = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] def getPos(self, num): return self.block[num] class Board: def __init__(self): self.BL1 = Block(block_1) self.BL2 = Block(block_2) self.BL3 = Block(block_3) self.BL4 = Block(block_4) self.BL5 = Block(block_5) self.BL6 = Block(block_6) self.BL7 = Block(block_7) self.BL8 = Block(block_8) self.BL9 = Block(block_9) self.board = [ [self.BL1, self.BL2, self.BL3], [self.BL4, self.BL5, self.BL6], [self.BL7, self.BL8, self.BL9] ] def __str__(self): space = " " row1 = f' {self.BL1.getPos(0)} {self.BL2.getPos(0)} {self.BL3.getPos(0)}' row2 = f' {self.BL1.getPos(1)} {self.BL2.getPos(1)} {self.BL3.getPos(1)}' row3 = f' {self.BL1.getPos(2)} {self.BL2.getPos(2)} {self.BL3.getPos(2)}' row4 = f' {self.BL4.getPos(0)} {self.BL5.getPos(0)} {self.BL6.getPos(0)}' row5 = f' {self.BL4.getPos(1)} {self.BL5.getPos(1)} {self.BL6.getPos(1)}' row6= f' {self.BL4.getPos(2)} {self.BL5.getPos(2)} {self.BL6.getPos(2)}' row7 = f' {self.BL7.getPos(0)} {self.BL8.getPos(0)} {self.BL9.getPos(0)}' row8 = f' {self.BL7.getPos(1)} {self.BL8.getPos(1)} {self.BL9.getPos(1)}' row9 = f' {self.BL7.getPos(2)} {self.BL8.getPos(2)} {self.BL9.getPos(2)}' return f'{row1}\n{row2}\n{row3}\n{space}\n{row4}\n{row5}\n{row6}\n{space}\n{row7}\n{row8}\n{row9}' b = Board() print(b)
import Rental import Movie class Customer: def __init__(self, name): self.Name = name self.Rentals = [] def addRental(self, arg): self.Rentals.append(arg) def getName(self): return self.Name def statement(self): totalAmount = 0 frequentRenterPoints = 0 result = "Rental Record for " + self.getName() + "\n" for each in self.Rentals: thisAmount = 0 # determine amounts for each line if each.Movie.PriceCode == Movie.REGULAR: thisAmount += 2 if (each.DaysRented > 2): thisAmount += (each.DaysRented - 2) * 1.5 elif each.Movie.PriceCode == Movie.NEW_RELEASE: thisAmount += each.DaysRented * 3 elif each.Movie.PriceCode == Movie.CHILDRENS: thisAmount += 1.5 if (each.DaysRented > 3): thisAmount += (each.DaysRented - 3) * 1.5 # add frequent renter points frequentRenterPoints += 1 # add bonus for a two day new release rental if ((each.Movie.PriceCode == Movie.NEW_RELEASE) and each.DaysRented > 1): frequentRenterPoints += 1 # show figures for this rental result += "\t" + each.Movie.Title + "\t" + thisAmount.ToString() + "\n" totalAmount += thisAmount # add footer lines result += "Amount owed is " + str(totalAmount) + "\n" result += "You earned " + str(frequentRenterPoints) + " frequent renter points" return result
#!/usr/bin/env python3 """ Author: Wing Yu Chung Given: A positive integer n≤7. Return: The total number of permutations of length n, followed by a list of all such permutations (in any order). """ #Import statements from sys import argv from itertools import permutations def read_file(filetxt): """ read file.txt and turns it into an integer Input: fasta file with permutation number Output: permutation integer """ with open(filetxt, 'r') as text: dataset = text.read() dataset = dataset.strip() return int(dataset) def permutation_list(integer): """ Create permutation list from integer input is integer output is print of number of permutations and combinations """ perm_list = list(permutations(range(1,integer+1))) print(len(perm_list)) for tuple in perm_list: for perm in tuple: print(perm, end=' ') print('') return perm_list if __name__ == "__main__": dataset = read_file(argv[1]) perm_list = permutation_list(dataset)
#!/usr/bin/env python3 """ Author: Wing Yu Chung Given: A DNA string s (of length at most 1 kbp) and a collection of substrings of s acting as introns. All strings are given in FASTA format. Return: A protein string resulting from transcribing and translating the exons of s. (Note: Only one solution will exist for the dataset provided.) """ # Import statements from sys import argv import re #FUNCTIONS def read_dataset(filetxt): """ Turns dataset into string object Input: txt file with string Output: string of data from txt file. """ text = open(filetxt, 'r') dataset = text.read() dataset = dataset.strip() text.close() return dataset def split_dataset(dataset): """ split dataset into dictionary dataset: string separates by enters """ fasta_dict = {} dataset = dataset.split() for line in dataset: if line.startswith('>'): fasta_dict[line[1:]] = '' current_line = line[1:] else: fasta_dict[current_line] += line return fasta_dict def transcribe(sequence): """ Change DNA string into RNA string by replacing T with U Input sequence: DNA sequence string Ouput: RNA sequence string """ transcription = sequence.replace('T','U') return transcription def find_index_match(substring, main_string): """" return indice of substring in mainstring yield integer of index substring in main string """ motif = re.compile(substring) match_motif = re.finditer(motif, main_string) for intron in match_motif: yield intron.start() def extract_sequences(fasta_dict): """ extract sequence into main sequence and introns Input: dictionary with sequences Output: exon """ fasta_list = [] for fasta_id, sequence in fasta_dict.items(): fasta_list.append(sequence) exon = fasta_list[0] introns = fasta_list[1:] intron_dict = {} for intron in introns: if intron in exon: #dont forget to check for duplicates and overlap for match in find_index_match(intron, exon): intron_dict[match] = len(intron) for key,value in sorted(intron_dict.items(), reverse=True): exon = exon[:key] + exon[key+value:] exon = transcribe(exon) return exon def translate(exon): """ Translate codons into amino acids Input: List with codons Output: string of amino acids Return the translated protein sequence of codons in list. """ amino_acids = '' codon = 0 while codon < len(exon): if exon[codon:codon+3] in AMINO_ACID_DICT.keys(): amino_acids += AMINO_ACID_DICT[exon[codon:codon+3]] codon += 3 print(amino_acids) return amino_acids if __name__ == "__main__": sequences = read_dataset(argv[1]) sequences = split_dataset(sequences) exon = extract_sequences(sequences) translate(exon)
''' #Bài 1 name = input("Nhap vao ho va ten: ") print("Ten cua ban la: " + name[0:]) print("In nguoc ten cua ban: " + name[::-1]) print("-----------------------------------------") #Bài 2 long = input("Nhập vào tên của Long :") tuyen = input("Nhập vào tên của Tuyến :") if len(long) < len(tuyen): print(tuyen +" là best ok!") print("-----------------------------------------") #Bài 3 chuoi = input("Nhập vào dãy số( cách nhau bởi dấu phẩy) :") list = chuoi.split(','); sum =0 for i in list: sum = sum + int(i) print("Tổng s = ", sum) print("-----------------------------------------") ''' #Bài 4 my_str = input("Nhập vào chuỗi của bạn :") print("Chuỗi của bạn sau khi in hoa: " + my_str.upper())
import sys import random def generate_markov(input): out = dict() for line in input: line = line.lower() words = line.replace("\n", "").split(" ") for i in range(len(words)-2): key = words[i]+" "+words[i+1] val = words[i+2] if key in out.keys(): out[key].append(val) else: out[key] = [val] return out def produce_sentence(mc): string = list() pair = random.choice(list(mc.keys())) val = random.choice(mc[pair]) string.extend(pair.split(" ")) while(True): string.append(val) pair = (string[-2])+" "+(string[-1]) if pair in mc.keys(): val = random.choice(mc[pair]) else: break sentence = " ".join(string) if not (sentence.endswith(".") or sentence.endswith("?") or sentence.endswith("!")): sentence += "." if sentence.endswith(","): sentence[-1] = "." return sentence.replace(" ,", ",").replace(" !", "!").replace(" ?", "?") def main(): mc = generate_markov(open("database.db", "r")) for i in range(0, int(sys.argv[1])): print(produce_sentence(mc)) if __name__ == "__main__": main()
def preOrder(root): preorder_list = [] # VISIT NODE THEN LEFT THEN RIGHT def traverse(node): preorder_list.append(node.info) if node.left is not None: traverse(node.left) if node.right is not None: traverse(node.right) traverse(root) for num in preorder_list: print(num, end=' ')
def cube(x): return x ** 3 def fibonacci(n): list = [] for i in range(0, n): if i == 0: list.append(0) elif i == 1: list.append(1) else: list.append(list[i-1] + list[i-2]) return list if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
import math class Points(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __sub__(self, O): x = self.x - O.x y = self.y - O.y z = self.z - O.z return Points(x, y, z) def dot(self, O): x = self.x * O.x y = self.y * O.y z = self.z * O.z return x + y + z def cross(self, O): x = self.y * O.z - self.z * O.y y = self.z * O.x - self.x * O.z z = self.x * O.y - self.y * O.x return Points(x, y, z) def absolute(self): return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), .5) if __name__ == '__main__':