text
stringlengths
37
1.41M
''' Created on 26 May 2016 @author: Sam ''' # Python 2.7 import sys if __name__ == '__main__': #store board and check rows board, queens = [], [] try: for i in xrange(8): row = raw_input() queens.append((row.index('*'), i)) board.append(row) except ValueError: print('invalid') sys.exit() #print queens #check diagonals/columns for eachqueen in queens: for eachdirection in [(1,-1), (-1,1), (1,1), (-1,-1), (0,-1), (0,1)]: pos = list(eachqueen[:]) #print 'q', pos, eachdirection while 1: pos[0] += eachdirection[0] pos[1] += eachdirection[1] if pos[0]<0 or pos[1]<0 or pos[0]>7 or pos[1]>7: break #print 'checking', pos if board[pos[1]][pos[0]] == '*': print('invalid') sys.exit() #print print('valid')
''' Created on 13 May 2016 @author: Sam ''' # Python 3.5 if __name__ == '__main__': n = int(input()) while n > -1: oldelapsed, miles = 0, 0 for i in range(n): line = input().split() elapsed = int(line[1]) miles += int(line[0]) * (elapsed - oldelapsed) oldelapsed = elapsed print(miles, 'miles') n = int(input())
''' Created on 13 May 2016 @author: Sam ''' # Python 3.5 if __name__ == '__main__': X, Y = set([]), set([]) for _ in range(3): line = input().split() newX, newY = int(line[0]), int(line[1]) if newX not in X: X.add(newX) else: X.remove(newX) if newY not in Y: Y.add(newY) else: Y.remove(newY) print(list(X)[0], list(Y)[0])
import os import ast def menu(): os.system('cls') print('account/password mgnt system') print('='*50) print(''' 1. input account and password 2. display account and password 3. change account and password 4. remove account and password 0. End''') print("="*50) def read_data(): mypath = os.path.join(par_dir, 'password.txt') with open(mypath, 'r', encoding='utf-8') as f: filedata = f.read() if filedata != '': data = ast.literal_eval(filedata) return data else: return dict() def display_data(): print('account\tpassword') print('='*50) for key in data: print('{}\t{}'.format(key, data[key])) input('any key back to menu') def input_data(): while True: name = input('name') if name == "": break if name in data: print('{} is existed.'.format(name)) continue password = input('password') data[name] = password mypath = os.path.join(par_dir, 'password.txt') with open(mypath, 'w', encoding='utf-8') as f: f.write(str(data)) print('{} is saved'.format(name)) break def edit_data(): while True: name = input('name') if name == '': break if not name in data: print("{} account is not existed") continue print('old password is {}'.format(data[name])) password = input('new password') data[name] = password mypath = os.path.join(par_dir, 'password.txt') with open(mypath, 'w', encoding='utf8') as f: f.write(str(data)) input('password is renewed') break def delete_data(): while True: name = input('input name') if name == '': break if not name in data: print('{} is not existed'.format(name)) continue print('Are you sure to delete account {}?'.format(name)) yn = input("(Y/N)?") if yn == 'Y' or yn == 'y': del data[name] mypath = os.path.join(par_dir, 'password.txt') with open(mypath, 'w', encoding='utf8') as f: f.write(str(data)) print('{} is removed'.format(name)) input('any key back to menu') break current_dir = os.path.dirname(__file__) par_dir = os.path.abspath(os.path.join(current_dir, os.pardir)) data = read_data() while True: menu() choice = int(input('your choice? ')) if choice == 1: input_data() elif choice == 2: display_data() elif choice == 3: edit_data() elif choice == 4: delete_data() else: break print("system terminated")
#! python # # http://adventofcode.com/2019/day/15 # import Intcode import click class Input: def __init__(self): self.calibrate() def SetOutput( self, mapOutput ): self.mapOutput = mapOutput def calibrate(self): print('Calibrate by pressing left arrow:') self.west = click.getchar() print('Calibrate by pressing right arrow:') self.east = click.getchar() print('Calibrate by pressing up arrow:') self.north = click.getchar() print('Calibrate by pressing down arrow:') self.south = click.getchar() print('Calibration complete, press enter:') self.done = click.getchar() def readInput(self): valid = False while not valid: self.dir = click.getchar() if self.dir == self.north: return 1 if self.dir == self.south: return 2 if self.dir == self.east: return 4 if self.dir == self.west: return 3 if self.dir == self.done: valid = self.mapOutput.ValidateAndCalculateOxygenFill() if not valid: print('Haven\'t found all locations, keep exploring') return None def lastDirection(self): if self.dir == self.north: return (0,1) if self.dir == self.south: return (0,-1) if self.dir == self.east: return (1,0) if self.dir == self.west: return (-1,0) class MapOutput: def __init__(self, input): self.map = {} self.input = input self.pos = (0,0) self.distance = {} self.distance[self.pos] = 0 self.map[self.pos] = '.' self.walkables = [(0,0)] self.oxygenPos = None self.minX = None self.maxX = None self.minY = None self.maxY = None def HandleOutput(self, val): attemptedDirection = self.input.lastDirection() if val == 0: self.AddWall( attemptedDirection ) elif val == 1: self.MovePos( attemptedDirection ) elif val == 2: self.MovePos( attemptedDirection ) self.map[self.pos] = 'O' self.oxygenPos = self.pos self.Render() def MovePos( self, delta ): distance = self.distance[self.pos] self.pos = MapOutput.AddPos( self.pos, delta ) self.map[self.pos] = '.' self.walkables += [self.pos] if self.pos not in self.distance or (self.distance[self.pos] > distance+1): self.distance[self.pos] = distance+1 def AddPos( pos1, pos2 ): return ( pos1[0]+pos2[0], pos1[1]+pos2[1] ) def AddWall( self, delta ): self.map[MapOutput.AddPos(self.pos,delta)] = '#' def Render( self ): lines = [] for y in range( self.pos[1]+10, self.pos[1]-10, -1): line = '' for x in range( self.pos[0]-10, self.pos[0]+10, 1): line += self.GetMap( (x,y) ) lines += [ line ] print("\n\n\n") print( '\n'.join(lines) ) print( 'Distance:', self.distance[self.pos] ) def GetMap( self, pos ): if pos == self.oxygenPos and pos == self.pos: return 'X' if pos == self.pos: return 'D' if pos in self.map: return self.map[pos] return ' ' def AllNeighborsFound(self, pos): neighbors = [(1,0),(-1,0),(0,1),(0,-1)] found = True for neighbor in neighbors: found = found and ' ' != self.GetMap( MapOutput.AddPos( pos, neighbor ) ) return found def Validate(self): for walkable in self.walkables: if not self.AllNeighborsFound(walkable): return False return True def CalculateOxygenFill(self): posMap = self.map.copy() addedOxygen = [self.oxygenPos] round = 0 posMap[self.oxygenPos] = 'O' neighbors = [(1,0),(-1,0),(0,1),(0,-1)] while len(addedOxygen) > 0: lastOxygen = addedOxygen.copy() addedOxygen = [] round += 1 for oxygen in lastOxygen: for neighbor in neighbors: possiblePos = MapOutput.AddPos( oxygen, neighbor ) if posMap[possiblePos] == '.': posMap[possiblePos] = 'O' addedOxygen += [possiblePos] print("Took {} rounds to fill the space with Oxygen".format( round - 1 )) def ValidateAndCalculateOxygenFill(self): if not self.Validate(): return False self.CalculateOxygenFill() return True class RobotIO: def __init__(self): self.state = {} print('Calibrate the RobotIO by pressing up:') self.north = click.getchar() print('Calibrate the RobotIO by pressing down:') self.south = click.getchar() print('Calibrate the RobotIO by pressing left:') self.west = click.getchar() print('Calibrate the RobotIO by pressing right:') self.east = click.getchar() print('Calibrate the RobotIO by hitting enter:', end='', flush=True) self.done = click.getchar() print('') print('Calibrate the RobotIO by hitting backspace:', end='', flush=True) self.backspace = click.getchar() print('') self.inputCommand = [] self.lastInput = '' self.outputFromComp = [] self.currentLineOfOutput = '' def handleOutput(self, val): if val == 10: self.outputFromComp += [self.currentLineOfOutput] self.currentLineOfOutput = '' print(self.outputFromComp[-1]) else: self.currentLineOfOutput += chr(val) def handleInput(self): if len(self.inputCommand) == 0: charval = click.getchar() if self.north == charval: self.inputCommand = list(map(ord, ['n','o','r','t','h'])) charval = self.done elif self.south == charval: self.inputCommand = list(map(ord, ['s','o','u','t','h'])) charval = self.done elif self.east == charval: self.inputCommand = list(map(ord, ['e','a','s','t'])) charval = self.done elif self.west == charval: self.inputCommand = list(map(ord, ['w','e','s','t'])) charval = self.done while charval != self.done: doEcho = True if charval == self.backspace: if len(self.inputCommand) > 0: self.inputCommand.pop(-1) else: doEcho = False else: self.inputCommand += [ord(charval)] if doEcho: print(charval, end='', flush=True) charval = click.getchar() self.lastInput = str(map(chr, self.inputCommand)) self.inputCommand += [ 10 ] return self.inputCommand.pop(0) if __name__ == '__main__': io = RobotIO() #input = Input() #mapOutput = MapOutput( input ) #input.SetOutput( mapOutput ) prog = Intcode.Intcode( Intcode.readProgInput('input.txt'), inputFunc=io.handleInput, outputFunc=io.handleOutput ) #mapOutput.Render() prog.Run()
import random class card: def __init__(self, suit=None, rank=None, faceUp=None): self.suits = { 0 : 'Diamonds', 1 : 'Clubs', 2 : 'Hearts', 3 : 'Spades' } self.ranks = { 1 : 'Ace', 2 : 'Two', 3 : 'Three', 4 : 'Four', 5 : 'Five', 6 : 'Six', 7 : 'Seven', 8 : 'Eight', 9 : 'Nine', 10 : 'Ten', 11 : 'Jack', 12 : 'Queen', 13 : 'King' } if suit is None: self.suit = self.suits[random.randint(0,3)] else: self.suit = suit if rank is None: self.rank = self.ranks[random.randint(1,13)] else: self.rank = rank if faceUp is None: self.faceUp = False else: self.faceUp = faceUp def flip(self): if self.faceUp == False: self.faceUp = True else: self.faceUp = False def shortHand(self, side=False): rankKey = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] for key in range(1, len(self.ranks)+1): if self.ranks[key] == self.rank[1]: rankString = rankKey[key-1] break suitKey = ['♦','♣','♥','♠'] for key in range(0,len(self.suits)): if self.suits[key] == self.suit[1]: suitString = suitKey[key] cardString = rankString + suitString if side is True: if self.faceUp is True: cardString += "_U" else: cardString += "_D" return cardString def pickACard(self): self.suit = self.suits[random.randint(0,3)] self.rank = self.ranks[random.randint(1,13)] print("Your card is a " + str(self.rank) + " of " + str(self.suit)) class cardset: def __init__(self): self.cardset = [] dummycard = card() for suit in dummycard.suits.items(): for rank in dummycard.ranks.items(): self.cardset.append(card(suit=suit, rank=rank, faceUp=False)) def flip(card): if card.faceUp == False: card.faceUp = True else: card.faceUp = False if __name__ == '__main__': somecard = card() somecard.pickACard() somecard.flip() print ("--- Cards in a Set ---") singledeck = cardset().cardset for eachcard in singledeck: print (eachcard.rank[1] + " of " + eachcard.suit[1])
def writeFile(): try: f = open('NewFile', 'w') f.write("Text to be written in NewFile") except: print "There was an error writing into the file" else: print "File has been written succesfully" def writeFile2(): try: f = open('NewFile', 'w') f.write("Text to bee written in NewFile from 2nd function!") except: print "There was an error writing into the file!!" else: print "File written Success 2" finally: print "I am from finally block, I will always appear!!" def readFile(): try: f = open('NewFile2', 'r') f.write("This won't be written if the file do not exists!") except: print "Intentional Error!!. There is not file wwith such name!" else: print "Written to the file!!" finally: print "Hello!! I am 'finally' here!!" def takeInput(): while True: try: print "Enter an Integer!!" val = int(raw_input("Please enter an integer : ")) except: print "You didn't enter anything!!" continue else: print "Yup, That is an Integer!" break finally: print "Guess Where I am From if I Will always appear!!" print val writeFile() writeFile2() readFile() takeInput()
file1 = open("Test.txt", "w") try: file1.read() except: print "You can't read, cause you are using the write parameter!!" file1.write("This is the ttest line to be written into the text file") #we need to close the file aafter writing in it file1.close() file2 = open("Test.txt", "r") print file2.read() #If the file already exists in the folder, the file will be rewritten # To avoid this, we need to append # you can both write and read using wb+
def exception(): try: print 2 + "Arjun" except: print "Cannot Add an integer and a string!! \n" def exception2(): try: print 2 + "Arjun" except: print "Cannot Add an integer and a string!!" finally: print "I am from finally block\n" def exception3(): try: x = 2+2 print "Try block x is %s"%(x) print "This code is written in try block!!\n" except: print "I wont'be reached!!\n" finally: print "The value of x is : %s" %(x) exception() exception2() exception3()
from Tkinter import * root = Tk() equalTo = "" def btnPress(num): global equalTo equalTo = equalTo + str(num) equation.set(equalTo) def equalPress(): global equalTo total = str(eval(equalTo)) equation.set(total) equalTo = "" def clear(): global equalTo equalTo = "" equation.set("Let's Calculate!") zero = Button(root, text = "0", command = lambda: btnPress(0)) zero.grid(row = 4, column = 1) one = Button(root, text = "1", command = lambda: btnPress(1)) one.grid(row = 1, column = 0) two = Button(root, text = "2", command = lambda: btnPress(2)) two.grid(row = 1, column = 1) three = Button(root, text = "3", command = lambda: btnPress(3)) three.grid(row = 1, column = 2) four = Button(root, text = "4", command = lambda: btnPress(4)) four.grid(row = 2, column = 0) five = Button(root, text = "5", command = lambda: btnPress(5)) five.grid(row = 2, column = 1) six = Button(root, text = "6", command = lambda: btnPress(6)) six.grid(row = 2, column = 2) seven = Button(root, text = "7", command = lambda: btnPress(7)) seven.grid(row = 3, column = 0) eight = Button(root, text = "8", command = lambda: btnPress(8)) eight.grid(row = 3, column = 1) nine = Button(root, text = "9", command = lambda: btnPress(9)) nine.grid(row = 3, column = 2) plus = Button(root, text="+", command = lambda: btnPress("+")) minus = Button(root, text="-", command = lambda: btnPress("-")) divide = Button(root, text="/", command = lambda: btnPress("/")) multiply = Button(root, text="*", command = lambda: btnPress("*")) equal = Button(root, text="=", command = equalPress) clear = Button(root, text="C", command = clear) plus.grid(row = 1, column = 3) minus.grid(row = 2, column = 3) multiply.grid(row = 3, column = 3) divide.grid(row = 4,column = 3 ) equal.grid(row = 4, column = 2) clear.grid(row = 4, column = 0) #String var to update the text of the label equation = StringVar() calculation = Label(root, textvariable = equation) equation.set("Let's Calculate!") calculation.grid(row=0,columnspan = 4) root.mainloop()
def up_low(s): d = {"upper":0, "lower":0} for c in s: if c.isupper(): d["upper"]+=1 elif c.islower(): d["lower"]+=1 else: pass print "Original String : ", s print "No. of Upper case Characters : ", d["upper"] print "No. of Lower case Characters : ", d["lower"] s = "Hello, My name is Arjun Dass" up_low(s)
import Tkinter import tkMessageBox root = Tkinter.Tk() tkMessageBox.showinfo("Title ", "Something went wrong!! ") answer = tkMessageBox.askquestion("Question 1:", "Are you a human?") if answer == "yes": tkMessageBox.showinfo("Congrats!!", "Well Duh!!") if answer == "no": tkMessageBox.showinfo("Nope!!", "You are an alien!!") root.mainloop()
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} for county, voters in counties_dict.items(): print(str(county) + " county has " + str(voters) + " registered voters.") voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] for counties_dict in voting_data: print(counties_dict['county'] + " county has " + str(counties_dict['registered_voters']) + " registered voters.")
t=int(input()) while t: n = int(input()) S = input() if "Y" in S: if S.count("Y") > S.count("I"): print("NOT INDIAN") elif "I" in S: print("INDIAN") else: print("NOT SURE") t = t-1
t = int(input()) while t: str1 = input() str2 = input() A = 0 B = 0 for i in range(len(str1)): if str1[i]=="?" or str2[i]=="?": B += 1 elif str1[i]!=str2[i]: A += 1 B += 1 print(A,B) t = t-1
import math t = int(input()) while t: A, B=list(map(int,input().split())) area = A*B hcf = math.gcd(A,B) print(int(area/(hcf*hcf))) t = t-1
""" -------------------------------------------------------------------------------------- Programa que implementa o client da comunicacao TCP/IP com Diffie-Hellman Objetivo: Comunicacao de cliente-servidor fazendo o estabelecimento de Chave Secreta com Diffie-Hellman Restricoes: o programa necessita que um servidor esteja em execucao para que seja possivel a comunicacao. Autor: Brendon e Marllon. Disciplina: Redes II Data da ultima atualizacao: 28/07/2021 ----------------------------------------------------------------------------------------""" import socket from common.util import * from des import DesKey def connect_to_server(host, port) -> socket.SocketIO: """ Create and return TCP/IP socket """ # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address = (host, port) print('[CLIENT LOG] connecting to {} port {}'.format(host,port)) sock.connect(server_address) return sock def send_message(sock, message) -> None: """ Send message to server """ print('[CLIENT LOG] sending message to server: {}'.format(str(message))) if type(message) == bytes: sock.sendall(message) else: sock.sendall(str.encode(str(message))) def close_connection(sock) -> None: """ Close connection """ sock.close() def generate_prime_module() -> int: """ Generate a random prime number to be used as module number (p) for Diffie-Hellman """ p = generate_random_prime() print('[CLIENT LOG] generate prime module (p) with the value equal {}'.format(p)) return p def generate_random_private_key() -> int: """ Generate a random private key """ private_key = random.randint(1, 10000) print('[CLIENT LOG] generate random private key equal: {}'.format(str(private_key))) return private_key def calculate_client_result(base, exp, mod) -> int: """ Calculate client result """ result = power(base, exp, mod) print('[CLIENT LOG] calculated public result to send for the server: {}'.format(result)) return result def calculate_private_shared_key(server_result, client_private_key, p) -> int: """ Calculate shared key """ shared_key = power(server_result, client_private_key, p) print('[CLIENT LOG] calculated shared key equal: {}'.format(shared_key)) return shared_key def main(): sock = connect_to_server('localhost', port=10000) print('[CLIENT LOG] connected to server') try: # Defines Diffie-Hellman shared parameters communicating with connected server print('[CLIENT LOG] defining Diffie-Hellman parameters with server') p = generate_prime_module() # Random prime generated by client to be used as module number (p) for Diffie-Hellman send_message(sock, str(p)) g = int(sock.recv(1024).decode(encoding='UTF-8')) # Randomly generated by server to be used as generator (g) for Diffie-Hellman print('[CLIENT LOG] received generator randomly generated by the server with value equal: {}'.format(g)) private_key = generate_random_private_key() result = calculate_client_result(g, private_key, p) send_message(sock, str(result)) server_result = int(sock.recv(1024).decode(encoding='UTF-8')) # Server's result received from the socket print('[CLIENT LOG] received server_result with value equal: {}'.format(server_result)) shared_private_key = calculate_private_shared_key(server_result, private_key, p) des_key = DesKey(shared_private_key.to_bytes(8, byteorder='big')) while True: message = input('Enter message to send: ') encrypted_message = des_key.encrypt(str.encode(message), padding=True) send_message(sock, encrypted_message) data = sock.recv(1024) print('[CLIENT LOG] received message: {}'.format(data)) print('[CLIENT LOG] message decrypted: {}'.format(des_key.decrypt(data, padding=True))) finally: print('[CLIENT LOG] closing socket') close_connection(sock) if __name__ == '__main__': print("===========================================================================") print("Inicio da execucao: programa que implementa o client da comunicacao TCP/IP.") print("Prof. Elias P. Duarte Jr. - Disciplina Redes II") print("Autores: Brendon e Marllon") print("===========================================================================") main()
import simplegui import random num = 100 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global tries, secret_number secret_number = random.randrange(0,num+1) if num == 100: tries = 7 else: tries = 10 print "Range is " + str(num) print "You have " + str(tries)+ " tries left" print "Enter a number" print " " # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global num num = 100 new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game global num num = 1000 new_game() def input_guess(guess): # main game logic goes here global tries print "Guess was " + guess if int(guess) > secret_number: print "lower" tries -= 1 if tries > 0: print "You have "+str(tries)+ " left" print " " else: print "You lose the secret number was" + str(secret_number) print " " new_game() elif int(guess) < secret_number: print "higher" tries -= 1 if tries > 0: print "You have "+str(tries)+ " left" print " " else: print "You lose the secret number was " + str(secret_number) print " " new_game() else: print "You are correct" print " " # create frame f = simplegui.create_frame("Guess the number.", 300, 300) # register event handlers for control elements and start frame f.add_input("Enter number",input_guess,100) f.add_button("Range [0,100]", range100, 100) f.add_button("Range [0,1000]", range1000, 100) # call new_game new_game()
''' 利用python的max()和min(), 在Python里字符串是可以比较的,按照ascII值排,举例abb, aba,abac,最大为abb,最小为aba。 所以只需要比较最大最小的公共前缀就是整个数组的公共前缀。 法一法二不相上下。 ''' class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return "" strs_max = max(strs) strs_min = min(strs) if strs_max == strs_min: # 企图加速 return strs_max # 两种处理方式 for i in range(len(strs_min)): # 一 if strs_min[i] != strs_max[i]: return strs_min[:i] # for i, value in enumerate(strs_min): # 二 # if value != strs_max[i]: # return strs_max[:i] return strs_min
''' External LED was connected to Pin 15 of the Raspberry Pi Pico''' ''' A resistor of 100 ohms was used''' from machine import Pin, Timer led = Pin(15, Pin.OUT) timer = Timer() #function def blink(timer): led.toggle() timer.init(freq=2.5, mode=Timer.PERIODIC, callback=blink)
total=0 print "how many are you adding" userinput= raw_input() for x in range(userinput): print "what is the number" total = total + userinput print total total2 =[] for x in range(3): print "input a number" userinput = int(raw_input()) total2.append(userinput) print sum(total2) total3=1 userinput = int(raw_input()) for x in range((1, userinput+1, 1)): total=total * x print total3 # hello!!
#Justin Moroz 1/27/2017 import random #create list called gumballs gumballs=[] #append appropriate amount into list for each color yellow=random.randint(10,15) count=0 while count<yellow: gumballs.append("yellow") count+=1 blue=random.randint(1,10) count=0 while count<blue: gumballs.append("blue") count+=1 white=random.randint(6,15) count=0 while count<blue: gumballs.append("blue") count+=1 green=random.randint(10,25) count=0 while count<blue: gumballs.append("green") count+=1 black=random.randint(1,12) count=0 while count<blue: gumballs.append("black") count+=1 purple=random.randint(5,10) count=0 while count<purple: gumballs.append("purple") count+=1 silver=random.randint(4,6) count=0 while count<silver: gumballs.append("silver") count+=1 cyan=random.randint(5,12) count=0 while count<blue: gumballs.append("cyan") count+=1 magenta=random.randint(0,10) count=0 while count<blue: gumballs.append("blue") count+=1 gumballs.append("red") #display gumball count print("You are starting with the following gumballs:") print(yellow,"yellow") print(blue,"blue") print(white,"white") print(green,"green") print(black,"black") print(purple,"purple") print(silver,"silver") print(cyan,"cyan") print(magenta,"magenta") print("and 1 red") print() print("Here are your random purchases:") #begin drawing at random draw="" taken=[] tracker=0 while draw!="red": draw_num=random.randint(0,(len(gumballs)-1)) draw=gumballs[draw_num] gumballs.remove(draw) taken.append(draw) tracker+=1 print(draw) #determine most common gumball drawn import collections countlist={"yellow":[],"blue":[],"white":[],"green":[],"black":[],"purple":[],"silver":[],"cyan":[],"magenta":[],"red":[]} yellow_count=taken.count("yellow") countlist["yellow"].append(yellow_count) blue_count=taken.count("blue") countlist["blue"].append(blue_count) white_count=taken.count("white") countlist["white"].append(white_count) green_count=taken.count("green") countlist["green"].append(green_count) black_count=taken.count("black") countlist["black"].append(black_count) purple_count=taken.count("purple") countlist["purple"].append(purple_count) silver_count=taken.count("silver") countlist["silver"].append(silver_count) cyan_count=taken.count("cyan") countlist["cyan"].append(cyan_count) magenta_count=taken.count("magenta") countlist["magenta"].append(magenta_count) countlist=collections.Counter(countlist) most=countlist.most_common(1) most=str(most[0]) most=most.replace("(","") most=most.replace("'","") most=most.replace(")","") most=most.replace("[","") most=most.replace("]","") most=most.split(",") print() print("You purchased",tracker,"gumballs for a price of $",(tracker*.25)) print("The most common color gumball you recieved was",most[0], "which you received",most[1],"times")
import sys def get_colour_map(colour_input): colour_map = {} for l in colour_input: primary_colour, contained_colour_string = [x.strip() for x in l.replace('.','').split('bags contain')] colour_map[primary_colour] = {} if 'no other bag' in contained_colour_string: continue contained_colours = [c.replace(' bags', '').replace(' bag', '').strip() for c in contained_colour_string.split(',')] for c in contained_colours: number_of_bags = int(c.split(' ')[0].strip()) secondary_colour = ' '.join(c.split(' ')[1:]).strip() colour_map[primary_colour][secondary_colour] = number_of_bags return colour_map def get_bags_that_eventually_contain_given_colour(given_colour, colour_map): present_list = [] for primary_colour in colour_map.keys(): # print(f"Checking {primary_colour}") if find_bags_that_contain_given_colour(given_colour, primary_colour, present_list, colour_map) and primary_colour not in present_list: present_list.append(primary_colour) # print(present_list) # print(present_list) return len(present_list) def find_bags_that_contain_given_colour(given_colour, current_colour_to_check, present_list, colour_map): if current_colour_to_check in present_list: return True secondary_colours = colour_map[current_colour_to_check] colour_found = False for sc in secondary_colours.keys(): # print(f'Checking secondary colour {sc}') if sc in present_list: # print(f'Colour {sc} already present') colour_found = True continue if sc == given_colour: colour_found = True continue if find_bags_that_contain_given_colour(given_colour, sc, present_list, colour_map): present_list.append(sc) colour_found = True continue return colour_found def get_number_of_bags_required(starting_colour, colour_map): total = 1 if colour_map[starting_colour].keys(): for next_start_colour in colour_map[starting_colour].keys(): totalToAdd = colour_map[starting_colour][next_start_colour] * get_number_of_bags_required(next_start_colour, colour_map) total += totalToAdd print(f"{starting_colour} contains {colour_map[starting_colour][next_start_colour]} {next_start_colour} bags which contains {totalToAdd} bags") else: total = 1 print(f"{starting_colour} contains a total of {total} bags") return total if __name__ == "__main__": args = sys.argv with open('python/inputday07.txt') as f: puzzle_input = [x.strip() for x in f.readlines() if x.strip() != ""] colour_map = get_colour_map(puzzle_input) if args[1] == "1": print(get_bags_that_eventually_contain_given_colour("shiny gold", colour_map)) if args[1] == "2": print(get_number_of_bags_required("shiny gold", colour_map) - 1)
import re def numberOfCharacters(inputString): mainString = inputString[1:-1] i = 0 numberOfQuotedCharacters = 0 numberOfBackSlashes = 0 numberOfHexCharacters = 0 while i < len(mainString): if mainString[i] == '\\': if mainString[i+1] == '"': numberOfQuotedCharacters += 1 i+=1 elif mainString[i+1] == '\\': numberOfBackSlashes += 1 i+=1 elif re.search(r'\\x[0-9a-z][0-9a-z]',mainString[i:i+4]): numberOfHexCharacters += 1 i+=3 i+=1 return len(mainString) - numberOfQuotedCharacters - numberOfBackSlashes - (numberOfHexCharacters*3) def encode(inputString): mainString = inputString[1:-1] newString = '\\"' i = 0 while i < len(mainString): if mainString[i] == '\\': newString += '\\\\' elif mainString[i] == '"': newString += '\\"' else: newString += mainString[i] i+=1 newString += '\\"' return newString def numberOfCharactersOfCode(inputString): return len(inputString) def runPartOne(): f = open('python/day8input', 'r') lines = f.readlines() totalNumberOfCharacters = 0 totalNumberOfCharactersInCode = 0 for line in lines[:]: totalNumberOfCharactersInCode += numberOfCharactersOfCode(line.strip('\n')) totalNumberOfCharacters += numberOfCharacters(line.strip('\n')) print("Total number of characters:", totalNumberOfCharacters) print("Total number of characters in code:", totalNumberOfCharactersInCode) print("Difference:", totalNumberOfCharactersInCode - totalNumberOfCharacters) f.close() def runPartTwo(): f = open('python/day8input', 'r') lines = f.readlines() totalNumberOfCharacters = 0 totalNumberOfCharactersInCode = 0 for line in lines[:]: totalNumberOfCharactersInCode += numberOfCharactersOfCode(line.strip('\n')) totalNumberOfCharacters += len(encode(line.strip('\n'))) + 2 print("Total number of characters:", totalNumberOfCharacters) print("Total number of characters in code:", totalNumberOfCharactersInCode) print("Difference:", totalNumberOfCharacters - totalNumberOfCharactersInCode ) f.close() if __name__ == "__main__": runPartOne() runPartTwo()
import unittest from . import day03 class TestDay3(unittest.TestCase): def test_manhattan_distance_is_calculated_correctly(self): self.assertTrue(True) def test_list_of_points_can_be_obtained_from_an_instruction(self): instruction = 'R2' starting_coordinates = (0,0) expected_result = [(1,0), (2,0)] returned_result = day03.get_points_from_current_position_to_next(instruction=instruction, starting_coordinates=starting_coordinates) self.assertEqual(returned_result, expected_result) instruction = 'U2' starting_coordinates = (0,0) expected_result = [(0,1), (0,2)] returned_result = day03.get_points_from_current_position_to_next(instruction=instruction, starting_coordinates=starting_coordinates) self.assertEqual(returned_result, expected_result) instruction = 'L4' starting_coordinates = (2,7) expected_result = [(1,7), (0,7), (-1,7), (-2,7)] returned_result = day03.get_points_from_current_position_to_next(instruction=instruction, starting_coordinates=starting_coordinates) self.assertEqual(returned_result, expected_result) instruction = 'D3' starting_coordinates = (3,-5) expected_result = [(3,-6), (3,-7), (3,-8)] returned_result = day03.get_points_from_current_position_to_next(instruction=instruction, starting_coordinates=starting_coordinates) self.assertEqual(returned_result, expected_result) def test_list_of_points_can_be_obtained_from_full_instruction_set(self): instruction_list = ['R2', 'U2', 'L4', 'D3'] expected_result = [ (1,0), (2,0), (2,1), (2,2), (1,2), (0,2), (-1,2), (-2,2), (-2,1), (-2,0), (-2,-1) ] returned_result = day03.get_points_for_given_instruction_set(instruction_list=instruction_list) self.assertEqual(returned_result, expected_result) def test_intersections_of_two_wires_can_be_found(self): instruction_list_A = 'R8,U5,L5,D3'.split(',') instruction_list_B = 'U7,R6,D4,L4'.split(',') intersection_points = day03.get_intersection_points_for_wires(instruction_list_A, instruction_list_B) self.assertTrue((3,3) in intersection_points) self.assertTrue((6,5) in intersection_points) self.assertEqual(len(intersection_points), 2) def test_smallest_manhattan_distance_can_be_found_for_two_wire_paths(self): instruction_list_A = 'R8,U5,L5,D3'.split(',') instruction_list_B = 'U7,R6,D4,L4'.split(',') self.assertEqual(day03.find_smallest_manhattan_distance(instruction_list_A, instruction_list_B), 6) instruction_list_A = 'R75,D30,R83,U83,L12,D49,R71,U7,L72'.split(',') instruction_list_B = 'U62,R66,U55,R34,D71,R55,D58,R83'.split(',') self.assertEqual(day03.find_smallest_manhattan_distance(instruction_list_A, instruction_list_B), 159) instruction_list_A = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51'.split(',') instruction_list_B = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7'.split(',') self.assertEqual(day03.find_smallest_manhattan_distance(instruction_list_A, instruction_list_B), 135) def test_smallest_number_of_steps_to_intersecting_point_can_be_found_for_two_wires(self): instruction_list_A = 'R8,U5,L5,D3'.split(',') instruction_list_B = 'U7,R6,D4,L4'.split(',') self.assertEqual(day03.find_intersecting_points_with_least_cumulative_steps(instruction_list_A, instruction_list_B), 30) instruction_list_A = 'R75,D30,R83,U83,L12,D49,R71,U7,L72'.split(',') instruction_list_B = 'U62,R66,U55,R34,D71,R55,D58,R83'.split(',') self.assertEqual(day03.find_intersecting_points_with_least_cumulative_steps(instruction_list_A, instruction_list_B), 610) instruction_list_A = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51'.split(',') instruction_list_B = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7'.split(',') self.assertEqual(day03.find_intersecting_points_with_least_cumulative_steps(instruction_list_A, instruction_list_B), 410) if __name__ == "__main__": unittest.main()
def get_input(): instruction_list_A, instruction_list_B = [instruction_line.split(',') for instruction_line in open('./python/inputday03.txt', 'r').read().split('\n')[:2]] return instruction_list_A, instruction_list_B def get_points_from_current_position_to_next(instruction='R0', starting_coordinates=(0,0)): direction = instruction[0] distance = int(instruction[1:]) points_travelled = [] current_x = starting_coordinates[0] current_y = starting_coordinates[1] for i in range(distance): if direction == 'R': current_x += 1 elif direction == 'U': current_y += 1 elif direction == 'L': current_x -= 1 elif direction == 'D': current_y -= 1 points_travelled.append((current_x, current_y)) return points_travelled def get_points_for_given_instruction_set(instruction_list=['R0']): points_travelled = [] current_coordinates = (0,0) for instruction in instruction_list: points_travelled.extend(get_points_from_current_position_to_next(instruction=instruction, starting_coordinates=current_coordinates)) current_coordinates = points_travelled[-1] return points_travelled def get_intersecting_points_for_given_instruction_set(instruction_list=['R0'], already_travelled_points=[]): current_coordinates = (0,0) intersecting_points = [] already_travelled_points_as_set = set(already_travelled_points) for instruction in instruction_list: points_travelled = (get_points_from_current_position_to_next(instruction=instruction, starting_coordinates=current_coordinates)) points_travelled_as_set = set(points_travelled) current_coordinates = points_travelled[-1] intersecting_points.extend(list(points_travelled_as_set & already_travelled_points_as_set)) return intersecting_points def get_intersection_points_for_wires(instruction_list_A, instruction_list_B): points_travelled_for_A = get_points_for_given_instruction_set(instruction_list=instruction_list_A) points_travelled_for_B = get_points_for_given_instruction_set(instruction_list=instruction_list_B) #return get_intersecting_points_for_given_instruction_set(instruction_list=instruction_list_B, already_travelled_points=points_travelled_for_A) return list(set(points_travelled_for_A) & set(points_travelled_for_B)) def find_smallest_manhattan_distance(instruction_list_A, instruction_list_B): intersection_points = get_intersection_points_for_wires(instruction_list_A, instruction_list_B) manhattan_distances = [abs(x[0]) + abs(x[1]) for x in intersection_points] return min(manhattan_distances) def find_intersecting_points_with_least_cumulative_steps(instruction_list_A, instruction_list_B): points_travelled_for_A = get_points_for_given_instruction_set(instruction_list=instruction_list_A) points_travelled_for_B = get_points_for_given_instruction_set(instruction_list=instruction_list_B) intersecting_points = list(set(points_travelled_for_A) & set(points_travelled_for_B)) steps_to_intersecting_points = [] for intersecting_point in intersecting_points: # the +2 is to account for the first step. Indexes start at 0 instead of 1 which means that the number of steps will always be # 2 less than the actual number of steps steps_to_intersecting_points.append(points_travelled_for_A.index(intersecting_point) + points_travelled_for_B.index(intersecting_point)+2) return min(steps_to_intersecting_points) def run_part_one(): instruction_list_A, instruction_list_B = get_input() return find_smallest_manhattan_distance(instruction_list_A, instruction_list_B) def run_part_two(): instruction_list_A, instruction_list_B = get_input() return find_intersecting_points_with_least_cumulative_steps(instruction_list_A, instruction_list_B) if __name__ == "__main__": part_one_result = run_part_one() print(part_one_result) part_two_result = run_part_two() print(part_two_result)
import unittest from . import day02 class TestDay2(unittest.TestCase): def test_input_can_be_broken_correctly(self): test_input = '1-3 a: abcde' output = day02.break_input_into_rules(test_input) expected_output = { 'min_times': 1, 'max_times': 3, 'test_letter': 'a', 'password': 'abcde' } self.assertEqual(output, expected_output) def test_password_can_be_validated(self): test_rule = { 'min_times': 1, 'max_times': 3, 'test_letter': 'a', 'password': 'abcde' } self.assertTrue(day02.validate_password(test_rule)) test_rule = { 'min_times': 1, 'max_times': 3, 'test_letter': 'b', 'password': 'cdefg' } self.assertFalse(day02.validate_password(test_rule)) test_rule = { 'min_times': 2, 'max_times': 9, 'test_letter': 'c', 'password': 'ccccccccc' } self.assertTrue(day02.validate_password(test_rule)) def test_input_can_be_broken_down_based_on_second_rules(self): test_input = '1-3 a: abcde' output = day02.break_input_into_new_rules(test_input) expected_output = { 'first_position': 0, 'second_position': 2, 'test_letter': 'a', 'password': 'abcde' } self.assertEqual(output, expected_output) def test_password_can_be_validated(self): test_rule = { 'first_position': 0, 'second_position': 2, 'test_letter': 'a', 'password': 'abcde' } self.assertTrue(day02.validate_password_with_new_rules(test_rule)) test_rule = { 'first_position': 0, 'second_position': 2, 'test_letter': 'b', 'password': 'cdefg' } self.assertFalse(day02.validate_password_with_new_rules(test_rule)) test_rule = { 'first_position': 1, 'second_position': 8, 'test_letter': 'c', 'password': 'ccccccccc' } self.assertFalse(day02.validate_password_with_new_rules(test_rule)) if __name__ == "__main__": unittest.main()
import argparse def find_common_character_in_column(column_index, input, least=False): character_count = {} for row in input: if row[column_index] not in character_count: character_count[row[column_index]] = 1 else: character_count[row[column_index]] += 1 if not least: return sorted(character_count.items(), key=lambda item: item[1], reverse=True)[0][0] else: return sorted(character_count.items(), key=lambda item: item[1], reverse=False)[0][0] def get_error_corrected_message(input, decoding_method="MOST"): input_length = len(input[0]) correct_message = "" for i in range(0,input_length): if decoding_method == "MOST": correct_message += find_common_character_in_column(i, input) else: correct_message += find_common_character_in_column(i, input, least=True) return correct_message if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--part', type=int) args = parser.parse_args() f = open('six/input', 'r') input_string = f.readlines() input = [s.strip() for s in input_string] if args.part == 1: print(get_error_corrected_message(input)) elif args.part == 2: print(get_error_corrected_message(input, decoding_method="LEAST"))
#wijziging # datatypes #----------- # int = integer = getal = nummer # string = tekst # boolean = (true or false) (1 of 0) #functies (built in functies van python zelf) #---------------------------------------------- # herkenning van een functie (ronde haakjes) # int() = functie zonder parameter # int(parameter) = functie met parameter # int() => die zorgt voor omzetting van tekst naar getal # input()=> input vraagt aan de gebruiker # input("Geef een getal in") => vraagt input aan de gebruiker # print()=> tekst op het scherm weergeven # controlestructuren #--------------------- # SEQUENTIE # is één enkele lijn in code # SELECTIE # ENKELVOUDIGE SELECTIE # if (conditie): # else: # TWEEVOUDIGE SELECTIE # if (conditie): # elif (conditie): # else: # MEERVOUDIGE SELECTIE # if (conditie): # elif (conditie): # elif (conditie): # elif (conditie): # else: # GENESTE SELECTIE # if (conditie): # if (conditie): # elif (conditie): # else: # else: # ITERATIES = LUSSEN = LOOPS #------------ #for loop # for x in range(start ,stop , stap ) # x IS start # for x in (3, 10, 1) # resultaat: 3 4 5 6 7 8 9 (stap:1) #for x in (3, 10, 2) #resultaat: 3 5 7 9 # while loop # zolang de conditie waar is voeren we de loop uit # while (conditie): # teller = 0 # while (teller < 5): # print("de teller is nog steeds kleiner dan 5") # teller = int(input("Geef een teller in:"))
getal1 = input("Geef getal 1 in:") getal2 = int(input("Geef getal 2 in:")) if(int(getal1) > getal2): product = int(getal1) * getal2 print("Product:", product) som = int(getal1) + getal2 print("Som:", som) verschil = int(getal1) - getal2 print("Verschil:", verschil) quotient = int(getal1) / getal2 print("Quotient:", quotient) else: print("error, getal1 moet groter zijn dan getal2")
from collections import deque def check(d): while d: big = d.popleft() if d[0]>d[-1] else d.pop() if not d: return "Yes" if d[-1]>big or d[0]>big: return "No" for i in range(int(input())): int(input()) d = deque(map(int,input().split())) print(check(d))
""" functions around vectors """ def normalize(position): """ Accepts `position` of arbitrary precision and returns the block containing that position. Parameters ---------- position : tuple of len 3 Returns ------- block_position : tuple of ints of len 3 """ x, y, z = position x, y, z = (int(round(x)), int(round(y)), int(round(z))) return x, y, z def sectorize(position): """ Returns a tuple representing the sector for the given `position`. Parameters ---------- position : tuple of len 3 Returns ------- sector : tuple of len 3 """ x, y, z = normalize(position) x, y, z = x // 16, y // 16, z // 16 return x, z
def benchmark_finder(corporate_bond, bond_dict): """ Finds government bond benchmark (government bond with closest term to corporate_bond) for a single corporate bond. @type bond_dict: dictionary @rtype: Bond """ min_diff = None benchmark = None for key, value in bond_dict.items(): if value.get_type() == "government": diff = corporate_bond.term_difference(value) if min_diff == None: min_diff = diff benchmark = value elif min_diff > diff: min_diff = diff benchmark = value return benchmark def yields_to_benchmark(bond_dict): """ Finds government bond benchmark for every corporate bond in a dictionary of bonds. @type bond_dict: dictionary @rtype: None """ for key, bond in bond_dict.items(): if bond.get_type() == "corporate": benchmark = benchmark_finder(bond, bond_dict) spread = str(round(benchmark.yield_spread(bond), 2)) print(bond.get_name() + "," + benchmark.get_name() \ + "," + spread + "%")
# -*- coding: utf-8 -*- # !/usr/bin/env python # @Time : 2021/7/8 11:58 上午 # @Author : [email protected] # @Site : # @File : myself.py """ 930. 和相同的二元子数组 给你一个二元数组 nums ,和一个整数 goal ,请你统计并返回有多少个和为 goal 的 非空 子数组。子数组 是数组的一段连续部分 示例 1: 输入:nums = [1,0,1,0,1], goal = 2 输出:4 解释: 有 4 个满足题目要求的子数组:[1,0,1]、[1,0,1,0]、[0,1,0,1]、[1,0,1] 示例 2: 输入:nums = [0,0,0,0,0], goal = 0 输出:15 提示: - 1 <= nums.length <= 3 * 104 - nums[i] 不是 0 就是 1 - 0 <= goal <= nums.length """ from typing import List class Solution: """ 耗时过长 """ def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: count = 0 for index in range(len(nums)): _sum = 0 + nums[index] if _sum == goal: count += 1 for after in range(index + 1, len(nums)): _sum += nums[after] if _sum == goal: count += 1 return count class Solution2: """ 参考题解,遇0则记,遇1则开始加直到等于 goal 后开始记后续的 0,遇1则算,且开始记count """ def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: count = 0 left_zero = 0 right_zero = 0 _sum = 0 for num in nums: if num == 0 and _sum == 0: left_zero += 1 elif num == 0 and _sum == goal: right_zero += 1 elif num == 1 and _sum == goal: print({ "left_zero": left_zero, "right_zero": right_zero }) count += (left_zero + 1) * (right_zero + 1) left_zero = 0 right_zero = 0 _sum = 0 else: _sum += 1 return count class Solution3: """ 参考题解,记下所有1前面的0的个数放入一个数组里,然后再新的数组里 每隔 goal 取出来相乘 """ def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: count = 0 zero_count_list = [] _sum = 0 for num in nums: if num == 0: _sum += 1 else: zero_count_list.append(_sum + 1) _sum = 0 zero_count_list.append(_sum + 1) if goal == 0: for c in zero_count_list: count += (c * (c - 1)) // 2 return count index = 0 while index + goal < len(zero_count_list): count += zero_count_list[index] * zero_count_list[index + goal] index += 1 return count if __name__ == '__main__': solution = Solution() solution2 = Solution2() solution3 = Solution3() nums = [1, 0, 1, 0, 1] goal = 2 result = solution.numSubarraysWithSum(nums, goal) print(result) result = solution2.numSubarraysWithSum(nums, goal) print(result) result = solution3.numSubarraysWithSum(nums, goal) print(result) print() nums = [0, 0, 0, 0, 0] goal = 0 result = solution.numSubarraysWithSum(nums, goal) print(result) result = solution2.numSubarraysWithSum(nums, goal) print(result) result = solution3.numSubarraysWithSum(nums, goal) print(result)
from Node import Node class LinkedList(object): def __init__(self): self.head = None self.counter = 0 # O(N) def traverseList(self): currentNode = self.head while currentNode is not None: print("%d" % currentNode.data) currentNode = currentNode.nextNode # O(1) def insertStart(self, data): newNode = Node(data) if not self.head: self.head = newNode else: newNode.nextNode = self.head self.head = newNode self.counter += 1 # O(1) def size(self): return self.counter # O(N) def insertEnd(self, data): if self.head is None: return self.insertStart(data) newNode = Node(data) current = self.head while current.nextNode is not None: current = current.nextNode current.nextNode = newNode self.counter += 1 # O(N), if head O(1) def remove(self, data): if self.head: # head isn't None, populated if data == self.head.data: self.head = self.head.nextNode else: self.head.remove(data, self.head) self.counter -= 1
def quick_sort(A): if len(A) <= 1: return left, right, middle = [], [], [] pivot = A[0] for i in range(len(A)): if A[i] < pivot: left.append(A[i]) elif A[i] > pivot: right.append(A[i]) else: middle.append(A[i]) quick_sort(left) quick_sort(right) A[:] = left + middle + right
def brackets(sequence): ''' Возвращает True, если переданная последовательность скобок правильная. Иначе False. ''' open_brackets = ('(', '[', '{') close_brackets = (')', ']', '}') stack = [] for bracket in sequence: if bracket in open_brackets: stack.append(bracket) elif not stack: return False elif close_brackets.index(bracket) != open_brackets.index(stack.pop()): return False return True if not stack else False
#!/usr/bin/env python """ evaluators.py: Collection of functions that are used to evaluate individuals in the population. """ def optimize_depot_nodes(vrp, **kwargs): """ Attempts to optimize depot nodes by selecting them for each vehicle in such a manner that travel costs are as low as possible on both trips where a depot node is involved (first and last path). This function is to be used only if the parameter 'Optimize Depot Nodes' is set to True. In addition to that, it should be used prior to validation. :param vrp: A population individual subject to depot node optimization. :param kwargs: Keyword arguments, from which the following are expected: - (numpy.ndarray) 'path_table': Square matrix that represents distances between nodes. """ depot_nodes = vrp.depot_node_list path_table = kwargs["path_table"] route_list = vrp.get_route_list() optimized_solution = [] for route in route_list: if len(route) < 2: # Vehicle does not move anywhere. # Attach it back into the solution list and continue. optimized_solution = optimized_solution + route continue # This function assumes that the only times that a vehicle deals # with a depot node is both at the beginning and at the end. first_trip_distances = [] last_trip_distances = [] for depot_node in depot_nodes: first_trip_distances.append(path_table[depot_node][route[1]]) last_trip_distances.append(path_table[route[len(route) - 1]][depot_node]) # Sum the two distances and select the one with the least distance total. total_distances = [i + j for i, j in zip(first_trip_distances, last_trip_distances)] minimum_index = total_distances.index(min(total_distances)) # Assign the optimal depot node for the vehicle route. route[0] = depot_nodes[minimum_index] # Attach revised route into the solution list. optimized_solution = optimized_solution + route vrp.assign_solution(optimized_solution) def evaluate_travel_distance(vrp, **kwargs): """ (UNUSED) Evaluates total travel distance of an individual's solution using a path table. :param vrp: A population individual subject to evaluation. :param kwargs: Keyword arguments. The following are expected from it: - (numpy.ndarray) 'path_table': Square matrix that represents distances between nodes. :return: Total travel distance that comes from the solution presented by given individual. Also returns distances travelled by each vehicle. (int/float, list<int/float>) """ path_table = kwargs["path_table"] route_list = vrp.get_route_list() route_distances = [] for active_route in route_list: route_distance = 0 if len(active_route) <= 1: # Vehicle does not move anywhere. continue recent_node = active_route[0] recent_depot = active_route[0] for i in range(1, len(active_route)): point_a = active_route[i - 1] point_b = active_route[i] route_distance += path_table[point_a][point_b] # Mark down most recent node for the return trip. recent_node = point_b # Traveling back to the depot node. route_distance += path_table[recent_node][recent_depot] # Add route distance to a list of vehicle distances. route_distances.append(route_distance) return sum(route_distances), route_distances def evaluate_travel_time(vrp, **kwargs): """ (UNUSED) Evaluates total travel time of an individual's solution using time windows, service times and a path table. :param vrp: A population individual subject to evaluation. :param kwargs: Keyword arguments. The following are expected from it: - (numpy.ndarray) 'path_table': Square matrix that represents distances between nodes. - (function) 'distance_time_converter': Function that converts distance to time. - (list<tuple>) 'time_window': List of tuples that represent time windows of each node. - (list<int>) 'service_time': List of integers that represent node service times. - (bool) 'ovrp': Flag that determines whether problem instance is an OVRP. :return: Total travel distance that comes from the solution presented by given individual. Also returns total times for each route. (int/float, list<int/float>) """ path_table = kwargs["path_table"] distance_time = kwargs["distance_time_converter"] time_windows = kwargs["time_window"] service_time = kwargs["service_time"] is_open = kwargs["ovrp"] route_list = vrp.get_route_list() route_times = [] for active_route in route_list: route_time = 0 if len(active_route) <= 1: continue recent_node = active_route[0] recent_depot = active_route[0] # In case the first destination of the route involves waiting. That waiting time is instead # converted into a time at which the vehicle starts its route. route_start_time = max( 0, time_windows[active_route[1]][0] - distance_time(path_table[active_route[0]][active_route[1]]) ) vrp.route_start_times.append(route_start_time) for i in range(1, len(active_route)): point_a = active_route[i - 1] point_b = active_route[i] distance_segment = path_table[point_a][point_b] route_time += distance_time(distance_segment) # Check if arrival time is too early. start_window = time_windows[point_b][0] if route_time < start_window: # Vehicle has to wait until the beginning of the time window. route_time += start_window - route_time # Upon arrival the servicing begins. This takes time to complete. route_time += service_time[point_b] # Mark down most recent node for the return trip. recent_node = point_b # Traveling back to the depot node. if not is_open: distance_segment = path_table[recent_node][recent_depot] route_time += distance_time(distance_segment) start_window = time_windows[recent_depot][0] if route_time < start_window: route_time += start_window - route_time route_time += service_time[recent_depot] # Take route start time into account. route_time -= route_start_time # Add route time to a list of vehicle times. route_times.append(route_time) return sum(route_times), route_times def evaluate_travel_cost(vrp, **kwargs): """ Evaluates total travel costs of an individual's solution using time windows, service times, penalties and a path table. :param vrp: A population individual subject to evaluation. :param kwargs: Keyword arguments. The following are expected from it: - (numpy.ndarray) 'path_table': Square matrix that represents distances between nodes. - (function) 'distance_time_converter': Function that converts distance to time. - (function) 'distance_cost_converter': Function that converts distance to cost. - (function) 'time_cost_converter': Function that converts time to cost. - (list<tuple>) 'time_window': List of tuples that represent time windows of each node. - (list<int>) 'service_time': List of integers that represent node service times. - (list<float>) 'penalty': List of penalty coefficients that represent the importance of the nodes. :return: Total travel costs that come from the solution presented by given individual. """ path_table = kwargs["path_table"] distance_time = kwargs["distance_time_converter"] distance_cost = kwargs["distance_cost_converter"] time_cost = kwargs["time_cost_converter"] time_windows = kwargs["time_window"] service_time = kwargs["service_time"] penalty = kwargs["penalty"] route_list = vrp.get_route_list() time = 0 cost = 0 for active_route in route_list: route_time = 0 if len(active_route) <= 1: continue recent_node = active_route[0] recent_depot = active_route[0] # In case the first destination of the route involves waiting. That waiting time is instead # converted into a time at which the vehicle starts its route. route_start_time = max( 0, time_windows[active_route[1]][0] - distance_time(path_table[active_route[0]][active_route[1]]) ) vrp.route_start_times.append(route_start_time) # Keeps track of total waiting time for later inspections. (Key: Destination. Value: Waiting Time until service) waiting_dict = {} # Keeps track of total penalties for later inspections. (Key: Destination. Value: Penalty on arrival) penalty_dict = {} for i in range(1, len(active_route)): point_a = active_route[i - 1] point_b = active_route[i] distance_segment = path_table[point_a][point_b] route_time += distance_time(distance_segment) cost += distance_cost(distance_segment) # Check if arrival time is too late. end_window = time_windows[point_b][1] if route_time > end_window: # Vehicle has arrived too late. A penalty is calculated. lateness_penalty = penalty[point_b] * (route_time - end_window) penalty_dict[point_b] = lateness_penalty cost += lateness_penalty # Check if arrival time is too early. start_window = time_windows[point_b][0] if route_time < start_window: # Vehicle has to wait until the beginning of the time window. waiting_time = start_window - route_time waiting_dict[point_b] = waiting_time route_time += waiting_time # Upon arrival the servicing begins. This takes time to complete. route_time += service_time[point_b] # Mark down most recent node for the return trip. recent_node = point_b # Traveling back to the depot node. distance_segment = path_table[recent_node][recent_depot] route_time += distance_time(distance_segment) cost += distance_cost(distance_segment) end_window = time_windows[recent_depot][1] if route_time > end_window: lateness_penalty = penalty[recent_depot] * (route_time - end_window) penalty_dict[recent_depot] = lateness_penalty cost += lateness_penalty start_window = time_windows[recent_depot][0] if route_time < start_window: waiting_time = start_window - time waiting_dict[recent_depot] = waiting_time route_time += waiting_time route_time += service_time[recent_depot] # Take route start time into account. route_time -= route_start_time # Add route time to total time taken. time += route_time # Mark down incurred waiting times. vrp.route_waiting_times.append(waiting_dict) # Mark down collected penalties. vrp.route_penalties.append(penalty_dict) # Convert total time taken into costs. cost += time_cost(time) return cost def evaluate_profits(vrp, **kwargs): """ Evaluates total profits acquired from visiting optional nodes. :param vrp: A population individual subject to evaluation. :param kwargs: Keyword arguments. The following are expected from it: - (list<int>) 'node_profit': List of profits that one could get from visiting optional nodes. :return: Total profits that come from visiting nodes specified by given individual. """ node_profit_list = kwargs["node_profit"] solution = vrp.solution unvisited_optional_nodes = vrp.unvisited_optional_nodes profit = 0 for i in range(len(solution)): node = solution[i] if node not in unvisited_optional_nodes: profit += node_profit_list[node] vrp.profits = profit return profit def evaluate_profit_cost_difference(vrp, **kwargs): """ Evaluates difference between total profits and total costs. :param vrp: A population individual subject to evaluation. :param kwargs: Keyword arguments. The following are expected from it: - (numpy.ndarray) 'path_table': Square matrix that represents distances between nodes. - (function) 'distance_time_converter': Function that converts distance to time. - (function) 'distance_cost_converter': Function that converts distance to cost. - (function) 'time_cost_converter': Function that converts time to cost. - (list<tuple>) 'time_window': List of tuples that represent time windows of each node. - (list<int>) 'service_time': List of integers that represent node service times. - (list<float>) 'penalty': List of penalty coefficients that represent the importance of the nodes. - (list<int>) 'node_profit': List of profits that one could get from visiting respective nodes. :return: Total net profit. """ return evaluate_profits(vrp, **kwargs) - evaluate_travel_cost(vrp, **kwargs)
from algorithms.gradient_descent import * from algorithms.logistic_regression import * def iterations_to_achieve_minimum_error(min_value, initial_u=1, initial_v=1, learning_rate=0.1): n_iterations = 1 u = initial_u v = initial_v actual_value = error_surface_result(u, v) while actual_value > min_value: actual_value, u, v = gradient_descent_step(u, v, learning_rate) n_iterations += 1 return n_iterations, u, v def minimum_error_given_iterations_number(iterations, initial_u=1, initial_v=1, learning_rate=0.1): u = initial_u v = initial_v actual_value = error_surface_result(u, v) while iterations > 0: actual_value, u, v = coordinate_descent_step(u, v, learning_rate, iterations) iterations -= 1 return actual_value, u, v def average_epochs_and_e_out_to_converge(iterations, n_elements, y_min, y_max, learning_rate): sum_epochs = [] e_outs = [] n_iterations = iterations while n_iterations > 0: epochs, weights = logistic_regression(n_elements, y_min, y_max, learning_rate) sum_epochs.append(epochs) e_out = calculate_logistic_regression_e_out(weights, n_elements, y_min, y_max) e_outs.append(e_out) n_iterations -= 1 average_epochs = sum(sum_epochs) / iterations average_e_out = sum(e_outs) / iterations return average_epochs, average_e_out def gradient_descent_part(min_value): n_iterations, u, v = \ iterations_to_achieve_minimum_error(min_value) print('\nIterations to error get bellow to 1.0e-14: {}'.format(n_iterations)) print(f'\nu and v coordinates at the end: ({u}, {v})') min_error, u, v = minimum_error_given_iterations_number(iterations=30) print('\nError after 15 full iterations: {:.3e}'.format(min_error)) def logistic_regression_part(iterations, n_elements=100, y_min=-1, y_max=1, learning_rate=0.01): average_epochs, average_e_out = \ average_epochs_and_e_out_to_converge(iterations, n_elements, y_min, y_max, learning_rate) print('\nAverage epochs to converge: {}'.format(average_epochs)) print('\nAverage e_out: {}'.format(average_e_out)) if __name__ == '__main__': gradient_descent_part(min_value=1e-14) logistic_regression_part(iterations=100)
import requests import sys from bs4 import BeautifulSoup from PIL import Image from io import BytesIO base_url = "http://xkcd.com/" n = raw_input("Enter the comic number\n> ") if n.isdigit() == False: print "Input is not a number" sys.exit() url = base_url + str(n) page = requests.get(url).content soup = BeautifulSoup(page, "lxml") if soup.title.string == "404 - Not Found": print "Comic not found" else: comicImageBlock = soup.find("div",{"id":"comic"}) comicImageTag = comicImageBlock.find("img") comicURL = comicImageTag['src'] imageURL = 'https:' + comicURL img_data = requests.get(imageURL) i = Image.open(BytesIO(img_data.content)) save_file_name = 'xkcd' + str(n) + '.png' i.save(save_file_name) print "XKCD"+str(n)+" has been saved successfully" ch = raw_input("\nDo you want to open the image? yes or no\n> ") if ch == "y" or ch == "yes": print "Opening image" i.show() elif ch == "n" or ch == "no": exit() else: print "Invalid input"
#Given a non-overlapping interval list which is sorted by start point. #Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary). #Insert (2, 5) into [(1,2), (5,9)], we get [(1,9)]. #Insert (3, 4) into [(1,2), (5,9)], we get [(1,2), (3,4), (5,9)]. #Solution 1: while #Reference: https://www.cnblogs.com/grandyang/p/4367569.html """ Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ class Solution: """ @param intervals: Sorted interval list. @param newInterval: new interval. @return: A new interval list. """ def insert(self, intervals, newInterval): result = [] num = len(intervals) if (num == 0): result.append(newInterval) return result i = 0 while (i < num and intervals[i].end < newInterval.start): result.append(intervals[i]) i += 1 while (i < num and intervals[i].start <= newInterval.end): newInterval.start = min(newInterval.start, intervals[i].start) newInterval.end = max(newInterval.end, intervals[i].end) i += 1 result.append(newInterval) while (i < num): result.append(intervals[i]) i += 1 return result
#!/bin/python3 import math import os import random import re import sys # # Complete the 'nonDivisibleSubset' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER k # 2. INTEGER_ARRAY s # def nonDivisibleSubset(k, s): # Write your code here counts = [0] * k for num in s: counts[num % k] += 1 sum_ = min(counts[0], 1) if k % 2: return sum_ + sum([max(counts[i], counts[k-i]) for i in range(1, k//2 + 1)]) else: return sum_ + 1 + sum([max(counts[i], counts[k-i]) for i in range(1, k//2)]) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) k = int(first_multiple_input[1]) s = list(map(int, input().rstrip().split())) result = nonDivisibleSubset(k, s) fptr.write(str(result) + '\n') fptr.close()
# Enter your code here. Read input from STDIN. Print output to STDOUT import re for i in range(0, int(input())): matches = re.findall( r"(#(?:[\da-f]{3}){1,2})(?!\w)(?=.*;)", input(), re.IGNORECASE) for m in matches: print(m)
# Enter your code here. Read input from STDIN. Print output to STDOUT K = int(input()) room_numbers = list(map(int, input().split())) first = set() existing = set() for room in room_numbers: if room in first: existing.add(room) else: first.add(room) print(first.difference(existing).pop())
# Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import groupby if __name__ == "__main__": S = input() print(*[(len(list(g)), int(k)) for k, g in groupby(S)])
#!/bin/python3 import math import os import random import re import sys # # Complete the 'breakingRecords' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY scores as parameter. # def breakingRecords(scores): # Write your code here current_min = scores[0] current_max = scores[0] count_min = 0 count_max = 0 for score in scores: if score < current_min: current_min = score count_min += 1 elif score > current_max: current_max = score count_max += 1 return count_max, count_min if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) scores = list(map(int, input().rstrip().split())) result = breakingRecords(scores) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys # # Complete the 'minimumDistances' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def minimumDistances(a): # Write your code here min_ = len(a) idx = {} for index, number in enumerate(a): if number in idx: distance = index - idx[number] min_ = min(min_, distance) idx[number] = index if min_ != len(a): return min_ else: return -1 if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) a = list(map(int, input().rstrip().split())) result = minimumDistances(a) fptr.write(str(result) + '\n') fptr.close()
# Enter your code here. Read input from STDIN. Print output to STDOUT import re def convert(line): return re.sub(r"(?<= )(&&|\|\|)(?= )", lambda x: "and" if x.group() == "&&" else "or", line) if __name__ == "__main__": N = int(input()) for i in range(N): print(convert(input()))
#!/bin/python3 import math import os import random import re import sys # # Complete the 'cavityMap' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts STRING_ARRAY grid as parameter. # def cavityMap(grid): # Write your code here idx_change = [] for i in range(1, len(grid) - 1): for j in range(1, len(grid) - 1): if grid[i][j] > max(grid[i-1][j], grid[i+1][j], grid[i][j-1], grid[i][j+1]): idx_change.append([i, j]) for x, y in idx_change: grid[x] = grid[x][:y] + "X" + grid[x][y+1:] return grid if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) grid = [] for _ in range(n): grid_item = input() grid.append(grid_item) result = cavityMap(grid) fptr.write('\n'.join(result)) fptr.write('\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys # # Complete the 'appendAndDelete' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # 2. STRING t # 3. INTEGER k # def appendAndDelete(s, t, k): # Write your code here common = 0 for i in reversed(range(len(s))): if s[:i] == t[:i]: common = i break min_ = k - (len(s) + len(t) - 2 * common) if min_ >= 0 and min_ % 2 == 0 or k >= len(s) + len(t): return "Yes" else: return "No" if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() t = input() k = int(input().strip()) result = appendAndDelete(s, t, k) fptr.write(result + '\n') fptr.close()
# Enter your code here. Read input from STDIN. Print output to STDOUT def print_mode(a, b, m): print(pow(a, b)) print(pow(a, b, m)) if __name__ == "__main__": print_mode(int(input()), int(input()), int(input()))
#!/bin/python3 import math import os import random import re import sys # # Complete the 'viralAdvertising' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER n as parameter. # def viralAdvertising(n): # Write your code here shared = 5 cum = 0 for _ in range(n): liked = math.floor(shared / 2) cum += liked shared = liked * 3 return cum if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) result = viralAdvertising(n) fptr.write(str(result) + '\n') fptr.close()
def char_counter(string): for char in string[::]: if char != ' ': if char not in unique: unique.append(char) charctr.append(string.count(char)) print(char + '---' + str(string.count(char))) unique = [] charctr = [] char_counter('Hello World') char_counter('Hello World') #string = 'Hello World' #unique = [] #charctr = [] #for char in string[::]: #if char != ' ': #if char not in unique: #unique.append(char) #charctr.append(string.count(char)) #print(char + '---' + str(string.count(char))) print(unique) print(charctr)
import os, sys def digitNum(num): result = 0 while num > 0: result += 1 num /= 10 return result dict = { 0: 1, 1: 1, 2: 2 } index = 3 tmp = 2 while digitNum(dict[tmp]) < 1000: prePre = (tmp - 1 + 3) % 3 pre = tmp tmp = (tmp + 1) % 3 dict[tmp] = dict[pre] + dict[prePre] index += 1 print index
import os, sys Tri = 2 Pen = 2 Hex = 2 def Triangle(num): return num * (num + 1) / 2 def Pentagonal(num): return num * (3 * num - 1) / 2 def Hexagonal(num): return num * (2 * num - 1) start = 2 number = 0 while 1: while Triangle(Tri) < start: Tri += 1 while Pentagonal(Pen) < start: Pen += 1 while Hexagonal(Hex) < start: Hex += 1 if Triangle(Tri) == Pentagonal(Pen) and Hexagonal(Hex) == Pentagonal(Pen): print Triangle(Tri) number += 1 start += 1 else: start += 1 start = max(start, Hexagonal(Hex)) start = max(start, Triangle(Tri)) start = max(start, Pentagonal(Pen)) if number > 1: break
import random def get_prime_dic_and_list(maxNumber) -> (dict, list): primeDic = {} primeList = [] for index in range(2, maxNumber): if index not in primeDic: primeList.append(index) facter = 2 while facter * index < maxNumber: primeDic[facter*index] = 1 facter += 1 return primeDic, primeList def is_mill_rabin_prime(num) -> bool: if num < 2: return False if num == 2: return True if num % 2 == 0: return False s = 0 d = num - 1 while True: quatient, reminder = divmod(d, 2) if reminder == 1: break s += 1 d = quatient def try_composite(a): if pow(a, d, num) == 1: return False for i in range(s): if pow(a, pow(2,i)*d, num) == (num-1): return False return True for i in range(0,5): a = random.randrange(2,num) if try_composite(a): return False return True
''' ''' #target = 10 target = pow(10,25) #target = pow(10,18) #target = 4 unit = [1] while unit[len(unit)-1] * 2 <= target: nt = unit[len(unit)-1] * 2 unit.append(nt) hashDic=dict() def GetAnsFor(n, mx): if n == 0: return 1 #print(n) ret = 0 for i in range(mx-1, -1, -1): if unit[i] * 4 - 2 >= n and unit[i] <= n: nt = n-unit[i] if (nt, i) not in hashDic: hashDic[(nt,i)] = GetAnsFor(nt, i) ret += hashDic[(nt,i)] if unit[i] * 2 <= n: nt = n -unit[i]*2 if (nt, i) not in hashDic: hashDic[(nt,i)] = GetAnsFor(nt, i) ret += hashDic[(nt,i)] return ret print(GetAnsFor(target, len(unit)))
# Assignment 2 - Puzzle Game # # CSC148 Fall 2015, University of Toronto # Instructor: David Liu # --------------------------------------------- """This module contains functions responsible for solving a puzzle. This module can be used to take a puzzle and generate one or all possible solutions. It can also generate hints for a puzzle (see Part 4). """ from puzzle import Puzzle def solve(puzzle, verbose=False): """Return a solution of the puzzle. Even if there is only one possible solution, just return one of them. If there are no possible solutions, return None. In 'verbose' mode, print out every state explored in addition to the final solution. By default 'verbose' mode is disabled. Uses a recursive algorithm to exhaustively try all possible sequences of moves (using the 'extensions' method of the Puzzle interface) until it finds a solution. @type puzzle: Puzzle @type verbose: bool @rtype: Puzzle | None """ if puzzle.is_solved(): if verbose: print(puzzle) return puzzle else: for item in puzzle.extensions(): if verbose and not item.is_solved(): print(item) final = solve(item, verbose) # if a solved puzzle state is found if final is not None: return final def solve_complete(puzzle, verbose=False): """Return all solutions of the puzzle. Return an empty list if there are no possible solutions. In 'verbose' mode, print out every state explored in addition to the final solution. By default 'verbose' mode is disabled. Uses a recursive algorithm to exhaustively try all possible sequences of moves (using the 'extensions' method of the Puzzle interface) until it finds all solutions. @type puzzle: Puzzle @type verbose: bool @rtype: list[Puzzle] """ if puzzle.is_solved(): if verbose: print(puzzle) return [puzzle] elif len(puzzle.extensions()) == 0: return [] else: acc = [] for item in puzzle.extensions(): if verbose and not item.is_solved(): print(item) acc += solve_complete(item, verbose) return acc def hint_by_depth(puzzle, n): """Return a valid str representation of what the user would need to input to get a step closer to the solution. If <puzzle> is already solved, return the string 'Already at a solution!'. If <puzzle> cannot lead to a solution or other valid state within <n> moves, return the string 'No possible extensions!'. Precondition: n >= 1 @type puzzle: Puzzle @type n: int The number of steps. @rtype: str """ if puzzle.is_solved(): return 'Already at a solution!' soln = _get_sol_and_num_moves(puzzle) # if number of steps took to get solution is greater than n move, there is # no solution in n move, so set it to None. if soln is not None: if soln[1] > n: soln = None puzzles_with_one_move = puzzle.extensions() # if soln is None, we did not find a solution with in n moves. if soln is None: if len(_items_at_move(puzzle, n)) != 0: # if there exists a valid state after n moves, pick the first one. valid_state = _items_at_move(puzzle, n)[0] if n > 1: # find which one of the first moves, the valid state belongs to puzzle_want = find_hint_puzzle(valid_state, puzzles_with_one_move, n) return puzzle.find_user_input(puzzle_want) else: # valid state is one move away, find the user input to that. return puzzle.find_user_input(valid_state) else: return 'No possible extensions!' else: solved_puzzle = soln[0] steps_took = soln[1] if n == 1: return puzzle.find_user_input(soln[0]) else: puzzle_want = find_hint_puzzle(solved_puzzle, puzzles_with_one_move, steps_took) return puzzle.find_user_input(puzzle_want) def find_hint_puzzle(solved_puzzle, puzzles_with_one_move, steps_took): """ Return the one puzzle which would lead user to the solution or a valid state. @type solved_puzzle: Puzzle @type puzzles_with_one_move: list[Puzzle] @type steps_took: int @rtype: Puzzle """ for puzzle in puzzles_with_one_move: for item in _items_at_move(puzzle, steps_took - 1): if solved_puzzle.same_game_state(item): return puzzle def _items_at_move(puzzle, d): """Return a list of possible puzzles after d number of possible moves made to the puzzle. created by extensions game sate. Precondition: d >= 0. @type puzzle: Puzzle @type d: int @rtype: list """ if d == 0: return [puzzle] else: items = [] for new_state in puzzle.extensions(): items.extend(_items_at_move(new_state, d - 1)) return items def _get_sol_and_num_moves(puzzle, n=0): """ Return a tuple of solved item and the number of moves it took to get to the solution If it did not find a solution in n stpes, return None @type puzzle: Puzzle @type n: int @rtype: tuple(Puzzle, int) | None """ # if there is no extension for the puzzle if len(puzzle.extensions()) == 0: return None else: # if item is solved for new_state in puzzle.extensions(): if new_state.is_solved(): return new_state, n + 1 # recursive to solve the puzzle for new_state in puzzle.extensions(): if new_state is not None: return _get_sol_and_num_moves(new_state, n + 1) if __name__ == '__main__': from sudoku_puzzle import SudokuPuzzle s = SudokuPuzzle([['A', 'B', 'C', 'D'], ['D', 'C', 'B', 'A'], \ ['', 'D', '', ''], ['', '', '', '']]) # s = SudokuPuzzle([['B', 'A', 'D', 'C'], # ['D', 'C', 'A', ''], # ['C', 'D', 'A', 'B'], # ['A', 'B', 'C', 'D']])
volt="radar" n=2 k=len(volt) uj=volt[k-1] while n<=k: uj=uj+volt[k-n] n=n+1 print (uj) if uj==volt: print ("palindrom") else: print ("nem palindrom")
""" Simple tools to make lists """ from collections import abc from typing import Any import numpy as np __all__ = [ "is_list_like", "listify", "ndfy", ] def is_list_like( *objs, allow_sets: bool = True, func: object = all ) -> bool: """ Check if inputs are list-like Parameters ---------- *objs : object Objects to check. allow_sets : bool, optional. If this parameter is `False`, sets will not be considered list-like. Default: `True` func : funtional object, optional. The function to be applied to each element. Useful ones are `all` and `any`. Default: `all` Notes ----- Direct copy from pandas, with slight modification to accept *args and all/any, etc, functionality by `func`. https://github.com/pandas-dev/pandas/blob/bdb00f2d5a12f813e93bc55cdcd56dcb1aae776e/pandas/_libs/lib.pyx#L1026 Note that pd.DataFrame also returns True. Timing on MBP 14" [2021, macOS 12.2, M1Pro(6P+2E/G16c/N16c/32G)] %timeit yfu.is_list_like("asdfaer.fits") 4.32 µs +- 572 ns per loop (mean +- std. dev. of 7 runs, 100000 loops each) """ # I don't think we need speed boost here but... # if `func` is `any`, below can be reorganized by for loop and can return # `True` once it reaches `True` for the first time. return func( isinstance(obj, abc.Iterable) # we do not count strings/unicode/bytes as list-like and not isinstance(obj, (str, bytes)) # exclude zero-dimensional numpy arrays, effectively scalars and not (isinstance(obj, np.ndarray) and obj.ndim == 0) # exclude sets if allow_sets is False and not (allow_sets is False and isinstance(obj, abc.Set)) for obj in objs ) def listify( *objs, scalar2list: bool = True, none2list: bool = False ) -> list: """Make multiple object into list of same length. Parameters ---------- objs : None, str, list-like If single object, it will be converted to a list ``[obj]`` or ``obj``, depending on `scalar2list`. Any scalar input will be converted to a list of a target length (largest length among `objs`). If `None`, an empty list (`[]`) or ``[None]`` is returned depending on `none2list`. If multiple objects are given, maximum length of them is used as the target length. scalar2list : bool, optional. If `True`, a single scalar input will be converted to a list of a target length. Otherwise, it will be returned as is. none2list : bool, optional. Whether to return an empty list (`[]`). If `True`, ``[None]`` is returned if `objs` is `None`. Default: `False` Notes ----- If any obj of `None` need to be converted to a length>1 list, it will be made as [None, None, ...], rather than an empty list, regardless of `empty_if_none`. Timing on MBP 14" [2021, macOS 12.2, M1Pro(6P+2E/G16c/N16c/32G)]: %timeit yfu.listify([12]) 8.92 µs +- 434 ns per loop (mean +- std. dev. of 7 runs, 100000 loops each) %timeit yfu.listify("asdf") 7.08 µs +- 407 ns per loop (mean +- std. dev. of 7 runs, 100000 loops each) %timeit yfu.listify("asdf", scalar2list=False) 7.37 µs +- 586 ns per loop (mean +- std. dev. of 7 runs, 100000 loops each) """ def _listify_single(obj, none2list=True): if obj is None: return [obj] if none2list else [] elif is_list_like(obj): return list(obj) else: return [obj] if scalar2list else obj if len(objs) == 1: return _listify_single(objs[0], none2list=none2list) objlists = [_listify_single(obj, none2list=True) for obj in objs] lengths = [len(obj) for obj in objlists] length = max(lengths) for objl in objlists: if len(objl) not in [1, length]: raise ValueError(f"Each input must be 1 or max(lengths)={length}.") return [obj*length if len(obj) == 1 else obj for obj in objlists] def ndfy( item, length: int | None = None, default: Any = None ): """ Make an item to ndarray of `length`. Parameters ---------- item : None, general object, list-like The item to be made into an ndarray. If `None`, it will be filled by `default`. length : int, optional. The length of the final ndarray. If `None`, the length of the input is used (if `item` is a scalar, a length-1 array is returned). default : general object The default value to be used if `item` or any element of `item` is `None`. Default is `None` Notes ----- Useful for the cases when bezels, sigma, ... are needed. For example, if ``bezel_nd = [ndfy(b, length=arr.ndim) for b in listify(bezels)]`` ``ndfy(bezel_nd, length=arr.ndim)`` will give correct bezel, e.g., ``[[10, 10], [10, 10]]`` for all of the following cases:: 1. ``bezel=10`` 2. ``bezel=[10, 10]``, 3. ``bezel=[[10, 10], [10, 10]]``. It is also useful for `slicefy`. Note that some cases can be ambiguous: ``ndfy([[1, 2, 3]], length=3)`` may mean either:: 1. ``((1, 2, 3), (1, 2, 3), (1, 2, 3))`` 2. ``((1, 1, 1), (2, 2, 2), (3, 3, 3))`` `ndfy` uses the first assumption. """ item = [default if i is None else i for i in listify(item, none2list=True)] item_length = len(item) if (length is None) or (item_length == length): return item elif item_length != 1: _length = "1" if item_length == 1 else f"1 or `length`(={length})" raise ValueError(f"`len(item)` must be {_length}. Now it is {item_length}.") # Now, item_length == 1 return [item[0] for _ in range(length)]
# -*- coding: utf-8 -*- """ @Software:spyder @File:NumberToHanzi.py @Created on Thu Jun 4 16:08:47 2020 @author: betty @description:数字转文本表达 """ class NumberToHanzi(): def __init__(self): self.han_list = ["零" , "一" , "二" , "三" , "四" , "五" , "六" , "七" , "八" , "九"] self.unit_list = ["十" , "百" , "千"] ''' 把一个四位的数字字符串变成汉字字符串 num_str 需要被转换的四位的数字字符串 返回四位的数字字符串被转换成汉字字符串 ''' def four_to_hanstr(self,num_str): result = "" num_len = len(num_str) for i in range(num_len): num = int(num_str[i]) if i != num_len - 1 and num != 0 : result += self.han_list[num] + self.unit_list[num_len - 2 - i] else : if num == 0 and result and result[-1]=='零': continue else: result += self.han_list[num] return result def dig2cn(self,num_str): str_len = len(num_str) if str_len > 12 : print('数字太大,翻译不了') return # 如果大于8位,包含单位亿 elif str_len > 8: hanstr = self.four_to_hanstr(num_str[:-8]) + "亿" + \ self.four_to_hanstr(num_str[-8: -4]) + "万" + \ self.four_to_hanstr(num_str[-4:]) # 如果大于4位,包含单位万 elif str_len > 4: hanstr = self.four_to_hanstr(num_str[:-4]) + "万" + \ self.four_to_hanstr(num_str[-4:]) else: hanstr = self.four_to_hanstr(num_str) if hanstr[-1]=='零': hanstr = hanstr[:-1] return hanstr if __name__ == "__main__": gg=NumberToHanzi() print(gg.dig2cn('5555'))
#O(2N) runtime (simplifies to O(N) runtime.) from collections import deque def main(): d = deque('abcdefgghh') print d dupes = listDupes(d) newD = removeDupes(d, dupes) print newD def listDupes(d): values = {} take_out = [] for item in d: if item in values: take_out.append(item) else: values[item] = 1 return take_out def removeDupes(d, dupes): for item in dupes: d.remove(item) return d if __name__ == "__main__": main()
''' Wall Class ''' import pygame from physical_object import PhysObj class Wall(PhysObj): # Inherits functions from superclass PhysObj def __init__(self, orientation, x, y): super(Wall, self).__init__(x, y) # Sets the attributes of wall self.orientation = orientation self.pos_x = x self.pos_y = y # Determines if the wall is horizontal or vertical by seeing if the orientation number is even or odd # Uploads the appropriate image according to the parity of the number if orientation % 2 == 0: self.image = pygame.image.load('wall_H.png').convert_alpha() elif orientation % 2 == 1: self.image = pygame.image.load('wall_V.png').convert_alpha() else: print 'Error: orientation is not defined or is not a number' # Update the image of the wall self.rect = self.image.get_rect() self.update_rect()
''' Created on Feb 14, 2016 @author: fzhang ''' import sys x = 1234 res = 'integers:...%d...%-6d...%06d' % (x, x, x) print(res) x = 1.23456789 res = '%e | %f |%g' % (x, x, x) print(res) res = '%-6.2f | %05.2f | %+06.1f' % (x, x, x) print(res) ''' When sizes are not known until runtime, you can use a computed width and precision by specifying them with a * in the format string to force their values to be taken from the next item in the inputs to the right of the % operator--the 4 in the tuple here gives precision: ''' res = '%f, %.2f, %.*f' % (1 / 3.0, 1 / 3.0, 4, 1 / 3.0) print(res) # Dictionary-Based Formatting Expressions res = '%(qty)d more %(food)s' % {'qty': 1, 'food': 'spam'} print(res) # working with vars() built-in function food = 'spam' qty = 10 # print(vars()) res = '%(qty)d more %(food)s' % vars() print(res) # Formatting Method Basics template = '{0}, {1} and {2}' print(template.format('spam', 'ham', 'eggs')) template = '{motto}, {pork} and {food}' print(template.format(motto='spam', pork='ham', food='eggs')) template = '{}, {} and {}' print(template.format('spam', 'ham', 'eggs')) # Adding Keys, Attributes, and Offsets res = 'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'laptop'}) print(res) res = 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'laptop'}) print(res) somelist = list('spam') res = 'first={0[0]}, third={0[2]}'.format(somelist) print(res) res = 'first={0}, last={1}'.format(somelist[0], somelist[-1]) print(res) parts = somelist[0], somelist[-1], somelist[1:3] res = 'first={0}, last={1}, middle={2}'.format(*parts) print(res)
""" Uma rainha requisitou os serviços de um monge e disse-lhe que pagaria qualquer preço. O monge, necessitando de alimentos, indagou à rainha sobre o pagamento, se poderia ser feito com grãos de trigo dispostos em um tabuleiro de xadrez, de tal forma que o primeiro quadro deveria conter apenas um grão e os quadros subseqüentes, o dobro do quadro anterior. A rainha achou o trabalho barato e pediu que o serviço fosse executado, sem se dar conta de que seria impossível efetuar o pagamento. Faça um algoritmo para calcular o número de grãos que o monge esperava receber. """ grains = 1 totgrains = 1 i = 1 while i <= 63: grains = grains * 2 totgrains = totgrains + grains i += 1 print(totgrains)
import random nbr_secret = random.randint(1,100) invite = 'Propose un nombre : ' while True: nbr_joueur = input(invite) if nbr_secret == int(nbr_joueur): print('Correct!') break elif nbr_secret > int(nbr_joueur): print('Trop bas') else: print('Trop haut')
class Node : def __init__(self, item, n=None): self.item = item self.next = n def enQueue(item): global front, rear newNode = Node(item) # 새로운 노드 생성 if front == None : # 큐가 비었다면 front = newNode else: rear.next = newNode rear = newNode def isEmpty(): return front == None def deQueue(): global front, rear if isEmpty(): print("EMPTY!") return None item = front.item front = front.next if front == None: rear = None return item def Qpeek(): return front.item def printQ(): f = front s = "" while f: s += str(f.item) + " " f = f.next return s front = rear = None ma = 20 check = 0 student = [0] * 22 first = 1 while (ma>0): if(check != 0): print(f"{check}번 학생 : 다시 줄을 선다.") enQueue(check) else : enQueue(first) print(f"학생 줄 : [{printQ()}]") if(first!=1): print(f"==>{first}번 학생: 입장하여 줄을 선다.") enQueue(first) print(f"학생 줄 : [{printQ()}]") check = deQueue() print(f"{check}번 학생 줄에서 나와...") cnt = student[check] + 1 print(f"학생 줄 : [{printQ()}]") print(f"{check}번 학생 : 선생님한테 사탕 {cnt}개를 받는다.") student[check] += 1 print("@@@@", student) ma -= cnt first +=1 if(ma<0): print(f"===== 남은 사탕의 개수는 0개다.") else : print(f"===== 남은 사탕의 개수는 {ma}개다.") print()
import time def insertion_sort(data,drawData,speed): for i in range(1,len(data)): key = data[i] drawData(data,['black' if x==i else 'red' for x in range(len(data))]) time.sleep(speed) j=i-1 while j>=0 and key < data[j]: data[j+1]=data[j] drawData(data,['green' if x==j or x==j+1 else 'red' for x in range(len(data))]) time.sleep(speed) j-=1 data[j+1] = key return data
# -*- coding: utf-8 -*- """ Created on Sat Sep 26 14:43:19 2015 @author: stoimenoff """ class KIntersect: def count(self, lists, n): nums = {} for i in range(n - 1): for item in lists[i]: if item in nums: nums[item] += 1 else: nums[item] = 1 result = [] for item in lists[n-1]: if item in nums: if nums[item] == n - 1: result.append(item) return result def main(): n = int(input()) lists = [] for i in range(n): list_i = [int(item) for item in input().split()][1:] lists.append(list_i) res = KIntersect().count(lists, n) for item in res: print(item) main()
# -*- coding: utf-8 -*- """ Created on Tue Jun 30 13:08:49 2015 @author: stoimenoff """ class Node: def __init__(self, value, next_node=None): self.value = value self.next_node = next_node def value(self): return self.value def get_next(self): return self.next_node def set_next(self, next_node): self.next_node = next_node def __gt__(self, node): return self.value > node.value def __lt__(self, node): return self.value < node.value def __str__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None self.tail = None self.size = 0 def add_tail(self, value): new_node = Node(value) if self.head == None: self.head = new_node self.tail = self.head else: self.tail.set_next(new_node) self.tail = new_node def add_head(self, value): new_node = Node(value) if self.head == None: self.head = new_node self.tail = self.head else: new_node.set_next(self.head) self.head = new_node def pop(self): if self.head != None: value = self.head.value self.head = self.head.get_next() if self.head == None: self.tail = None return value class Queue: def __init__(self): self.items = LinkedList() self.size = 0 # Adds value to the end of the Queue. # Complexity: O(1) def push(self, value): self.items.add_tail(value) self.size += 1 # Returns value from the front of the Queue and removes it. # Complexity: O(1) def pop(self): if self.size > 0: self.size -= 1 return self.items.pop() return None # Returns value from the front of the Queue without removing it. # Complexity: O(1) def peek(self): if self.size > 0: return self.items.head.value return None # Returns the number of elements in the Queue. # Complexity: O(1) def size(self): return self.size class ClosestCoffeeStore: # Finds the closest coffee store to a point. # graph - [[bool]] # starting_point - int # is_coffee_store - [bool] def closestCoffeeStore(self, graph, is_coffee_store, starting_point): verts = Queue() verts.push(starting_point) verts.push(-1) visited = [0] * len(graph) visited[starting_point] = 1 distance = 0 while verts.size != 0: vert = verts.pop() if vert == -1: distance += 1 if verts.size != 0: verts.push(-1) continue if is_coffee_store[vert] == 1: return distance else: for i in range(len(graph)): if graph[vert][i] == 1 and visited[i] == 0: verts.push(i) visited[i] = 1 return -1 def main(): n = int(input()) graph = [] for i in range(n): row = [int(num) for num in input().split()] graph.append(row) starting_point = int(input()) is_coffee_store = [int(num) for num in input().split()] print(ClosestCoffeeStore().closestCoffeeStore(graph, is_coffee_store, starting_point)) main()
class Vector: def __init__(self, capacity): self.items = [None] * capacity self.capacity = capacity self.size = 0 # Adds value at a specific index in the Vector. # Complexity: O(n) def insert(self, index, value): if self.size == self.capacity: self.items += self.capacity * [None] self.capacity *= 2 for i in range(self.size - 1, index, -1): self.items[i] = self.items[i - 1] self.items[index] = value self.size += 1 # Adds value to the end of the Vector. # Complexity: O(1) def add(self, value): if self.size == self.capacity: self.items += self.capacity * [None] self.capacity *= 2 self.items[self.size] = value self.size += 1 # Returns value at a specific index in the Vector # Complexity: O(1) def get(index): return self.items[index] # Removes element at the specific index # Complexity: O(n) def remove(self, index): for i in range(index, self.size - 1): self.items[i] = self.items[i + 1] self.items[self.size - 1] = None self.size -= 1 # Removes element at the last index # Complexity: O(1) def pop(self): self.items[self.size - 1] = None self.size -= 1 # Returns the number of elements in the Vector. # Complexity: O(1) def size(self): return self.size # Returns the total capacity of the Vector. # Complexity: O(1) def capacity(self): return self.capacity
# -*- coding: utf-8 -*- """ Created on Thu Jun 11 13:39:00 2015 @author: stoimenoff """ class Sorting: # Sorts a sequence of integers. def sort(self, sequence): for index in range(0, len(sequence)): minEl = sequence[index] minElIndex = index for second_index in range(index+1, len(sequence)): if sequence[second_index] < minEl: minEl = sequence[second_index] minElIndex = second_index swap = sequence[minElIndex] sequence[minElIndex] = sequence[index] sequence[index] = swap return sequence
class Library: def __init__(self, listOfBooks): self.books = listOfBooks def displayAvailBooks(self): print("Books present in this libray are:") for book in self.books: print("\t*", book) def borrowBook(self,bookName): if bookName in self.books: print(f"You have been issued {bookName}. Please keep it safe") self.books.remove(bookName) else: print("Sorry, this book is not available") return False def returnBook(self,bookName): self.books.append(bookName) print("Thanks for returning this book") class Student: def requestBook(self): self.book = input("Enter the name of Book you want to borrow : ") return self.book def returnBook(self): self.book = input("Enter the book of name you want to return") return self.book if __name__ =="__main__": collegeLibrary = Library(["Python", "Django", "Git", "Rest"]) student = Student() while(True): welcomeMsg = """ =====Welcome to our Library ====== Please choose an option: 1. List all Books 2. Request a book 3. Add/Return a book 4. Exit the Library """ print(welcomeMsg) a = int(input("Enter a choice - ")) if a ==1: collegeLibrary.displayAvailBooks() elif a == 2: collegeLibrary.borrowBook(student.requestBook()) elif a ==3: collegeLibrary.returnBook(student.returnBook()) elif a == 4: print("Thanks for choosing Library") exit() else: print("invalid choice")
from tkinter import * from tkinter import font window = Tk() def from_kg(): gram = float(e2_value.get())*1000 pound = float(e2_value.get())*2.20462 ounce = float(e2_value.get())*35.274 t1.delete("1.0",END) t1.insert(END, gram) t2.delete("1.0", END) t2.insert(END, pound) t3.delete("1.0", END) t3.insert(END, ounce) window.title("created by sohel") e1 = Label(window, text=" weight in KG",font=(font.ITALIC,10,font.BOLD)) e2_value = StringVar() e2 = Entry(window, textvariable=e2_value) e3 = Label(window, text="Gram",fg="blue") e4 = Label(window, text="Pound",fg="blue") e5 = Label(window, text="Ounce",fg="blue") t2 = Text(window, height=2, width=30,bg="red") t3 = Text(window, height=2, width=30,bg="yellow") t1 = Text(window, height=2, width=30,bg="green") b1 = Button(window, text="Convert", command=from_kg,bd=4) e1.grid(row=0, column=0) e2.grid(row=0, column=1) e3.grid(row=1, column=0) e4.grid(row=1, column=1) e5.grid(row=1, column=2) t1.grid(row=2, column=0) t2.grid(row=2, column=1) t3.grid(row=2, column=2) b1.grid(row=0, column=2) window.mainloop()
import socket import select HEADER_LENGTH = 10 IP = "127.0.0.1" PORT = 1234 # Create a socket # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX # socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SO_ - socket option # SOL_ - socket option level # Sets REUSEADDR (as a socket option) to 1 on socket server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind, so server informs operating system that it's going to use given IP and port # For a server using 0.0.0.0 means to listen on all available interfaces, useful to connect locally to 127.0.0.1 and remotely to LAN interface IP server_socket.bind((IP, PORT)) # This makes server listen to new connections server_socket.listen() # List of sockets for select.select() sockets_list = [server_socket] # List of connected clients - socket as a key, user header and name as data clients = {} print(f'Listening for connections on {IP}:{PORT}...') def receive_message(client_socket): try: message_header = client_socket.recv(HEADER_LENGTH) if not len(message_header): return False message_length = int(message_header.decode("utf-8").strip()) return {"header": message_header, "data": client_socket.recv(message_length)} except: return False while True: # Calls Unix select() system call or Windows select() WinSock call with three parameters: # - rlist - sockets to be monitored for incoming data # - wlist - sockets for data to be send to (checks if for example buffers are not full and socket is ready to send some data) # - xlist - sockets to be monitored for exceptions (we want to monitor all sockets for errors, so we can use rlist) # Returns lists: # - reading - sockets we received some data on (that way we don't have to check sockets manually) # - writing - sockets ready for data to be send thru them # - errors - sockets with some exceptions # This is a blocking call, code execution will "wait" here and "get" notified in case any action should be taken read_socket, _, exception_sockets = select.select(sockets_list, [], sockets_list) # Iterate over notified sockets for notified_socket in read_socket: # If notified socket is a server socket - new connection, accept it if notified_socket == server_socket: client_socket, client_address = server_socket.accept() user = receive_message(client_socket) if user is False: continue sockets_list.append(client_socket) clients[client_socket] = user print(f"Accepted new connection from {client_address[0]}:{client_address[1]} username:{user['data'].decode('utf-8')}") else: message = receive_message(notified_socket) if message is False: print(f"Close connection from {clients[notified_socket]['data'].decode('utf-8')}") sockets_list.remove(notified_socket) del clients[notified_socket] continue user = clients[notified_socket] print(f"Receive message from {user['data'].decode('utf-8')}: {message['data'].decode('utf-8')}") for client_socket in clients: if client_socket != notified_socket: client_socket.send(user['header'] + user['data'] + message['header'] + message['data']) for notified_socket in exception_sockets: sockets_list.remove(notified_socket) del clients[notified_socket]
#Menor e Maior valor a = int(input('Digite o 1º número. ')) b = int(input('Digite o 2º número. ')) c = int(input('Digite o 3º número. ')) d = int(input('Digite o 4º número. ')) e = int(input('Digite o 5º número. ')) menor = a if b <= a and b <= c and b <= d and b <= e: menor = b if c <= a and c <= b and c <= d and c <= e: menor =c if d <= a and d <= b and d <= c and d <= e: menor = d if e <= a and e <= b and e <= c and e <= d: menor = e maior = a if b >= a and b >= c and b >= d and b >= e: maior = b if c >= a and c >= b and c >= d and c >= e: maior =c if d >= a and d >= b and d >= c and d >= e: maior = d if e >= a and e >= b and e >= c and e >= d: maior = e print('O menor valor digitado é: {}'.format(menor)) print('O maior valor digitado é: {}'.format(maior))
import pandas as pd import numpy as np import math from evaluation import evaluation filename = "datasets/" + input("Enter the dataset name : ") dataset = pd.read_csv(filename) y = dataset.iloc[:,0].to_numpy() x = dataset.iloc[:,1:].to_numpy() k = 1 baco = True lambda_ = 10 ** (-1*(len(str(len(x[0]))))) f,acc = evaluation(x,y,lambda_,k=k,baco=baco) print("\n\nTotal number of features = {}".format(len(x[0]))) print("k value used for knn = {}".format(k)) print("\nAccuracy = {}%\n".format(round(acc*100,2)))
import os def Menu(): os.system("clear") print "---NetSend---" print "[1] Send message to a single computer" print "[2] Send message to multiple computers" print "[3] Send spam to a single computer" print "[4] Send spam to multiple computers" print "[5] view computers on network" try: option = int(raw_input("Option: ")) if option == 1: get_mach("single", "one", "single_msg_one_mach") elif option == 2: get_mach("single", "multi", "single_msg_multi_mach") elif option == 3: get_mach("spam", "one", "spam_msg_one_mach") elif option == 4: get_mach("spam", "multi", "spam_msg_multi_mach") elif option == 5: view_comps_on_network() else: print "error testing..." pause = raw_input() exit() errors("menu_option_err") except ValueError: print "error testing..." pause = raw_input() exit() errors("menu_option_err") def get_mach(msg_type, mach_type, net_send_type): if mach_type == "one": computer_name = raw_input("computer name or ip: ") if len(computer_name) == 0: #call error print "error testing..." pause = raw_input() exit() else: get_msg(msg_type, mach_type, net_send_type, computer_name) elif mach_type == "multi": computer_names = [] try: print "enter the name or ip of the computes with a space between each one" print "for example: computer1 computer2 computer3\n" computer_names_str = raw_input("computer names: ") if len(computer_names_str) < 1: #calls errors print "error testing..." pause = raw_input() exit() else: computer_names = computer_names_str.split() get_msg(msg_type, mach_type, net_send_type, computer_names) except ValueError: #call errors print "error testing..." pause = raw_input() exit() def get_msg(msg_type, mach_type, net_send_type, computerNames): message = raw_input("message: ") if len(message) == 0: #calls errors print "error testing..." pause = raw_input() exit() else: if msg_type == "single": net_send(net_send_type, computerNames, message, "NA") else: try: spam_count = int(raw_input("number of times to spam: ")) if spam_count == 0: #calls errors print "error testing..." pause = raw_input() exit() else: net_send(net_send_type, computerNames, message, spam_count) except ValueError: #calls errors print "error testing..." pause = raw_input() exit() def net_send(net_send_type, computerNames, message, spamCount): if net_send_type == "single_msg_one_mach": #send message to single machine #os.system("net send %s %s" % (computerNames, message)) #os.system("PAUSE") #Menu() print "net send %s %s" % (computerNames, message) print "message sent to %s" % computerNames pause = raw_input("Press any key to continue...") Menu() elif net_send_type == "single_msg_multi_mach": numb_of_computers = len(computerNames) i = 0 while i < numb_of_computers: #os.system("net send %s %s" % (computerNames[i], message)) print "net send %s %s" % (computerNames[i], message) print "message sent to %s" % computerNames[i] i += 1 pause = raw_input("Press any key to continue...") Menu() elif net_send_type == "spam_msg_one_mach": print net_send_type print computerNames print message print spamCount elif net_send_type == "spam_msg_multi_mach": print net_send_type print computerNames print message print spamCount else: pass def view_comps_on_network(): #os.system("net view") #os.system("PAUSE") print "will use the 'net view' command to list computers on network" pause = raw_input() Menu() def errors(error_type): print "test1" print "error testing..." Menu()
from sys import argv script, username = argv prompt ='>' print ("Hi %s, I am the %r script." % (username, script)) print ("I'd like to ask you a few questions") print ("Do you like me %s?" % username) likes = input(prompt) print ("Where do you live?") lives = input(prompt) print ("What kind of computer do you have?") computer = input(prompt) print (""" Alright you said %r about liking me. You said you live in %s. Not sure where it is. And you have a %r computer. Nice. """ % (likes, lives, computer))
container = ['a','b','c'] string_build = "" for data in container: string_build += str(data) # inefficient because it is done with immuatable object (string) print(string_build) builder_list = [] for data in container: builder_list.append(str(data)) # efficient because it is done with mutable object (list) print("".join(builder_list)) t = ("test", builder_list) # the tuple t is itself not mutable. But the list builder_list inside that is mutable builder_list.append('qrs') print(t) ### Another way is to use a list comprehension print("".join([str(data) for data in container])) # efficient because it is done with mutable object (list) ### or use the map function print("".join(map(str, container))) # efficient because it is done with mutable object (list) def my_function(param=[]): param.append("thing") return param print(my_function()) # returns ["thing"] print(my_function()) # returns ["thing", "thing"] def my_function2(param=None): if param is None: param = [] param.append("thing") return param print(my_function2()) # returns ["thing"] print(my_function2()) # returns ["thing"] def updateList(list1): list1.append(10) n = [5, 6] print(id(n)) # 140312184155336 updateList(n) # we have called the list via call by reference, so the changes are made to the original list itself print(n) # [5, 6, 10] print(id(n)) # 140312184155336 m = [] print(id(m)) updateList(m) print(m) print(id(m)) def updateNumber(n): print(id(n)) n += 10 b = 5 print(id(b)) # 10055680 updateNumber(b) # 10055680 # The same object is passed to the function, but the variables value doesn’t change even though the object is identical. This is called pass by value. # So what is exactly happening here? When the value is called by the function, only the value of the variable is passed, not the object itself. # So the variable referencing the object is not changed, but the object itself is being changed but within the function scope only. # Hence the change is not reflected. print(b) # 5
def func(x, y, z): return x + y + z print(func(2, 3, 4)) f = lambda x, y, z: x + y + z print(f(2, 3, 4)) a = lambda x = 'fee', y = 'fie', z = 'foe': x + y + z print(a('wee')) def knights(): title = 'Sir' action = (lambda x: title+' '+x) return action act = knights() msg = act('Muthu') print(msg) L = [lambda x: x**2, lambda x: x**3, lambda x: x**4] for f in L: print(f(2)) print(L[0](8)) def f1(x): return x ** 2 def f2(x): return x ** 3 # Define named functions def f3(x): return x ** 4 L = [f1, f2, f3] # Reference by name for f in L: print(f(2)) # Prints 4, 8, 16 print(L[0](3)) # Prints 9 key = 'got' dict1 = {'already': (lambda: 2 + 2), 'got': (lambda: 2 * 4), 'one': (lambda: 2 ** 6)} print(dict1[key]()) print(dict1['one']()) dict2 = {'one': 3+2, 'two': 3*4, 'three': 3**6} print(dict2['two']) lower = (lambda x, y: x if x < y else y) higher = (lambda x, y : x if x > y else y) print(lower('aa','bb')) print(higher('bb','aaa')) ##### import sys showall = lambda x: list(map(sys.stdout.write, x)) # 3.X: must use list t = showall(['spam\n', 'toast\n', 'eggs\n']) # 3.X: can use print showall = lambda x: [sys.stdout.write(line) for line in x] t = showall(('bright\n', 'side\n', 'of\n', 'life\n')) showall = lambda x: [print(line, end='') for line in x] # Same: 3.X only t = showall(('bright\n', 'side\n', 'of\n', 'life\n')) showall = lambda x: print(*x, sep='', end='') # Same: 3.X only t = showall(('bright\n', 'side\n', 'of\n', 'life\n')) ##### def action(x): return (lambda y: x + y) # Make and return function, remember x act = action(99) print(act) #<function action.<locals>.<lambda> at 0x00000000029CA2F0> print(act(2)) # Call what action returned action = (lambda x: (lambda y: x + y)) #poor readability - avoid nested lambdas act = action(99) print(act(3)) print(((lambda x: (lambda y: x + y))(99))(4)) #poor readability - avoid nested lambdas
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] print (animals[0], animals[-1], animals[:2], animals[2:], animals[1:1], animals[1:2])
# write your code here import random def get_task(): global a, b, opr, base_n if level == 2: base_n = random.randint(11, 29) print(base_n) elif level == 1: opr_list = ['+', '-', '*'] operands = [random.randrange(2, 10) for _ in range(2)] a = operands[0] b = operands[1] opr = random.choice(opr_list) print(f"{a} {opr} {b}") def calc_task(): global result result = 0 if level == 2: result = base_n ** 2 elif level == 1: if opr == '+': result = a + b elif opr == '-': result = a - b elif opr == '*': result = a * b elif opr == '/': try: result = a / b except ArithmeticError: print("Divide with zero!") mark = 0 while True: print("Which level do you want? Enter a number:") print("1 - simple operations with numbers 2-9") print("2 - integral squares of 11-29") try: level = int(input()) except ValueError: print("Wrong format! Try again.") else: if level not in (1, 2): print("Incorrect format.") else: break for _ in range(5): get_task() calc_task() while True: try: answer = int(input()) except ValueError: print("Incorrect format.") else: if answer == result: print("Right!") mark += 1 break else: print("Wrong!") break print(f"Your mark is {mark}/5. Would you like to save the result? Enter yes or no.") should_save = input().lower() if should_save in ('y', 'Y', 'YES', 'Yes', 'yes'): print("What is your name?") name = input() with open("results.txt", mode='a') as file: level_text = "in level 1 (simple operations with numbers 2-9)." if level == 1 else \ "in level 2 (integral squares of 11-29)." file.write(f"{name}: {mark}/5 {level_text}\n") print('The results are saved in "results.txt".')
import copy class TreeNode: ''' This is a tree Node class ''' def __init__(self, key): self.left = None self.right = None self.key = key class BinaryTree(): ''' This is a Binary Tree Class ''' def __init__(self, root): self.root = root def preorderR(self, root): if not root: return print root.key, self.preorderR(root.left) self.preorderR(root.right) def inorderR(self, root): if not root: return self.inorderR(root.left) print root.key, self.inorderR(root.right) def postorderR(self, root): if not root: return self.postorderR(root.left) self.postorderR(root.right) print root.key def is_leaf(self, root): if root.right or root.left: return False return True def count(self, root): if not root: return 0 return 1 + self.count(root.right) + self.count(root.left) def max_sum_max_le_utility(self, root, curr_length, max_length, max_sum, sum): if max_length[0] < curr_length: max_sum[0] = sum max_length[0] = curr_length elif max_length[0] == curr_length: max_sum[0] = max(max_sum[0], sum) if not root: return self.max_sum_max_le_utility(root.left , curr_length + 1, max_length, max_sum, sum + root.key) self.max_sum_max_le_utility(root.right, curr_length + 1, max_length, max_sum, sum + root.key) def max_sum_max_length(self, root): max_length = [-100000000000] # for passing through the reference max_sum = [-100000000] # for passing through the reference self.max_sum_max_le_utility(root, 0 , max_length, max_sum ,0) return max_sum[0] def max_sum_path_utility(self, root, max_sum): if not root: return 0 la = self.max_sum_path_utility(root.left, max_sum) ra = self.max_sum_path_utility(root.right, max_sum) big_edge = max(la + root.key, ra + root.key) max_sum[0] = max(max_sum[0],max(la, max(ra, big_edge))) max_sum[0] = max(max_sum[0], la + ra + root.key) return big_edge def max_sum_path(self, root): max_sum = [-1] self.max_sum_path_utility(root, max_sum) return max_sum[0] def largest_sum_subtree_utility(self, root, max_sum): if not root: return 0 ls = self.largest_sum_subtree_utility(root.left,max_sum) rs = self.largest_sum_subtree_utility(root.right,max_sum) max_sum[0] = max(max(max_sum[0],ls),rs) max_sum[0] = max(max_sum[0],ls+rs+root.key) return ls + rs + root.key def largest_sum_subtree(self, root): max_sum = [-1] self.largest_sum_subtree_utility(root, max_sum) return max_sum[0] # prints downward paths only def print_k_path_sum(self, root, path, k): if not root: return path.append(root.key) self.print_k_path_sum(root.left, path=copy.deepcopy(path), k=k) self.print_k_path_sum(root.right, path=copy.deepcopy(path), k=k) # now we have path till this node. sum = 0 for i in range(len(path)-1 , -1,-1): sum += path[i] # print sum, if sum == k: # print 'YIKES !!!\n' , path , '\n' print path[i:len(path)] , '\n' # for each in pr_path: # print each , # print '\n' def subtree_with_given_sum_utilty(self, root,flag, sum): if not root: return 0 ls = self.subtree_with_given_sum_utilty(root.left, flag=flag, sum=sum) rs = self.subtree_with_given_sum_utilty(root.right, flag = flag, sum=sum) # print ls , rs , root.key , '\n' if ls + rs + root.key == sum: flag[0] = True return ls + rs + root.key def subtree_with_given_sum(self, root, sum): flag = [False] self.subtree_with_given_sum_utilty(root, flag, sum) if flag[0]: return "YES" else: return "NO" if __name__ == '__main__': n1 = TreeNode(26) # root n2 = TreeNode(10) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(6) n6 = TreeNode(1) n7 = TreeNode(13) n1.left = n2 n1.right = n3 n2.left = n4 n2.right = n5 n3.left = n6 n3.right = n7 # n1 = TreeNode(-15) # n2 = TreeNode(5) # n3 = TreeNode(6) # n4 = TreeNode(-8) # n5 = TreeNode(1) # n6 = TreeNode(3) # n7 = TreeNode(9) # n8 = TreeNode(2) # n9 = TreeNode(6) # n10 = TreeNode(0) # n11 = TreeNode(4) # n12 = TreeNode(-1) # n13 = TreeNode(10) # n1.left = n2 # n1.right = n3 # n2.left = n4 # n2.right = n5 # n3.left = n6 # n3.right = n7 # n4.left = n8 # n4.right = n9 # n7.right = n10 # n10.left = n11 # n10.right = n12 # n12.left = n13 tree = BinaryTree(root=n1) # n1 as a root # print tree.max_sum_path(tree.root) # path = [] # tree.print_k_path_sum(root=tree.root,path=path,k=16) # l = [0] # tree.check(l, root=tree.root , count=1) # print 'Final ' , l print tree.subtree_with_given_sum(root=tree.root,sum=220)
import math class Vector2: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, b): if isinstance(b, Vector2): return Vector2(self.x + b.x, self.y + b.y) else: raise TypeError('do no go') def __truediv__(self, b): if isinstance(b, (float, int)): return Vector2(self.x/b, self.y/b) else: raise TypeError('do no go') def __mul__(self, b): if isinstance(b, (float, int)): return Vector2(self.x*b, self.y*b) else: raise TypeError('do no go') def length(self): return math.sqrt(self.x ** 2 + self.y ** 2) class Point: def __init__(self, position=None, velocity=None): self.position = position or Vector2() self.velocity = velocity or Vector2() def step(self, steps_per_sec, gravity=Vector2(0, -9.8)): self.position += self.velocity / steps_per_sec self.velocity += gravity if self.position.y <= 0: self.velocity.y = 0 self.position.y = 0 class Ball: def __init__(self, radius, bounce, density, friction, position=None, velocity=None): self.position = position or Vector2() self.velocity = velocity or Vector2() self.radius = radius self.bounce = bounce self.density = density self.friction = friction def step(self, steps_per_sec, gravity=Vector2(0, -9.8)): self.position += self.velocity / steps_per_sec self.velocity += gravity if self.position.y - self.radius <= 0: self.velocity.y = 0 self.position.y = self.radius if self.velocity.x != 0: self.velocity.x = self.radius * self.ang_speed @property def mass(self): return self.density / self.area @property def rotation(self): return atan(self.position.x / self.position.y) @property def area(self): return math.pi * self.radius**2 @property def intertia(self): return (2/5) * self.mass * (self.radius**2) @property def ang_speed(self): return (self.radius * self.mass * self.velocity.x) / self.inertia @property def friction(self): return Vector2(friction * self.mass * gravity).y def simulate_bodies(bodies, duration, steps_per_sec=1, gravity=Vector2(0, -9.8)): time = 0 while time < duration: time += 1 / steps_per_sec for body in bodies: body.step(steps_per_sec, gravity) def ball_throw(ang, speed): """ angle is in degrees and speed in meters/second""" ball_throw_dict = dict() # Convert angle to radians converted_ang = (ang * math.pi) / 180 # Get the vertical speed of the ball v_speed = speed * math.sin(converted_ang) acceleration = 9.8 # Calculate the time it takes for ball to land time = round(2 * v_speed/acceleration, 2) # Check to see if trig functuion made time negative if time < 0: time = -1 * time # Use the range equation to find the distance distance = round((speed**2 * math.sin(2*converted_ang))/ acceleration, 2) # Store time and distance into dictionary ball_throw_dict["distance"] = distance ball_throw_dict["time"] = time return fysics_dict def simulated_ball_throw(ang, speed): acceleration = 9.8 simulated_dict = dict() steps_per_sec = 500 position = Vector2() converted_ang = (ang * math.pi) / 180 v_speed = speed * math.sin(converted_ang) h_speed = speed * math.cos(converted_ang) velocity = Vector2(v_speed, h_speed) time = 0 while True: position += velocity / steps_per_sec velocity.y -= 9.8/steps_per_sec distance = abs(round(position.x, 1)) # Calculate the time it takes for ball to land time += 1 / steps_per_sec # Verify the velocity to find the maximum height if velocity.y >= 0: max_altitude = round(position.y, 2) # Store the maximum altitude into the dictionary simulated_dict["maximum height"] = max_altitude current_velocity = velocity.length() if current_velocity > simulated_dict.get('max velocity', 0): simulated_dict['max velocity'] = current_velocity # Store time and range into dictionary if position.y < 0: simulated_dict["distance"] = distance simulated_dict["time"] = time return simulated_dict
list_tuple=[] sorted_list=[] n=int(input("Enter the no of tuples : ")) for i in range(0,n): ele=input("Enter the tuple : ") list_tuple.append(tuple(ele.split())) l1=[] def convert(list): for i in list: l1.append (i[-1]) return (l1) def sort(sorted_list): sorted_list.sort() sorted_list = [(ele, ) for ele in sorted_list] print("Sorted list is",sorted_list) print("Original list of tuples",list_tuple) convert(list_tuple) sort(l1)
import math OPERATORLAENGE = 1 OPERATORADDITION = "+" OPERATORSUBTRAKTION = "-" OPERATORDIVISION = ":" OPERATORMULTIPLIKATION = "*" ZEILENABSTAND = "\n\n" def output(string): # Erstellt, um zu einem spaeteren Zeitpunkt die Ausgabe in eine Textdatei zu schreiben print (string) def multiplikationMitEingabe(): output("erste Zahl:") temp_faktor1: int = input() output("\nzweite Zahl:") temp_faktor2: int = input() multiplikation(temp_faktor1, temp_faktor2) def multiplikation(faktor1, faktor2): ergebnis = int(faktor1) * int(faktor2) aufgabenlaenge = len(str(faktor1) + str(faktor2)) + OPERATORLAENGE anzahl_zeilen_fuer_zwischenrechnungen = len(str(faktor2)) output(str(faktor1) + "*" + str(faktor2)) output('-' * aufgabenlaenge) # malt den Strich unter der Rechnung for x in str(faktor2): temp_result = int(faktor1) * int(x) * (10 ** (anzahl_zeilen_fuer_zwischenrechnungen - 1)) # "-1" Am Ende, da die Einerstelle 10⁰ sein muss anzahl_leerzeichen_einruecken_von_links = aufgabenlaenge - len(str(temp_result)) output((anzahl_leerzeichen_einruecken_von_links * " ") + (str(temp_result))) anzahl_zeilen_fuer_zwischenrechnungen = anzahl_zeilen_fuer_zwischenrechnungen - 1 output('-' * aufgabenlaenge) # malt den Strich unter der Rechnung anzahl_leerzeichen_einruecken_von_links = aufgabenlaenge - len(str(ergebnis)) output((anzahl_leerzeichen_einruecken_von_links * " ") + (str(ergebnis)) + ZEILENABSTAND) # gibt das Ergebnis richtig eingerueckt aus def division(dividend, divisor): ergebnis_output = dividend / divisor # Wird berechnet um es anzuzeigen rest_output = dividend % divisor # Wird berechnet um es anzuzeigen output(str(dividend) + ":" + str(divisor) + "=" + str(int(ergebnis_output)) + " Rest: " + str(rest_output)) # gibt die Rechnung aus aufgaben_laenge_mit_ergebnis = len(str(dividend) + str(divisor) + str(ergebnis_output) + str(rest_output)) # Addiert die Länge der Zahlen aufgaben_laenge_mit_ergebnis = aufgaben_laenge_mit_ergebnis + len(" Rest: " + str(2 * OPERATORLAENGE)) # Addiert die Schrift dazu output('-' * aufgaben_laenge_mit_ergebnis) # malt einen Bindestrich unter der Rechnung ergebnis = "" # wird genutzt, um die einzelenen Zahlen auf dem weg zum Gesamtergebnis zu speichern tempzahl = "" # Stellt die Rechnenvariable bei den einzelnen Rechenschritten dar einrueckung_zwischen_rechnung = 0 # Hiermit soll die nötige Einrückung zum korrekten Darstellen mitgezaehlt werden tempergebnis = "" for zahl in str(dividend): # geht nacheinander durch jede Zahl, die im dividend vorkommt (vlnr) tempzahl = tempzahl + str(zahl) if divisor > int(tempzahl): ergebnis = ergebnis + "0" # output(str(einrueckung_zwischen_rechnung * " ") + tempzahl) continue elif (int(tempzahl) % int(divisor)) == 0: zwischenergebnis = int(int(tempzahl) / int(divisor)) ergebnis = ergebnis + str(zwischenergebnis) output(str(einrueckung_zwischen_rechnung * " ") + tempzahl) if tempzahl[0] == "0": for null in tempzahl: if null == "0": einrueckung_zwischen_rechnung = einrueckung_zwischen_rechnung + 1 else: continue output(str(einrueckung_zwischen_rechnung * " ") + str(zwischenergebnis * divisor)) output(str(einrueckung_zwischen_rechnung * " ") + '-' * len(str(int(tempzahl)))) tempzahl = str(int(int(tempzahl) % int(divisor))) einrueckung_zwischen_rechnung = einrueckung_zwischen_rechnung + 1 else: zwischenergebnis = int(int(tempzahl) / int(divisor)) ergebnis = ergebnis + str(zwischenergebnis) output(str((einrueckung_zwischen_rechnung - (len(tempzahl) - len(str(int(tempzahl))))) * " ") + (tempzahl)) output(str(einrueckung_zwischen_rechnung * " ") + str(zwischenergebnis * divisor)) output(str(einrueckung_zwischen_rechnung * " ") + '-' * len(str(int(tempzahl)))) # output(str(einrueckung_zwischen_rechnung * " ") + str((int(tempzahl) % int(divisor))) + str()) einrueckung_zwischen_rechnung = einrueckung_zwischen_rechnung + 1 tempzahl = str(int(int(tempzahl) % int(divisor))) output(str(einrueckung_zwischen_rechnung * " ") + tempzahl) output("Das Ergebnis ist: " + str(int(ergebnis)) + " mit Rest: " + str(int(tempzahl))) output(ZEILENABSTAND) # gibt ZEILENABSTAND nachd er Rechnung aus. Soll die einzelnen Rechnungen von einander trennen # Press the green button in the gutter to run the script. if __name__ == '__main__': # multiplikation(5, 12345) # division(200, 4) # division(746, 7) # division(12345, 5) # division(465733, 7) # division(451064, 8) division(252546, 6) division(26800, 4) division(6048, 6) # while True: # multiplication() # print("Nächste Aufgabe?\n1: Ja\n2: Programm verlassen") # auswahl = int(input()) # # if auswahl == 1: # calculate() # auswahl = 0 # elif auswahl == 2: # break # See PyCharm help at https://www.jetbrains.com/help/pycharm/
def maximum(*arguments): """ returns the maximum number *arguments: integer arguments e.g. 1,22,3,2 """ maximum_number = 0 *create_list, = arguments duplicate_list = [i for i in create_list] list_of_small_numbers = [i for i in create_list for j in duplicate_list if i < j] for i in duplicate_list: if i not in list_of_small_numbers: maximum_number = i return maximum_number
import sqlite3 import Student import Methods methods = Methods.Methods() while True: print("""Press (a) to display all students Press (b) to create a new student Press (c) to update an existing student Press (d) to delete a student Press (e) to query students Press (q) to quit""") command = raw_input("Enter your decision: ") if command == "a": methods.print_all() elif command == "b": methods.create_student() elif command == "c": methods.update_student() elif command == "d": methods.delete_student() elif command == "e": methods.query() elif command == "q": print("Exiting program...") break else: print("Invalid input. Please try again") print("")
from typing import List from copy import deepcopy class Phrase(object): def __init__(self, words: List[str], occ: int): """ 表示一个词组 :param words: 词组 :paran occ: 词组出现的次数,若为临时使用,请设为0 """ self.__words = deepcopy(words) self.__occ = occ def words(self): """ 将存储的词组以List[str]的形式返回 """ return deepcopy(self.__words) def phrase(self, sep=''): """ 将存储的词组以单个string的形式返回 :param sep: 分隔符 """ ret: str = "" length = len(self.__words) for i in range(length): ret = ret + self.__words[i] if i != length - 1: ret = ret + sep return ret def occ(self): """ 返回该词组出现的次数 """ return self.__occ def length(self): """ 返回组成词组的字的个数 """ return len(self.phrase()) def gram(self): """ 返回组成词组的单词的个数 """ return len(self.__words)
import unittest from unittest.mock import * from car import * class TestCar(unittest.TestCase): def test_needsFuel_true(self): # prepare mock self.car.needsFuel = Mock(name='needsFuel') self.car.needsFuel.return_value = True # testing self.assertEqual(self.car.needsFuel(), True) def test_needsFuel_false(self): # prepare mock self.car.needsFuel = Mock(name='needsFuel') self.car.needsFuel.return_value = False # testing self.assertEqual(self.car.needsFuel(), False) @patch.object(Car, 'getEngineTemperature') def test_getEngineTemperature(self, mock): mock.return_value = 85 result = self.car.getEngineTemperature() self.assertEqual(result, 85) @patch.object(Car, 'driveTo') def test_driveTo(self, mock): mock.return_value = "Søliljevej 28, 2650 Hvidovre, Denmark" result = self.car.driveTo("Søliljevej 28, 2650 Hvidovre, Denmark") self.assertEqual(result, "Søliljevej 28, 2650 Hvidovre, Denmark") def setUp(self): self.car = Car() def tearDown(self): self.car = None if __name__ == '__main__': unittest.main()
import unittest from app.models.game import * from app.models.player import Player class TestGame(unittest.TestCase): def test_play_game(self): play_game(player1, player3) self.assertEqual("Harry wins by playing rock", play_game(player1, player3)) def test_play_game_draw(self): player2= Player("Ron", "paper") player3= Player("Hermione", "paper") play_game(player2, player3) self.assertEqual("It's a draw!", play_game(player2, player3))
from prob004func import is_palindrome def revNum(num): numstr = str(num) length = len(numstr) pos = length - 1 #Position in the number, start at end newstr = '' while pos >= 0: newstr += numstr[pos] pos -= 1 newnum = int(newstr) return newnum def isLychrel(num, maxitr): count = 1 while count <= maxitr: total = num + revNum(num) if is_palindrome(total): return False count += 1 num = total return True
size = 0 i1 = 1 i2 = 1 i3 = 0 count = 2 # Start at 2 because we've already set i1 and i2 while size < 1000: i3 = i1 + i2 size = len(str(i3)) i1 = i2 i2 = i3 count += 1 print(count)
def is_palindrome(test): teststr = str(test) length = len(teststr) count = 0 ending = length - 1 first = int(teststr[count]) last = int(teststr[ending]) if length == 1: return True while count <= ending: if first != last: return False count += 1 ending -= 1 first = int(teststr[count]) last = int(teststr[ending]) return True
from math import factorial i = 3 sum = 0 while i < 100000: i_str = str(i) sub_sum = 0 for j in i_str: j = int(j) sub_sum += factorial(j) if sub_sum == i: sum += i print(i) i += 1 print("Sum: ", sum)
def to_word(num): if num > 9999: exit("Error! Too big to convert") thousands = int(num / 1000) hundreds = int((num % 1000) / 100) tens = int((num % 100) / 10) ones = int(num % 10) word = "" if thousands > 0: word += word_ones(thousands) + " thousand " if hundreds > 0: word += word_ones(hundreds) + " hundred " if tens > 0: if thousands > 0 or hundreds > 0: word += "and " if tens == 1: word += word_teens(ones) else: word += word_tens(tens) + " " if ones > 0 and tens > 1: word += word_ones(ones) if ones > 0 and tens == 0: if thousands > 0 or hundreds > 0: word += "and " word += word_ones(ones) #print(word) return word def word_ones(num): if num == 1: return "one" elif num == 2: return "two" elif num == 3: return "three" elif num == 4: return "four" elif num == 5: return "five" elif num == 6: return "six" elif num == 7: return "seven" elif num == 8: return "eight" elif num == 9: return "nine" else: return "zero" def word_tens(num): if num == 1: return "one" elif num == 2: return "twenty" elif num == 3: return "thirty" elif num == 4: return "forty" elif num == 5: return "fifty" elif num == 6: return "sixty" elif num == 7: return "seventy" elif num == 8: return "eighty" elif num == 9: return "ninety" else: return "zero" def word_teens(num): if num == 1: return "eleven" elif num == 2: return "twelve" elif num == 3: return "thirteen" elif num == 4: return "fourteen" elif num == 5: return "fifteen" elif num == 6: return "sixteen" elif num == 7: return "seventeen" elif num == 8: return "eighteen" elif num == 9: return "nineteen" else: return "ten" def to_word_num(num): if num > 9999: exit("Error! Too big to convert") thousands = int(num / 1000) hundreds = int((num % 1000) / 100) tens = int((num % 100) / 10) ones = int(num % 10) word = 0 if thousands > 0: word += word_ones_num(thousands) + 8 #thousand if hundreds > 0: word += word_ones_num(hundreds) + 7 #" hundred " if tens > 0: if thousands > 0 or hundreds > 0: word += 3 #"and " if tens == 1: word += word_teens_num(ones) else: word += word_tens_num(tens) # + " " if ones > 0 and tens > 1: word += word_ones_num(ones) if ones > 0 and tens == 0: if thousands > 0 or hundreds > 0: word += 3 #"and " word += word_ones_num(ones) #print(word) return word def word_ones_num(num): if num == 1: return 3 #"one" elif num == 2: return 3 #"two" elif num == 3: return 5 #"three" elif num == 4: return 4 #"four" elif num == 5: return 4 #"five" elif num == 6: return 3 #"six" elif num == 7: return 5 #"seven" elif num == 8: return 5 #"eight" elif num == 9: return 4 #"nine" else: return 4 #"zero" def word_tens_num(num): if num == 1: return 3 #"one" elif num == 2: return 6 #"twenty" elif num == 3: return 6 #"thirty" elif num == 4: return 5 #"forty" elif num == 5: return 5 #"fifty" elif num == 6: return 5 #"sixty" elif num == 7: return 7 #"seventy" elif num == 8: return 6 #"eighty" elif num == 9: return 6 #"ninety" else: return 4 #"zero" def word_teens_num(num): if num == 1: return 6 #"eleven" elif num == 2: return 6 #"twelve" elif num == 3: return 8 #"thirteen" elif num == 4: return 8 #"fourteen" elif num == 5: return 7 #"fifteen" elif num == 6: return 7 #"sixteen" elif num == 7: return 9 #"seventeen" elif num == 8: return 8 #"eighteen" elif num == 9: return 8 #"nineteen" else: return 3 #"ten"
import random def read_sudoku(filename): """ Прочитать Судоку из указанного файла """ digits = [c for c in open(filename).read() if c in '123456789.'] grid = group(digits, 9) return grid def display(values): """Вывод Судоку """ width = 2 line = '+'.join(['-' * (width * 3)] * 3) for row in range(9): print(''.join(values[row][col].center(width) + ('|' if str(col) in '25' else '') for col in range(9))) if str(row) in '25': print(line) print() def group(values, n): """ Сгруппировать значения values в список, состоящий из списков по n элементов >>> group([1,2,3,4], 2) [[1, 2], [3, 4]] >>> group([1,2,3,4,5,6,7,8,9], 3) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] """ values_matrix = [] for i in range (0 , len(values), n): values_matrix.append(values[slice(i,i+n)]) return values_matrix def get_row(values, pos): """ Возвращает все значения для номера строки, указанной в pos >>> get_row([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']], (0, 0)) ['1', '2', '.'] >>> get_row([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']], (1, 0)) ['4', '.', '6'] >>> get_row([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (2, 0)) ['.', '8', '9'] """ for i in range(len(values)): if pos[0] == i: return values[i] def get_col(values, pos): """ Возвращает все значения для номера столбца, указанного в pos >>> get_col([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']], (0, 0)) ['1', '4', '7'] >>> get_col([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']], (0, 1)) ['2', '.', '8'] >>> get_col([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (0, 2)) ['3', '6', '9'] """ column=[] for r in range(len(values)): column.append(values[r][pos[1]]) return column def get_block(values, pos): """ Возвращает все значения из квадрата, в который попадает позиция pos """ l = len(values) tmp = l/(pos[0]+1) if tmp>=3 and tmp<=9: row_ind = 0 elif tmp<=2.25 and tmp>=1.5: row_ind = 3 else: row_ind = 6 tmp = l/(pos[1]+1) if tmp>=3 and tmp<=9: col_ind = 0 elif tmp<=2.25 and tmp>=1.5: col_ind = 3 else: col_ind = 6 result=[] for r in range(row_ind,row_ind+3): for c in range(col_ind, col_ind+3): result.append(values[r][c]) return result def find_empty_positions(grid): """ Найти первую свободную позицию в пазле >>> find_empty_positions([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']]) (0, 2) >>> find_empty_positions([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']]) (1, 1) >>> find_empty_positions([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']]) (2, 0) """ for row in range(0, 9): for col in range(0, 9): if grid[row][col] == '.': pos = row, col return pos return False def find_possible_values(grid, pos): """ Вернуть все возможные значения для указанной позиции """ row_values = get_row(grid,pos) block_values = get_block(grid,pos) col_values = get_col(grid,pos) possible_values = [] for m in range(1,10): if not str(m) in row_values and not str(m) in col_values and not str(m) in block_values: possible_values.append(str(m)) return possible_values def check_solution(solution): """ Если решение solution верно, то вернуть True, в противном случае False """ m = True for row in range(0, 9): for col in range(0, 9): pos = row, col b = get_block(solution, pos) c = get_col(solution, pos) r = get_row(solution, pos) for i in range(1, 10): if not (str(i) in b and str(i) in c and str(i) in r): m = False # Если решение solution верно, то вернуть True, в противном случае False return m def solve(grid): """ Решение пазла, заданного в grid """ """ Как решать Судоку? 1. Найти свободную позицию 2. Найти все возможные значения, которые могут находиться на этой позиции 3. Для каждого возможного значения: 3.1. Поместить это значение на эту позицию 3.2. Продолжить решать оставшуюся часть пазла """ pos = find_empty_positions(grid) if pos == False : return grid else: val = find_possible_values(grid, pos) for i in val: grid[pos[0]][pos[1]] = i if solve(grid): return grid else: grid[pos[0]][pos[1]] = '.' return False grid = read_sudoku('C:\cs102\puzzle1.txt') display(grid) display(solve(grid)) print(check_solution(grid)) def replace(grid): posR = random.randint(0,8) posC = random.randint(0,8) pos = posR, posC s = find_possible_values(grid,pos) if grid[posR][posC] == '.' and s != []: grid[posR][posC] = s[0] else: grid = replace(grid) return grid def f(grid): posR = random.randint(0,8) posC = random.randint(0,8) if grid[posR][posC] != '.': grid[posR][posC] = '.' else: f(grid) return grid def generate_sudoku(N): grid = [] for i in range(81): grid.append('.') grid = group(grid, 9) d = random.randint(10,20) for i in range(0,d): grid = replace(grid) grid = solve(grid) for i in range(81-N): grid = f(grid) return grid display(generate_sudoku(55))
# First we need to import Lock and then we can re-write our functions to use the lock from multiprocessing import Process, Lock, Value import time def add_5000_lock(total, lock): '''This function adds 5000 to the shared value total. Even with the time.sleep functions the race condition should not occur because of the lock.''' for i in range(1000): time.sleep(0.001) lock.acquire() # This line is only run by one process at a time total.value += 5 lock.release() def sub_5000_lock(total, lock): '''This function subtracts 5000 from the shared value total. Even with the time.sleep functions the race condition should not occur because of the lock.''' for i in range(1000): time.sleep(0.001) lock.acquire() # This line is only run by one process at a time total.value -= 5 lock.release() if __name__ == '__main__': total = Value('i', 300) lock = Lock() # We then need to define a lock object and pass it into each process add_proc = Process(target=add_5000_lock, args=(total, lock)) sub_proc = Process(target=sub_5000_lock, args=(total, lock)) add_proc.start() sub_proc.start() add_proc.join() sub_proc.join() print(total.value)
import random str_list=['самовар','весна','лето'] word=random.choice(str_list) letter=random.choice(word) print(word.replace(letter,"?")) input_letter=input('Введите букву: ') if input_letter==letter: print('Победа!\nСлово: {str}'.format(str=word)) else: print('Увы! Попробуй в другой раз.\nСлово: {str}'.format(str=word))