text
stringlengths
37
1.41M
#NAME:KYOMUHENDO ESTHER DIANA #REGISTRATION NUMBER:16/U/516 #STUDENT NUMBER:216000728 #COMPUTER YEAR ONE import calendar #imports the calendar module from the python modules from datetime import datetime now = datetime.now()#gets the current date and time age = int(input("Enter your age: ")) year = int(input('Enter year:')) month = int(input("Enter the month: ")) day = int(input("Enter the day of the month: ")) cal = calendar.weekday(year,month,day)#calculates the day of the week days = {0:'Monday',1:'Tuesday',2:'Wednesday',3:'Thursday',4:'Friday',5:'Saturday',6:'Sunday'} print('You were born on',days[cal])#final statement that prints the day of week
import sqlite3 connection = sqlite3.connect("db.sqlite3") cursor = connection.cursor() class Car: def __init__(self, mark, model, volume, year, color, id): self.id = id self.mark = mark self.model = model self.volume = volume self.year = year self.color = color def save(self): cursor.execute(f"INSERT INTO cars values (?, ?, ?, ?, ?)", (self.mark, self.model, self.volume, self.year, self.color)) connection.commit() def link(self, cls): pass class Retailer: def __init__(self, name, address, id): self.name = name self.address = address self.id = id def save(self): try: cursor.execute(f"INSERT INTO retailers values (?, ?, ?)", (self.name, self.address, self.id)) connection.commit() except Exception: # CREATE TABLE cursor.execute("") cursor.execute(f"INSERT INTO retailers values (?, ?, ?)", (self.name, self.address, self.id)) connection.commit() car = Car("Ford", "Mondeo", 1.8, 2003, 'gold', 1) car.save() car2 = Car("Honda", "Bit", 0.5, 2009, 'white', 2) car2.save() r = Retailer("Honda Center", "Bishkek", 1) car.link(r)
# There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. # You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point. # Example 1: # Input: gain = [-5,1,5,0,-7] # Output: 1 # Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. # Example 2: # Input: gain = [-4,-3,-2,-1,4,3,2] # Output: 0 # Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. g = [-4, -3, -2, -1, 4, 3, 2] t = 0 m = [] for x in g: t += x m.append(t) max_alt = max(m) if max_alt < 0: max_alt = 0
real_egoing = "11" real_k8805 = "ab" in_str = input("아이디를 입력해주세요.\n") print(type(in_str)) if in_str == real_egoing: print("Hello! "+ "egoing") elif in_str == real_k8805: print("Hello! "+ "k8805") else: print("who are you")
def re_sequence(seq): """(str)->str replace T to A, A to T, G to C and C to G""" seq = seq.lower() seq = seq.replace('a','T') seq = seq.replace('t','A') seq = seq.replace('g','C') seq = seq.replace('c','G') return seq print(re_sequence('AATTGCCGT'))
from random import shuffle # Wrapper class to add asSymbol method for strings class String(str): def asSymbol(self): return self class Direction(object): left = 0 up = 1 right = 2 down = 3 @staticmethod def opposite(position): base = int('11', 2) oppositeDir = (position + 2) & base #print "oppositeDir: " + str(oppositeDir) return oppositeDir class BoardSpace(object): #length = 0 #width = 0 #connectedTo = [None, None, None, None] def __init__(self, length, width, name, position): #self.boardPosition = [0,0] self.length = length self.width = width self.name = name self.position = position self.connectedTo = [None, None, None, None] #[left, up, right, down] self.boardObjects = [] #print "in boardspace" def addConnection(self, position, connection): self.connectedTo[position] = connection connection.connectedTo[Direction.opposite(position)] = self def asSymbol(self): return "x" def addBoardObject(self, boardObject): self.boardObjects.append(boardObject) def delBoardObject(self, boardObject): self.boardObjects.remove(boardObject) class Room(BoardSpace): #length = 3 #width = 3 #connectedTo = [None, None, None, None] def __init__(self, name, position): #connections is an array #print "in Room" super(Room,self).__init__(3,3,name,position) #print "Room length: " + str(self.length) def initializeMatrix(self): self.matrix = [[ self for x in range(self.width)] for y in range(self.length) ] # def print(self): # for i in range(self.length): # for j in range(self.width): # print "+" class Hallway(BoardSpace): def __init__(self, name, position): #connections is an array #print "in Hallway" super(Hallway,self).__init__(1,1,name,position) def initializeMatrix(self): self.matrix = [[String(' ')]] if self.connectedTo[Direction.right] == None: self.matrix[0] += [self] + [String(' ')] elif self.connectedTo[Direction.up] == None: self.matrix += [[self]] + [[String(' ')]] #return returnMatrix # def print(self): # for connection in connectedTo: # if connection == None: # print " " class BoardObject(object): def __init__(self, name, symbol, position=None): self.name = name self.symbol = symbol self.position = position def setPosition(self, position): self.position = position def asSymbol(self): return self.symbol def getName(self): return self.name class Character(BoardObject): pass class Weapon(BoardObject): pass class GameBoard(object): # def __init__(self): # self.sideLength = 11 # self.board = [[ ' ' for x in range(self.sideLength)] for y in range(self.sideLength) ] # self.testB01 = [[ 'x' for x in range(3)] for y in range(3) ] # self.testB02 = [[ 'y' for x in range(3)] for y in range(1) ] # self.testA = self.testB01 + self.testB02 # print "in gameboard" # print self.testB02 # print self.testA # self.printBoard(self.testA) # def test(self): # for row in self.board: # for item in row: # print item def printBoard(self): return '\n'.join([''.join(['{:2}'.format(item.asSymbol()) for item in row]) for row in self.board]) def concatenateMatrices(self, *matrices): # rowNum = 0 # while rowNum < len(attachment): # try: # self.board[rowNum] += attachment[rowNum] # except IndexError: # self.board += attachment[rowNum:] returnMatrix = [[] for i in range(len(matrices[0]))] for matrix in matrices: for rowNum in range(len(matrix)): returnMatrix[rowNum] += matrix[rowNum] return returnMatrix def initialize(self): mustard = Character("Colonel Mustard", "M") scarlet = Character("Miss Scarlet", "S") plum = Character("Professor Plum", "P") green = Character("Mr. Green", "G") white = Character("Mrs. White", "W") peacock = Character("Mrs. Peacock", "B") self.characters = [mustard, scarlet, plum, green, white, peacock] rope = Weapon("Rope", "R") pipe = Weapon("Lead Pipe", "L") knife = Weapon("knife", "K") wrench = Weapon("Wrench", "H") candlestick = Weapon("Candlestick", "C") revolver = Weapon("Revolver", "R") self.weapons = [rope, pipe, knife, wrench, candlestick, revolver] study = Room("Study",[1,1]) hall = Room("Hall",[1,5]) library = Room("Library",[5,1]) lounge = Room("Lounge",[1,9]) billiardRoom = Room("Billiard Room",[5,5]) diningRoom = Room("Dining Room",[5,9]) conservatory = Room("Conservatory",[9,1]) ballRoom = Room("Ball Room",[9,5]) kitchen = Room("Kitchen",[9,9]) self.rooms = [study, hall, library, lounge, billiardRoom, diningRoom, conservatory, ballRoom, kitchen] hallway1 = Hallway("Hallway1",[1,3]) hallway2 = Hallway("Hallway2",[1,7]) hallway3 = Hallway("Hallway3",[3,1]) hallway4 = Hallway("Hallway4",[3,5]) hallway5 = Hallway("Hallway5",[3,9]) hallway6 = Hallway("Hallway6",[5,3]) hallway7 = Hallway("Hallway7",[5,7]) hallway8 = Hallway("Hallway8",[7,1]) hallway9 = Hallway("Hallway9",[7,5]) hallway10 = Hallway("Hallway10",[7,9]) hallway11 = Hallway("Hallway11",[9,3]) hallway12 = Hallway("Hallway12",[9,7]) self.hallways = [hallway1, hallway2, hallway3, hallway4, hallway5, hallway6, hallway7, hallway8 , hallway9, hallway10, hallway11, hallway12] study.addConnection(Direction.right, hallway1) study.addConnection(Direction.down, hallway3) hall.addConnection(Direction.left, hallway1) hall.addConnection(Direction.right, hallway2) hall.addConnection(Direction.down, hallway4) lounge.addConnection(Direction.left, hallway2) lounge.addConnection(Direction.down, hallway5) library.addConnection(Direction.up, hallway3) library.addConnection(Direction.right, hallway6) library.addConnection(Direction.down, hallway8) billiardRoom.addConnection(Direction.left, hallway6) billiardRoom.addConnection(Direction.up, hallway4) billiardRoom.addConnection(Direction.right, hallway7) billiardRoom.addConnection(Direction.down,hallway9) diningRoom.addConnection(Direction.up, hallway5) diningRoom.addConnection(Direction.left, hallway7) diningRoom.addConnection(Direction.down, hallway10) conservatory.addConnection(Direction.up, hallway8) conservatory.addConnection(Direction.right, hallway11) ballRoom.addConnection(Direction.left, hallway11) ballRoom.addConnection(Direction.up, hallway9) ballRoom.addConnection(Direction.right, hallway12) kitchen.addConnection(Direction.left, hallway12) kitchen.addConnection(Direction.up, hallway10) for room in self.rooms: room.initializeMatrix() for hallway in self.hallways: hallway.initializeMatrix() self.board = self.concatenateMatrices(study.matrix, hallway1.matrix, hall.matrix, hallway2.matrix, lounge.matrix) + \ self.concatenateMatrices(hallway3.matrix, [[String(' ')]], hallway4.matrix, [[String(' ')]], hallway5.matrix) + \ self.concatenateMatrices(library.matrix, hallway6.matrix, billiardRoom.matrix, hallway7.matrix, diningRoom.matrix) + \ self.concatenateMatrices(hallway8.matrix, [[String(' ')]], hallway9.matrix, [[String(' ')]], hallway10.matrix) + \ self.concatenateMatrices(conservatory.matrix, hallway11.matrix, ballRoom.matrix, hallway12.matrix, kitchen.matrix) self.discardedObj = {} #self.board[0][2] = scarlet self.addBoardObject(mustard, [3,9]) self.addBoardObject(scarlet, [1,7]) self.addBoardObject(plum, [3,1]) self.addBoardObject(peacock, [7,1]) self.addBoardObject(green, [9,3]) self.addBoardObject(white, [9,7]) randomRooms = self.randomRooms() for WeaponIndex in range(len(self.weapons)): self.addBoardObject(self.weapons[WeaponIndex], randomRooms[WeaponIndex].position) def randomRooms(self): randomRooms = self.rooms shuffle(randomRooms) return randomRooms def addBoardObject(self, boardObject, position): positionString = str(position[0]) + "," + str(position[1]) originalObj = self.board[position[0]][position[1]] originalObj.addBoardObject(boardObject) self.discardedObj[positionString] = originalObj self.board[position[0]][position[1]] = boardObject boardObject.setPosition(position) def delBoardObject(self, boardObject): position = boardObject.position positionString = str(position[0]) + "," + str(position[1]) originalObj = self.discardedObj[positionString] originalObj.delBoardObject(boardObject) self.board[position[0]][position[1]] = originalObj del self.discardedObj[positionString] def moveBoardObject(self, boardObject,position): self.delBoardObject(boardObject) self.addBoardObject(boardObject,position) def translatePosition(self,position): if (position[0]==3 or position[0]==7): return [1,0] elif (position[0]>=4 and position[0]<=6): position[0]-=4 elif (position[0]>=8 and position[0]<=10): position[0]-=8 if (position[1]==3 or position[1]==7): return [0,1] elif (position[1]>=4 and position[1]<=6): position[1]-=4 elif (position[1]>=8 and position[1]<=10): position[1]-=8 return position if __name__ == '__main__': gameBoard = GameBoard() gameBoard.initialize() print(gameBoard.printBoard())
from twitter_stream import * def main(): count = input("Enter the number of tweets to fetch: ") ticker = input("Enter the ticker of the tweets to fetch: ") # converts count to int type, if conversion fails, sets count to default value of 1000 try: count = int(count) except ValueError: # default value count = 1000 # inserts cashtag $ symbol if not already there if ticker[0] != "$": ticker = "$" + ticker tweets = twitter_streaming(ticker, count) with open("testoutput_20160706.txt", "w") as fout: for tweet in tweets: print(tweet, file=fout) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Created on 21 Aug 2014 Functions and classes for convolutional and turbo codes. Author: Venkat Venkatesan """ import math import numpy as np def bitxor(num): ''' Returns the XOR of the bits in the binary representation of the nonnegative integer num. ''' count_of_ones = 0 while num > 0: count_of_ones += num & 1 num >>= 1 return count_of_ones % 2 def maxstar(eggs, spam, max_log=False): ''' Returns log(exp(eggs) + exp(spam)) if not max_log, and max(eggs, spam) otherwise. ''' return max(eggs, spam) + ( 0 if max_log else math.log(1 + math.exp(-abs(spam - eggs)))) def turbo_int_3gpp2(n_bits): ''' Computes 3GPP2 turbo interleaver and deinterleaver for specified packet size. Parameters ---------- n_bits : int Number of bits per packet. Must exceed 128 and not exceed 32768. Returns ------- turbo_int : list List of length n_bits with int elements, specifying the interleaver. turbo_deint : list List of length n_bits with int elements, specifying the deinterleaver. ''' # Look-up table int_table = ( (1, 1, 3, 5, 1, 5, 1, 5, 3, 5, 3, 5, 3, 5, 5, 1, 3, 5, 3, 5, 3, 5, 5, 5, 1, 5, 1, 5, 3, 5, 5, 3), (5, 15, 5, 15, 1, 9, 9, 15, 13, 15, 7, 11, 15, 3, 15, 5, 13, 15, 9, 3, 1, 3, 15, 1, 13, 1, 9, 15, 11, 3, 15, 5), (27, 3, 1, 15, 13, 17, 23, 13, 9, 3, 15, 3, 13, 1, 13, 29, 21, 19, 1, 3, 29, 17, 25, 29, 9, 13, 23, 13, 13, 1, 13, 13), (3, 27, 15, 13, 29, 5, 1, 31, 3, 9, 15, 31, 17, 5, 39, 1, 19, 27, 15, 13, 45, 5, 33, 15, 13, 9, 15, 31, 17, 5, 15, 33), (15, 127, 89, 1, 31, 15, 61, 47, 127, 17, 119, 15, 57, 123, 95, 5, 85, 17, 55, 57, 15, 41, 93, 87, 63, 15, 13, 15, 81, 57, 31, 69), (3, 1, 5, 83, 19, 179, 19, 99, 23, 1, 3, 13, 13, 3, 17, 1, 63, 131, 17, 131, 211, 173, 231, 171, 23, 147, 243, 213, 189, 51, 15, 67), (13, 335, 87, 15, 15, 1, 333, 11, 13, 1, 121, 155, 1, 175, 421, 5, 509, 215, 47, 425, 295, 229, 427, 83, 409, 387, 193, 57, 501, 313, 489, 391), (1, 349, 303, 721, 973, 703, 761, 327, 453, 95, 241, 187, 497, 909, 769, 349, 71, 557, 197, 499, 409, 259, 335, 253, 677, 717, 313, 757, 189, 15, 75, 163)) # Results of bit-reversing 0,1,...,31 bit_rev32 = ( 0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30, 1, 17, 9, 25, 5, 21, 13, 29, 3, 19, 11, 27, 7, 23, 15, 31) # Integer n such that 3 <= n <= 10 interleaver_param = math.ceil(math.log(n_bits) / math.log(2)) - 5 # Mask used to extract n LSBs of an integer ctr_mask = (1 << interleaver_param) - 1 # Generate interleaver and deinterleaver turbo_int = [-1 for n in range(n_bits)] turbo_deint = [-1 for n in range(n_bits)] in_addr = 0 for ctr in range(1 << (interleaver_param + 5)): msb, lsb = ctr >> 5, ctr & 31 new_val = (msb + 1) & ctr_mask lut_out = int_table[interleaver_param - 3][lsb] out_addr = ((bit_rev32[lsb] << interleaver_param) + ((new_val * lut_out) & ctr_mask)) if out_addr < n_bits: turbo_int[in_addr], turbo_deint[out_addr] = out_addr, in_addr in_addr += 1 return turbo_int, turbo_deint class Conv(object): ''' Encoder and decoder for a binary convolutional code of rate 1/N (1 input bit stream and N output bit streams). Attributes ---------- mem_len : int Number of bits in encoder state. state_space : tuple Encoder state space, taken as all integers in [0, 2 ** mem_len). n_out : int Number of encoder output bits per input bit. next_state_msb : tuple Tuple of length 2, with next_state_msb[b] being a tuple of length 2 ** mem_len, and next_state_msb[b][s] being the MSB of the next state when the current state is s and the input bit is b. out_bits : tuple Tuple of length 2, with out_bits[b] being a tuple of length 2 ** mem_len, and out_bits[b][s] being a tuple of length n_out representing the output bits when the current state is s and the input bit is b. next_state : tuple Tuple of length 2, with next_state[b] being a tuple of length 2 ** mem_len, and next_state[b][s] being the next state when the current state is s and the input bit is b. ''' INF = 1e6 def __init__(self, back_poly, fwd_polys): ''' Init method. Parameters ---------- back_poly : int For a code of constraint length L, back_poly must be in the range [2^(L-1), 2^L). fwd_polys : tuple For a code of constraint length L and rate 1/N, fwd_polys must be of length N, with int elements in the range [1, 2^L). Notes ----- The generator polynomials for the binary convolutional code are specified through back_poly (positive integer) and fwd_polys (tuple of positive integers). For a code of constraint length L and rate 1/N: (a) back_poly must be in the range [2^(L-1), 2^L); (b) fwd_polys must be of length N and its elements must be in the range [1, 2^L). Let b[0], b[1],..., b[L-1] be the binary representation of back_poly, with b[0] = 1 being the MSB. Similarly, let f[n][0], f[n][1],..., f[n][L-1] be the L-bit binary representation of fwd_polys[n], with f[n][0] being the MSB. The input-output relationship of the encoder can then be described as follows. Let x[k] be the input bit at time k to the encoder, and let y[n][k], n = 0,1,...,N-1, be the n^th output bit at time k from the encoder. Then, y[n][k] = sum_{i=0}^{L-1} f[n][i] * s[k-i], where the sequence of bits s[k] is given by s[k] = b[0] * x[k] + sum_{i=1}^{L-1} b[i] * s[k-i]. The encoder has 2^(L-1) states, with the state at time k being comprised of the bits s[k-1], s[k-2],..., s[k-L+1]. The output bits at time k are read out in the order y[0][k], y[1][k],..., y[N-1][k]. For the constituent recursive systematic convolutional (RSC) code in the 3GPP/3GPP2 turbo code, set back_poly = 11, and fwd_polys = (11, 13, 15). ''' # Number of bits in encoder state. self.mem_len = math.floor(math.log(back_poly) / math.log(2)) # Encoder state space (integers in the range [0, 2 ** mem_len)). self.state_space = tuple(n for n in range(1 << self.mem_len)) # Number of encoder output bits per input bit. self.n_out = len(fwd_polys) # MSB of next encoder state, given current state and input bit. self.next_state_msb = tuple(tuple( bitxor(back_poly & ((b << self.mem_len) + s)) for s in self.state_space) for b in (0, 1)) # Encoder output bits, given current state and input bit. self.out_bits = tuple(tuple(tuple( bitxor(p & ((self.next_state_msb[b][s] << self.mem_len) + s)) for p in fwd_polys) for s in self.state_space) for b in (0, 1)) # Next encoder state, given current state and input bit. self.next_state = tuple(tuple( (self.next_state_msb[b][s] << (self.mem_len - 1)) + (s >> 1) for s in self.state_space) for b in (0, 1)) return def encode(self, info_bits): ''' Encodes a given sequence of info bits (does not modify self). Parameters ---------- info_bits : ndarray of dtype int Array specifying the info bits (0 or 1) to be encoded. Returns ------- code_bits : ndarray of dtype int 1-dim array of size self.n_out * (info_bits.size + self.mem_len), giving the resulting code bits. Notes ----- The encoder begins in state 0, and is brought back to state 0 at the end with self.mem_len tail bits. ''' info_bits = np.asarray(info_bits).ravel() n_info_bits = info_bits.size code_bits, enc_state = -np.ones( self.n_out * (n_info_bits + self.mem_len), dtype=int), 0 for k in range(n_info_bits + self.mem_len): in_bit = (info_bits[k] if k < n_info_bits else self.next_state_msb[0][enc_state]) code_bits[self.n_out * k : self.n_out * (k + 1)] = ( self.out_bits[in_bit][enc_state]) enc_state = self.next_state[in_bit][enc_state] return code_bits def _branch_metrics(self, out_bit_llrs, pre_in_bit_llr=0): ''' Computes branch metrics (does not modify self). Parameters ---------- out_bit_llrs : tuple Tuple of length self.n_out with float elements, specifying the LLRs for the output bits. pre_in_bit_llr : float Prior LLR for the input bit. Returns ------- gamma_val : tuple Tuple of length 2, with gamma_val[b] being a list of length len(self.state_space) giving the branch metrics for the transitions out of all states when the input bit is b. ''' gamma_val = ([pre_in_bit_llr / 2 for s in self.state_space], [-pre_in_bit_llr / 2 for s in self.state_space]) for enc_state in self.state_space: for bit0, bit1, val in zip(self.out_bits[0][enc_state], self.out_bits[1][enc_state], out_bit_llrs): gamma_val[0][enc_state] += val / 2 if bit0 == 0 else -val / 2 gamma_val[1][enc_state] += val / 2 if bit1 == 0 else -val / 2 return gamma_val def _update_path_metrics(self, out_bit_llrs, path_metrics, best_bit): ''' Updates path metrics and finds best input bits for all states (does not modify self). Parameters ---------- out_bit_llrs : tuple Tuple of length self.n_out with float elements, specifying the LLRs for the output bits at time k. path_metrics : list List of length len(self.state_space) with float elements, specifying the path metric for each state at time k+1. This list is modified in place to contain the path metrics of all states at time k. best_bit : list List of length len(self.state_space). This list is modified in place to contain the best input bit in each state at time k. ''' gamma_val = self._branch_metrics(out_bit_llrs) pmn = path_metrics[:] for enc_state in self.state_space: cpm0 = gamma_val[0][enc_state] + pmn[self.next_state[0][enc_state]] cpm1 = gamma_val[1][enc_state] + pmn[self.next_state[1][enc_state]] path_metrics[enc_state], best_bit[enc_state] = ( (cpm0, 0) if cpm0 >= cpm1 else (cpm1, 1)) return def decode_viterbi(self, code_bit_llrs): ''' Decoder based on Viterbi algorithm (does not modify self). Parameters ---------- code_bit_llrs : ndarray of dtype float Array of code bit LLRs (+ve for 0, -ve for 1). Returns ------- info_bits_hat : ndarray of dtype int 1-dim array of size code_bit_llrs.size / self.n_out - self.mem_len, giving the decoded info bits. Notes ----- The encoder is assumed to have begun in state 0 and to have been brought back to state 0 at the end with self.mem_len tail bits. ''' code_bit_llrs = np.asarray(code_bit_llrs).ravel() n_in_bits = int(code_bit_llrs.size / self.n_out) n_info_bits = n_in_bits - self.mem_len # Path metric for each state at time n_in_bits. path_metrics = [(0 if s == 0 else -Conv.INF) for s in self.state_space] # Best input bit in each state at times 0 to n_in_bits - 1. best_bit = [[-1 for s in self.state_space] for k in range(n_in_bits)] # Start at time n_in_bits - 1 and work backward to time 0, finding # path metric and best input bit for each state at each time. for k in range(n_in_bits - 1, -1, -1): self._update_path_metrics( code_bit_llrs[self.n_out * k : self.n_out * (k + 1)], path_metrics, best_bit[k]) # Decode by starting in state 0 at time 0 and tracing path # corresponding to best input bits. info_bits_hat, enc_state = -np.ones(n_info_bits, dtype=int), 0 for k in range(n_info_bits): info_bits_hat[k] = best_bit[k][enc_state] enc_state = self.next_state[info_bits_hat[k]][enc_state] return info_bits_hat def _update_alpha( self, out_bit_llrs, pre_in_bit_llr, alpha_val, alpha_val_next, max_log): ''' Computes alpha value for each state at time k+1, given output bit LLRs for time k and prior input bit LLR for time k, and alpha value for each state at time k. Does not modify self. Parameters ---------- out_bit_llrs : tuple Tuple of length self.n_out with float elements, specifying the LLRs for the output bits at time k. pre_in_bit_llr : float Prior LLR for the input bit at time k. alpha_val : list List of length len(self.state_space) specifying alpha values for all states at time k. alpha_val_next : list List of length len(self.state_space). This list is modified in place to contain alpha values for all states at time k+1. max_log : bool Set to True to use the max-log approximation. ''' gamma_val = self._branch_metrics(out_bit_llrs, pre_in_bit_llr) for enc_state in self.state_space: alpha_val_next[self.next_state[0][enc_state]] = maxstar( alpha_val_next[self.next_state[0][enc_state]], alpha_val[enc_state] + gamma_val[0][enc_state], max_log) alpha_val_next[self.next_state[1][enc_state]] = maxstar( alpha_val_next[self.next_state[1][enc_state]], alpha_val[enc_state] + gamma_val[1][enc_state], max_log) return def _update_beta_tail(self, out_bit_llrs, beta_val, max_log): ''' Computes beta value for each state at time k, given output bit LLRs for time k and beta value for each state at time k+1. The prior input bit LLR for time k is taken as 0. Does not modify self. Parameters ---------- out_bit_llrs : tuple Tuple of length self.n_out with float elements, specifying the LLRs for the output bits at time k. beta_val : list List of length len(self.state_space) specifying beta values for all states at time k+1. This list is modified in place to contain beta values for all states at time k. max_log : bool Set to True to use the max-log approximation. ''' gamma_val = self._branch_metrics(out_bit_llrs, 0) bvn = beta_val[:] for enc_state in self.state_space: beta_val[enc_state] = maxstar( gamma_val[0][enc_state] + bvn[self.next_state[0][enc_state]], gamma_val[1][enc_state] + bvn[self.next_state[1][enc_state]], max_log) return def _update_beta( self, out_bit_llrs, pre_in_bit_llr, alpha_val, beta_val, max_log): ''' Computes beta value for each state at time k, given output bit LLRs and prior input bit LLR for time k, and beta value for each state at time k+1. Also computes and returns posterior input bit LLR for time k, given alpha value for each state at time k. Does not modify self. Parameters ---------- out_bit_llrs : tuple Tuple of length self.n_out with float elements, specifying the LLRs for the output bits at time k. pre_in_bit_llr : float Prior LLR for the input bit at time k. alpha_val : list List of length len(self.state_space) specifying alpha values for all states at time k. beta_val : list List of length len(self.state_space) specifying beta values for all states at time k+1. This list is modified in place to contain beta values for all states at time k. max_log : bool Set to True to use the max-log approximation. Returns ------- post_info_bit_llr : float Posterior LLR for the input bit at time k. ''' gamma_val = self._branch_metrics(out_bit_llrs, pre_in_bit_llr) met0 = -Conv.INF met1 = -Conv.INF bvn = beta_val[:] for enc_state in self.state_space: beta_val[enc_state] = maxstar( gamma_val[0][enc_state] + bvn[self.next_state[0][enc_state]], gamma_val[1][enc_state] + bvn[self.next_state[1][enc_state]], max_log) met0 = maxstar( alpha_val[enc_state] + gamma_val[0][enc_state] + bvn[self.next_state[0][enc_state]], met0, max_log) met1 = maxstar( alpha_val[enc_state] + gamma_val[1][enc_state] + bvn[self.next_state[1][enc_state]], met1, max_log) return met0 - met1 def decode_bcjr( self, code_bit_llrs, pre_info_bit_llrs=None, max_log=False): ''' Decoder based on BCJR algorithm (does not modify self). Parameters ---------- code_bit_llrs : ndarray of dtype float Array of code bit LLRs (+ve for 0, -ve for 1). pre_info_bit_llrs : ndarray of dtype float Array of size code_bit_llrs.size / self.n_out - self.mem_len, specifying pre-decoding info bit LLRs (+ve for 0, -ve for 1). If set to None, then all such LLRs are taken as 0. max_log : bool Set to True to use the max-log approximation. Returns ------- post_info_bit_llrs : ndarray of dtype float 1-dim array of size code_bit_llrs.size / self.n_out - self.mem_len, giving the post-decoding info bit LLRs. Notes ----- The encoder is assumed to have begun in state 0 and to have been brought back to state 0 at the end with self.mem_len tail bits. The computation of the post-decoding info bit LLRs assumes that code_bit_llrs was generated by BPSK-modulating the encoder output (+sqrt(Es) for 0 and -sqrt(Es) for 1), passing the BPSK symbols through a memoryless real AWGN channel with noise of zero mean and variance N0 / 2, and scaling the resulting channel output by 4 * sqrt(Es) / N0. The post-decoding LLR for info bit k is M(0,k) - M(1,k), where M(b,k) = maxstar[alpha(s,k) + gamma(s,ss,k) + beta(ss,k+1)], with the maxstar being over all state transitions from s at time k to ss at time k+1 that correspond to an input bit of b. Here, gamma(s,ss,k) is the branch metric for the transition. The alpha and beta values are respectively obtained by the Viterbi-like "forward" and "backward" recursions alpha(s,k+1) = maxstar[alpha(ss,k) + gamma(ss,s,k)] over all states ss at time k, and beta(s,k) = maxstar[gamma(s,ss,k) + beta(ss,k+1)] over all states ss at time k+1. Both recursions are initialized with state 0 having metric 0 and all other states having metrics of -Inf. ''' code_bit_llrs = np.asarray(code_bit_llrs).ravel() n_in_bits = int(code_bit_llrs.size / self.n_out) n_info_bits = n_in_bits - self.mem_len if pre_info_bit_llrs is None: pre_info_bit_llrs = np.zeros(n_info_bits) else: pre_info_bit_llrs = np.asarray(pre_info_bit_llrs).ravel() # FORWARD PASS: Recursively compute alpha values for all states at # all times from 1 to n_info_bits - 1, working forward from time 0. alpha = [[(0 if s == 0 and k == 0 else -Conv.INF) for s in self.state_space] for k in range(n_info_bits)] for k in range(n_info_bits - 1): out_bit_llrs = code_bit_llrs[ self.n_out * k : self.n_out * (k + 1)] self._update_alpha( out_bit_llrs, pre_info_bit_llrs[k], alpha[k], alpha[k + 1], max_log) # BACKWARD PASS (TAIL): Recursively compute beta values for all # states at time n_info_bits, working backward from time n_in_bits. beta = [(0 if s == 0 else -Conv.INF) for s in self.state_space] for k in range(n_in_bits - 1, n_info_bits - 1, -1): out_bit_llrs = code_bit_llrs[self.n_out * k : self.n_out * (k + 1)] self._update_beta_tail(out_bit_llrs, beta, max_log) # BACKWARD PASS: Recursively compute beta values for all states at # each time k from 0 to n_info_bits - 1, working backward from time # n_info_bits, and also obtaining the post-decoding LLR for the info # bit at each time. post_info_bit_llrs = np.zeros_like(pre_info_bit_llrs) for k in range(n_info_bits - 1, - 1, -1): out_bit_llrs = code_bit_llrs[self.n_out * k : self.n_out * (k + 1)] post_info_bit_llrs[k] = self._update_beta( out_bit_llrs, pre_info_bit_llrs[k], alpha[k], beta, max_log) return post_info_bit_llrs class Turbo(object): ''' Encoder and decoder for a turbo code, formed by the parallel concatenation of two identical binary recursive systematic convolutional (RSC) codes of rate 1/N (1 input bit stream and N output bit streams). The turbo code is then of rate 1/(2*N-1). The turbo interleaver is from 3GPP2. Attributes ---------- rsc : Conv Encoder and decoder for constituent RSC code. n_out : int Number of output bits per input bit. n_tail_bits : int Number of tail bits per input block. turbo_int : list List with int elements specifying the turbo interleaver. turbo_deint : list List with int elements specifying the turbo deinterleaver. ''' def __init__(self, back_poly, parity_polys): ''' Init method. Parameters ---------- back_poly : int For a constituent RSC code of constraint length L, back_poly must be in the range [2^(L-1), 2^L). parity_polys : tuple For a constituent RSC code of constraint length L and rate 1/N, parity_polys must be of length N-1, with int elements in the range [1, 2^L). Notes ----- The generator polynomials for the constituent RSC codes are specified through back_poly (positive integer) and parity_polys (sequence of positive integers). For a constituent RSC code of constraint length L and rate 1/N: (a) back_poly must be in the range [2^(L-1), 2^L); (b) parity_polys must be of length N-1 and its elements must be in the range [1, 2^L). The rate of the resulting turbo code is 1/(2*N-1). Let b[0], b[1],..., b[L-1] be the binary representation of back_poly, with b[0] = 1 being the MSB. Similarly, let f[n][0], f[n][1],..., f[n][L-1] be the L-bit binary representation of parity_polys[n], with f[n][0] being the MSB. The input-output relationship of each RSC encoder can then be described as follows. Let x[k] be the input bit at time k to the encoder, and let y[n][k], n = 0,1,...,N-1, be the n^th output bit at time k from the encoder. Then, y[0][k] = x[k] (systematic bit) and, for n = 1,2,...,N-1, y[n][k] = sum_{i=0}^{L-1} f[n-1][i] * s[k-i], where the sequence of bits s[k] is given by s[k] = b[0]*x[k] + sum_{i=1}^{L-1} b[i] * s[k-i]. The encoder has 2^(L-1) states, with the state at time k being comprised of the bits s[k-1], s[k-2],..., s[k-L+1]. The output bits at time k from each constituent encoder are read out in the order y[0][k], y[1][k],..., y[N-1][k]. For the final turbo code output, the systematic bit from the bottom encoder is suppressed. The output bits from the top encoder are followed by just the parity outputs from the bottom encoder. At the end, all the tail bits from the top encoder are read out, followed by all the tail bits from the bottom encoder. For the 3GPP/3GPP2 turbo code, set back_poly = 11, and parity_polys = [13, 15]. ''' # Encoder and decoder for constituent RSC code self.rsc = Conv(back_poly, [back_poly] + parity_polys) # Number of output bits per input bit and number of tail bits # per input block for the turbo code self.n_out = self.rsc.n_out + (self.rsc.n_out - 1) self.n_tail_bits = self.rsc.n_out * self.rsc.mem_len * 2 # Turbo interleaver and deinterleaver self.turbo_int, self.turbo_deint = [], [] return def encode(self, info_bits): ''' Encodes a given sequence of info bits (could modify self). Parameters ---------- info_bits : ndarray of dtype int Array specifying the info bits (0 or 1) to be encoded. Returns ------- code_bits : ndarray of dtype int 1-dim array of size self.n_out * info_bits.size + self.n_tail_bits, giving the resulting code bits. Notes ----- Both top and bottom encoders begin in state 0, and are brought back to state 0 at the end with self.rsc.mem_len tail bits. ''' info_bits = np.asarray(info_bits).ravel() n_info_bits = info_bits.size if n_info_bits != len(self.turbo_int): self.turbo_int, self.turbo_deint = turbo_int_3gpp2(n_info_bits) # Get code bits from each encoder. ctop = self.rsc.encode(info_bits) cbot = self.rsc.encode(info_bits[self.turbo_int]) # Assemble code bits from both encoders. code_bits, pos = -np.ones( self.n_out * n_info_bits + self.n_tail_bits, dtype=int), 0 for k in range(n_info_bits): code_bits[pos : pos + self.rsc.n_out] = ctop[ self.rsc.n_out * k : self.rsc.n_out * (k + 1)] pos += self.rsc.n_out code_bits[pos : pos + self.rsc.n_out - 1] = cbot[ self.rsc.n_out * k + 1 : self.rsc.n_out * (k + 1)] pos += self.rsc.n_out - 1 code_bits[pos : pos + self.rsc.n_out * self.rsc.mem_len] = ctop[ self.rsc.n_out * n_info_bits :] code_bits[pos + self.rsc.n_out * self.rsc.mem_len :] = cbot[ self.rsc.n_out * n_info_bits :] return code_bits def decode(self, code_bit_llrs, n_turbo_iters, max_log=False): ''' Decoder based on specified number of turbo iterations (could modify self). Parameters ---------- code_bit_llrs : ndarray of dtype float Array of code bit LLRs (+ve for 0, -ve for 1). n_turbo_iters : int Number of turbo iterations to run. max_log : bool Set to True to use the max-log approximation. Returns ------- info_bits_hat : ndarray of dtype int 1-dim array of size (code_bit_llrs.size - self.n_tail_bits) / self.n_out, giving the decoded info bits. post_info_bit_llrs : ndarray of dtype float 1-dim array of size (code_bit_llrs.size - self.n_tail_bits) / self.n_out, giving the post-decoding info bit LLRs. Notes ----- Both top and bottom encoders are assumed to have begun in state 0 and to have been brought back to state 0 at the end with self.rsc.mem_len tail bits. ''' code_bit_llrs = np.asarray(code_bit_llrs).ravel() n_info_bits = int((code_bit_llrs.size - self.n_tail_bits) / self.n_out) if n_info_bits != len(self.turbo_int): self.turbo_int, self.turbo_deint = turbo_int_3gpp2(n_info_bits) # Systematic bit LLRs for each decoder sys_llrs_top = code_bit_llrs[0 : self.n_out * n_info_bits : self.n_out] sys_llrs_bot = sys_llrs_top[self.turbo_int] # Code bit LLRs for each decoder ctop_llrs = np.zeros(self.rsc.n_out * (n_info_bits + self.rsc.mem_len)) cbot_llrs = np.zeros(self.rsc.n_out * (n_info_bits + self.rsc.mem_len)) pos = 0 for k in range(n_info_bits): num = self.rsc.n_out * k ctop_llrs[num] = sys_llrs_top[k] cbot_llrs[num] = sys_llrs_bot[k] pos += 1 ctop_llrs[num + 1 : num + self.rsc.n_out] = code_bit_llrs[ pos : pos + self.rsc.n_out - 1] pos += self.rsc.n_out - 1 cbot_llrs[num + 1 : num + self.rsc.n_out] = code_bit_llrs[ pos : pos + self.rsc.n_out - 1] pos += self.rsc.n_out - 1 ctop_llrs[self.rsc.n_out * n_info_bits :] = code_bit_llrs[ pos : pos + self.rsc.n_out * self.rsc.mem_len] cbot_llrs[self.rsc.n_out * n_info_bits :] = code_bit_llrs[ pos + self.rsc.n_out * self.rsc.mem_len :] # Main loop for turbo iterations ipre_llrs, ipost_llrs = np.zeros(n_info_bits), np.zeros(n_info_bits) for _ in range(n_turbo_iters): ipost_llrs[:] = self.rsc.decode_bcjr(ctop_llrs, ipre_llrs, max_log) ipre_llrs[:] = (ipost_llrs[self.turbo_int] - ipre_llrs[self.turbo_int] - sys_llrs_top[self.turbo_int]) ipost_llrs[:] = self.rsc.decode_bcjr(cbot_llrs, ipre_llrs, max_log) ipre_llrs[:] = (ipost_llrs[self.turbo_deint] - ipre_llrs[self.turbo_deint] - sys_llrs_bot[self.turbo_deint]) # Final post-decoding LLRs and hard decisions post_info_bit_llrs = ipost_llrs[self.turbo_deint] info_bits_hat = (post_info_bit_llrs < 0).astype(int) return info_bits_hat, post_info_bit_llrs
########################################################### # cards.py - This file contains the Card class and Deck # class. # # author: Connor Brewton cnb0013@auburn.edu # created: 2/12/19 # last modified: 2/12/19 ########################################################### # import sys import random # import math # import numpy as np # import matplotlib.pyplot as plt class Card: def __init__(self,suit,value): self.suit = suit self.value = value # compare value of two cards def __cmp__(self, other): if self.value < other.value: return -1 elif self.value == other.value: return 0 return 1 # compare suit of two cards # returns 1 if suits match def cmpSuit(self, other): if self.suit == other.suit: return 1 else: return 0 # get a string for given card def __str__(self): text = "" # set value text if self.value == 11: text = "J" elif self.value == 12: text = "Q" elif self.value == 13: text = "K" elif self.value == 14: text = "A" else: text = str(self.value) if self.suit == 0: text += "H" elif self.suit == 1: text += "C" elif self.suit == 2: text += "D" elif self.suit == 3: text += "S" else: text += "?" return text class Deck: # init the deck by adding 52 unique cards # self.cards = [] of 52 unique cards # self.drawnCards = [] cards popped by deal() stored here # returned when shuffle() called def __init__(self): self.cards = [] self.drawnCards = [] for suit in range(0,4): for value in range(2,15): self.cards.append(Card(suit,value)) # self.num_cards = 52 # restore drawnCards to deck and shuffle def shuffle(self): self.cards.extend(self.drawnCards) self.drawnCards = [] random.shuffle(self.cards) # deal num_cards # return [] of cards len = num_cards # cards drawn are popped and added to drawnCards def deal(self,num_cards): if (num_cards > len(self.cards)): return False drawnCards = [] for i in range(0, num_cards): drawnCards.append(self.cards.pop(0)) self.drawnCards.extend(drawnCards) return drawnCards # returns the number of cards left in deck def cardsLeft(self): return len(self.cards) # print the deck def printDeck(self): text = "Deck\n" i = 0 for c in self.cards: if i == 4: i = 0 text += str(c) + "\n" else: i += 1 text += str(c) + "," print(text) # main function only used to test card functions, # this file should be a library file to import Card/Deck classes def main(): deck = Deck() deck.printDeck() deck.shuffle() deck.printDeck() if __name__ == '__main__': main()
def odd_num(s, i, j): if i >= j: return s else: while i < j and s[i] % 2 == 0: i += 1 while j > i and s[j] % 2 != 0: j -= 1 s[i], s[j] = s[j], s[i] return odd_num(s, i+1, j-1) if __name__ == '__main__': s = [6, 5, 2, 4, 7, 8] print(odd_num(s, 0, len(s)-1))
from collections import deque from sixth_chapter.queue import ArrayQueue def sort_dq(D, Q): # 先将双端队列的元素写入队列Q中,变为[1,2,3,8,7,6,4,5] for i in range(0, len(D)): if i < 3: Q.enqueue(D.popleft()) if i > 4: Q.enqueue(D.pop()) Q.enqueue(D.popleft()) Q.enqueue(D.pop()) # 接下来将Q元素出队从双端队列的尾部写入变为[1,2,3,8,7,6,4,5] while not Q.is_empty(): D.append(Q.dequeue()) # 接下来的处理,就是借用队列Q,将[8,7,6,4,5]变为[5,4,6,7,8] for j in range(0, 5): Q.enqueue(D.pop()) # 将[5,4,6,7,8]写回双端队列 while not Q.is_empty(): D.append(Q.dequeue()) if __name__ == '__main__': D = deque() Q = ArrayQueue() for i in range(1, 9): D.append(i) print(D) sort_dq(D, Q) print(D)
import random def insert_half(nums, num_insert, low, high): while low <= high: mid = (low+high) // 2 if num_insert > nums[mid]: low = mid + 1 else: high = mid - 1 nums.insert(low, num_insert) return nums if __name__ == '__main__': nums = [] for i in range(8): nums.append(random.randint(1, 100)) print(nums) nums.sort() num_insert = int(input("please enter num:")) print(insert_half(nums, num_insert, 0, len(nums)-1))
class Solution: def climbStairs(self, n: int) -> int: count = [0, 1, 2] for i in range(3, n+1): count.append(count[i-1] + count[i-2]) return count[n] if __name__ == '__main__': n = 3 s = Solution() print(s.climbStairs(n))
import shelve def store(database): uid = input("please enter id:") person = {} person['name'] = input("please enter name:") person['age'] = input("please enter age:") person['phone_number'] = input("please enter phone number:") database['uid'] = person def lookup(database): uid = input("please enter the uid:") info = input("please enter info:(name,age,phone_number)") look_info = info.strip().lower() print(look_info.capitalize() + ':', database[uid][look_info]) def print_help(): print("The available commands are:") print("store: Stores information about a person") print("lookup: Looks up a person from ID number") print("quit: Save changes and exit") print("?: Prints this message") def cmd(): cmd = input("please enter the command (? for help):") cmd = cmd.strip().lower() return cmd def main(): database = shelve.open('E:\\pycharm\day06_3_11\data.dat') try: while True: main_cmd = cmd() if main_cmd == 'store': store(database) elif main_cmd == 'lookup': lookup(database) elif main_cmd == '?': print_help() elif main_cmd == 'quit': exit() except Exception as e: print(e) finally: database.close() if __name__ == '__main__': main()
def harm_num(n, sum): if n == 0: return sum else: sum = sum + 1/n return harm_num(n-1, sum) if __name__ == '__main__': print(harm_num(3, 0))
def work(time, m): time = sorted(time, reverse=True) if m >= len(time): return time[0] else: tmp = time[:m] for i in time[m:]: ind = tmp.index(min(tmp)) tmp[ind] += i return max(tmp) if __name__ == '__main__': time = [30, 26, 10, 35, 20, 18, 2, 7] m = 3 print(work(time, m))
class Person: def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary def setName(self, name): self.name = name def getName(self): return self.name def getId(self): return self.id def comSalary(self): return float(self.salary) class Worker(Person): def __init__(self, id, name, hours, h_salary): super().__init__(id, name, h_salary) self.hours = hours def comSalary(self): return float(self.hours * self.salary) class SaleMan(Person): def __init__(self, id, name, sale_balance, ratio): super().__init__(id, name, sale_balance) self.ratio = ratio def comSalary(self): return float(self.salary * self.ratio) class Manager(Person): def __init__(self, id, name, salary): super().__init__(id, name, salary) class SaleManager(Person): def __init__(self, id, name, salary, sale_balance, ratio): super().__init__(id, name, salary) self.sale_balance = sale_balance self.ratio = ratio def comSalary(self): print(float(self.sale_balance * self.ratio)) return self.salary + float(self.sale_balance * self.ratio) if __name__ == '__main__': worker = Worker('100010', '王五', 250, 50) sale_man = SaleMan('100012', '张三', 180000, 0.20) manager = Manager('100001', '赵四', 86500) sale_manager = SaleManager('100008', '黄六', 8000, 260000, 0.273) w_Salary = worker.comSalary() man_Salary = sale_man.comSalary() m_Salary = manager.comSalary() manager_Salary = sale_manager.comSalary() print('姓名:{0}, ID:{1}, 工资:{2}'.format(worker.getName(), worker.getId(), w_Salary)) print('姓名:{0}, ID:{1}, 工资:{2}'.format(sale_man.getName(), sale_man.getId(), man_Salary)) print('姓名:{0}, ID:{1}, 工资:{2}'.format(manager.getName(), manager.getId(), m_Salary)) print('姓名:{0}, ID:{1}, 工资:{2}'.format(sale_manager.getName(), sale_manager.getId(), manager_Salary))
from sixth_chapter.stack import ArrayStack def is_matched(raw): S = ArrayStack() j = raw.find('<') while j != -1: k = raw.find('>', j + 1) if k == -1: return False tag = raw[j + 1:k] if not tag.startswith('/'): S.push(tag) else: if S.is_empty(): return False e = S.pop() if tag[1:] != e[:len(tag) - 1]: return False j = raw.find('<', k + 1) return S.is_empty() if __name__ == '__main__': print(is_matched('<name attribute="seda"></name>'))
class Solution: def defangIPaddr(self, address): addr = address.split('.') for i in range(1, len(addr) + 2, 2): addr.insert(i, '[.]') return ''.join(addr) if __name__ == '__main__': address = "1.1.1.1" s = Solution() print(s.defangIPaddr(address))
""" 基于数组的队列实现 """ class ArrayQueue: # 队列的容量 CAPACITY = 10 def __init__(self): # 创建一个数组,初始的容量为10 self.data = [None] * ArrayQueue.CAPACITY # size表示队列中存储的当前元素个数,初始化时队列为空,元素个数为0 # front表示队列的第一个元素的索引,初始化时队列为空,第一个元素应该放在0位置 self.size = 0 self.front = 0 # 返回当前队列的元素个数 def __len__(self): return self.size # 若队列为空,返回True def is_empty(self): if self.size == 0: return True return False # 在不移除元素的前提下(不出队)返回队列的第一个元素 def first(self): if self.is_empty(): raise Exception('Queue is empty') return self.data[self.front] # 出队方法,返回出队的元素 def dequeue(self): if self.is_empty(): raise Exception('Queue is empty') # 出队遵循FIFO,取出队头元素,替换为None answer = self.data[self.front] self.data[self.front] = None # 取出第一个元素之后,第二元素变为了第一个,取余操作是解决循环队列问题 self.front = (self.front + 1) % len(self.data) self.size -= 1 # 当存储的元素降低到数组总的存储能力的1/4时,将数组的大小缩小到当前容量的一半, # 保证队列的健壮性 if 0 < self.size < len(self.data) // 4: self.resize(len(self.data) // 2) return answer # 入队操作,向队尾插入一个元素 def enqueue(self, e): # 当队满时,需要扩充队列的容量,一般就是将当前队列容量变成2倍 if self.size == len(self.data): self.resize(2 * len(self.data)) # 插入的位置(队尾) avail = (self.front + self.size) % len(self.data) self.data[avail] = e self.size += 1 # 动态的改变队列的存储容量 def resize(self, cap): old = self.data self.data = [None] * cap walk = self.front for k in range(self.size): self.data[k] = old[walk] walk = (1+walk) % len(old) self.front = 0
class Solution: def numberOfSteps(self, num): count = 0 while num != 0: count += 1 if num % 2 == 0: num = num/2 else: num = num-1 return count if __name__ == '__main__': s = Solution() num = 123 print(s.numberOfSteps(num))
def reserve(s, start, end): if start >= end: return ''.join(s) else: s[start], s[end] = s[end], s[start] return reserve(s, start+1, end-1) if __name__ == '__main__': s = 'asdh$ssy' print(reserve(list(s), 0, len(s)-1))
""" 开发过程中使用线程,在线程间共享多个资源的时候, 如果两个线程分别占有一部分资源并且同时等待对方的资源,就会造成死锁。 尽管死锁很少发生,但一旦发生就会造成应用的停止响应,程序不做任何事情。 """ import threading import time lockA = threading.Lock() lockB = threading.Lock() def task1(): if lockA.acquire(timeout=5): print('获取了A锁') # 如果可以获取到锁则返回True time.sleep(0.5) if lockB.acquire(timeout=5): # 如果锁被占用,等待 print('又获取了B锁') lockB.release() lockA.release() def task2(): if lockB.acquire(timeout=5): print('获取了B锁') time.sleep(0.5) if lockA.acquire(timeout=5): print('又获取了A锁') lockA.release() lockB.release() if __name__ == '__main__': t1 = threading.Thread(target=task1) t2 = threading.Thread(target=task2) t1.start() t2.start()
import time import random # 简单的装饰器 def decorater(func): def wrapped(*args, **kwargs): # 参数是为了应对各种带参或不带参的函数作为参数传入 start = time.time() func(*args, **kwargs) print('刷白墙') print('铺地板') print('买家具') time.sleep(random.randint(1, 5)) print('装修结束') end = time.time() print('装修花费的时间:', end-start) return wrapped # 装饰有返回值的函数的装饰器 def decorater1(func): def wrapped(*args, **kwargs): start = time.time() r = func(*args, **kwargs) # 原函数带有返回值,这儿需要变量进行接收 print('预计装修花费:{}'.format(r)) print('刷白墙') print('铺地板') print('买家具') time.sleep(random.randint(1, 5)) print('装修结束') end = time.time() print('装修花费的时间:', end-start) return r+10000 return wrapped ''' 原函数home(),开始并未装修,但是未来遵循开放封闭原则,不对原函数进行更改, 就用装饰器进行修改装修,装饰器实质上就将home()作为参数传入进去, 然后就可以对原函数内容进行各种添加和修改 也就相当于:home = decorater(home),由于decorater中的返回值是wrapped, 所以,执行完毕后,home实质上也就是wrapped()了 ''' @decorater def home(): print('买了一套房,没装修') @decorater def school(address, area): print('学校位于:{0},面积是:{1}'.format(address, area)) @decorater def hotel(name, address, area): print('酒店叫:{0}, 酒店位于:{1},面积是:{2}'.format(name, address, area)) @decorater1 def factory(name, address, area): print('工厂叫:{0}, 工厂位于:{1},面积是:{2}'.format(name, address, area)) return 50000 if __name__ == '__main__': home() print('-----------') school('北京', '1200') print('-----------') hotel(name='锦江之星', address='上海', area='1500') print('-----------') r = factory(name='苹果', address='加利福尼亚', area='150000') print('实际装修花费:{}'.format(r))
class Person: def set_name(self, name): self.name = name def get_name(self): return self.name def __fun(self): print("asdufhu") def greet(self): print("Hello, {0}!".format(self.name)) self.__fun() foo = Person() foo.set_name("Tom") print(foo.get_name()) foo.greet()
class Student: count = 0 def __init__(self, name): self.name = name Student.count += 1 print(Student.count) s = Student('Bart') print(s.count) s = Student('Bart') print(s.count)
#indexGame # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals): intervals.sort(key = lambda x : x[0]) res = [] for i in intervals: if res and res[-1][1] >= i[0]: res[-1][1] = max(res[-1][1],i[1]) else: res += [i] return res
#Merge sort example # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head def merge(a,b): dummy = ListNode(0) p = dummy while a or b: if not a: p.next, b = b, b.next elif not b: p.next, a = a, a.next elif a.val < b.val: p.next, a = a, a.next else: p.next, b = b, b.next p = p.next return dummy.next s, f, pre = head,head,None while f and f.next: s, f, pre = s.next, f.next.next, s pre.next = None return merge(self.sortList(head),self.sortList(s))
from math import * def isp(x): if x <= 1: return False if x == 2: return True for i in range(2, int(x ** 0.5) + 1): if x % i == 0: return False return True def sim(x): return x % 2 != 0 and x % 3 != 0 and x % 5 != 0 n = int(raw_input()) print [';Not Prime';, ';Prime';][isp(n) or sim(n) and n != 1]
nums = map(int, raw_input().split()) nums.sort() if nums[0] == nums[2]: print(nums[0]) else: if nums[0] == nums[1]: print(nums[2]) elif nums[1] == nums[2]: print(nums[0])
a = int(raw_input()) b = int(raw_input()) n = int(raw_input()) while (n % a or n % b): n += 1 print n
from tkinter import * import random from PIL import ImageTk, Image root = Tk() root.geometry("600x600") root.iconbitmap(True, "images/icon.ico") root.title("Rock Paper Scissors") root.resizable(False,False) computerScore = 0 playerScore = 0 # main game function def game(number): global playerScore,computerScore computerChoiceList = [1,2,3] # 1:rock 2:paper 3:scisors computerChoice = random.choice(computerChoiceList) diff = number-computerChoice while True: if diff in [1,-2]: playerScore += 1 scoreLabel = Label(text=playerScore,font="Segoe 16") scoreLabel.place(x=220,y=62) result.set("Player wins") elif diff in [-1,2]: computerScore += 1 scoreLabel = Label(text=computerScore,font="Segoe 16") scoreLabel.place(x=350,y=62) result.set('Computer wins') elif diff == 0: result.set('Oops...Tie') imgDict ={1: rock,2: paper,3: scissors} imgName = imgDict.get(computerChoice) computerLabel = Label(text="Computer Has Choosen,",font="Segoe 16") computerLabel.place(x=70,y=170) computerImageLabel = Label(image=imgName) computerImageLabel.place(x=250,y=200) break welcomeLabel = Label(root,text="Rock Paper Scissors", font="Segoe 24") welcomeLabel.place(x=150,y=10) # Score board frame scoreFrame = Frame(root) scoreFrame.place(x=100,y=60) scoreBoard = Label(scoreFrame,text="Player | Computer",font="Segoe 18") scoreBoard.grid(row=0,column=0) # Images rock = ImageTk.PhotoImage(Image.open("images/rock.png").resize((100,100))) paper = ImageTk.PhotoImage(Image.open("images/paper.png").resize((100,100))) scissors = ImageTk.PhotoImage(Image.open("images/scissors.png").resize((100,100))) iconFrame = Frame(root) iconFrame.place(x=150,y=350) rockButton = Button(iconFrame, image=rock,command=lambda: game(1),borderwidth=0) rockButton.grid(row=5,column=1) paperButton = Button(iconFrame, image=paper,command=lambda: game(2),borderwidth=0) paperButton.grid(row=5,column=3) scissorsButton = Button(iconFrame, image=scissors,command=lambda: game(3),borderwidth=0) scissorsButton.grid(row=5,column=5) result = StringVar() resultLabel = Label(root,textvariable=result,font="Segoe 18") resultLabel.place(x=220,y=500) root.mainloop()
# a121_catch_a_turtle.py #-----import statements----- import turtle as trtl import random import leaderboard as lb #-----game configuration---- turtleshape = "turtle" trutlecolor = "green" turtlesize = 2 score = 0 font_setup = ("Arial", 20, "normal") timer = 30 counter_interval = 1000 #1000 represents 1 second timer_up = False #scoreboard varibles leaderboard_file_name = "a122_leaderboard.txt" leader_names_list = [] leader_scores_list = [] player_name = input("Please enter your name") #-----initialize turtle----- joe = trtl.Turtle(shape = turtleshape) joe.color(trutlecolor) joe.shapesize(turtlesize) joe.speed(0) scoreboard = trtl.Turtle() scoreboard.ht() scoreboard.speed(0) scoreboard.penup() scoreboard.goto(-370,270) font_setup = ("Arial", 30, "bold") scoreboard.write(score, font=font_setup) counter = trtl.Turtle() counter.ht() counter.penup() counter.speed(0) counter.goto(-270,270) counter.ht() counter.pendown #------game functions------ def turtle_clicked(x,y): print("joe got clicked") change_position() update_score() def change_position(): joe.penup() joe.ht() if not timer_up: joex = random.randint(-400,400) joey = random.randint(-300,300) joe.goto(joex,joey) joe.st() def update_score(): global score score += 1 print(score) scoreboard.clear() scoreboard.write(score, font=font_setup) def countdown(): global timer, timer_up counter.clear() if timer <= 0: counter.write("Game Over ", font=font_setup) timer_up = True manage_leaderboard() else: counter.write("Timer: " + str(timer), font=font_setup) timer -= 1 counter.getscreen().ontimer(countdown, counter_interval) # manages the leaderboard for top 5 scorers def manage_leaderboard(): global leader_scores_list global leader_names_list global score global joe # load all the leaderboard records into the lists lb.load_leaderboard(leaderboard_file_name, leader_names_list, leader_scores_list) # TODO if (len(leader_scores_list) < 5 or score > leader_scores_list[4]): lb.update_leaderboard(leaderboard_file_name, leader_names_list, leader_scores_list, player_name, score) lb.draw_leaderboard(leader_names_list, leader_scores_list, True, joe, score) else: lb.draw_leaderboard(leader_names_list, leader_scores_list, False, joe, score) #------events------ wn = trtl.Screen() wn.bgcolor("lightblue") joe.onclick(turtle_clicked) wn.ontimer(countdown, counter_interval) wn.mainloop()
# -*- coding: utf-8 -*- """ Spyder Editor This temporary script file is located here: C:\Users\Yuanze LEO\.spyder2\.temp.py """ from math import * c = [1]*2000025 a = [2] #Q1:sum 1000 def sum1000(n): count = 0 #initialize count for i in range(n-1): if (i+1)%3 ==0 or (i+1)%5 == 0: count += (i+1) return count #Q2:sum the prime numbers in 2000000 #use shai method to pick up prime numbers def shaifa(n): sums = 2 for i in range(3,n,2): if c[i] == 1: count = i*2 while count<n: c[count] = 0 count += i a.append(i) sums += i print sums #Q3: #judge if the year is leapyear,and return the day of months def monthdays_of_year(year): monthdays = [31,28,31,30,31,30,31,31,30,31,30,31] if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0): monthdays[1] = 29 return monthdays else: return monthdays def Q3(): c_Sunday = 0 p_days = 1 for n in range(12): p_days += monthdays_of_year(1900)[n] for year in range(1901,2001): for month in range(12): if p_days % 7 == 0: c_Sunday += 1 p_days += monthdays_of_year(year)[month] print c_Sunday print sum1000(1000) shaifa(2000000) Q3() #Q4: #use the 'a' list from Q2 to finish Q4 def Q4(): count = 1 #create a list called bools to marked the prime that have been checked for i in range(0,len(a)): e = a[i] if (e>=1000)and (c[e]== 0): break else: m = str(e) k = len(m)-1 d = k if ('0' in m) or ('2' in m) or ('4' in m) or ('6' in m) or ('8' in m): continue m = m + m #check if i is a looping prime while k>0: w = int(m[(1+d-k):(1+d-k+d+1)]) if w >=1000000: break #print c,' ',k,'***',i if c[w]==0: break k -= 1 else: count += 1 print count Q4()
""" 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. """ def days_calc(start_distance, needed_distance): day_count = 1 finish = a while finish < b: finish *= 1.1 day_count += 1 return day_count a = int(input("Please, enter 1-st day distance: ")) b = int(input("Please, enter needed final distance: ")) print(days_calc(a, b))
#Programme qui affiche des "*", avec une "*" de plus a chaque ligne, 7 fois. a=1 b="*" while a<=7 : # boucle 7 fois print(b) b=b+"*" #Ajout d'un "*" a la précédente variable a=a+1
#Python - Partie 2 - Script 5) #Script qui affiche vrai ou faux en fonction d'un nombre donné. n=int(input('Entrez un nombre quelconque')) if n: print('vrai') else: print('faux')
#Python - Partie 2 - Exercice 9 #Script qui affiche 8 carré à la suite. #Importation des module from turtle import * from dessins_tortue import * #Tailles: #Carré: 30 #Triangle: 27 up() goto(-80,240) angle=0 taille = 60 speed("fast") down() carre(taille,"blue",angle) up() goto(0,280) for i in range (9): angle-=60 taille-=5 up() setheading(angle) forward(taille) down() etoile6(taille,"red",angle) up() setheading(angle) forward(taille) down() triangle(taille,"green",angle) up() forward(taille+20) down() etoile5(taille,"brown",angle) up() forward(taille+20) down() carre(taille,"blue",angle) up() setheading(angle+20) forward(taille+30) up()
# Write a function that accepts a list of numbers as an argument. # It should return the smallest number in the list. def smallest(list_of_numbers): minimum = 0 for number in list_of_numbers: if number < minimum: minimum = number return minimum numbers = [7, 21, 4, 33, -456, 8, 99, 1, 12340, 2, 79, 88, 124, 90] print(" ") print(f"Original List: {numbers}") print(" ") print(f"Smallest Number: {smallest(numbers)}") print(" ")
class StructureException(Exception): """Exception raised for errors in the structure. Attributes: message -- explanation of the error """ def __init__(self, message="incorrect structure"): if len(message) > 0: message = message[0].lower() + message[1:] self.message = "Error in the structure, " + message + "." super().__init__(self.message) class LabelsRequirementException(Exception): """Exception raised for errors in the labels. Attributes: message -- explanation of the error """ def __init__(self, message="incorrect label requirement"): if len(message) > 0: message = message[0].lower() + message[1:] self.message = "Error in the structure, " + message + "." super().__init__(self.message) class StructureFileElementDoesNotExists(Exception): """Exception raised for errors in the structure. Attributes: message -- explanation of the error """ def __init__(self, message="element does not exist"): if len(message) > 0: message = message[0].lower() + message[1:] self.message = "Error in structure file, " + message + "." super().__init__(self.message)
def bonAppetite(bill, k, b): b_actual = 0 n = len(bill) for i in range(n): if i != k: b_actual += bill[i] b_actual = int(b_actual / 2) b_charged = b charge = b_charged - b_actual if charge > 0: print(str(charge)) return print('Bon Appetit') return bill = [3,10,2,9] k = 1 b = 12 bonAppetite(bill, k, b)
def TwoStrings(s1, s2): n1 = len(s1) n2 = len(s2) if n1 >= n2: temp = {} for char in s1: if char not in temp.keys(): temp[char] = 1 else: temp[char] += 1 for char in s2: if char in temp.keys(): return "YES" return "NO" else: temp = {} for char in s2: if char not in temp.keys(): temp[char] = 1 else: temp[char] += 1 for char in s1: if char in temp.keys(): return "YES" return "NO" s1 = 'hello' s2 = 'world' print(TwoStrings(s1,s2))
''' Simple dequeue implementation in python ''' # Auxiliary class for the Node object class Node: # Initialization of Node def __init__(self, value, next=None, prev=None): self.value = value self.next = next self.prev = prev # Main class for Dequeue class Dequeue: # Initialization of Dequeue def __init__(self): self.front = None self.back = None # Print # Printing all element, isFront indicates if printing is done from the front or the back def print(self, isFront=True): if isFront: pointer = self.front while pointer: print(pointer.value) pointer = pointer.next else: pointer = self.back while pointer: print(pointer.value) pointer = pointer.prev # addFront # Adding element in the front of the queue def addFront(self, node): if not self.front and not self.back: self.front = node self.back = node else: pointer = self.front self.front = node self.front.next = pointer pointer.prev = self.front # addBack # Adding element in the back of the queue def addBack(self, node): if not self.front and not self.back: self.front = node self.back = node else: pointer = self.back self.back = node self.back.prev = pointer pointer.next = self.back # removeFront # Remove element in the front of the queue def removeFront(self): if not self.front and not self.back: return elif not self.front.next and not self.back.prev: print("Deleted ", self.front.value) self.front = None self.back = None else: print("Deleted ", self.front.value) self.front = self.front.next self.front.prev = None # removeBack # Remove element in the front of the queue def removeBack(self): if not self.front and not self.back: return elif not self.back.prev and not self.front.next: print("Deleted ", self.back.value) self.front = None self.back = None else: print("Deleted ", self.back.value) self.back = self.back.prev self.back.next = None # Test use cases node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) test = Dequeue() test.addFront(node1) test.addFront(node2) test.addFront(node3)
''' Binary Tree implementation on Python Assuming left <= data <= right ''' class BinaryTree: def __init__(self, data): self.left = None self.data = data self.right = None def insert(self, data): if data < self.data: if self.left: self.left.insert(data) else: self.left = BinaryTree(data) elif data > self.data: if self.right: self.right.insert(data) else: self.right = BinaryTree(data) def print(self): if self.left: self.left.print() print(self.data) if self.right: self.right.print() BT = BinaryTree(12) BT.insert(6) BT.insert(14) BT.insert(3) BT.print() # # Main class for the Binary Tree # class Node: # # Initialization # def __init__(self, data): # self.data = data # self.right = None # self.left = None # # # Insert # # Insertion of a node to the binary tree # def insert(self, data): # if not self.data: # self.data = data # else: # if data < self.data: # if self.left is None: # self.left = Node(data) # else: # self.left.insert(data) # elif data > self.data: # if self.right is None: # self.right = Node(data) # else: # self.right.insert(data) # # # Print # # Iterate through the tree # def print(self): # if self.left: # self.left.print() # print(self.data) # if self.right: # self.right.print() # root = Node(12) # root.insert(6) # root.insert(14) # root.insert(3) # # root.print()
''' Using whatever languages, frameworks and libraries you choose write a Roguelike dungeon generator. (http://en.wikipedia.org/wiki/Roguelike) Your system should generate random but sensible dungeons - e.g. there should not be isolated areas that are unreachable and there should be an entrance and exit. The presentation of your dungeons is up to you. Take the implementation as far as you'd like. Some ideas: - generate dungeons with provided x/y dimensions - treasures - monsters - locked doors w/ accessible keys - other terrain types - obstacles (fire, water, pits, traps) Please don't spend more than one working day on your solution. Provide a brief README detailing how to build and run your project. Ideally share your project via Github. ''' import random from tiles import Tile, WallTile, FloorTile, DoorTile, EntranceTile, ExitTile # split out to config ROOM_MIN_SIZE = 6 ROOM_MAX_SIZE = 10 MIN_DOORS_PER_ROOM = 1 MAX_DOORS_PER_ROOM = 2 MIN_PATHS_PER_DOOR = 1 MAX_PATHS_PER_DOOR = 2 CHANCE_DOOR_LOCKED = .4 MAX_PLACEMENT_ATTEMPTS = 200 CHANCE_FOR_MONSTER = .3 CHANCE_FOR_LOOT = .05 class Room(): def __init__(self, topleft, bottomright): self.topleft = topleft self.bottomright = bottomright self.x1 = topleft.x self.y1 = topleft.y self.x2 = bottomright.x self.y2 = bottomright.y class Point(): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "Point({},{})".format(self.x,self.y) def __eq__(self, obj): return self.x == obj.x and self.y == obj.y def __hash__(self): return hash((self.x, self.y)) class Dungeon(): def __init__(self, width, height, density=.25, rooms=[], doors=[], mobs=[]): self.width = width self.height = height self.density = density # developer note: home of the most hateful bug that stressed me out to no end :) #self.tiles = [[Tile()]*width]*height self.tiles = [[WallTile() for i in range(width)] for j in range(height)] self.entrance = None self.exit = None self.rooms = rooms self.doors = doors self.mobs = mobs self.generate() def __repr__(self): # prettifies the print a bit return '\n'.join([''.join(['{:2}'.format(item) for x, item in enumerate(row)]) for y, row in enumerate(self.tiles)]) def load_configuration(config): #set parameters from configuration pass def clear(self): self.tiles = [[WallTile() for i in range(self.width)] for j in range(self.height)] self.entrance = None self.exit = None def generate(self): self.clear() print('Generating Dungeon') # create rooms attempts = 0 while self.should_add_room() and attempts < MAX_PLACEMENT_ATTEMPTS: x1 = random.randint(1, self.width-ROOM_MIN_SIZE) y1 = random.randint(1, self.height-ROOM_MIN_SIZE) x2 = min(x1+random.randint(ROOM_MIN_SIZE, ROOM_MAX_SIZE), self.width-1) y2 = min(y1+random.randint(ROOM_MIN_SIZE, ROOM_MAX_SIZE), self.height-1) topleft = Point(x1, y1) bottomright = Point(x2, y2) if self.valid_room(topleft, bottomright): current_room = Room(topleft, bottomright) print('Attempting to add room at ({},{}),({},{})'.format(x1, y1, x2, y2)) self.rooms.append(current_room) self.fill_with_tile(topleft, bottomright, FloorTile) self.add_walls(topleft, bottomright) if not self.entrance: room = random.choice(self.rooms) self.entrance = self.place_in_room(room, EntranceTile) walls = self.get_tiles_in_bounds(topleft, bottomright, WallTile) # remove corner pieces so we dont add doors to those for corner in [topleft, bottomright, Point(topleft.x, bottomright.y), Point(bottomright.x, topleft.y)]: if corner in walls: walls.remove(corner) self.add_doors(walls) self.add_mobs() attempts += 1 #place exit if not self.exit: room = random.choice(self.rooms) self.entrance = self.place_in_room(room, ExitTile) #connect our rooms self.create_paths() self.add_traps() self.add_hazards() return def should_add_room(self): # if the amount of room tiles exceeds the percentage of total tiles specified by # density, return False, else return True return len(self.get_tiles(FloorTile)) < (self.width*self.height) * self.density def valid_room(self, topleft, bottomright): #check bounds if topleft.x <= 0 or topleft.y <= 0: return False if bottomright.x >= self.width or bottomright.y >= self.height: return False #print('Ranging: x:{}, y:{}'.format(range(topleft.x-1, bottomright.x+2), range(topleft.y-1, bottomright.y+2))) for row in range(topleft.y-1, min(bottomright.y+2, self.height-1)): for col in range(topleft.x-1, min(bottomright.x+2, self.width-1)): if not self.is_wall(row, col) or not self.is_empty(row, col): return False #check to make sure that all tiles within the room are walls presently return True def is_tile(self, row, col, tile): if col >= self.width or row >= self.height: return False return isinstance(self.tiles[row][col], tile) def is_empty(self, row, col): return self.is_tile(row, col, Tile) def is_wall(self, row, col): return self.is_tile(row, col, WallTile) def fill_with_tile(self, topleft, bottomright, tile): for row in range(topleft.y, bottomright.y+1): for col in range(topleft.x, bottomright.x+1): self.tiles[row][col] = tile() def add_walls(self, topleft, bottomright): for x in range(topleft.x, bottomright.x+1): self.tiles[topleft.y][x] = WallTile() self.tiles[bottomright.y][x] = WallTile() for y in range(topleft.y, bottomright.y+1): self.tiles[y][topleft.x] = WallTile() self.tiles[y][bottomright.x] = WallTile() def add_doors(self, walls): num_doors = random.randint(MIN_DOORS_PER_ROOM, MAX_DOORS_PER_ROOM) points = random.sample(walls, num_doors) for point in points: self.tiles[point.y][point.x] = DoorTile() self.doors.append(point) def place_in_room(self, room, tile): row, col = self.get_point_in_bounds(room.topleft, room.bottomright) self.tiles[row][col] = tile() return row, col def get_point_in_bounds(self, topleft, bottomright): col = random.randint(topleft.x, bottomright.x) row = random.randint(topleft.y, bottomright.y) return row, col def create_paths(self): for door in self.doors: connect_to = [door] # make sure every door gets at least one connection, and make sure a connection doesnt include itself # todo: or another door in the same room while door in connect_to: connect_to = set(random.sample(self.doors, random.randint(MIN_PATHS_PER_DOOR, MAX_PATHS_PER_DOOR))) for connection in connect_to: #choose the spot opposite the room to start the door and connection door_x, door_y = self._get_opposite_of_room(door) connection_x, connection_y = self._get_opposite_of_room(connection) self.connect_path(self.tiles, door_x, door_y, connection_x, connection_y) def _get_opposite_of_room(self, door): if door.x <= 0 or door.y <= 0 or door.x >= self.width or door.y >= self.height: #best to just start where we're at return door.x, door.y if self.is_tile(door.y+1, door.x, FloorTile): return door.x, door.y-1 if self.is_tile(door.y, door.x+1, FloorTile): return door.x-1, door.y if self.is_tile(door.y-1, door.x, FloorTile): return door.x, door.y+1 if self.is_tile(door.y, door.x-1, FloorTile): return door.x+1, door.y # fell through return door.x, door.y def connect_path(self, tiles, currx, curry, goalx, goaly): if currx == goalx and curry == goaly: return tiles if currx >= self.width or curry >= self.height or currx < 0 or curry < 0: return tiles if self.is_wall(curry, currx): tiles[curry][currx] = FloorTile() movex = random.choice([True, False]) if movex: if self.is_wall(curry, currx): tiles[curry][currx] = FloorTile() if currx < goalx: self.connect_path(tiles, currx+1, curry, goalx, goaly) elif currx > goalx: self.connect_path(tiles, currx-1, curry, goalx, goaly) else: if curry < goaly: self.connect_path(tiles, currx, curry+1, goalx, goaly) elif curry > goaly: self.connect_path(tiles, currx, curry-1, goalx, goaly) return tiles def get_tiles_in_bounds(self, topleft, bottomright, tile_type): tiles = [] for y in range(topleft.y, bottomright.y+1): for x in range(topleft.x, bottomright.x+1): if isinstance(self.tiles[y][x], tile_type): tiles.append(Point(x, y)) return tiles def get_tiles(self, tile_type): return self.get_tiles_in_bounds(Point(0, 0), Point(self.width-1, self.height-1), tile_type) def add_mobs(self): pass def add_traps(self): pass def add_hazards(self): pass if __name__ == '__main__': #set seed for testing #random.seed(9001) d = Dungeon(50, 50) print(d)
import numpy as np import sympy import math def mod_inverse(x, y): modular_inverse = sympy.mod_inverse(x, y) return modular_inverse def solve_linear_congruence(a, b, m): """ Describe all solutions to ax = b (mod m), or raise ValueError. """ g = math.gcd(a, m) if b % g: raise ValueError("No solutions") a, b, m = a//g, b//g, m//g return pow(a, -1, m) * b % m, m def main(): # a*x ≡ 1 (mod p) # a*x = c # a = x_ * c p = 88619509055522082453204780866094153179701708680210152273575985657978607113243 x = 38751234384983559040347094325349107850289644025269636239010846543908547616067 #print(p) #print(x) #print(type(p)) #print(type(x)) #a = mod_inverse(x, p) # Python FTW x_ = pow(x, -1, p) print(x_) print(x_ * x) print(x_**2 % p) print(x_ * x % p) #res = solve_linear_congruence(x, 1 ,p) #print(res) if __name__ == "__main__": main()
# Define path_find as instructed in the email def path_find(n, start_loc, goal_loc, values): x_shift = [0,0,-1,1] #x_shift and y_shift will serve to shift the parent node either up, down, left or right y_shift = [-1,1,0,0] min_length = 10000 #Initialize min_lenght to a large number (as initial number for testing) visited = values #visited will be an nxn map (initialized with the original values) where -1 entries will imply visited nodes in a path. This will serve as a way to stop the algorithm from visiting nodes it already has been import Queue #Create a FIFO queue that will hold the nodes to expand on. A node will be comprised of 4 components: q = Queue.Queue() #Current location, Path taken, Lenght of path, Visited array described earlier (in that order) q.put((start_loc, [start_loc], 0, visited)) #Place start_loc into the queue as defined above while not q.empty(): #While there is still nodes to expand on, remove the node from the queue test = q.get() if test[0] == goal_loc and test[2]<min_length: #Check whether a path has reached the goal AND if the path length is min_length = test[2] #less than the current min_length. If so, change the values of best_path = test[1] #min_length and best_path else: for i in range(0,4): #Otherwise, loop through all 4 possible directions for a path to take row = test[0][0] + x_shift[i] #NOTE test[0][0] will be the first input of current location (row) col = test[0][1] + y_shift[i] #Check whether the new row and col is still in the grid of values AND whether this new location does not have a -1 in the visited array. If these are all satisfied, set the parent node in the visited array to -1 and place the new child node into the queue after updating all node components. if (row>0 and row<=n and col>0 and col<=n and test[3][row-1][col-1]!=-1): test[3][test[0][0]-1][test[0][1]-1]=-1 q.put(((row,col), test[1]+[(row,col)], test[2]+1+values[row-1][col-1], test[3])) return best_path #The best_path will be returned once all possible paths are considered. ##TESTING #n = 8 #start_loc = (2,3) #goal_loc = (8,7) #values = [[4,3,3,4,2,3,1,2],[2,4,6,1,3,4,2,2],[3,2,1,5,4,5,3,2],[2,9,3,4,12,5,1,2],[7,4,9,3,3,2,4,2],[3,9,11,3,2,1,8,4],[6,1,1,6,2,5,6,1],[1,14,19,9,4,1,5,2]] #n = 5 #start_loc = (1,1) #goal_loc = (5,4) #values = [[4,3,3,4,2],[2,4,4,2,2],[3,4,5,3,2],[2,3,4,5,2],[4,3,3,2,4]] #n = 3 #start_loc = (1,1) #goal_loc = (3,1) #values = [[3,1,2],[6,1,3],[2,1,5]] least_cost_path = path_find(n,start_loc,goal_loc,values) print(least_cost_path)
from itertools import product def change124(n): count = 1 digit = 1 while count != n : for i in product('124', repeat=digit): cur_num = ''.join(i) if count == n : break count += 1 digit += 1 return cur_num # 아래는 테스트로 출력해 보기 위한 코드입니다. print(change124(1))
palindrome = [] def get_palindrome(num1, num2): max_palindrome = 0 num2_org = num2 while num1 > (num1/10): #why not 99? and (num1/10)? while num2 > (num2/10): multiple = num1 * num2 if is_palindrome(multiple) and (max_palindrome < multiple): max_palindrome = multiple num2 -= 1 num1 -= 1 num2 = num2_org return max_palindrome def is_palindrome(multiple): if str(multiple) == str(multiple)[::-1]: #[::-1] 는 역순으로 한칸씩 return True else: return False print(get_palindrome(999, 999))
# 131. palindrome partitioning s = "aabaaabcba" # output = # [ # ["aa","b"], # ["a","a","b"] # ] def partition(s): if not s: return [[]] result = [] for i in range(len(s)): if isPalindrome(s[ : i+1]): print(partition(s[i+1 : ])) for r in partition(s[i+1 : ]): # print(r) result.append([s[ : i+1]] + r) return result def isPalindrome(s): return s == s[::-1]
# -*- coding: utf-8 -*- """ Created on Wed Mar 28 11:46:11 2018 @author: spoonertaylor This file is to answer #2 in STATS 701 HW9 Obtain simple summery stats (sample size, mean and variance). """ from mrjob.job import MRJob from mrjob.step import MRStep from functools import reduce import sys # Each MR Job makes you make a class that extends MRJob class MRWordFrequencyCount(MRJob): # Define the steps we are going to take to run this. def steps(self): return [ MRStep(mapper=self.mapper, reducer=self.reducer_sums), MRStep(reducer=self.reducer_stats)] # Mapper. For each word in the line, yield that word and a count of 1 def mapper(self, _, line): # Split each line l = line.split() if len(l) != 2: print(l) sys.exit(1) # Label is first label = int(l[0]) # Get value and cast to int values = float(l[1]) yield label, values # Value is of type generator. def reducer_sums(self, label, values): # Reduce by making a tuple, first element is N, # Second is summing up the values and third is summing up the squared values v = reduce(lambda x, y: (x[0]+1, x[1]+y, x[2]+y**2), values, (0.0,0.0,0.0)) yield (label, v)#(v[0], v[1]/v[0], v[2]/v[0])) def reducer_stats(self, label, values): # Our values, v, is now a generator but only of one thing since # we have already reduced. make it a list. mn_v = reduce(lambda x,y: (y[0], y[1]/y[0], y[2]/y[0]-(y[1]/y[0])**2), values, (0,0,0)) yield (label, mn_v) ### YOU MUST HAVE THESE LINES!!! if __name__ == '__main__': MRWordFrequencyCount.run()
# -*- coding=utf-8 -*- # @ Author:HeZichen # @ Email:irvingChen1518@gmail.com # @ Python script """ 迷宫寻宝env,探索一般自写RL环境的一般形式 ### 黑色矩形:地狱 --> [Reward=-1] 黄色圆形:天堂 --> [Reward=+1] 其他状态:地面 --> [Reward= 0] 红色矩形: 探索者... """ import numpy as np import time import sys if sys.version_info.major == 2: import Tkinter as tk else: import tkinter as tk UNIT = 5 MAZE_H = 100 MAZE_W = 100 class MAZE(tk.Tk,object): """ 迷宫环境...厉害了! """ def __init__(self): super(MAZE,self).__init__() self.action_space = ['u','d','l','r'] # 上下左右 self.n_actions = len(self.action_space) # action行为维度 self.title('maze') self.geometry('{0}x{1}'.format(MAZE_H*UNIT,MAZE_H*UNIT)) self._build_maze() def _build_maze(self): """搭建MAZE环境""" self.canvas = tk.Canvas(self,bg='gray',height=MAZE_H*UNIT,width=MAZE_W*UNIT) # 画布 # create grids for c in range(0,MAZE_W*UNIT,UNIT): x0,y0,x1,y1 = c,0,c,MAZE_H*UNIT # 画竖线 self.canvas.create_line(x0,y0,x1,y1) # 起始点、终点 for r in range(0,MAZE_H*UNIT,UNIT): x0,y0,x1,y1 = 0,r,MAZE_W*UNIT,r self.canvas.create_line(x0,y0,x1,y1) # 画横线 # create origin origin = np.array([20,20]) # 第一个grid(尺寸40)的中心' paradise = np.array([497.5,497.5]) # hell hell1_center = origin+np.array([UNIT*4,UNIT]) # hell的中心坐标 self.hell1 = self.canvas.create_rectangle(hell1_center[0]-15,hell1_center[1]-15, hell1_center[0]+15,hell1_center[1]+15, fill = 'white') # 起始点、终点 hell2_center = origin+np.array([UNIT,4*UNIT]) self.hell2 = self.canvas.create_rectangle(hell2_center[0]-15,hell2_center[1]-15, hell2_center[0]+15,hell2_center[1]+15, fill = 'white') # 最终奖励标志 # oval_center = origin+UNIT*4 oval_center = paradise self.oval = self.canvas.create_oval(oval_center[0]-2.5,oval_center[1]-2.5, oval_center[0]+2.5,oval_center[1]+2.5, fill = 'yellow') # explorer 探索者 self.rect = self.canvas.create_rectangle(origin[0]-15,origin[1]-15, origin[0]+15,origin[1]+15, fill = 'red') # pack all self.canvas.pack() def reset(self): """重置初始化""" self.update() time.sleep(0.5) self.canvas.delete(self.rect) # 回到原点 origin = np.array([20,20]) self.rect = self.canvas.create_rectangle(origin[0]-15,origin[1]-15, origin[0]+15,origin[1]+15, fill = 'red') # 返回rect的坐标 return self.canvas.coords(self.rect) def step(self,action): """执行action""" s = self.canvas.coords(self.rect) # 获得探索者坐标 base_action = np.array([0,0]) if action == 0: #up if s[1] > UNIT: base_action[1] -= UNIT elif action == 1: # down if s[1]<(MAZE_H - 1)*UNIT: base_action[1] += UNIT elif action == 2: # right if s[0]<(MAZE_W - 1)*UNIT: # 右边界 base_action[0] += UNIT elif action == 3: # left if s[0]>UNIT: # 左边界 base_action[0] -= UNIT self.canvas.move(self.rect,base_action[0],base_action[1]) # 移动探索者 s_ = self.canvas.coords(self.rect) # next_state # reward function if s_ == self.canvas.coords(self.oval): # 若当前位置在天堂处 reward = 1 done = True s_ = 'terminal' elif s_ in [self.canvas.coords(self.hell1),self.canvas.coords(self.hell2)]: # 跑到地狱去了 reward = -1 done = True s_ = 'terminal' else: reward = 0 done = False return s_, reward,done def render(self): """使能""" time.sleep(0.01) self.update() def update(env): for t in range(10): s = env.reset() while True: env.render() a = 1 s,r,done = env.step(a) if done or s: break # if __name__ == '__main__': # env = MAZE() # # env.after(100,update()) # # env.mainloop() # s = env.reset() # while True: # env.render() # a = 1 # s,r,done = env.step(a) # if s[1]==(MAZE_H-2)*UNIT: # s = env.reset()
import unittest from models import news NEWS = news.news class NewsTest(unittest.TestCase): ''' Test Class to test the behaviour of the Movie class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_news = News('cnn','CNN',"Faith Karimi, CNN","Georgia is reopening hair salons, gyms and bowling alleys despite a rise in coronavirus deaths statewide - CNN", "Undeterred by a barrage of criticism, Georgia is moving ahead with its plan to reopen some nonessential businesses despite an increase in coronavirus deaths statewide.", "https://www.cnn.com/2020/04/24/us/georgia-coronavirus-reopening-businesses-friday/index.html", "https://cdn.cnn.com/cnnnext/dam/assets/200423233851-georgia-businesses-reopen-0422-super-tease.jpg", "2020-04-24T10:35:51Z","(CNN)Undeterred by a barrage of criticism, Georgia is moving ahead with its plan to reopen some nonessential businesses despite an increase in coronavirus deaths statewide.\r\nGov. Brian Kemp was one of the last state leaders to issue a stay-at-home order effec… [+5500 chars]") def test_instance(self): self.assertTrue(isinstance(self.new_news,news)) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- """ Created on Fri Sep 3 15:59:28 2021 @author: USER """ # Condicionales # Tablas de verdad # Tabla del and # v and v = v # v and f = f # f and v = f # f and f = f print(True and True) # True print(True and False) # False print(False and True) # False print(False and False) # False # Tabla del or # v or v = v # v or f = v # f or v = v # f or f = f print(True or True) # True print(True or False) # True print(False or True) # True print(False or False) # False # Negacion print(not True) # False print(not False) # True # Mas de dos condicionales al mismo tiempo print(True and False and True or False or True or True) # True print(True and (False and True) or False or (True or True)) # True # Jerarquia de operaciones # 1. Parentesis y llaves # 2. Potencias y raices # 3. Multiplicacion y division # 4. Sumas y restas # Jerarquia de operaciones booleanas # 1. Parentesis y llaves # 2. Tabla de verdad # Estructura if x = -1 if (x > 0): print('1') else: print('2') # Haga un algoritmo que dada la edad de una persona, indique si es mayor # o menor de edad edad = int(input('Digite la edad de la persona: ')) if(edad >= 18): print('Si es mayor de edad') else: print('No es mayor de edad') # Haga un algoritmo que indique su un estudiante aprobo o reprobo una # asignatura, teniendo en cuenta que aprieba con minimo una # calificasion de 3.0 hasta 5.0 nota = float(input('Digite su nota: ')) if(nota >= 3.0 and nota <= 5.0): print('Aprobó') elif(nota < 3.0 and nota > 0): print('Reprobó') else: print('La nota ingresada no es válida') # Haga un algoritmo que diga si un numero es negativo, positivo o cero numero = float(input('Digite el número: ')) if(numero > 0): print('Positivo') elif(numero < 0): print('Negativo') else: print('El número es cero') # Ciclos # Ciclo for for _ in range(5): print('Perdon') for valor in range(11): print(valor) for valor in range(1, 11): print(valor) for valor in range(0, 13, 3): print(valor) for valor in range(11): print(valor) print(valor + 1) # Haga un algoritmo que reciba N notas de un estudiante y calcule el # promedio total cn = int(input('Digite la cantidad de notas: ')) if(cn > 0): acumulador = 0 for x in range(cn): nota = float(input(f'Digite la nota {x + 1}: ')) acumulador = acumulador + nota promedio = acumulador / cn # Para redondear el resultado promedio = round(promedio, 2) print(f'El promedio final es: {promedio}') else: print('El numero de notas no puede ser menor o igual a cero')
#string operations print('String Slicing') #for long string use (''') s= ''' WOW 0 0 ___ ''' print(s) print(type('Hello'),end='\n\n') print('Hello ' + 'Arjun',end='\n\n' ) #Type Conversion print(type(str(int(100)))) #converting int 100 into string print(type(int(str(100)))) #converting string 100 into int print(end='\n\n') #formatted strings name= 'Aj' age=21 print(f'Hi {name}. You are {age} years old',end='\n\n') #Normal method-print ('hi '+ name +'. You are '+ str(age)+' years old') #String Indexing op='0123456789' #012345678910 #[start:stop:stepover] print(f'We get all items: {op[0:10]}',end='\n\n') print(f'We get every second element: {op[0:9:2]}',end='\n\n') #02468 print(f'We get items starting from index 1: {op[1:]}',end='\n\n') #123456789 print(f'We get items upto index 5: {op[:5]}',end='\n\n') #0124 print(f'We get elements at gap of 1: {op[::1]}',end='\n\n') #0123456789 print(f'We get last item of string: {op[-1]}',end='\n\n') #negative index start from end i.e 9 here #reversing string print(f'It reverses the string: {op[::-1]}',end='\n\n') #9874563210 #Methods of String kj='Hello Arjun' print(f'We get string in Uppercase: {kj.upper()}',end='\n\n') print(f'We get Arjun replaced by Kunal: {kj.replace("Arjun","Kunal")}',end='\n\n') print(f'It finds the occurance of letter "u" in string: {kj.find("u")}',end='\n\n')
import json import random # Simple Script to read Strings from a file and convert them to json # and save them in a different file # Read and Convert with open('names.txt') as f: lines = f.readlines() res = [line.rstrip() for line in lines] # shuffle the list to mix girls names with boys names random.shuffle(res) names = json.JSONEncoder().encode(res) # Write with open('names.json', "w") as fout: fout.write(str(names))
def racecar(lst): n = len(lst) average = 0 for i in range(n): for j in range(0, len(lst)-1): # traverse the list from 0 to len(lst)-1 # Swap if the element found is greater # than the next element if lst[j] > lst[j + 1]: lst[j], lst[j + 1] = lst[j + 1], lst[j] average += 1 return average # Driver Code lst = [4, 3, 1, 2, 5] print(f"total count is {racecar(lst)}") """ """
class Person: def __init__(self, fname, lname): self.first = fname self.last = lname def print_person_name(self): print(self.first, self.last) class Student(Person): def __init__(self, fname, lname, yearofpassing): # there are two ways of calling the parent class's init object. one is using the normal ParentClassName.__init__(self,other paramteres) # Person.__init__(self, fname, lname) # the other option is calling the super fucntion, here you don't need to write the parent calss name as well as the self keyword super().__init__(fname, lname) self.gradyear = yearofpassing def showgradyear(self): print(self.gradyear) X = Student("Sagnik", "Mitra", 2022) X.showgradyear()
# pong game 0.3 import pygame import sys import random # initialize pygame mainClock = pygame.time.Clock() from pygame.locals import * pygame.init() clock = pygame.time.Clock() # making the screen screen_width = 1530 screen_height = 810 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("P0NG") # shapes that are empty rectangles without pygame.draw ball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30, 30) player = pygame.Rect(screen_width - 20, screen_height/2 - 70, 10, 140) opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140) bg_color = (0, 0, 0) white = (255, 255, 255) font = pygame.font.SysFont(None, 64) def ball_animation(): global ball_speed_x, ball_speed_y, player_score, opponent_score # increments the position of the ball with +ve and -ve values ball.x += ball_speed_x ball.y += ball_speed_y # -ve speed induces backwards movement if ball.top <= 0 or ball.bottom >= screen_height: ball_speed_y *= -1 if ball.left <= 0: player_score += 1 winlose() if ball.right >= screen_width: opponent_score += 1 winlose() if ball.colliderect(player) and ball_speed_x > 0: ball_speed_x *= -1 if ball.colliderect(opponent) and ball_speed_x < 0: ball_speed_x *= -1 def player_animation(): player.y += player_speed opponent.y += opponent_speed if player.top <= 0: player.top = 0 if player.bottom >= screen_height: player.bottom = screen_height if opponent.top <= 0: opponent.top = 0 if opponent.bottom >= screen_height: opponent.bottom = screen_height def winlose(): global ball_speed_x, ball_speed_y ball.center = (screen_width/2, screen_height/2) ball_speed_x *= random.choice((1, -1)) ball_speed_y *= random.choice((1, -1)) # the base speed of the ball ball_speed_x = 7 * random.choice((1, -1)) ball_speed_y = 7 * random.choice((1, -1)) # display text variables player_score = 0 opponent_score = 0 game_font = pygame.font.Font("freesansbold.ttf", 32) # players player_speed = 0 opponent_speed = 0 # game loop def draw_text(text, font, color, surface, x, y): textobj = font.render(text, 1, color) textrect = textobj.get_rect() textrect.topleft = (x, y) surface.blit(textobj, textrect) click = False def main_menu(): while True: screen.fill((0,0,0)) draw_text('Main Menu', font, (255, 255, 255), screen, 647, 810/2) draw_text('Pong - By R9', font, (255, 255, 255), screen, 20, 20) mx, my = pygame.mouse.get_pos() button_1 = pygame.Rect(665, 505, 200, 50) button_2 = pygame.Rect(665, 605, 200, 50) if button_1.collidepoint((mx, my)): if click: game() if button_2.collidepoint((mx, my)): if click: options() pygame.draw.rect(screen, (0, 0, 0), button_1) pygame.draw.rect(screen, (0, 0, 0), button_2) draw_text('Start', font, (255, 255, 255), screen, 665, 505) draw_text('Options', font, (255, 255, 255), screen, 665, 605) click = False for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: if event.button == 1: click = True pygame.display.update() mainClock.tick(60) def game(): global player_speed global opponent_speed while True: # input for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: player_speed += 7 if event.key == pygame.K_UP: player_speed -= 7 if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: player_speed -= 7 if event.key == pygame.K_UP: player_speed += 7 # player 2 if event.type == pygame.KEYDOWN: if event.key == pygame.K_s: opponent_speed += 7 if event.key == pygame.K_w: opponent_speed -= 7 if event.type == pygame.KEYUP: if event.key == pygame.K_s: opponent_speed -= 7 if event.key == pygame.K_w: opponent_speed += 7 ball_animation() player_animation() # objects screen.fill(bg_color) pygame.draw.rect(screen, white, player) pygame.draw.rect(screen, white, opponent) pygame.draw.ellipse(screen, white, ball) pygame.draw.aaline(screen, white, (screen_width/2, 0), (screen_width/2, screen_height)) # aaline stands for anti-aliasing line # text player_text = game_font.render(f"{player_score}", False, white) # the false is for anti-aliasing opponent_text = game_font.render(f"{opponent_score}", False, white) screen.blit(player_text, (1500, 20)) # this function says take the background surface and draw it onto the screen and position it at (x,y) screen.blit(opponent_text, (15, 20)) # updates the game window pygame.display.flip() clock.tick(60) def options(): running = True while running: screen.fill((0,0,0)) draw_text('options', font, (255, 255, 255), screen, 20, 20) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False pygame.display.update() mainClock.tick(60) main_menu()
teen_code = { "hc": "hoc", "ng" :"nguoi", "pt" :"biet", "eny" :"em nguoi yeu", "any" : "anh nguoi yeu", "ns":"noi", "ngta":"nguoi ta", "lm": "lam", "r" :"roi", "stt": "status" } loop = True while loop: for key in teen_code.keys(): print(key, end="\t") print() code= input("your code?") if code in teen_code: print("traslation:", teen_code[code]) else: add=input("add anything?(Y/N)").lower if add == "y": trans = input("your trans:") teen_code[code]= trans else: break
n = int(input("enter a 214number:")) while True: if n**(1/2)== 0: print("square number") break else: print("not square number") break
def cal(x,y,op): if op == "+": res = x + y elif op == "-": res = x - y elif op == "*": res = x * y elif op == "/": res = x / y return res # res=cal(2, 7,"*") # print (res)
from turtle import * speed(-1) shape("turtle") color("yellow") for i in range (100): circle(100) left(5) mainloop()
n = int(input(''' Enter the total number of 1 and 0:''')) for i in range (n): print("1","0",end="")
import pandas as pd def df_shape(x): return x.shape vehicles = pd.read_csv('data/vehicles.csv', sep=',') print("Dataframe shape:", df_shape(vehicles)) def df_rows(x): return len(x) print("Dataframe rows:", df_rows(vehicles)) def df_cols(x): return len(x.columns) print("Dataframe columns:", df_cols(vehicles)) def df_col_name(x): return x.columns.to_list() print("Column names:", df_col_name(vehicles))
x = int(input()) i = 2 while i < x: if x % i ==0: answer = i i = x else: i = i + 1 print(answer)
import math a = float(input()) b = float(input()) c = float(input()) di = b ** 2 - 4 * a * c if di > 0: x1 = (-b + math.sqrt(di)) / (2 * a) x2 = (-b - math.sqrt(di)) / (2 * a) elif di == 0: x = -b / (2 * a) print(x) else: print() if di > 0 and x1 < x2: print(x1, x2) else: print(x2, x1)
n = int(input()) lenght = 0 while n != 0: n = int(input()) lenght += 1 print(lenght)
a = int(input()) if a != 0 and a % 3 == 0 or a % 5 == 0: print('YES') else: print('NO')
# Part 3: Subqueries & Joins def top_postcodes_for_chain_stores(): """ From the businesses table, selects the top 10 most popular postal_codes. They are filtered to only count the restaurants owned by people/entities that own 5 or more restaurants. The result returns a row (postal_code, frequency) for each 10 selections, sorted by descending order to get the most relevant zip codes :return: a string representing the SQL query :rtype: str """ sqlite_query = """ SELECT b1.postal_code, COUNT(b1.business_id) as "count" FROM businesses as b1 WHERE b1.owner_name IN ( SELECT b2.owner_name FROM businesses as b2 GROUP BY b2.owner_name HAVING COUNT(b2.business_id) > 4 ) GROUP BY b1.postal_code ORDER BY count DESC LIMIT 10 """ return sqlite_query def inspection_scores_in_94103(): """ Let's get an idea about the inspection score our competition has. Based on multiple inspections, this gives the minimum Score ("min_score"), average Score ("avg_score"), and maximum Score ("max_score"), for all restaurant in post code "94103". The average score is rounded to one decimal. :return: a string representing the SQL query :rtype: str """ sqlite_query = """ SELECT min(score) as "min_score" , round(avg(score), 1) as "avg_score" , max(score) as "max_score" FROM inspections WHERE business_id IN (select business_id from businesses where postal_code = '94103') AND score <> 'None' """ return sqlite_query def risk_categories_in_94103(): """ How many times restaurants in Market street (postal_code: 94103) have committed health violations? Group them based on their risk category. The output is (risk_category, count as frequency) sorted in descending order by frequency :return: a string representing the SQL query :rtype: str """ sqlite_query = """ SELECT risk_category, COUNT(v.business_id) as "frequency" FROM violations as v INNER JOIN businesses as b ON v.business_id = b.business_id WHERE (postal_code = '94103') GROUP BY risk_category ORDER BY frequency DESC """ return sqlite_query
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 23 23:07:18 2019 @author: saurabh Write a Python program to reverse a word after accepting the input from the user. Sample Output: Input word: AcadGild Output: dilGdacA """ inp = input("Enter String :- ") print("Original String - ",inp) rev = inp[::-1] print("Reverse Of the String :- ",rev)
# Polynomial Lists # # In this program, we represent coefficients of polynomials as lists. # The list index corresponds to the polynomial term power (ie, list[0] holds # the coeffient for x**0, and so-on. ## Evaluate a Function ## def evaluatePoly(poly, x): ''' Computes the value of a polynomial function at given value x. Returns that value as a float. poly: list of numbers, length > 0 x: number returns: float ''' polyPower = 0.0 polyEval = 0.0 for polyCoefficient in poly: polyEval += (x**polyPower)*polyCoefficient polyPower+=1 return float(polyEval) ## Take a derivative of a function ## def computeDeriv(poly): ''' Computes and returns the derivative of a polynomial function as a list of floats. If the derivative is 0, returns [0.0]. In other words, we want the actual polynomial derivative, not the value of the derivative evaluated at a given point, x poly: list of numbers, length &gt; 0 returns: list of numbers (floats) ''' # Since we do not know ahead of time what polynomial is being # differentiated, we define a dynamic list. # FILL IN YOUR CODE HERE... if len(poly) == 1: return [0.0] else: polyDerivative = [] for polyPower in range(1,len(poly)): polyDerivative.append(float(polyPower*poly[polyPower])) return polyDerivative ## Main Program ## print evaluatePoly([0.0, 0.0, 5.0, 9.3, 7.0], -13) print computeDeriv([4, 0, 8, 1])
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re import os import shutil import commands """Copy Special exercise """ # +++your code here+++ # Write functions and modify main() to call them def get_files(dir): cmd = 'ls ' + dir #print 'calling get_files:',dir,'with command',cmd (status,output) = commands.getstatusoutput(cmd) abs_path = os.path.abspath(dir) #print abs_path files_in_path = [] if status: sys.stderr.write(output) else: files_in_path = output.split('\n') special_files = [] for file in files_in_path: if is_special(file): print file special_files.append(abs_path+'/'+file) return special_files def is_special(filename): """ Takes a filename with or without a prepended path and determins whether or not the file is 'special'. Specialness is determined based on whether or not the filename contains a string: __<stuff>__ """ #print "calling is_special:",filename matches = re.findall(r'__.*__',filename) if len(matches) > 0: return True return False def copy_to(paths,dir): """ Given a list of paths, copies special files into a directory, dir. """ if len(paths) == 0: sys.stderr.write("No paths to copy") sys.exit(1) for file in paths: print "copying",file,"to",dir shutil.copy(file,dir) #print "calling copy_to",paths,dir return def zip_to(paths,zippath): """ given a list of paths, zip those files up into zippath """ cmd = 'zip -j '+zippath+' '+' '.join(paths) print cmd (status,output) = commands.getstatusoutput(cmd) if status: sys.stderr.write('Problem zipping files!') sys.exit(1) else: print 'zipping successful!' return def main(): # This basic command line argument parsing code is provided. # Add code to call your functions below. # Make a list of command line arguments, omitting the [0] element # which is the script itself. args = sys.argv[1:] print "CHECK THAT ARGS ARE EXACTLY --todir or --tozip" if not args: print "usage: [--todir dir][--tozip zipfile] dir [dir ...]"; sys.exit(1) # todir and tozip are either set from command line # or left as the empty string. # The args array is left just containing the dirs. # Order of arguments matters. todir = '' if args[0] == '--todir': print 'deleting todir!' todir = args[1] print todir del args[0:2] tozip = '' if args[0] == '--tozip': print 'deleting tozip!' tozip = args[1] del args[0:2] if len(args) == 0: print "error: must specify one or more dirs" sys.exit(1) # +++your code here+++ # Call your functions print args for dir in args: if todir: # copy directories copy_to(get_files(dir),todir) elif tozip: # zip special files to zip file zip_to(get_files(dir),tozip) if __name__ == "__main__": main()
import time balance = 987654321 startingBalance = balance annualInterestRate = 0.02 monthlyPaymentRate = 0.04 monthlyInterestRate = annualInterestRate / 12 TotalPaid = 0.00 LowerBound = balance / 12 UpperBound = (balance * (1+monthlyInterestRate)**12)/12 #print FixedPayment def Balance(PrevBalance, MonthlyPayment, Interest): currentBalance = (PrevBalance - MonthlyPayment)*(1.00 + Interest) return currentBalance def minPayment(X): minPayment = X * monthlyPaymentRate return minPayment def guess(a, b): midPoint = (a + b) / 2 return midPoint def endingBalance(balance, monthlyInterestRate): i = 1 while (i <= 12): #payment = balance = Balance(balance, guess(LowerBound, UpperBound), monthlyInterestRate) i = i + 1 return balance while (abs(startingBalance) > 0.001): startingBalance = balance FixedPayment = guess(LowerBound, UpperBound) startingBalance = endingBalance(startingBalance, monthlyInterestRate) #print startingBalance if (startingBalance < 0): UpperBound = guess(LowerBound, UpperBound) #print ("UpperBound is: " + str(UpperBound)) else: LowerBound = guess(LowerBound, UpperBound) #print ("lowerbound is: " + str(LowerBound)) print ("Lowest Payment is: " + str(round(FixedPayment, 2))) print ("Time: " + str(time.clock())) #endingBalance(balance, monthlyInterestRate)
import sys class FunTime: # no such thing as private variable, but convention is to # prepend '_' to something that is private. # Note too that variables do not need to be explicitly called, # they are available as soon as we define them, within the scope # of the class. # or: _concat = '' def __init__(self,name='',val=''): print('initializing FunTime') self.name = name self.val = val # or self._concat = '' def Concat(self): self._concat = str(self.val)+str(self.name) def GetConcat(self): return self._concat def main(): # Default arguments allow an 'empty class call' inst1 = FunTime() # Unnamed arguments require correct order inst2 = FunTime("Sally","2131") # Named arguments are placed correctly inst3 = FunTime(val="4216",name="Thomas") # Error prone if you do not use named arguments. inst4 = FunTime("124","NAAME") # Can individually define the class by calling members directly inst1.name = "Harry" inst1.val = "12" inst1.Concat() inst2.Concat() inst3.Concat() inst4.Concat() # Demo what's going on print(inst1.GetConcat()) # does the right thing print(inst2.GetConcat()) # does the right thing print(inst3.GetConcat()) # does the right thing print(inst4.GetConcat()) # ERROR, arguments were supplied in wrong order! return 0 if __name__ == "__main__": sys.exit(main())
import random, pylab def generateScores(trials): gradeList = [] for trial in range(0,trials): midterm1 = random.randint(50,80) midterm2 = random.randint(60,90) final = random.randint(55,95) score = 0.25*midterm1 + 0.25*midterm2+0.5*final gradeList.append(score) return gradeList def plotQuizzes(): scores = generateScores(10000) pylab.hist(scores,7) pylab.title("Distribution of Scores") pylab.xlabel("Final Score") pylab.ylabel("Number of Trials") pylab.show()
""""Ricky Tran - 1832920""" integers = input().split(' ') numbers = [] for num in integers: num = int(num) numbers.append(num) positive = [] for num in numbers: if num >= 0: positive.append(num) positive.sort() for num in positive: print(num, end=' ')
""""Ricky Tran - 1832920""" p1jn = int(input('Enter player 1\'s jersey number:\n')) p1r = int(input('Enter player 1\'s rating:\n')) print() p2jn = int(input('Enter player 2\'s jersey number:\n')) p2r = int(input('Enter player 2\'s rating:\n')) print() p3jn = int(input('Enter player 3\'s jersey number:\n')) p3r = int(input('Enter player 3\'s rating:\n')) print() p4jn = int(input('Enter player 4\'s jersey number:\n')) p4r = int(input('Enter player 4\'s rating:\n')) print() p5jn = int(input('Enter player 5\'s jersey number:\n')) p5r = int(input('Enter player 5\'s rating:\n')) print() roster = {} roster[p1jn] = p1r roster[p2jn] = p2r roster[p3jn] = p3r roster[p4jn] = p4r roster[p5jn] = p5r print('ROSTER') for jersey, rating in sorted(roster.items()): print('Jersey number: {}, Rating: {}'.format(jersey, rating)) menu = ('\nMENU\n' 'a - Add player\n' 'd - Remove player\n' 'u - Update player rating\n' 'r - Output players above a rating\n' 'o - Output roster\n' 'q - Quit\n') print(menu, end='\n') option = '' while (option != 'q'): option = input('Choose an option:\n') if option == 'o': print('ROSTER') for jersey, rating in sorted(roster.items()): print('Jersey number: {}, Rating: {}'.format(jersey, rating)) print(menu, end='\n') if option == 'a': npjn = int(input('Enter a new player\'s jersey number:\n')) npr = int(input('Enter a new player\'s rating:\n')) nroster = {} nroster[npjn] = npr roster.update(nroster) nroster.clear() print(menu, end='\n') if option == 'd': dp = int(input('Enter a jersey number:\n')) roster.pop(dp) print(menu, end='\n') if option == 'r': ar = int(input('Enter a rating:\n')) print('ABOVE', ar) for jersey, rating in sorted(roster.items()): if rating > ar: print('Jersey number: {}, Rating: {}'.format(jersey, rating)) print(menu, end='\n') if option == 'u': ujr = int(input('Enter a jersey number:\n')) ur = int(input('Enter a new rating for player:\n')) roster[ujr] = ur print(menu, end='\n')
temperatuur = int(input("Palun sisestage õhutemperatuur: ")) jaatumis_oht = 4.00 if jaatumis_oht > temperatuur: print("On jäätumise oht") if jaatumis_oht < temperatuur: print("Ei ole jäätumis oht") if jaatumis_oht == temperatuur: print("On jäätumise oht") # Õpetaja versioon # temperatuur = float(input("Sisesta õhutemperatuur: ")) #if temperatuur > 4.0: # print("Ei ole jäätumis oht") #else: # print("On olemas jäätumise oht")
# https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ def lengthOfLongestSubstring(s): # Solution 1 # run from left # initalize: right = 1 res = 0 di = {} if len(s) == 1: return 1 if len(s) == 0: return 0 for left in range(len(s)): # Add the fist element into dictionary if left == 0: di[s[left]] = left # for current window(start from left point) # move right step by step and see if it has repeated while right < len(s) and right >= left: # if current right point char is not in dict # add it and its current pos (right) into dict if s[right] not in di: di[s[right]] = right else: # if lat repeated element occured pos is smaller than current windows first pos(left), # it means that current window does not has this element and we can just ignore this repetiton # if not, it means that the repetiton occurs and we should update the max_len = res left = max(di[s[right]] + 1, left) # update pos of the repeated element di[s[right]] = right # right is point to the repeated char now res = max(res, right - left + 1) right += 1 # Solution 2 # run from right # less O # mapSet = {} # start, result = 0, 0 # for end in range(len(s)): # if s[end] in mapSet: # start = max(mapSet[s[end]], start) # result = max(result, end-start+1) # mapSet[s[end]] = end+1 return res s = "acbabbca" print(lengthOfLongestSubstring(s))
#!/usr/bin/env python3 """ Assignment 1 CSSE1001/7030 Semester 2, 2018 """ import string from a1_support import is_word_english, is_numeric from typing import List, Tuple __author__ = "Weiting Yin" # Write your functions here def generate_ascii_lowercase() -> str: """(str) Return a 26 english letters in lowercase -> abcdefghijklmnopqrstuvwxyz """ return string.ascii_lowercase[:] def generate_ascii_uppercase() -> str: """(str) Return a 26 english letters in uppercase -> ABCDEFGHIJKLMNOPQRSTUVWXYZ """ return string.ascii_uppercase[:] def generate_ascii() -> str: """(str) Return a 52 english letters with both lowercase and uppercase -> abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ """ return string.ascii_letters[:] def translate_text(target_str: str, base_str: str, shift_str: str) -> str: """ (str) Returns string be translated according to the template, template is generated by the last two parameters Parameter: target_str (str): the target str that needed to be translated base_str (str): the template base url shift_str (str): the shift str that make all the base_str in target_str replaced to this str """ template = str.maketrans(base_str, shift_str) return target_str.translate(template) def generate_shift_str(base_str: str, offset: int) -> str: """ (str) Returns the shifted str based on the offset Parameter: base_str (str): the base str that needed to be shifted offset (int): the shift number """ shift_str = base_str[offset:] + base_str[:offset] return shift_str def generate_shifted_ascii(offset: int) -> str: """ (str) Returns the shifted ascii str based on the offset Parameter: offset (int): the shift number """ lowercase_ascii = generate_ascii_lowercase() uppercase_ascii = generate_ascii_uppercase() shifted_lowercase_ascii = generate_shift_str(lowercase_ascii, offset) shifted_uppercase_ascii = generate_shift_str(uppercase_ascii, offset) shifted_ascii = shifted_lowercase_ascii + shifted_uppercase_ascii return shifted_ascii def remove_dash(dashed_list: list) -> List[str]: """(list) Returns the list that translate the dashed_list to no dash list Parameter: dashed_list (list): word list contains dash """ result: List[str] = [] word: str for word in dashed_list: if '-' in word: new_list: List[str] = word.split('-') result.extend(new_list) else: result.append(word) return result def ignore_contractions(apostrophe_list: list) -> List[str]: """(list) Returns the list that remove all the words contains contractions Parameter: apostrophe_list (list): word list contains contractions """ result: List[str] = apostrophe_list[:] word: str for word in result: if "'" in word: result.remove(word) return result def get_alpha_word(word: str) -> str: """(str) return the str that only contains alpha letters Parameter: word (str): word that contains non-alpha letters """ alpha_word: str = '' for letter in word: if letter.isalpha(): alpha_word += letter return alpha_word def cypher(text: str, offset: int) -> str: """ (str) Returns the cyphered text Parameter: text (int): the input text needed to be cyphered offset (int): the number of shift of each letter, between 1 and 25, inclusive """ ascii_text: str = generate_ascii() original_text: str = text[:] cyphertext: str = '' for each_offset in range(1, 26): if offset == 0: shifted_ascii: str = generate_shifted_ascii(each_offset) cyphertext += f'\n {each_offset:0=2d}: ' \ + translate_text(original_text, ascii_text, shifted_ascii) else: shifted_ascii: str = generate_shifted_ascii(offset) cyphertext += translate_text(original_text, ascii_text, shifted_ascii) break return cyphertext def encrypt(text: str, offset: int) -> str: """ (str) Returns the encrypted text Parameter: text (int): the input text needed to be encrypted offset (int): the number of shift of each letter, between 1 and 25, inclusive """ encrypted_text: str = cypher(text, offset) return encrypted_text def decrypt(text: str, offset: int) -> str: """ (str) Returns the decrypted text Parameter: text (int): the input text needed to be decrypt offset (int): the number of shift of each letter, between 1 and 25, inclusive """ decrypted_text: str = cypher(text, -offset) return decrypted_text def find_encryption_offsets(encrypted_text: str) -> Tuple[int]: """ (tuple) Returns the offset which could make encrypted_text decrypted to a english text if no such offset, nothing will be append to the turple Parameter: encrypted_text (int): the input text that was encrypted """ offsets: List[int] = [] for offset in range(1, 26): decrypted_text: str = decrypt(encrypted_text, offset) decrypted_text_list: List[str] = [word for word in decrypted_text.split(' ')] decrypted_text_list = ignore_contractions(remove_dash(decrypted_text_list)) decrypted_text_list: List[str] = list(map(get_alpha_word, decrypted_text_list)) lower_word_list: List[str] = [word.lower() for word in decrypted_text_list] is_english_list: List[bool] = list(map(is_word_english, lower_word_list)) if all(is_english_list): offsets.append(offset) return tuple(offsets) def question_e() -> bool: """ (Bool) The function will show question a content and show relative result and then return True to represent question asking will continue Parameter: (void) No parameter, only process question """ text_to_encrypt: str = input('Please enter some text to encrypt: ') offset: str = input('Please enter a shift offset (1-25): ') if is_numeric(offset): encrypted_text = encrypt(text_to_encrypt, int(offset)) if offset == '0': print(f'The encrypted text is:{encrypted_text}') else: print(f'The encrypted text is: {encrypted_text}') print() return True def question_d() -> bool: """ (Bool) The function will show question a content and show relative result and then return True to represent question asking will continue Parameter: (void) No parameter, only process question """ text_to_encrypt: str = input('Please enter some text to decrypt: ') offset: str = input('Please enter a shift offset (1-25): ') if is_numeric(offset): decrypted_text = decrypt(text_to_encrypt, int(offset)) if offset == '0': print(f'The decrypted text is:{decrypted_text}') else: print(f'The decrypted text is: {decrypted_text}') print() return True def question_a() -> bool: """ (Bool) The function will show question a content and show relative result and then return True to represent question asking will continue Parameter: (void) No parameter, only process question """ result = '' encrypted_text = input('Please enter some encrypted text: ') offsets: Tuple[int] = find_encryption_offsets(encrypted_text) if len(offsets) == 1: encryption_offset = ''.join(str(offsets[0])) decrypted_message = decrypt(encrypted_text, offsets[0]) result += f'Encryption offset: {encryption_offset}\n' \ + f'Decrypted message: {decrypted_message}' elif len(offsets) > 1: multi_encryption_offsets = ', '.join(map(str, offsets)) result += f"Multiple encryption offsets: {multi_encryption_offsets}" else: result += 'No valid encryption offset' print(result) print() return True def question_q() -> bool: """ (Bool) print 'bye' and then return False to represent the program will be terminated Parameter: (void) No parameter, only process question """ print('Bye!') return False def show_question() -> str: """ (Str) The function will show all the questions and allow user to choose one The user choice will be returned Parameter: (void) """ question = 'Please choose an option [e/d/a/q]:\n' \ + ' e) Encrypt some text\n' \ + ' d) Decrypt some text\n' \ + ' a) Automatically decrypt English text\n' \ + ' q) Quit\n' \ + '> ' user_option = input(question) return user_option def do_question(user_option: str) -> bool: """ (Bool) The function will provide relevant answers according to each question if relevant question number is input, 'Invalid command' will pop up every question will continue show up unless user input q, wich will generate False in the result, and the loop will be terminated Parameter: (void) """ continued = True options = { 'e': question_e, 'd': question_d, 'a': question_a, 'q': question_q, } if user_option in options.keys(): continued: bool = options[user_option]() else: print('Invalid command\n') return continued def show_title() -> None: """(Void) show the start title of the program Parameter: (void) """ print('Welcome to the simple encryption tool!\n') def process() -> None: """(Void) The function will process the program and decide whether to stop depends on user choice Parameter: (void) """ while True: user_option = show_question() continued: bool = do_question(user_option) if not continued: break def main() -> None: """ (void) The main function to show question and provide relevant value Parameter: (void) """ show_title() process() ################################################## # !! Do not change (or add to) the code below !! # # # This code will run the main function if you use # Run -> Run Module (F5) # Because of this, a "stub" definition has been # supplied for main above so that you won't get a # NameError when you are writing and testing your # other functions. When you are ready please # change the definition of main above. ################################################### if __name__ == '__main__': main()
from tkinter import * # Button click def btnClick(numbers): global operator operator = operator + str(numbers) text_input.set(operator) # Clear button def btnClearDisplay(): global operator operator = '' text_input.set('') # Equal Button def btnEqualsInput(): global operator sumup = str(eval(operator)) text_input.set(sumup) # Creation of the Calculator's 'body' cal = Tk() cal.title('Calculator') operator = '' text_input = StringVar() # Calculator's Text Display txtDisplay = Entry(cal, textvariable=text_input, bd=30, insertwidth=4, bg='grey', justify='right').grid(columnspan=4) # ============================================================================= # Before going to the code, it is important for you to understand the parameters in each button: # padx - Padding of the button # bd - Button size # fg - Font Color # font - Text Font and Size # text - The Text Shown On The Button # bg - Background Color # command - the execution once that button is clicked # ============================================================================= # Button 7, 8, 9, Sum - First row btn7 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="7", bg='grey', command=lambda: btnClick(7)).grid(row=1, column=0) btn8 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="8", bg='grey', command=lambda: btnClick(8)).grid(row=1, column=1) btn9 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="9", bg='grey', command=lambda: btnClick(9)).grid(row=1, column=2) add_btn = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="+", bg='grey', command=lambda: btnClick('+')).grid(row=1, column=3) # ============================================================================= # Button 4, 5, 6, Subtract - Second row btn4 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="4", bg='grey', command=lambda: btnClick(4)).grid(row=2, column=0) btn5 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="5", bg='grey', command=lambda: btnClick(5)).grid(row=2, column=1) btn6 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="6", bg='grey', command=lambda: btnClick(6)).grid(row=2, column=2) sub_btn = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="-", bg='grey', command=lambda: btnClick('-')).grid(row=2, column=3) # ============================================================================= # Button 1, 2, 3, Multiply - Third row btn1 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="1", bg='grey', command=lambda: btnClick(1)).grid(row=3, column=0) btn2 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="2", bg='grey', command=lambda: btnClick(2)).grid(row=3, column=1) btn3 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="3", bg='grey', command=lambda: btnClick(3)).grid(row=3, column=2) mult_btn = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="*", bg='grey', command=lambda: btnClick('*')).grid(row=3, column=3) # ============================================================================= # Button 0, Clear, Equal, Divide - Last row btn0 = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="0", bg='grey', command=lambda: btnClick(0)).grid(row=4, column=1) clear_btn = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="C", bg='grey', command=lambda: btnClearDisplay()).grid(row=4, column=0) equal_btn = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="=", bg='grey', command=btnEqualsInput).grid(row=4, column=2) div_btn = Button(cal, padx=16, bd=5, fg='white', font=('arial', 20), text="/", bg='grey', command=lambda: btnClick('/')).grid(row=4, column=3) # ============================================================================ # Execute the code in a loop that won't close except the user closes the calculator's tab cal.mainloop()
import sqlite3 import csv conn = sqlite3.connect('map_bellevue.db') conn.text_factory = str c = conn.cursor() def create_tables(): c.execute('CREATE TABLE IF NOT EXISTS nodes(id INTEGER PRIMARY KEY NOT NULL, lat REAL, lon REAL, user TEXT, uid INTEGER, version INTEGER, changeset INTEGER, timestamp TEXT)') c.execute('CREATE TABLE IF NOT EXISTS nodes_tags(id INTEGER, key TEXT, value TEXT, type TEXT, FOREIGN KEY (id) REFERENCES nodes(id))') c.execute('CREATE TABLE IF NOT EXISTS ways(id INTEGER PRIMARY KEY NOT NULL, user TEXT, uid INTEGER, version TEXT, changeset INTEGER, timestamp TEXT)') c.execute('CREATE TABLE IF NOT EXISTS ways_tags(id INTEGER NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, type TEXT, FOREIGN KEY (id) REFERENCES ways(id))') c.execute('CREATE TABLE IF NOT EXISTS ways_nodes(id INTEGER NOT NULL,node_id INTEGER NOT NULL, position INTEGER NOT NULL, FOREIGN KEY (id) REFERENCES ways(id), FOREIGN KEY (node_id) REFERENCES nodes(id))') create_tables() # insert nodes.csv to nodes table def insert_nodes(): # read in the data - read in the csv file as a dictionary, # format the data as a list of tuples: with open('nodes.csv','r') as csvfile: # csv.DictReader uses first line in file for column headings by default reader = csv.DictReader(csvfile) # comma is default delimiter to_db = [(r['id'], r['lat'],r['lon'], r['user'], r['uid'], r['version'], r['changeset'], r['timestamp']) for r in reader] # insert the data c.executemany('INSERT INTO nodes(id, lat, lon, user, uid, version, changeset, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?);', to_db) # commit the changes conn.commit() # insert nodes_tags.cv to nodes_tags table def insert_nodes_tags(): # read in the data - read in the csv file as a dictionary, # format the data as a list of tuples: with open('nodes_tags.csv','r') as csvfile: # csv.DictReader uses first line in file for column headings by default reader = csv.DictReader(csvfile) # comma is default delimiter to_db = [(r['id'], r['key'],r['value'], r['type']) for r in reader] # insert the data c.executemany('INSERT INTO nodes_tags(id, key, value,type) VALUES (?, ?, ?, ?);', to_db) # commit the changes conn.commit() # insert ways.csv to ways table def insert_ways(): # read in the data - read in the csv file as a dictionary, # format the data as a list of tuples: with open('ways.csv','r') as csvfile: # csv.DictReader uses first line in file for column headings by default reader = csv.DictReader(csvfile) # comma is default delimiter to_db = [(r['id'], r['user'], r['uid'], r['version'], r['changeset'], r['timestamp']) for r in reader] # insert the data c.executemany('INSERT INTO ways(id, user, uid, version, changeset, timestamp) VALUES (?, ?, ?, ?, ?, ?);', to_db) # commit the changes conn.commit() # insert ways_tags.csv to ways_tags table def insert_ways_tags(): # read in the data - read in the csv file as a dictionary, # format the data as a list of tuples: with open('ways_tags.csv','r') as csvfile: # csv.DictReader uses first line in file for column headings by default reader = csv.DictReader(csvfile) # comma is default delimiter to_db = [(r['id'], r['key'],r['value'], r['type']) for r in reader] # insert the data c.executemany('INSERT INTO ways_tags(id, key, value,type) VALUES (?, ?, ?, ?);', to_db) # commit the changes conn.commit() # insert ways_nodes.csv to ways_nodes table def insert_ways_nodes(): # read in the data - read in the csv file as a dictionary, # format the data as a list of tuples: with open('ways_nodes.csv','r') as csvfile: # csv.DictReader uses first line in file for column headings by default reader = csv.DictReader(csvfile) # comma is default delimiter to_db = [(r['id'], r['node_id'],r['position']) for r in reader] # insert the data c.executemany('INSERT INTO ways_nodes(id, node_id, position) VALUES (?, ?, ?);', to_db) # commit the changes conn.commit() # execute all functions to insert data to sql tables insert_nodes() insert_nodes_tags() insert_ways() insert_ways_nodes() insert_ways_tags() conn.close()
import unittest from player import Player class TestGame(unittest.TestCase): def test_get_guess_returns_int(self): player = Player("test", 5) guess = player.get_guess() self.assertIsInstance(guess, int) def test_get_guess_same_seed_same_number(self): player = Player("test", 5) guess1 = player.get_guess(seed=5) guess2 = player.get_guess(seed=5) self.assertEqual(guess1, guess2) def test_get_guess_defaults(self): player = Player("test", 5) guess = player.get_guess() result = guess in range(0,11) self.assertEqual(result, True) def test_get_guess_change_to_from_int(self): player = Player("test", 5) guess = player.get_guess(_from=0, _to=2) result = guess in range(0,3) self.assertEqual(result, True) def test_get_guess_change_to_from_float(self): player = Player("test", 5) guess = player.get_guess(_from=0, _to=2.3) result = guess in range(0,3) self.assertEqual(result, True) def test_get_defense_array_defaults(self): player = Player("test", 5) defense_array = player.get_defense_array() self.assertEqual(5, len(defense_array)) def test_get_defense_array_returns_int_array(self): player = Player("test", 5) defense_array = player.get_defense_array() for item in defense_array: self.assertIsInstance(item, int) def test_get_defense_array_change_to_from_int(self): player = Player("test", 5) defense_array = player.get_defense_array(_from=0, _to=6) for item in defense_array: res = item in range(0,7) self.assertEqual(res, True) def test_get_defense_array_change_to_from_float(self): player = Player("test", 5) defense_array = player.get_defense_array(_from=0, _to=6.6) for item in defense_array: res = item in defense_array self.assertIsInstance(res, int) def test_get_defense_array_zero_defense_array_length(self): player = Player("test", 5) defense_array = player.get_defense_array() self.assertEqual(5, len(defense_array)) if __name__ == '__main__': unittest.main()
total = float(input()) real = int(total) moedas = int((total - real) * 100) print("NOTAS:") troco = int(real / 100) real = real % 100 print(troco, "nota(s) de R$ 100.00") troco = int(real / 50) real = real % 50 print(troco, "nota(s) de R$ 50.00") troco = int(real / 20) real = real % 20 print(troco, "nota(s) de R$ 20.00") troco = int(real / 10) real = real % 10 print(troco, "nota(s) de R$ 10.00") troco = int(real / 5) real = real % 5 print(troco, "nota(s) de R$ 5.00") troco = int(real / 2) real = real % 2 print(troco, "nota(s) de R$ 2.00") troco = int(real / 1) real = real % 1 print("MOEDAS:") print(troco, "moeda(s) de R$ 1.00") troco = int(moedas / 50) moedas = moedas % 50 print(troco, "moeda(s) de R$ 0.50") troco = int(moedas / 25) moedas = moedas % 25 print(troco, "moeda(s) de R$ 0.25") troco = int( moedas / 10) moedas = moedas % 10 print(troco, "moeda(s) de R$ 0.10") troco = int(moedas / 5) moedas = moedas % 5 print(troco, "moeda(s) de R$ 0.05") troco = int(moedas / 1) moedas = moedas % 1 print(troco, "moeda(s) de R$ 0.01")
#!/usr/bin/python import sys # Loop around the data # It will be in the format "questionId type" # All child nodes for a given question will be present # # The task for this reducer is to get a count of all the answers and comments a given question has. # The reducer will output the question node id for each question that doesn't have an answer or comment. # # This map reduce pair would be something similar to the following SQL statement # select a.node_id from forum_node a where a.node_id not in (select distinct b.abs_parent_id from forum_node b) class QuestionCount(object): questionId=0 commentCount=0 answerCount=0 def reducer(): oldQuestion = None # Loop around the data questionData = QuestionCount(); for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 2: # Something has gone wrong. Skip this line. continue question, type = data_mapped if oldQuestion and oldQuestion != question: #Here we can do all the processing we want to do on a question regarding its count #For this case I am interested in getting a list of the questions that don't have #any answers or comments if questionData.answerCount==0 and questionData.commentCount==0 : print oldQuestion #print out the question's node id oldQuestion = question; questionData = QuestionCount(); oldQuestion = question if type == "answer": questionData.answerCount += 1 elif type == "comment": questionData.commentCount += 1 elif type == "question": questionData.questionId=question if oldQuestion != None and questionData.answerCount==0 and questionData.commentCount==0: print oldQuestion #print out the question's node id reducer()
# # Print 사용법 # # # print('Python Start!') # print("Python Start!") # print('''Python Start!''') # print("""Python Start!""") # # print() # print() # print() # # # print('p', 'y', 't', 'h', 'o', 'n', sep='') # # print("welcome to ", end='') # print("IT news", end='') # # import sys # # # print('Lean Python', file='') # # print('%s %s' % ('one', 'two')) print('{} {}'.format('one', 'two')) print('{1} {0}'.format('one', 'two')) print('sout')
#coding=utf-8 ''' Created on 2015年4月29日 @author: shenlinan ''' #print'HelloWorld','double','bye' #print 100+200 #name = raw_input() #print '3班23号:'+name # #a=100 #if a>0: # print a #else: # print -a # #print '''line1\nline2...line3''' age = input('请输入您的年龄:') if age>=18: print '成年人' else: print '未成年'
# coding=utf-8 import random def insertion_sort(a_list): """Take a list and sort it using insertion_sort.""" for item in a_list[1:]: current_val_index = a_list.index(item) left_index = current_val_index - 1 while left_index >= 0 and a_list[left_index] > item: a_list[left_index + 1] = a_list[left_index] left_index = left_index - 1 a_list[left_index + 1] = item return a_list if __name__ == '__main__': """Run in console.""" import timeit ordered_list = [] unordered_list = [] reversed_list = [] for item in range(10000): ordered_list.append(item) for item in range(10000): unordered_list.append(random.randint(0, 10000)) for item in range(10000, 0, -1): reversed_list.append(item) def get_ordered_list(): """Call insertion_sort on ordered list.""" insertion_sort(ordered_list) def get_unordered_list(): """Call insertion_sort on unordered list.""" insertion_sort(unordered_list) def get_reversed_list(): """Call insertion_sort on reversed list.""" insertion_sort(reversed_list) print('The Insertion Sort function sorts a list item in comparison to the' ' other items in the list before it.') print('Insertion Sort time on an ordered list of 10000: ', timeit.timeit( 'get_ordered_list', setup='from __main__ import get_ordered_list')) print('Insertion Sort time on an unordered list of 10000: ', timeit.timeit( 'get_unordered_list', setup='from __main__ import get_unordered_list' )) print('Insertion Sort time on an reversed list of 10000: ', timeit.timeit( 'get_reversed_list', setup='from __main__ import get_reversed_list'))
# coding=utf-8 from linked_list import LinkedList from linked_list import Node class DoubleLink(object): """Create a double linked list.""" def __init__(self): """Initialize the double linked list.""" self.prev = None self.head = None self.length = 0 self.linked_list = LinkedList() def insert(self, value): """Insert a value onto the double linked list.""" try: for i in value: new_node_value = Node(i) if self.head is None: self.head = new_node_value self.length += 1 else: new_node_value.next_node = self.head new_node_value.next_node.prev = new_node_value self.head = new_node_value self.length += 1 except TypeError: new_node_value = Node(value) if self.head is None: self.head = new_node_value self.length += 1 else: new_node_value.next_node = self.head new_node_value.next_node.prev = new_node_value self.head = new_node_value self.length += 1 def append(self, value): """Append a value to the end of a double link list.""" current_node = self.head if current_node is not None: while current_node.next_node is not None: current_node = current_node.next_node new_node = Node(value) current_node.next_node = new_node new_node.prev = current_node else: new_node = Node(value) current_node = new_node self.head = current_node def pop(self): """Remove the first value of the list.""" pop_value = self.head.value self.head = self.head.next_node self.length -= 1 return pop_value def shift(self): """Remove the last value of the list.""" current_node = self.head if current_node is not None: while current_node.next_node is not None: current_node = current_node.next_node try: current_node.prev.next_node = None except AttributeError: current_node.next_node = None self.head = None return current_node.value def remove(self, value): """Remove a specified value from the list.""" current_node = self.head if current_node is not None: while current_node.next_node is not None: if (current_node.value == value): node_val = current_node current_node = current_node.next_node if (current_node.value == value): node_val = current_node prev_node = node_val.prev next_node = node_val.next_node node_val.prev.next_node = next_node node_val.next_node.prev = prev_node
# coding=utf-8 from linked_list import LinkedList # from linked_list import Node class Stack(object): """Create a new Stack.""" def __init__(self, value): """Initialize the stack.""" self.head = None self.length = 0 self.stack = LinkedList() self.stack.insert(value) def push(self, value): """Push a new value onto the stack.""" self.stack.insert(value) def pop(self): """Remove the first value on the stack.""" pop_val = self.stack.pop() return pop_val
# -*- coding: utf-8 -*- def test_hash(): """Test hash function.""" from hash_table import HashTable new_hash = HashTable(100) hashed = new_hash._hash('string') assert hashed < len(new_hash.table) assert isinstance(hashed, int) def test_set(): """Test set function.""" from hash_table import HashTable new_hash = HashTable(1) new_hash.set('chicken', 'robot') assert new_hash.table[0][0][0] == 'chicken' assert new_hash.table[0][0][1] == 'robot' assert new_hash.table[0][0] == ('chicken', 'robot') def test_get(): """Test get fucntion.""" from hash_table import HashTable new_hash = HashTable(100) new_hash.set('pirate', 'ninja') assert new_hash.get('pirate') == 'ninja' def test_hash_on_word_list(): """Test that hash works on a giant list of words.""" from hash_table import HashTable import io new_hash = HashTable(500) file = io.open('/usr/share/dict/words') for i in range(250000): key = value = file.readline() new_hash.set(key, value) assert new_hash.get(key) == value
def negate_sequence(words): prev = [] result = [] neg = ["not", "n't", "no"] j = 0 for word in words: if word not in neg: if prev in neg: result.append('not_' + word) else: result.append(word) j += 1 prev = word return(result)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from math_lib import add,div import argparse def add_divide(a,b,c): """ Calculates the sum of two numbers and divides them by a third Parameters ---------- a,b: int numbers added together c: int number to divide the first two by Returns ------- d: float result of the computation """ s = add(a,b) d = div(s,c) return d def main(): parser = argparse.ArgumentParser(description='Process some input numbers') parser.add_argument('--first_number','-a', type=int, help='First integer to be added', required=True) parser.add_argument('--second_number','-b', type=int, help='Second integer to be added', required=True) parser.add_argument('--third_number','-c', type=int, help='Integer to divide by', required=True) args = parser.parse_args() print(args.first_number,args.second_number,args.third_number) d = add_divide(args.first_number,args.second_number,args.third_number) print(d) if __name__ == '__main__': main()
# Checking Values ''' name = input('Enter your name: ') NameList = ['Vishal', 'Vikas', 'Akash'] if name in NameList: print('Name is in the list') else: print('Name is not in the list') if name not in NameList: print('Name is not in the list') else: print('Name is in the list') ''' # if elif else statement print('Loan Application') salary = int(input('Enter your salary:')) if salary >= 10000 and salary < 50000: print('your are eligible for Rs.5000') elif salary >= 50000: print('your are eligible for Rs.', int(salary/2)) else: print('you are not eligible')
#Utilizando o FOR e o RANGE para imprimir os números primeiros que existem de 0 a 100 print('Os números primos entre 1 a 100 são:') for i in range(1, 101): div = 0 for x in range(1, i + 1): resto = i % x if resto == 0: div+=1 if div == 2: print(' O número: {} é primo.'.format(i))
#Task2_1 a=0 b=100 n1=input("Please, input number's between \n H= %d and P= %d using spaces as spliter and press enter: " %(b,a) ) n2=n1.replace('-',"") nn=n2.split(" ") lengh=(len(nn)) n=n1.split(" ") s=1 ss=0 ssg=0 for i in n: si=int(i) if si > b: s*=si elif si < a: ss+=si else: ssg+=1 print("Numbers between H and P are: %d "%ssg) print("Sum of numbers less than P : %d "%ss) print("Mult of numbers more than H are: %d "%s)
""" Completed file i/o demo. If you want to use this code, you'll need to create corpus and counts directories in the directory where you run it. """ import csv from pathlib import Path kFileName = Path('hunger_games.txt') kOutPath = Path('hunger_counts.csv') kCorpusDir = Path('./corpus') def read_file(path): with open(path, 'r', encoding="UTF-8") as f: text = f.read() return text def read_lines(path): with open(path, 'r') as f: lines = f.readlines() return lines def loop_lines(path): with open(path, 'r') as f: lines = [] for line in f: if line != '\n': lines.append(line) return lines def write_counts(path, counts): with open(path, 'w', encoding="UTF-8") as f: writer = csv.writer(f, dialect=csv.unix_dialect) writer.writerow(['word', 'count']) for count in counts.items(): writer.writerow(count) def sort_counts(counts) -> list: """ Takes in a dictionary of counts, and returns a sorted list of tuples containing the words and their counts. We won't cover how this works in class, but it's essentially a compact version of looping over the dictionary to make all the word-count pairs and put them into the list, and then sorting the list by the second item in each of those pairs (the count) """ return sorted(counts.items(), key=lambda kv: kv[1], reverse=True) def count_all_words(text) -> dict: # the equal sign means the parameter gets this value by "default" """ >>> count_all_words("Once, me father Jeb gave me some advice.", dict_filter=False) {'once': 1, 'me': 2, 'father': 1, 'jeb': 1, 'gave': 1, 'some': 1, 'advice': 1} >>> count_all_words("Once, me father Jeb gave me some advice.", dict_filter=True) {'once': 1, 'me': 2, 'father': 1, 'gave': 1, 'some': 1, 'advice': 1} """ counts = {} words = text.split() for word in words: word = word.lower().strip(',.:;?!\'\"') if word not in counts: counts[word] = 0 counts[word] += 1 return counts def main(): # hunger_counts: counting files in a single text file text = read_file(kFileName) counts = count_all_words(text) write_counts(kOutPath, counts) # corpus counts: counting all files in a directory for path in kCorpusDir.iterdir(): print(f'Generating counts form {path}') text = read_file(path) counts = count_all_words(text) outfile = Path('./counts/' + path.name).with_suffix('.csv') write_counts(outfile, counts) print(f'Wrote counts to {outfile}') return 0 if __name__ == '__main__': main()
# prompt = "\nPlease enter the name of a city you have visited." # prompt += "\n(Enter 'quit' when you are finished.)" # while True: # city = input(prompt) # if city == 'quit': # break # elif city == '': # print("Input can't be blank. Please input again!") # else: # print("I'd love to go to %s!" % city.title()) def describe_city(city_name, city_country='China'): print("%s is in %s." % (city_name.title(), city_country.title())) describe_city('wuhan') describe_city(city_name='shanghai') describe_city('tokyo', 'japan')
def formmated_city_country_name(city, country, population=''): """Return a single string: City, Country - population xxx""" if population: city_country_name = city.title() + ', ' + country.title() city_country_name += ' - population ' + str(population) else: city_country_name = city.title() + ', ' + country.title() return city_country_name