text
stringlengths
37
1.41M
# from tkinter import * # root = Tk() # root.geometry("100x100") # btn = Button(root, text="Button1",bd= '5',command=root.destroy) # btn.pack(side="bottom") # root.mainloop() # import everything from tkinter module from tkinter import * # create a tkinter window root = Tk() # Open window having dimension 100x100 root.geometry('100x100') root.title("Hello") # Create a Button btn = Button(root, text = 'Click me !', bd = '5', command = root.destroy) # Set the position of button on the top of window. btn.pack(side = 'top') root.mainloop()
#!/usr/bin/python import socket WEB_HOST = socket.gethostname() PORT = "8080" def main(): request = "GET / HTTP/1.1\r\n" \ "Host: " + WEB_HOST + "\r\n" \ "Accept: text/html\r\n\r\n" print(request) s = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # now connect to the web server on port 80 # - the normal http port s.connect((WEB_HOST, int(PORT))) s.send(request.encode()) s.settimeout(1) answer = s.recv(1024) print(str(answer)) if __name__ == '__main__': main()
#User function Template for python3 import math class Solution: def digitsInFactorial(self,N): # code here if(N<0): return 0 else: count = 0 for d in str(math.factorial(N)): count +=1 return count #{ # Driver Code Starts #Initial Template for Python 3 import math def main(): T=int(input()) while(T>0): N=int(input()) ob=Solution() print(ob.digitsInFactorial(N)) T-=1 if __name__=="__main__": main() # } Driver Code Ends
def calculate_total_ticket_cost(no_of_adults, no_of_children): total_ticket_cost=0 adult=no_of_adults*37550 child=no_of_children*(37550/3) sum=adult+child after_tax=sum+(7*sum)/100 total_ticket_cost=after_tax-(10*after_tax)/100 return total_ticket_cost #Provide different values for no_of_adults, no_of_children and test your program total_ticket_cost=calculate_total_ticket_cost(1,2) print("Total Ticket Cost:",total_ticket_cost)
def encode(s): # changed string newS = "" # iterate for every characters for i in range(len(s)): # ASCII value val = ord(s[i]) #if k-th ahead character exceed 'z' if val + 5>122: newS += chr(96 + (val - 117)) else: newS += chr(val + 5) print (newS) # driver code str = input() encode(str)
list_of_airlines=["AI","EM","BA"] airline="AI" if airline in list_of_airlines: print("Airline found") else: print("Airline not found")
class Solution: def immediateSmaller(self,arr,n,x): #return required ans smallest = -1 for i in arr: if(i>smallest and i<x): smallest = i if smallest != -1: return smallest return -1 #code here #{ # Driver Code Starts #Initial Template for Python 3 if __name__ =='__main__': tcs=int(input()) for _ in range(tcs): n=int(input()) arr=[int(e) for e in input().split()] x=int(input()) ob=Solution() ans=ob.immediateSmaller(arr,n,x) print(ans) # } Driver Code Ends
#Input 1: #Enter your PlainText: All the best #Enter the Key: 1 #Expected Output : The encrypted Text is: Bmm uif Cftu #Explanation #The function Caesar(int key, String message) will accept \ #plaintext and key as input parameters and returns its #ciphertext as output. def ceaser(text, key): result = "" #transverse plain text for i in range(len(text)): char = text[i] #encrypt uppercase in plain text if (char.isupper()): result += chr((ord(char) + key-65) % 26 + 65) #Encrypt lowercase characters in plain text elif (char.islower()): result += chr((ord(char) + key - 97) % 26 + 97) elif(char.isdigit()): result += str(int(char) + key) elif(char == '-'): result += '-' elif (char.isspace()): result += " " return result #check the above function text = input("Enter your plain text:") key = int(input("Enter the key:")) print(ceaser(text,key))
#arr[] = {1,2,3,4,5} #Output: 2 1 4 3 5 class Solution: #Complete this function #Function to sort the array into a wave-like array. def convertToWave(self,arr,N): #Your code here arr.sort() for i in range(0,N-1,2): arr[i], arr[i+1] = arr[i+1], arr[i] #{ # Driver Code Starts #Initial Template for Python 3 import math def main(): T=int(input()) while(T>0): N=int(input()) A=[int(x) for x in input().split()] ob=Solution() ob.convertToWave(A,N) for i in A: print(i,end=" ") print() T-=1 if __name__=="__main__": main() # } Driver Code Ends
#Code1 print("code-1") def func6(a,b,c): res_avg=(a+b+c)/3 return res_avg print("1st invocation of code-1") func6(6,8,10) print("returned value is not assigned to any variable") print("------------------------------------------------") print("2nd invocation of code-1") average=func6(10,15,20) print("returned value assigned to a variable") print("value of variable, average:", average) print("------------------------------------------------") print("3rd invocation of code-1") print("returned value is directly printed") print(func6(1,2,3)) #Code2 print("------------------------------------------------") print("code-2") print("------------------------------------------------") def func7(a,b): if(a>b): return True return False x=5 y=6 print("1st invocation of code-2") if(func7(x,y)): print("inside if block") else: print("inside else block") x=6 y=5 print("------------------------------------------------") print("2nd invocation of code-2") if(func7(x,y)): print("inside if block") else: print("inside else block")
year = int(input()) if ((year%400 == 0) or ((year%4 ==0) and (year%100 != 0))): print("Leap year") else: print("Not a leap year")
#Every character in the input string is followed by its frequency. #Write a function to decrypt the string and find the nth character of the decrypted string. If no character exists at that positionthen then return "-1". #For eg:- If the input string is "a2b3" the decrypted string is "aabbb". #Note: The frequency of encrypted string cannot be greater than a single digit i.e.<10. */ def decrypt(s): output = [] for i in s: if(i.isalpha()): output.append(i) else: for i in range(int(i)-1): output.append(output[-1]) print(''.join(output)) s=input("Enter the string: ") decrypt(s) #decrypt("a9b7") #'aabbb'
#Given a maximum of 100 digit numbers as input, #find the difference between the sum of odd and #even position digits import math num = [int(d) for d in str(input("Enter your number: "))] even, odd = 0,0 for i in range(0, len(num)): if i%2 == 0: even = even + num[i] else: odd = odd + num[i] print(abs(odd-even)) #absolute difference
def function_name(name,num): print('Hello '+name) print(num) function_name('name',34) #help(function_name) def check(str): if 'dd' in str: return True else: return False ret = check('dd in it') print(ret)
def gensqre(n): for x in range(n): yield x**2 for x in gensqre(10): print(x) h="hello" g=iter(h) print(next(g)) print(next(g)) print(next(g))
def check(str): if 'dd' in str: return True else: return False ret = check('dd in it') print(ret) def check2(str): return 'dd' in str print(check2('dd in it'))
word="abcd" for item in enumerate(word): #it will simply output the elemnts of the index and the index number according to the index print(item) #or just for index,letter in enumerate(word): print(index) print(letter) print('\n')
def pig_atin(w): first_letter=w[0] if first_letter in 'aeiou' : return w+'ay' else: return w[1:]+w[0]+'ay' print(pig_atin('appale')) print(pig_atin('ppale'))
from tkinter import * root = Tk() # code to add widgets and style window will go here root.geometry("500x650") root.title("Ticket Sales (Uthmaan Breda)") root.config(bg="black") ticket = PhotoImage(file="ticket.png") img = Label(root, image=ticket, bg="black", fg="white") img.place(x=120, y=5) # create class class Cell: price1 = StringVar() amt_tick_ent = StringVar() reserve_ent = StringVar() def __init__(self, master): # define labels self.lab1 = Label(master, text="Enter Cell Number: ", bg="black", fg="white") self.lab1.place(x=5, y=200) self.entry1 = Entry(master, bg="black", fg="white") self.entry1.place(x=150, y=200) self.entry1.focus() self.lab2 = Label(master, text="Ticket Category: ", bg="black", fg="white") self.lab2.place(x=5, y=250) # define option menu self.option = ["Soccer", "Movie", "Theatre"] # set values for option list self.values = StringVar(root) # set variable to keep track of option value selected self.values.set("Select an option") # set default value on display (value from list can be put sayin option[0]) self.opt = OptionMenu(master, self.values, *self.option) self.opt.config(width=15, bg="black", fg="white") self.opt.place(x=150, y=250) # spinbox self.lab3 = Label(master, text="Number of Tickets: ", bg="black", fg="white") self.lab3.place(x=5, y=300) self.spin_box = Spinbox( master, from_=0, to=10000, increment=1, bg="black", fg="white" ) self.spin_box.place(x=150, y=300) # using Labels to display results self.lab4 = Label(master, text="Amount Payable: ", bg="black", fg="white").place(x=5, y=450) self.amount1 = Label(master, text="", width="20", textvariable=self.price1, bg="black", fg="white") self.amount1.place(x=150, y=450) self.lab5 = Label(master, text="Reservation for: ", bg="black", fg="white").place(x=5, y=475) self.amount2 = Label(master, text="", width="20", textvariable=self.amt_tick_ent, bg="black", fg="white") self.amount2.place(x=150, y=475) self.lab5 = Label(master, text="Was done by: ", bg="black", fg="white").place(x=5, y=500) self.amount3 = Label(master, text="", width="20", textvariable=self.reserve_ent, bg="black", fg="white") self.amount3.place(x=150, y=500) # create buttons self.mybutton = Button(master, text="calculate price", command=self.price, bg="black", fg="white") self.mybutton.place(x=150, y=390) self.mybutton2 = Button(master, text="Clear", command=self.clear, bg="black", fg="white") self.mybutton2.place(x=150, y=550) # define functions for equations, clear and exit def reserve(self): res = self.entry1.get() self.reserve_ent.set(res) def price(self): self.amt_tick_ent.set(self.spin_box.get()) self.reserve() if self.values.get() == "Soccer": pay_me = float(self.spin_box.get()) * 40 + 0.14 * (float(self.spin_box.get()) * 40) self.price1.set("R" + str(pay_me)) elif self.values.get() == "Movie": pay_me = float(self.spin_box.get()) * 75 + 0.14 * (float(self.spin_box.get()) * 75) self.price1.set("R" + str(pay_me)) elif self.values.get() == "Theatre": pay_me = float(self.spin_box.get()) * 100 + 0.14 * (float(self.spin_box.get()) * 100) self.price1.set("R" + str(pay_me)) def clear(self): self.entry1.delete(0, END) self.spin_box.delete(0, END) self.values.set("Select an option") self.price1.set("") self.amt_tick_ent.set("") self.reserve_ent.set("") self.entry1.focus() y = Cell(root) # call class to root frame root.mainloop() # continuously runs program in window
#Write a program to generate 5 random integers between 1 to 20 such that numbers should be unique import random s = set() while len(s)<5: s.add(random.randint(1,20)) print(s)
#Python Program to Check Whether a Number is Positive or Negative. num = int(input("Enter the number")) if num >0: print("Positive") else: print("Negative")
#Python Program to Calculate the Number of Upper Case Letters and Lower Case Letters in a String. str1 = str(input("Enter the string")) L,U = 0,0 for i in str1: if i.isupper(): U = U+1 elif i.islower(): L = L+1 else: pass print("No. of Upper case is ",U) print("No. of Lower case is ",L)
#Python Program to Read a number n and Compute n+nn+nnn. n = int(input("Enter the value of n")) nn = str(n)+str(n) nnn = str(n)+str(n)+str(n) n = n +int(nn)+int(nnn) print("value of n is ",n)
from . import opcodes from ..java import opcodes as JavaOpcodes class Command: """A command is a sequence of instructions producing a distinct result. The `operation` is the final instruction that yields a result. A series of other instructions, known as `arguments` will be used to execute `operation`. The command also tracks the line number and code offset that it represents, plus whether the command is a jump target. Each argument is itself a Command; leaf nodes are Commands with no arguments. A command knows how many items it will pop from the stack, and how many it will push onto the stack. The stack count on a Command reflects the effect of the operation itself, plus *all* the arguments. A command may also encompass an internal block - for example, a for or while loop. Those blocks """ def __init__(self, instruction, arguments=None): self.operation = instruction if arguments: self.arguments = arguments else: self.arguments = [] def __repr__(self): try: return '<Command %s (%s args)> %s' % (self.operation.opname, len(self.arguments), self.arguments[0].operation.name) except: return '<Command %s (%s args)>' % (self.operation.opname, len(self.arguments)) @property def consume_count(self): return sum(c.consume_count for c in self.arguments) + self.operation.consume_count @property def product_count(self): return sum(c.product_count for c in self.arguments) + self.operation.product_count def is_main_start(self): return ( self.operation.opname == 'POP_JUMP_IF_FALSE' and self.arguments[0].operation.opname == 'COMPARE_OP' and self.arguments[0].operation.comparison == '==' and self.arguments[0].arguments[0].operation.opname == 'LOAD_NAME' and self.arguments[0].arguments[0].operation.name == '__name__' and self.arguments[0].arguments[1].operation.opname == 'LOAD_CONST' and self.arguments[0].arguments[1].operation.const == '__main__' ) def is_main_end(self, main_end): if main_end == self.operation.python_offset: return True elif self.arguments and main_end <= self.arguments[0].operation.python_offset: return True return False def dump(self, depth=0): for op in self.arguments: op.dump(depth=depth + 1) print ('%s%4s:%4d -%s +%s' % ( '>' if self.operation.is_jump_target else ' ', self.operation.starts_line if self.operation.starts_line is not None else ' ', self.operation.python_offset, self.operation.consume_count, self.operation.product_count ) + ' ' * depth, self.operation) def transpile(self, context): self.operation.transpile(context, self.arguments) class TryExcept: def __init__(self, start, end, start_offset, end_offset, starts_line): self.start = start self.end = end self.start_offset = start_offset self.end_offset = end_offset self.starts_line = starts_line self.commands = [] self.exceptions = [] self.else_block = None self.finally_block = None def __repr__(self): return '<Try %s-%s | %s%s%s>' % ( self.start, self.end, ', '.join(str(handler) for handler in self.exceptions), ' %s' % self.else_block if self.else_block else '', ' %s' % self.finally_block if self.finally_block else '' ) @property def resume_index(self): if self.finally_block and self.exceptions: return self.start - 2 else: return self.start - 1 @property def consume_count(self): return sum(c.consume_count for c in self.commands) @property def product_count(self): return sum(c.product_count for c in self.commands) def is_main_start(self): return False def is_main_end(self, main_end): return False def dump(self, depth=0): print (' %4s:%4d ' % ( self.starts_line if self.starts_line is not None else ' ', self.start_offset, ) + ' ' * depth, 'TRY:' ) for command in self.commands: command.dump(depth=depth + 1) for handler in self.exceptions: handler.dump(depth=depth) if self.else_block: self.else_block.dump(depth=depth) if self.finally_block: self.finally_block.dump(depth=depth) print (' :%4d ' % ( self.end_offset, ) + ' ' * depth, 'END TRY' ) def extract(self, instructions, blocks): self.operation = instructions[self.start - 1] i = self.end self.commands = [] while i > self.start: i, command = extract_command(instructions, blocks, i, self.start) self.commands.append(command) self.commands.reverse() for handler in self.exceptions: handler.extract(instructions, blocks) if self.else_block: self.else_block.extract(instructions, blocks) if self.finally_block: self.finally_block.extract(instructions, blocks) def transpile(self, context): context.add_opcodes(opcodes.TRY( self.else_block, self.finally_block )) for command in self.commands: command.transpile(context) for handler in self.exceptions: # Define the exception handler. # On entry to the exception, the stack will contain # a single value - the exception being thrown. # This exception must be wrapped into an org/python/types/Object # so it can be used as an argument elsewhere. if len(handler.exceptions) > 1: # catch multiple - except (A, B) as v: context.add_opcodes( opcodes.CATCH([ 'org/python/exceptions/%s' % e for e in handler.exceptions ]), ) if handler.var_name: context.store_name(handler.var_name), else: # No named exception, but there is still an exception # on the stack. Pop it off. context.add_opcodes(JavaOpcodes.POP()) handler.transpile(context) elif len(handler.exceptions) == 1: # catch single - except A as v: context.add_opcodes( opcodes.CATCH('org/python/exceptions/%s' % handler.exceptions[0]), ) if handler.var_name: context.store_name(handler.var_name), else: # No named exception, but there is still an exception # on the stack. Pop it off. context.add_opcodes(JavaOpcodes.POP()) handler.transpile(context) else: # The bucket case - except: # No named exception, but there is still an exception # on the stack. Pop it off. context.add_opcodes( opcodes.CATCH(), JavaOpcodes.POP(), ) handler.transpile(context) if self.finally_block: context.add_opcodes( opcodes.FINALLY(), ) opcodes.ASTORE_name(context, '##exception-%d##' % id(self)) for command in self.finally_block.commands: command.transpile(context) opcodes.ALOAD_name(context, '##exception-%d##' % id(self)), context.add_opcodes( JavaOpcodes.ATHROW(), ) context.add_opcodes(opcodes.END_TRY()) class ExceptionBlock: def __init__(self, exceptions, var_name, start, end, start_offset, end_offset, starts_line): self.exceptions = exceptions self.var_name = var_name self.start = start self.end = end self.start_offset = start_offset self.end_offset = end_offset self.starts_line = starts_line self.commands = [] def __repr__(self): if self.exceptions: if self.var_name: return '%s (%s): %s-%s' % (','.join(self.exceptions), self.var_name, self.start, self.end) else: return '%s: %s-%s' % (','.join(self.exceptions), self.start, self.end) else: return 'Bucket: %s-%s' % (self.start, self.end) def dump(self, depth=0): print (' %4s:%4d ' % ( self.starts_line if self.starts_line is not None else ' ', self.start_offset, ) + ' ' * depth, 'CATCH %s%s:' % ( ', '.join(self.exceptions) if self.exceptions else '', ' as %s' % self.var_name if self.var_name else '', ) ) for command in self.commands: command.dump(depth=depth + 1) def extract(self, instructions, blocks): i = self.end self.commands = [] while i > self.start: i, command = extract_command(instructions, blocks, i, self.start) self.commands.append(command) self.commands.reverse() def transpile(self, context): context.next_opcode_starts_line = self.starts_line for command in self.commands: command.transpile(context) class FinallyBlock: def __init__(self, start, end, start_offset, end_offset, starts_line): self.start = start self.end = end self.start_offset = start_offset self.end_offset = end_offset self.starts_line = starts_line self.commands = [] def __repr__(self): return 'Finally: %s-%s' % (self.start, self.end) def dump(self, depth=0): print (' %4s:%4d ' % ( self.starts_line if self.starts_line is not None else ' ', self.start_offset, ) + ' ' * depth, 'FINALLY:' ) for command in self.commands: command.dump(depth=depth + 1) def extract(self, instructions, blocks): i = self.end self.commands = [] while i > self.start: i, command = extract_command(instructions, blocks, i, self.start) self.commands.append(command) self.commands.reverse() def transpile(self, context): context.next_opcode_starts_line = self.starts_line for command in self.commands: command.transpile(context) class ElseBlock: def __init__(self, start, end, start_offset, end_offset, starts_line): self.start = start self.end = end self.start_offset = start_offset self.end_offset = end_offset self.starts_line = starts_line self.commands = [] def __repr__(self): return 'Else: %s-%s' % (self.start, self.end) def dump(self, depth=0): print (' %4s:%4d ' % ( self.starts_line if self.starts_line is not None else ' ', self.start_offset, ) + ' ' * depth, 'ELSE:' ) for command in self.commands: command.dump(depth=depth + 1) def extract(self, instructions, blocks): i = self.end self.commands = [] while i > self.start: i, command = extract_command(instructions, blocks, i, self.start, literal=(i == self.end)) self.commands.append(command) self.commands.reverse() def transpile(self, context): context.next_opcode_starts_line = self.starts_line for command in self.commands: command.transpile(context) class ForLoop: def __init__(self, start, loop, varname, end, start_offset, loop_offset, end_offset, starts_line): self.start = start self.loop = loop self.end = end self.varname = varname self.start_offset = start_offset self.loop_offset = loop_offset self.end_offset = end_offset self.starts_line = starts_line self.loop_commands = [] self.commands = [] def __repr__(self): return '<For %s: %s-%s>' % ( self.start, self.loop, self.end, ) @property def consume_count(self): return sum(c.consume_count for c in self.commands) @property def product_count(self): return sum(c.product_count for c in self.commands) @property def resume_index(self): return self.start - 1 def is_main_start(self): return False def is_main_end(self, main_end): return False def dump(self, depth=0): print (' %4s:%4d ' % ( self.starts_line if self.starts_line is not None else ' ', self.start_offset, ) + ' ' * depth, 'FOR:' ) for command in self.loop_commands: command.dump(depth=depth + 1) print (' :%4d ' % ( self.loop_offset, ) + ' ' * depth, 'LOOP:' ) for command in self.commands: command.dump(depth=depth + 1) print (' :%4d ' % ( self.end_offset, ) + ' ' * depth, 'END FOR' ) def extract(self, instructions, blocks): # Collect the commands related to setting up the loop variable i = self.end while i > self.loop: i, command = extract_command(instructions, blocks, i, self.loop) self.commands.append(command) self.commands.reverse() # Collect the commands for the actual loop i = self.loop - 2 while i > self.start: i, command = extract_command(instructions, blocks, i, self.start) self.loop_commands.append(command) self.loop_commands.reverse() def pre_loop(self, context): pass def pre_iteration(self, context): context.add_opcodes( JavaOpcodes.DUP(), ) def post_loop(self, context): context.add_opcodes( JavaOpcodes.POP(), ) def transpile(self, context): context.next_opcode_starts_line = self.starts_line self.pre_loop(context) for command in self.loop_commands: command.transpile(context) loop = opcodes.START_LOOP() context.add_opcodes( loop, opcodes.TRY(), ) self.pre_iteration(context) context.add_opcodes( JavaOpcodes.INVOKEINTERFACE('org/python/Iterable', '__next__', '()Lorg/python/Object;'), opcodes.CATCH('org/python/exceptions/StopIteration'), ) self.post_loop(context) context.add_opcodes( opcodes.jump(JavaOpcodes.GOTO(0), context, loop, opcodes.Opcode.NEXT), opcodes.END_TRY(), ) context.store_name(self.varname), for command in self.commands: command.transpile(context) context.add_opcodes(opcodes.END_LOOP()) class ComprehensionForLoop(ForLoop): def __init__(self, start, loop, varname, end, start_offset, loop_offset, end_offset, starts_line): super().__init__(start, loop, varname, end, start_offset, loop_offset, end_offset, starts_line) def pre_loop(self, context): context.store_name('##FOR-%s' % id(self)), context.load_name('##FOR-%s' % id(self)), def pre_iteration(self, context): context.add_opcodes( JavaOpcodes.DUP(), ) context.load_name('.0'), def post_loop(self, context): context.add_opcodes( JavaOpcodes.POP(), ) context.load_name('##FOR-%s' % id(self)), class WhileLoop: def __init__(self, start, end, start_offset, end_offset, starts_line): self.start = start self.end = end self.start_offset = start_offset self.end_offset = end_offset self.starts_line = starts_line self.commands = [] def __repr__(self): return '<For %s-%s>' % ( self.start, self.end, ) @property def consume_count(self): return sum(c.consume_count for c in self.commands) @property def product_count(self): return sum(c.product_count for c in self.commands) @property def resume_index(self): return self.start - 1 def is_main_start(self): return False def is_main_end(self, main_end): return False def dump(self, depth=0): print (' %4s:%4d ' % ( self.starts_line if self.starts_line is not None else ' ', self.start_offset, ) + ' ' * depth, 'WHILE:' ) for command in self.commands: command.dump(depth=depth + 1) print (' :%4d ' % ( self.end_offset, ) + ' ' * depth, 'END WHILE' ) def extract(self, instructions, blocks): self.operation = instructions[self.start] i = self.end self.commands = [] while i > self.start: i, command = extract_command(instructions, blocks, i, self.start) self.commands.append(command) self.commands.reverse() def transpile(self, context): context.next_opcode_starts_line = self.starts_line context.add_opcodes(opcodes.START_LOOP()) for command in self.commands: command.transpile(context) end_loop = opcodes.END_LOOP() context.add_opcodes(end_loop) context.jump_targets[self.end_offset] = end_loop def find_try_except(offset_index, instructions, i): instruction = instructions[i] try_start_index = i + 1 try_end_index = offset_index[instruction.argval] - 2 # Find the end of the entire try block end_jump_index = offset_index[instruction.argval] - 1 end_block_offset = instructions[end_jump_index].argval end_block_index = offset_index[end_block_offset] while instructions[end_block_index].opname != 'END_FINALLY': end_block_index -= 1 # print("START INDEX", try_start_index) # print("START OFFSET", instructions[try_start_index].offset) # print("TRY END INDEX", try_end_index) # print("TRY END OFFSET", instructions[try_end_index].offset) # print("END INDEX", end_block_index) # print("END OFFSET", instructions[end_block_index].offset) block = TryExcept( start=try_start_index, end=try_end_index, start_offset=instructions[try_start_index].offset, end_offset=instructions[try_end_index].offset, starts_line=instruction.starts_line ) # find all the except blocks i = offset_index[instruction.argval] + 1 while i < end_block_index: exceptions = [] starts_line = instructions[offset_index[instruction.argval]].starts_line while instructions[i].opname == 'LOAD_NAME': exceptions.append(instructions[i].argval) i = i + 1 # If there's more than 1 exception named, there will be # a BUILD_TUPLE instruction that needs to be skipped. if len(exceptions) > 1: i = i + 1 if instructions[i].opname == 'COMPARE_OP': # An exception has been explicitly named i = i + 3 # print ("CHECK", i, instructions[i].opname) if instructions[i].opname == 'POP_TOP': # Exception is specified, but not a name. var_name = None except_start_index = i + 2 # print("EXCEPT START", except_start_index) elif instructions[i].opname == 'STORE_NAME': var_name = instructions[i].argval except_start_index = i + 3 # print("EXCEPT START e", except_start_index) else: i = i + 3 # Exception is specified, but not a name. var_name = None except_start_index = i # print("EXCEPT START anon", except_start_index) while not (instructions[i].opname in ('JUMP_FORWARD', 'JUMP_ABSOLUTE') and instructions[i].argval >= end_block_offset): i = i + 1 if var_name: except_end_index = i - 7 else: except_end_index = i - 1 jump_offset = instructions[i].argval # print("EXCEPT END", except_end_index) # Step forward to the start of the next except block # (or the end of the try/catch) i = i + 2 block.exceptions.append( ExceptionBlock( exceptions=exceptions, var_name=var_name, start=except_start_index, end=except_end_index, start_offset=instructions[except_start_index].offset, end_offset=instructions[except_end_index].offset, starts_line=starts_line ) ) if jump_offset > end_block_offset: start_else_index = end_block_index + 1 end_else_index = offset_index[jump_offset] if instructions[end_else_index-1].opname == 'JUMP_FORWARD': end_else_index -= 1 block.else_block = ElseBlock( start=start_else_index, end=end_else_index, start_offset=instructions[start_else_index].offset, end_offset=jump_offset, starts_line=instructions[end_block_index].starts_line ) i = end_else_index return i, block def find_blocks(instructions): offset_index = {} # print(">>>>>" * 10) for i, instruction in enumerate(instructions): # print("%4d:%4d %s %s" % (i, instruction.offset, instruction.opname, instruction.argval if instruction.argval is not None else '')) offset_index[instruction.offset] = i # print(">>>>>" * 10) blocks = {} i = 0 while i < len(instructions): instruction = instructions[i] if instruction.opname == 'SETUP_EXCEPT': i, block = find_try_except(offset_index, instructions, i) blocks[i - 1] = block elif instruction.opname == 'SETUP_FINALLY': start_index = offset_index[instruction.argval] # print("FINALLY START INDEX", start_index) # print("FINALLY START OFFSET", instructions[start_index].offset) i = i + 1 if instructions[i].opname == 'SETUP_EXCEPT': i, block = find_try_except(offset_index, instructions, i) else: # print("START INDEX", i) # print("START OFFSET", instructions[i].offset) # print("END INDEX", start_index - 2) # print("END OFFSET", instructions[start_index - 2].offset) block = TryExcept( start=i, end=start_index - 2, start_offset=instructions[i].offset, end_offset=instructions[start_index - 2].offset, starts_line=instruction.starts_line ) i = i + 1 while instructions[i].opname != 'END_FINALLY': i = i + 1 # print("FINALLY END INDEX", i) # print("FINALLY END OFFSET", instructions[i].offset) block.finally_block = FinallyBlock( start=start_index, end=i, start_offset=instructions[start_index].offset, end_offset=instructions[i].offset, starts_line=instruction.starts_line ) blocks[i] = block i = i + 1 elif instruction.opname == 'SETUP_LOOP': i = i + 1 start_index = i while instructions[i].opname not in ('FOR_ITER', 'POP_JUMP_IF_FALSE'): i = i + 1 # Find the end of the entire loop block. # Ignore the final instruction to jump back to the start. end_offset = instructions[i].argval end_index = offset_index[end_offset] - 1 # print("START INDEX", start_index) # print("START OFFSET", instructions[start_index].offset) # print("END INDEX", end_index) # print("END OFFSET", end_offset) if instructions[i].opname == 'FOR_ITER': loop_offset = instructions[i + 2].offset loop_index = offset_index[loop_offset] # print("LOOP INDEX", loop_index) # print("LOOP OFFSET", loop_offset) # print("LOOP VAR", instructions[loop_index - 1].argval) block = ForLoop( start=start_index, loop=loop_index, varname=instructions[loop_index - 1].argval, end=end_index, start_offset=instructions[start_index].offset, loop_offset=loop_offset, end_offset=end_offset, starts_line=instruction.starts_line ) else: block = WhileLoop( start=start_index, end=end_index, start_offset=instructions[start_index].offset, end_offset=end_offset, starts_line=instruction.starts_line, ) blocks[end_index + 1] = block i = i + 1 elif instruction.opname == 'FOR_ITER': i = i + 1 start_index = i - 1 # Find the end of the entire loop block. # Ignore the final instruction to jump back to the start. end_offset = instruction.argval end_index = offset_index[end_offset] - 1 # print("START INDEX", start_index) # print("START OFFSET", instructions[start_index].offset) # print("END INDEX", end_index) # print("END OFFSET", end_offset) loop_offset = instructions[i+1].offset loop_index = offset_index[loop_offset] # print("LOOP INDEX", loop_index) # print("LOOP OFFSET", loop_offset) # print("LOOP VAR", instructions[loop_index].argval) block = ComprehensionForLoop( start=start_index, loop=loop_index, varname=instructions[loop_index - 1].argval, end=end_index, start_offset=instructions[start_index].offset, loop_offset=loop_offset, end_offset=end_offset, starts_line=instruction.starts_line ) blocks[end_index + 1] = block i = i + 1 else: i = i + 1 return blocks def extract_command(instructions, blocks, i, start_index=0, literal=False): """Extract a single command from the end of the instruction list. See the definition of Command for details on the recursive nature of commands. We start at the *end* of the instruction list and work backwards because each command is essentially working towards a final result; each Command can be thought of as a "result". """ i = i - 1 instruction = instructions[i] argval = instruction.argval OpType = getattr(opcodes, instruction.opname) # If this instruction is preceded by EXTENDED_ARG, then # there is more arugment information to come. Integrate it # into the instruction argument we've already read. if i > 0 and instructions[i - 1].opname == 'EXTENDED_ARG': i = i - 1 extended = instructions[i] argval = argval | extended.argval try: if literal: raise KeyError() # If this is a known block, defer to the block for # extraction instructions. cmd = blocks[i] cmd.extract(instructions, blocks) i = cmd.resume_index except KeyError: if instruction.arg is None: opcode = OpType(instruction.offset, instruction.starts_line, instruction.is_jump_target) else: opcode = OpType(argval, instruction.offset, instruction.starts_line, instruction.is_jump_target) cmd = Command(opcode) # print('>', i, instruction.offset, cmd.operation.opname, cmd.operation.consume_count) required = cmd.operation.consume_count while required > 0 and i > start_index: i, arg = extract_command(instructions, blocks, i) cmd.arguments.append(arg) required = required - arg.product_count + arg.consume_count # print('<', i, instruction.offset, cmd.operation.opname) # Since we did everything backwards, reverse to get # arguments back in the right order. cmd.arguments.reverse() return i, cmd
class Board: "Creates and displays the 15x15 Matrix based gridded Scrabble board." def __init__(self): #Creates a 2-dimensional array to form the game board, as well as adding the premium points squares. self.board = [[" " for i in range(15)] for j in range(15)] self.add_premium_squares() self.board[7][7] = " * " def get_board(self): #Returns the board in string form. board_str = " | " + " | ".join(str(item) for item in range(10)) + " | " + " | ".join(str(item) for item in range(10, 15)) + " |" board_str += "\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n" board = list(self.board) for i in range(len(board)): if i < 10: board[i] = str(i) + " | " + " | ".join(str(item) for item in board[i]) + " |" if i >= 10: board[i] = str(i) + " | " + " | ".join(str(item) for item in board[i]) + " |" board_str += "\n |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|\n".join(board) board_str += "\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _" return board_str def add_premium_squares(self): #Adds all of the premium points squares that influence the word's score. TRIPLE_WORD_SCORE = ((0,0), (7, 0), (14,0), (0, 7), (14, 7), (0, 14), (7, 14), (14,14)) DOUBLE_WORD_SCORE = ((1,1), (2,2), (3,3), (4,4), (1, 13), (2, 12), (3, 11), (4, 10), (13, 1), (12, 2), (11, 3), (10, 4), (13,13), (12, 12), (11,11), (10,10)) TRIPLE_LETTER_SCORE = ((1,5), (1, 9), (5,1), (5,5), (5,9), (5,13), (9,1), (9,5), (9,9), (9,13), (13, 5), (13,9)) DOUBLE_LETTER_SCORE = ((0, 3), (0,11), (2,6), (2,8), (3,0), (3,7), (3,14), (6,2), (6,6), (6,8), (6,12), (7,3), (7,11), (8,2), (8,6), (8,8), (8, 12), (11,0), (11,7), (11,14), (12,6), (12,8), (14, 3), (14, 11)) for coordinate in TRIPLE_WORD_SCORE: self.board[coordinate[0]][coordinate[1]] = "TWS" for coordinate in TRIPLE_LETTER_SCORE: self.board[coordinate[0]][coordinate[1]] = "TLS" for coordinate in DOUBLE_WORD_SCORE: self.board[coordinate[0]][coordinate[1]] = "DWS" for coordinate in DOUBLE_LETTER_SCORE: self.board[coordinate[0]][coordinate[1]] = "DLS" def place_word(self, word, location, direction, player): #Allows the player to play the word, assuming that the validity check on the word has been performed. global premium_spots premium_spots = [] direction = direction.lower() word = word.upper() #Places the word rightwards if selected by the player. if direction.lower() == "right": for i in range(len(word)): if self.board[location[0]][location[1]+i] != " ": premium_spots.append((word[i], self.board[location[0]][location[1]+i])) self.board[location[0]][location[1]+i] = " " + word[i] + " " #Places the word downwards if selected by the player. elif direction.lower() == "down": for i in range(len(word)): if self.board[location[0]][location[1]+i] != " ": premium_spots.append((word[i], self.board[location[0]][location[1]+i])) self.board[location[0]+i][location[1]] = " " + word[i] + " " #Removes tiles from the player's rack and replaces them with tiles from the bag, after the word has been played successfully. for letter in word: for tile in player.get_rack_arr(): if tile.get_letter() == letter: player.rack.remove_from_rack(tile) player.rack.replenish_rack() def board_array(self): #Returns the 2-dimensional board array and displays the played word. return self.board
# Contains all piece classes for chess 3D from constant import * from utils import * board = [[([None] * 8) for row in range(8)] for i in range(2)] check = False # the board keeps track of the locations of all the pieces class Piece(object): def __init__(self, color, modelPath, pos, node, scale=1, rotation=0): # number is so different pieces arent equivalent and can be selected # individually self.model = loader.loadModel(modelPath) self.model.reparentTo(node) self.model.setColor(color) self.model.setPos(squarePos(pos)) if rotation != 0: self.model.setHpr(rotation, 0, 0) if scale != 1: self.model.setScale(scale) self.position = pos self.color = None def move(self, newCoor, chessObj, promotion=False): self.take = False self.takenPiece = None # just moves the model to a new spot if self.testCollision(newCoor) or promotion: # sees if collides with friendly piece print("no collision") oldPos = self.position origCoor = indexToTuple(self.position) origPiece = board[origCoor[0]][origCoor[1]][origCoor[2]] if not self.checkTests(newCoor, chessObj): print("legal") print("new Coor:", newCoor, "old Coor:", origCoor) # a tuple containing the pieces original location # sets old spot on board to None and new to the piece newPos = tupleToIndex(newCoor) self.model.setPos(squarePos(newPos)) if self.isCheck(newCoor, chessObj): print("CHECK") check = True if self.isCheckMate(newCoor, chessObj, origCoor): return "gameOver" return "success" else: print("puts king in check") # must undo move self.position = oldPos if self.take: self.unTake(self.takenPiece, chessObj) board[origCoor[0]][origCoor[1]][origCoor[2]] = self board[newCoor[0]][newCoor[1]][newCoor[2]] = origPiece return "collision" else: return "collision" def checkTests(self, newCoor, chessObj): # makes sure move wont put self in check newPos = tupleToIndex(newCoor) origCoor = indexToTuple(self.position) board[origCoor[0]][origCoor[1]][origCoor[2]] = None board[newCoor[0]][newCoor[1]][newCoor[2]] = self self.position = newPos for Possibleking in chessObj.king: if Possibleking.color == self.color: king = Possibleking kingCoor = indexToTuple(king.position) else: secondKing = Possibleking for pawn in chessObj.pawn: if pawn.color != king.color: moves = pawn.getSquares(indexToTuple(pawn.position)) for move in moves: if move == kingCoor: return True for knight in chessObj.knight: if knight.color != king.color: moves = knight.getSquares(indexToTuple(knight.position)) for move in moves: if move == kingCoor: return True for rook in chessObj.rook: if rook.color != king.color: moves = rook.getSquares(indexToTuple(rook.position)) for move in moves: if move == kingCoor: return True for bishop in chessObj.bishop: if bishop.color != king.color: moves = bishop.getSquares(indexToTuple(bishop.position)) for move in moves: if move == kingCoor: return True for queen in chessObj.queen: if queen.color != king.color: moves = queen.getSquares(indexToTuple(queen.position)) for move in moves: if move == kingCoor: return True for secondKing in chessObj.king: if secondKing != king: moves = king.getSquares(indexToTuple(king.position)) for move in moves: if move == kingCoor: return True for newPiece in chessObj.newPieces: if newPiece.color != king.color: moves = newPiece.getSquares(indexToTuple(newPiece.position)) for move in moves: if move == kingCoor: return True return False def isCheck(self, newCoor, chessObj, color=None): # checks if the new move will put opponent in check if color == None: color = self.color for Possibleking in chessObj.king: if Possibleking.color != color: king = Possibleking kingCoor = indexToTuple(king.position) else: secondKing = Possibleking for pawn in chessObj.pawn: if pawn.color != king.color: moves = pawn.getSquares(indexToTuple(pawn.position)) for move in moves: if move == kingCoor: return True for knight in chessObj.knight: if knight.color != king.color: moves = knight.getSquares(indexToTuple(knight.position)) for move in moves: if move == kingCoor: return True for rook in chessObj.rook: if rook.color != king.color: moves = rook.getSquares(indexToTuple(rook.position)) for move in moves: if move == kingCoor: return True for bishop in chessObj.bishop: if bishop.color != king.color: moves = bishop.getSquares(indexToTuple(bishop.position)) for move in moves: if move == kingCoor: return True for queen in chessObj.queen: if queen.color != king.color: moves = queen.getSquares(indexToTuple(queen.position)) for move in moves: if move == kingCoor: return True for newPiece in chessObj.newPieces: if newPiece.color != king.color: moves = newPiece.getSquares(indexToTuple(newPiece.position)) for move in moves: if move == kingCoor: return True return False def isCheckMate(self, newCoor, chessObj, origCoor): for potentKing in chessObj.king: if potentKing.color != self.color: king = potentKing for kingMove in king.getSquares(indexToTuple(king.position)): if self.testCollision(newCoor, king): newPos = tupleToIndex(newCoor) board[origCoor[0]][origCoor[1]][origCoor[2]] = None board[newCoor[0]][newCoor[1]][newCoor[2]] = king if not checkTests(self, newCoor, chessObj): return False else: return True def testCollision(self, curCoor, piece=None): # tests if a piece can move somewhere squareVal = board[curCoor[0]][curCoor[1]][curCoor[2]] # the object currently located at the board location if piece == None: piece = self print("squareVal:", squareVal) if squareVal == None: print("empty space") return True else: if squareVal == piece: print("itself") return False elif squareVal.color == piece.color: print("same color:", piece.color) return False else: piece.takePiece(squareVal) print("different color") self.take = True self.takenPiece = squareVal return True def takePiece(self, piece): # add piece to list of taken pieces and removes from board piece.model.removeNode() # call detachNode() to not draw but not delete print("piece taken") def unTake(self, piece, chessObj): chessObj.newPieces.append(piece) def getSquares(self, curCoor): moves = self.getMoves(curCoor) # z, y, x = curCoor[0], curCoor[1], curCoor[2] for move in moves: if move[0] == 1 and (type(board[0][move[1]][move[2]]) == King or \ type(board[0][move[1]][move[2]]) == Queen): moves.remove(move) return moves def gridMoves(self, z, y, x): # returrns the files and ranks that can be travelled by rooks and queens moves = [] for i in range(1, 8 - x): # generates moves to the right if z == 1: if (type(board[0][y][x + i]) == King or \ type(board[0][y][x + i]) == Queen): break if board[z][y][x + i] == None: moves.append([z, y, x + i]) elif board[z][y][x + i].color != self.color: moves.append([z, y, x + i]) # can attack can't jump over break else: break # can't move there and can't jump over piece for i in range(1, x + 1): # moves to the left if z == 1: if (type(board[0][y][x - i]) == King or \ type(board[0][y][x - i]) == Queen): break if board[z][y][x - i] == None: moves.append([z, y, x - i]) elif board[z][y][x - i].color != self.color: moves.append([z, y, x -i]) break else: break for i in range(1, 8 - y): # moves above if z == 1: if (type(board[0][y + i][x]) == King or \ type(board[0][y + i][x]) == Queen): break if board[z][y + i][x] == None: moves.append([z, y + i, x]) elif board[z][y + i][x].color != self.color: moves.append([z, y + i, x]) break else: break for i in range(1, y + 1): # moves below if z == 1: if (type(board[0][y - i][x]) == King or \ type(board[0][y - i][x]) == Queen): break if board[z][y - i][x] == None: moves.append([z, y - i, x]) elif board[z][y - i][x].color != self.color: moves.append([z, y - i, x]) break else: break return moves def diagonalMoves(self, z, y, x): # returns the diagonals for the movesets of bishops and queens moves = [] mRight = 8 - x # includes all but last move mUp = 8 - y mLeft = x + 1 mDown = y + 1 for i in range(1, min(mRight, mUp)): if z == 1: if (type(board[0][y + i][x + i]) == King or \ type(board[0][y + i][x + i]) == Queen): break if board[z][y + i][x + i] == None: moves.append([z, y + i, x + i]) elif board[z][y + i][x + i].color != self.color: moves.append([z, y + i, x + i]) break else: break for i in range(1, min(mUp, mLeft)): if z == 1: if (type(board[0][y + i][x - i]) == King or \ type(board[0][y + i][x - i]) == Queen): break if board[z][y + i][x - i] == None: moves.append([z, y + i, x - i]) elif board[z][y + i][x - i].color != self.color: moves.append([z, y + i, x - i]) break else: break for i in range(1, min(mLeft, mDown)): if z == 1: if (type(board[0][y - i][x - i]) == King or \ type(board[0][y - i][x - i]) == Queen): break if board[z][y - i][x - i] == None: moves.append([z, y - i, x - i]) elif board[z][y - i][x - i].color != self.color: moves.append([z, y - i, x - i]) break else: break for i in range(1, min(mDown, mRight)): if z == 1: if (type(board[0][y - i][x + i]) == King or \ type(board[0][y - i][x + i]) == Queen): break if board[z][y - i][x + i] == None: moves.append([z, y - i, x + i]) elif board[z][y - i][x + i].color != self.color: moves.append([z, y - i, x + i]) break else: break return moves class Pawn(Piece): def __init__(self, number, color, node): if color == "black": col = BLACKP pos = number + 48 board[0][6][number] = self else: col = WHITEP pos = number + 8 board[0][1][number] = self super(Pawn, self).__init__(col, "models/pawn", pos, node) self.color = color self.specialMove = True def __repr__(self): return "Pawn" def getSquares(self, curCoor): return super(Pawn, self).getSquares(curCoor) def getMoves(self, curCoor): # returns a list of all legal moves possible # pawn can jump between boards in addition to traditional moveset z, y, x = curCoor[0], curCoor[1], curCoor[2] moves = [] moves.append([(z + 1) % 2, y, x]) # board jump if self.color == "white": if y + 1 < 8 and board[z][y + 1][x] == None: # forward move moves.append([z, y + 1, x]) # diagonal attacks if x + 1 < 8 and y + 1 < 8 and board[z][y + 1][x + 1] != None and \ board[z][y + 1][x + 1].color != self.color: moves.append([z, y + 1, x + 1]) if x - 1 >= 0 and y + 1 < 8 and board[z][y + 1][x - 1] != None and \ board[z][y + 1][x - 1].color != self.color: moves.append([z, y + 1, x - 1]) # now to implement starting special move if self.specialMove and board[z][y + 1][z] == None and \ board[z][y + 2][x] == None: moves.append([z, y + 2, x]) else: if y - 1 >= 0 and board[z][y - 1][x] == None: # forward move moves.append([z, y - 1, x]) if x + 1 < 8 and y - 1 >= 0 and board[z][y - 1][x + 1] != None and \ board[z][y - 1][x + 1].color != self.color: moves.append([z, y - 1, x + 1]) if x - 1 >= 0 and y - 1 >= 0 and board[z][y - 1][x - 1] != None and \ board[z][y - 1][x - 1].color != self.color: moves.append([z, y - 1, x - 1]) if self.specialMove and board[z][y - 1][x] == None and \ board[z][y - 2][x] == None: moves.append([z, y - 2, x]) return moves def move(self, newCoor, chessObj): self.specialMove = False returnVal = "success" if super(Pawn, self).move(newCoor, chessObj): if (self.color == "black" and newCoor[1] == 0) or \ (self.color == "white" and newCoor[1] == 7): returnVal = "promotion" return returnVal class Rook(Piece): def __init__(self, number, color, node, implicit=True): if color == "black": col = BLACKP if implicit: # implied that its just being called to set up the board pos = number * 7 + 56 board[0][7][number * 7] = self else: pos = number coor = indexToTuple(pos) board[coor[0]][coor[1]][coor[2]] = self else: col = WHITEP if implicit: pos = number * 7 board[0][0][number * 7] = self else: pos = number coor = indexToTuple(pos) board[coor[0]][coor[1]][coor[2]] = self super(Rook, self).__init__(col, "models/rook", pos, node) self.color = color def __repr__(self): return "Rook" def getSquares(self, curCoor): return super(Rook, self).getSquares(curCoor) def getMoves(self, curCoor): # returns a list of all legal moves possible # rook can move along ranks, files, and to upper board z, y, x = curCoor[0], curCoor[1], curCoor[2] moves = self.gridMoves(z, y, x) moves.append([(z + 1) % 2, y, x]) # moves vertically return moves class Knight(Piece): def __init__(self, number, color, node, implicit=True): if color == "black": col = BLACKP if implicit: pos = number * 5 + 57 board[0][7][number * 5 + 1] = self else: pos = number coor = indexToTuple(pos) board[coor[0]][coor[1]][coor[2]] = self rotation = 180 else: col = WHITEP if implicit: pos = number * 5 + 1 board[0][0][number * 5 + 1] = self else: pos = number coor = indexToTuple(pos) board[coor[0]][coor[1]][coor[2]] = self rotation = 0 super(Knight, self).__init__(col, "models/knight", pos, node, rotation=rotation) self.color = color def __repr__(self): return "Knight" def getSquares(self, curCoor): moves = super(Knight, self).getSquares(curCoor) result = [] for move in moves: if not (board[move[0]][move[1]][move[2]] != None and \ board[move[0]][move[1]][move[2]].color == self.color): result.append(move) return result def getMoves(self, curCoor): # knight can move in an 'L' shape in 3D now, as long as path is still # preserved z, y, x = curCoor[0], curCoor[1], curCoor[2] moves = [] if z == 1: moves.append([0, y, x]) if y + 2 < 8: # no other clean way but if statements unfortunately if x + 1 < 8: moves.append([z, y + 2, x + 1]) if x - 1 >= 0: moves.append([z, y + 2, x - 1]) if z == 0: moves.append([1, y + 2, x]) if y - 2 >= 0: if x + 1 < 8: moves.append([z, y - 2, x + 1]) if x - 1 >= 0: moves.append([z, y - 2, x - 1]) if z == 0: moves.append([1, y - 2, x]) if x + 2 < 8: if y + 1 < 8: moves.append([z, y + 1, x + 2]) if y - 1 >= 0: moves.append([z, y - 1, x + 2]) if z == 0: moves.append([1, y, x + 2]) if x - 2 >= 0: if y + 1 < 8: moves.append([z, y + 1, x - 2]) if y - 1 >= 0: moves.append([z, y - 1, x - 2]) if z == 0: moves.append([1, y, x - 2]) return moves class Bishop(Piece): def __init__(self, number, color, node, implicit=True): if color == "black": col = BLACKP if implicit: pos = number * 3 + 58 board[0][7][number * 3 + 2] = self else: pos = number coor = indexToTuple(pos) board[coor[0]][coor[1]][coor[2]] = self rotation = 180 else: col = WHITEP if implicit: pos = number * 3 + 2 board[0][0][number * 3 + 2] = self else: pos = number coor = indexToTuple(pos) board[coor[0]][coor[1]][coor[2]] = self rotation = 0 super(Bishop, self).__init__(col, "models/bishop", pos, node, rotation = rotation) self.color = color def __repr__(self): return "Bishop" def getSquares(self, curCoor): return super(Bishop, self).getSquares(curCoor) def getMoves(self, curCoor): # bishops can jump boards in addition to their traditional moveset z, y, x = curCoor[0], curCoor[1], curCoor[2] moves = self.diagonalMoves(z, y, x) moves.append([(z + 1) % 2, y, x]) return moves class Queen(Piece): def __init__(self, number, color, node, scale=1, implicit=True): if color == "black": col = BLACKP if implicit: pos = 59 board[0][7][3] = self else: pos = number coor = indexToTuple(pos) board[0][coor[1]][coor[2]] = self else: col = WHITEP if implicit: pos = 3 board[0][0][3] = self else: pos = number coor = indexToTuple(pos) board[coor[0]][coor[1]][coor[2]] = self super(Queen, self).__init__(col, "models/queen", pos, node, scale) self.color = color def __repr__(self): return "Queen" def getSquares(self, curCoor): moves = super(Queen, self).getSquares(curCoor) return moves def getMoves(self, curCoor): z, y, x = curCoor[0], curCoor[1], curCoor[2] moves = self.gridMoves(z, y, x) moves += self.diagonalMoves(z, y, x) return moves class King(Piece): def __init__(self, color, node, scale=1): rotation = 90 if color == "black": col = BLACKP pos = 60 board[0][7][4] = self else: col = WHITEP pos = 4 board[0][0][4] = self super(King, self).__init__(col, "models/king", pos, node, scale, rotation = rotation) self.color = color def __repr__(self): return "King" def getSquares(self, curCoor): moves = super(King, self).getSquares(curCoor) result = [] for move in moves: if not (board[move[0]][move[1]][move[2]] != None and \ board[move[0]][move[1]][move[2]].color == self.color): result.append(move) return result def getMoves(self, curCoor): # can move one square in any direction but up z, y, x = curCoor[0], curCoor[1], curCoor[2] moves = [] if x + 1 < 8: # moves to the right moves.append([z, y, x + 1]) if y + 1 < 8: moves.append([z, y + 1, x + 1]) if y - 1 >= 0: moves.append([z, y - 1, x + 1]) if x - 1 >= 0: # to the left moves.append([z, y, x - 1]) if y + 1 < 8: moves.append([z, y + 1, x - 1]) if y - 1 >= 0: moves.append([z, y - 1, x - 1]) if y + 1 < 8: # forward and back moves.append([z, y + 1, x]) if y - 1 >= 0: moves.append([z, y - 1, x]) return moves
# def my_func(x, y, z): # try: # sorted_list = [x, y, z] # sorted_list = sorted(sorted_list) # return print(int(sorted_list[-1]) + int(sorted_list[-2])) # except ValueError: # return print('You have entered string') # # # my_func(5, 2 , 1) #записал себе для красоты def my_func(x, y, z): try: return print(sum(sorted([x, y, z])[1:])) except TypeError: return print('You have entered string') my_func(5, -1 , 1)
from math import factorial # def fact(): # global n # n = int(input('Input number: ')) # yield factorial(n) # # f = fact() # # for i in f: # print(i) # c = 0 # for el in fact(n): # if c < n: # print(el) # c +=1 # else: # break def fibo_gen(): global num, user_num n = int(input('Insert positive number: ')) m = 1 user_num = factorial(n + 1) for num in range(1, n + 1): m *= num yield m for i in fibo_gen(): if num <= 15: print(f'Factorial {num} = {i}') else: print(f'\rCustom factorial of {num} = {user_num}', end='')
from itertools import count my_file = open('05_02.txt', 'r') i = 1 for line in my_file: if line == '\n': line = line.rstrip('\n') print(f"Line {i} doesn't contain words") i +=1 else: line = line.rstrip('\n') word_count = line.count(' ') + 1 print(f'Line {i} contains {word_count} words') i += 1 print(f'File contains {i} lines totally.') my_file.close()
#подсмотрел и добавил реализацию ошибки некорректного месяца user_month = int(input('Insert month count: ')) month_dict = { 'spring': [3, 4, 5], 'summer': [6, 7, 8], 'autumn': [9, 10, 11], 'winter': [12, 1, 2] } while user_month < 0 or user_month > 12: user_month = int(input('You have entered wrong month. Insert month count: ')) for key, value in month_dict.items(): if value[0] == user_month: print(f'You have inserted {key}') elif value[1] == user_month: print(f'You have inserted {key}') elif value[2] == user_month: print(f'You have inserted {key}') month_list = ['winter', 'winter', 'spring', 'spring', 'spring', 'summer', 'summer', 'summer', 'autumn', 'autumn', 'autumn', 'winter'] print(f'The month refers to {month_list[user_month-1]}')
class MyList: print_list = [] # Попробуем сделать исключение как класс в классе.. @staticmethod class NotFloatExcept(Exception): def __init__(self, txt): self.txt = txt # Проверим что вновь введенная строка является числом, если да, перобразуем к числовому типу def __is_float(self, input_str): is_one_dot, is_one_minus = 0, 0 for i in input_str: if ord(i) >= 48 and ord(i) <= 57: pass # В числе может быть одн точка elif ord(i) == 46 and is_one_dot == 0: is_one_dot += 1 # А еще минус elif ord(i) == 45 and is_one_minus == 0: is_one_minus += 1 else: raise self.NotFloatExcept('Введенная строка не является числом!') # Если число целое, так и вернем if is_one_dot == 0: return int(input_str) return float(input_str) # Добавляем новое число в список def __call__(self, new_str): try: self.print_list.append(self.__is_float(new_str)) except self.NotFloatExcept as e: print(e) # Выводим на печать def __str__(self): return str(self.print_list)[1:-1] list = MyList() while True: print('Введите число: ', end='') n = input() if n == '': print('Окончание программы') break else: list(n) print(list)
user_number = int(input('Insert nubmer: ')) max_figure = 0 num = user_number while num >0: digit = num % 10 if digit > max_figure: max_figure = digit if max_figure == 9: break num = num // 10 # max_figure = 0 # dozens = None # units = 0 # if user_number == 0: # max_figure = 'empty' # elif user_number < 10: # max_figure = user_number # elif user_number == 10: # max_figure = 1 # elif user_number > 10: # while dozens != 0: # dozens = user_number // 10 # units = user_number % 10 # if units > max_figure: # max_figure = units # if dozens < 10 and dozens > max_figure: # max_figure = dozens # elif dozens < 10 and units > max_figure: # max_figure = units # elif dozens > 10: # user_number = dozens # dozens = user_number // 10 # units = user_number % 10 # if dozens < 10 and units > max_figure: # max_figure = units # elif dozens < 10 and dozens > max_figure: # max_figure = dozens # else: # continue # break print(f'Max figure in your number is {max_figure}')
#Problem 10 from Project Euler #http://projecteuler.net/problem=10 import math import sys #Had to set the recursion higher otherwise the maxmum would be reached. #Efficiency was not attempted, although it will be in the future. sys.setrecursionlimit(7000) #Function that returns the sum of the prime numbers under 2000000 def primeSum(): answer = [] for x in xrange(2, 2000000): if isPrime(x): answer.append(x) #print answer return sum(answer) #Abstracts a level to avoid the divisor parameter. #Determines if a number is prime. def isPrime(number): return isPrimeHelper(number, 2) #Recursive function that calculates if given number is divisble by any number #under it > 0 def isPrimeHelper(number, divisor): y = math.trunc(math.sqrt(number)) if divisor <= y: if number%divisor == 0: return False else: return True and isPrimeHelper(number, divisor + 1) else: return True print primeSum()
#Problem 15 from Project Euler #https://projecteuler.net/problem=15 #Thanks ronbrz for suggesting I try Pascal's Triangle #Create a size x size array filled with 0's def initializeLattice(size): baseLattice = [[0 for x in range(size+1)] for y in range(size+1)] return baseLattice #Fill the edges of the lattice with 1's def fillEdgesOfLattice(lattice): for y in range(len(lattice)): if y != 0: lattice[y][0] += 1 for x in range(len(lattice[0])): if x != 0: lattice[0][x] += 1 return lattice #Fill the inner portion of the array. #Which is just going to be the sum of the two adjacent corners def fillInnerLattice(lattice): for y in range(1,len(lattice)): for x in range(1,len(lattice)): lattice[y][x] = lattice[y][x-1] + lattice[y-1][x] return lattice print fillInnerLattice(fillEdgesOfLattice(initializeLattice(20)))
""" file: run.py autor: PC """ from misvariables import * # uso de condicional simple nota = input("Por favor ingrese la primera nota: ") nota2 = input("Por favor ingrese la segundsa nota: ") # Se convierte en entero las variables cadena nota = int(nota) nota2 = int(nota2) # Estructuras condicional Si-Entonces if nota >=18: print(mensaje) if nota2 >=18: print(mensaje)
import random # Запрашивать у пользователя команду. # В зависимости от введенной команды выполнять действие. todos = {} HELP = ''' * help - напечатать справку по программе. * add - добавить задачу в список (название задачи запрашиваем у пользователя). * show - напечатать все добавленные задачи. * random - добавить случайную задачу на сегодня ''' # Дата:[Задача1, Задача2,....] RANDOM_TASK = ["Главное не заснуть", 'Выгулять собаку', 'Учить английский'] def add_todo(date, task): if date in todos: todos[date].append(task) else: todos[date] = [] todos[date].append(task) print(f'Задача {task} добавлена на дату {date}') #command = input("Введите команду: ") while True: command = input("Введите команду: ") if command == "help": print(HELP) elif command == "add": date = input("Введите дату: ") task = input("Введите задачу: ") add_todo(date, task) elif command == 'show': date = input('Введите дату: ') if date in todos: for task in todos[date]: print(f'[] {task}') else: print("Задач на эту дату нет") elif command == 'random': date = 'сегодня' add_todo(date, random.choice(RANDOM_TASK)) else: print("Неизвестная команда!") break
#!/usr/bin/env python #--*-- coding: utf-8 --*-- #合并两个有序列表,因为是一个列表当作两个列表,所以需要注意界限 #注意mid是属于左边列表还是右边的 #注意最后按照left到right的顺序赋值回来 def merge(a, left, mid, right): low = left high = mid + 1 tmp = [] while low <= mid and high <= right: if a[low] <= a[high]: tmp.append(a[low]) low += 1 else: tmp.append(a[high]) high += 1 while low <= mid: tmp.append(a[low]) low += 1 while high <= right: tmp.append(a[high]) high += 1 cnt = 0 while cnt < len(tmp): a[left] = tmp[cnt] cnt += 1 left += 1 def merge_sort(a, left, right): #当左小于右时,往下分,直到list长度为1,进行合并,变为有序列表,再递归回来继续合并 if left < right: mid = (left + right) / 2 merge_sort(a, left, mid) merge_sort(a, mid+1, right) merge(a, left, mid, right) if __name__ == "__main__": a = [11, 2, 32, 76, 27, 53, 49] print "before merge" print a merge_sort(a, 0, len(a)-1) print "after merge" print a
#基本python规则 #第一个示例 print("Hello,world!") #变量 a=10 #整数 十进制:21,八进制:025,十六进制:0x15 b="你好" #字符串 c=True #布尔数 d=1.2 #浮点数 f=1+1j #复数 #查看类型 print(type(a)) z=int(d) #强制类型转换 str float bool # 1.为什么区分对象类型? # 不同类型对象运算规则不同 # 如:整数的加法和字符串的加法含义不同 # 2.不同类型对象在计算机内表示方式不同 # 如:整数和字符串 # 3。为何区分整数与浮点数? # 浮点数表示能力更强 # 浮点数有精度损失 # CPU有专门的浮点数运算部件
from turtle import Turtle,mainloop def main(): #设置窗口信息和turtle画笔 turtle.title('数据驱动的动态路径绘制') turtle.setup(800,600,0,0) pen=turtle.Turtle() pen.color('red') pen.width(5) #pen.shape('turtle') pen.speed(5) #读取数据文件到列表result中 result=[] file=open('C:\\Users\Devil\Desktop\python学习\Chapter 6\文件实例一数据\data.txt','r') for line in file: result.append(list(map(float,line.split(',')))) print(result) #根据每一条数据进行绘制 for i in range(len(result)): pen.color((result[i][3],result[i][4],result[i][5])) pen.forward(result[i][0]) if result[i][1]: pen.right(result[i][2]) else: pen.left(result[i][2]) pen_goto(0,0) if _name_ == '_main_': main()
''' Created on Sep 14, 2014 @author: melvic It's very simple Scissors cuts paper Paper covers rock Rock crushes lizard Lizard poisons Spock Spock smashes scissors Scissors decapitates lizard Lizard eats paper Paper disproves Spock Spock vaporizes rock And as it always has been Rock crushes scissors ''' def winner(shape1, shape2): res = (shape1 - shape2) % 5 if res > 2: return shape2 elif res > 0: return shape1 else: return None def normalize(x): xs = {0: 0, 1: 2, 2: 4, 3: 3, 4: 1} return xs[x - 1] if __name__ == '__main__': print '1 - Rock' print '2 - Paper' print '3 - Scissors' print '4 - Lizard' print '5 - Spock' shape1 = raw_input("Player 1's Shape: ") shape2 = raw_input("Player 2's Shape: ") shape1 = normalize(int(shape1)) shape2 = normalize(int(shape2)) names = {0:'Rock', 1: 'Spock', 2: 'Paper', 3: 'Lizard', 4: 'Scissors'} winner = winner(shape1, shape2) if winner == None: print 'Draw' else: print names[winner] + ' wins'
def number_base(n,k): s='' while n: s = s+str(n%k) #print s n=n/k return s[::-1] def is_palindrome(s): length = len(str(s)) for x in xrange(0,length): if str(s)[x]!=str(s)[length-1-x]: return 0 return 1 sum1 =0 n,k=map(int,raw_input().split()) for x in xrange(1,n+1): ans1 = is_palindrome(x) ans2 = is_palindrome(number_base(x,k)) if ans1==1 and ans2==1: sum1 = sum1+x print sum1
from spy_details import spy, Spy, chat, friends #transferring data from spy_details file to main from steganography.steganography import Steganography #To hide information in plain sight from datetime import datetime default_status = ["Hello! friends what's up","what a cool weather","Hanging out with music","what a busy day!"]#they are the default statuses or previous updated statuses print "Hello! Let's explore :)" spy_continue = "Do you want to continue as " + spy.salutation + " " + spy.name + " (Y/N)? " #if user types y , below if statement will execute #if user types n, below else statement will execute SC = raw_input(spy_continue) def status_update():#defining status_update current_status = None#displays current status if spy.current_status_message != None: print "Your current status is:\n" + spy.current_status_message else: print "Your status is empty :( \n" older_select = raw_input("Do you want to select from your previous statuses? (Y\N) ") if older_select.upper() == "N":#if user types N,it means user should type new status new_status = raw_input("Please type your new status.....") if len(new_status) > 0: default_status.append(new_status) current_status = new_status#status will be stored as current status elif older_select.upper() == 'Y':#if user types Y,it means user will select from previously stored statuses item_position = 1 for message in default_status: print '%d. %s' % (item_position, message) item_position = item_position + 1#position is incremented i.e current typed status will be stored message_selection = int(raw_input("\nPlease select from above")) if len(default_status) >= message_selection: current_status = default_status[message_selection - 1] else: print "Invalid Input :(" #error if user types other than y or n if current_status: print "Your current status is " + current_status else: print "You current status is empty" return current_status#the current_status value is returned def add_new_friend():#defining add_new_friend new_friend = Spy('','',0,0.0) print"Please fill the details below:" new_friend.name = raw_input("New friend name: ") new_friend.salutation = raw_input("Mr. or Ms.?: ") new_friend.name = new_friend.salutation + " " + new_friend.name new_friend.age = raw_input("Age:") new_friend.age = int(new_friend.age) new_friend.rating = raw_input("Spy rating:") new_friend.rating = float(new_friend.rating)#details of new friend if len(new_friend.name) > 0 and new_friend.age > 12 and new_friend.rating >= spy.rating: friends.append(new_friend)#storing the info. of new friend print 'congratulations! Friend Added!' else: print "Sorry!your friend's details doesn't fulfil our requirements" return len(friends)#returning lenth of added friend to increment/count no. of friends def friend_selection():#defining friend_selection item_number = 0 for friend in friends: print '%d. %s %s aged %d with rating %.2f is online' % (item_number +1, friend.salutation, friend.name,friend.age,friend.rating) item_number = item_number + 1 choose_friend = raw_input("select your friend") friend_choice_position = int(choose_friend) - 1 return friend_choice_position def send_message():#defining send_message.used to send secret message choose_friend = friend_selection() original_image = raw_input("please type image name:") output_path = "output.jpg" text = raw_input("Type the text to hide ") Steganography.encode(original_image, output_path, text)#to hide text ,encode is done new_chat = chat(text,True) friends[choose_friend].chats.append(new_chat) print "congratulations! You have successfully created a secret message and is ready to use!" def read_message():#to read secret message sender = friend_selection() output_path = raw_input("Enter name of file:") secret_text = Steganography.decode(output_path)#decoding is done to access the text hidden in image new_chat = chat(secret_text,False) friends[sender].chats.append(new_chat) print "Your secret message is saved successfully!" def chat_history():#to check message history read_for = friend_selection() print '\n' for chat in friends[read_for].chats: if chat.sent_by_me: print '[%s] %s: %s' % (chat.time.strftime("%d %B %Y"), 'You said:', chat.msg) else: print '[%s] %s said: %s' % (chat.time.strftime("%d %B %Y"), friends[read_for].name, chat.msg) def chat_begin(spy): spy.name = spy.salutation + " " + spy.name if spy.age>=12 and spy.age<=50: print "Welcome " + spy.name + " age: " \ + str(spy.age) + " and rating of: " + str(spy.rating) + " :)" show_menu = True while show_menu:#while loop continues until show_menu=false menu_choices = "What do you want to do? \n 1. Update a status \n 2. Add a friend \n 3. Send a secret message \n 4. Read a secret message \n 5. Read Chats \n 6. Exit \n" menu_choice = raw_input(menu_choices) if len(menu_choice) > 0:#len counts the length of text menu_choice = int(menu_choice)#converts str into int if menu_choice == 1: spy.current_status_message = status_update()#executes status_update() defined earlier elif menu_choice == 2: number_of_friends = add_new_friend()#moves and executes add_new_friend defined above print 'You have %d friends' % (number_of_friends) elif menu_choice == 3: send_message()#executes send_message defined above elif menu_choice == 4: read_message()#executes read_message defined above elif menu_choice == 5: chat_history()#executes chat_history defined above else: show_menu = False #while loop terminates else: print "Sorry ! couldn't proceed \neither you have entered wrong input or your details doesn't fulfil our requirements" if SC == "Y" or SC == "y":#for old spy_user username=raw_input("Enter your username:") password=raw_input("Enter your password:") if username == "nabinkarna02" and password == "nnnnn":#if else is used for username and password chat_begin(spy) else: print"Incorrect Username or Password" exit() elif SC == "N" or SC == "n":#for new user spy = Spy('','',0,0.0) spy.name = raw_input("Welcome!\n Your Name: ") spy.salutation = raw_input("Are you Mr. or Ms.?: ") spy.age = raw_input("Your age:") spy.age = int(spy.age) spy.rating = raw_input("Your rating (out of 5):") spy.rating = float(spy.rating) if spy.rating >=0.0 and spy.rating <= 2.0: print"Poor spy rating" exit() elif spy.rating >2.0 and spy.rating <= 3.0: print"Your spy rating is preety good" chat_begin(spy) elif spy.rating > 3.0 and spy.rating <=5.0: print"You've superb spy rating" chat_begin(spy) else: print"wrong input" else:#else statement executes if the user input does not satisfy if and elif condition print"wrong input" exit()
#Course:CS2302 #aAuthor:Daniela Flores #Lab1 #Instructor:Olac Fuentes #T.A: Dita Nath #date of last Mod: 2/8/19 #purpose of program: in this program I had to write recursive methods that'll draw various shapes. import matplotlib.pyplot as plt import numpy as np import math #the next two methods draw circles within the previous circle, the center is the radious def circle(center,rad): n = int(4*rad*math.pi) t = np.linspace(0,6.3,n) x = center[0]+rad*np.sin(t) y = center[1]+rad*np.cos(t) return x,y def draw_circles(ax,n,center,radius,w): if n>0: x,y = circle(center,radius) #here the radius is added to the center ax.plot(x+radius,y,color='k') draw_circles(ax,n-1,center,radius*w,w) #call where 10 circles are drawn plt.close("all") fig, ax = plt.subplots() draw_circles(ax, 10, [100,0], 100,.6) ax.set_aspect(1.0) ax.axis('off') plt.show() fig.savefig('circles.png') #call where 40 circles are drawn plt.close("all") fig, ax = plt.subplots() draw_circles(ax, 40, [100,0], 100,.87) ax.set_aspect(1.0) ax.axis('off') plt.show() fig.savefig('circles.png') #call where 62 circles are drawn plt.close("all") fig, ax = plt.subplots() draw_circles(ax, 62, [100,0], 100,.94) ax.set_aspect(1.0) ax.axis('off') plt.show() fig.savefig('circles.png') ########################################################################## #the following methods draw squares in the vertices of the larger square def draw_squares(ax,n,p,r,c): if n>0: #i1 = [[c[0]+radius],2,3,0,1] newCor = np.array([ [c[0]+r,c[1]+r], [c[0]-r,c[1]+r],[c[0]-r,c[1]-r],[c[0]+r,c[1]-r],[c[0]+r,c[1]+r]]) # 0+25 , 0+25 // 0-25 , 0+25 // 0-25 , 0-25 // 0+25 , 0-25// 0+25, 0+25 # (25,25) (-25,25) (-25,-25) (25,-25) (25,25) ax.plot(newCor[:,0],newCor[:,1],color = 'k') #with respect to center: newR = r//2 newCenter = [c[0]+r,c[1]+r] newCenter2 = [c[0]-r,c[1]+r] newCenter3 = [c[0]-r,c[1]-r] newCenter4 = [c[0]+r,c[1]-r] draw_squares(ax,n-1,newCor,newR,newCenter) draw_squares(ax,n-1,newCor,newR,newCenter2) draw_squares(ax,n-1,newCor,newR,newCenter3) draw_squares(ax,n-1,newCor,newR,newCenter4) #call where 2 sets of circles are drawn plt.close("all") radius = 40 center = [0,0] p = np.array([[-radius,-radius],[-radius,radius],[radius,radius],[radius,-radius],[-radius,-radius]]) fig, ax = plt.subplots() draw_squares(ax,2,p,radius,center) ax.set_aspect(1.0) ax.axis('off') plt.show() fig.savefig('squares.png') #call where 3 sets of squares are drawn plt.close("all") radius = 40 center = [0,0] p = np.array([[-radius,-radius],[-radius,radius],[radius,radius],[radius,-radius],[-radius,-radius]]) fig, ax = plt.subplots() draw_squares(ax,3,p,radius,center) ax.set_aspect(1.0) ax.axis('off') plt.show() fig.savefig('squares.png') #call where 4 sets of squares are drawn plt.close("all") radius = 40 center = [0,0] p = np.array([[-radius,-radius],[-radius,radius],[radius,radius],[radius,-radius],[-radius,-radius]]) fig, ax = plt.subplots() draw_squares(ax,4,p,radius,center) ax.set_aspect(1.0) ax.axis('off') plt.show() fig.savefig('squares.png') ############################################################################## #the following methods draw 5 smaller circles inside the bigger circle def circle2(center,rad): n = int(4*rad*math.pi) t = np.linspace(0,6.3,n) x = center[0]+rad*np.sin(t) y = center[1]+rad*np.cos(t) return x,y def draw_circles2(ax,n,center,Radius): if n>0: x,y = circle2(center,Radius) ax.plot(x,y,color='k') Radius = Radius/3 newCenterL =np.array( [((1/3)*center[0]),0]) x,y = circle2(newCenterL,Radius) ax.plot(x,y,color='r') newCenterM = np.array([center[0],0]) x,y = circle2(newCenterM,Radius) ax.plot(x,y,color='m') newCenterR = np.array( [(((2/3)*center[0])+center[0]),0]) x,y = circle2(newCenterR,Radius) ax.plot(x,y,color='c') newCenterUp =np.array( [center[0],((2/3)*center[0])]) x,y = circle2(newCenterUp,Radius) ax.plot(x,y,color='b') newCenterDown =np.array( [center[0],((-2/3)*center[0])]) x,y = circle2(newCenterDown,Radius) ax.plot(x,y,color='g') draw_circles2(ax,n-1,newCenterL,Radius) draw_circles2(ax,n-1,newCenterM,Radius) draw_circles2(ax,n-1,newCenterR,Radius) draw_circles2(ax,n-1,newCenterUp,Radius) draw_circles2(ax,n-1,newCenterDown,Radius) #here 2 sets of circles are drawn plt.close("all") fig, ax = plt.subplots() draw_circles2(ax, 1, np.array([100,0]), 100) ax.set_aspect(1.0) ax.axis('on') plt.show() fig.savefig('circles.png') #here 3 sets of circles are drawn plt.close("all") fig, ax = plt.subplots() draw_circles2(ax, 2, np.array([100,0]), 100) ax.set_aspect(1.0) ax.axis('on') plt.show() fig.savefig('circles.png') #4 sets of circles are drawn plt.close("all") fig, ax = plt.subplots() draw_circles2(ax, 3, np.array([100,0]), 100) ax.set_aspect(1.0) ax.axis('on') plt.show() fig.savefig('circles.png') ##################################################################### #the following methods draw an upside down tree def draw_triangle(ax,n,p,len,center): leftsubL = [-len,-len] rightsubL =[len,-len] treeAr = np.array([leftsubL,center,rightsubL]) if n>0: LL = ((leftsubL[0]+leftsubL[0]//2),(leftsubL[0]+leftsubL[0]//2)) newRightC = [(leftsubL[0]+leftsubL[1]//-2),(leftsubL[0]+leftsubL[0]//2)] new = np.array([leftsubL,LL,leftsubL,newRightC]) ax.plot(new[:,0],new[:,1],color = 'k') newLeftR = [(rightsubL[0]-rightsubL[1]//-2),(rightsubL[0]-rightsubL[0]//-2)] newRightR = [(rightsubL[0]+rightsubL[0]//2),(rightsubL[0]+rightsubL[1]//2)] new2 = np.array([rightsubL,newLeftR,rightsubL,newRightR]) # ax.plot(new2[:,0],new2[:,1],color = 'k') newLen = len+(len//3) draw_triangle(ax,n-1,treeAr,newLen,leftsubL) draw_triangle(ax,n-1,treeAr,newLen,rightsubL) #here 2 branches are drawn plt.close("all") length = 25 center = [0,0] p = np.array([[-length,-length],[center[0],center[1]],[length,-length]]) fig, ax = plt.subplots() draw_triangle(ax,2,p,length,center) ax.set_aspect(1.0) ax.axis('on') plt.show() fig.savefig('squares.png') #here three branches are drawn plt.close("all") length = 25 center = [0,0] fig, ax = plt.subplots() draw_triangle(ax,3,p,length,center) ax.set_aspect(1.0) ax.axis('on') plt.show() fig.savefig('squares.png') #here 4 sets of branches are drawn plt.close("all") length = 25 center = [0,0] fig, ax = plt.subplots() draw_triangle(ax,4,p,length,center) ax.set_aspect(1.0) ax.axis('on') plt.show() fig.savefig('squares.png')
from random import randint class Encrypt: def __init__(self, data, pin): self.data = list(data) self.pin = pin self.ceaser = [] def build(self): len_pre = (int(self.pin[0]) + int(self.pin[2])) \ if (int(self.pin[0]) + int(self.pin[2])) else 4 len_app = (int(self.pin[1]) + int(self.pin[2])) \ if (int(self.pin[1]) + int(self.pin[2])) else 4 swap = self.data[::2] + self.data[1::2] swap.reverse() shift = int(self.pin[3]) if int(self.pin[3]) else 5 for pos, char in enumerate(swap): origin = ord(char) if pos%2 == 0: new = chr((((origin-33+shift)%93)+33)) else: new = chr((((origin-33-shift)%93)+33)) self.ceaser.append(new) for _prepend in range(len_pre): insert_chr = chr(randint(33, 126)) self.ceaser.insert(0, insert_chr) for _append in range(len_app): insert_chr = chr(randint(33, 126)) self.ceaser.append(insert_chr) return ''.join(self.ceaser) def __str__(self): printable = ''.join(self.ceaser) return printable class Decrypt: def __init__(self, data, pin): self.data = data self.pin = pin self.ceaser = [] def restore(self): len_pre = (int(self.pin[0]) + int(self.pin[2])) \ if (int(self.pin[0]) + int(self.pin[2])) else 4 len_app = (int(self.pin[1]) + int(self.pin[2])) \ if (int(self.pin[1]) + int(self.pin[2])) else 4 shift = int(self.pin[3]) if int(self.pin[3]) else 5 stripped = self.data[len_pre:len_app*-1] for pos, char in enumerate(stripped): origin = ord(char) if pos%2 == 0: new = chr((((origin-33-shift)%93)+33)) else: new = chr((((origin-33+shift)%93)+33)) self.ceaser.append(new) self.ceaser.reverse() password = ['' for _ in self.ceaser] first_half = (len(password)/2)+(len(password)%2) for char_pos in range(first_half): password[char_pos*2] = self.ceaser[char_pos] for char_pos in range(len(password)-first_half): password[(char_pos*2)+1] = self.ceaser[first_half+char_pos] return password def test(): for _ in range(100000): password = '' for l in range(randint(5,15)): password += chr(randint(34,125)) pin = str(randint(1000, 9999)) print _, password, pin, e = Encrypt(password, pin) x = e.build() d = Decrypt(x, pin) a = d.restore() if ''.join(a) == password: print True else: print False print a break def manual_test(): pin = '4321' e = Encrypt('password', pin) x = e.build() print x d = Decrypt(x, pin) a = d.restore() print a manual_test()
# 1 - imports / bibliotecas import json # 2 - Classe # 3 - Métodos e Funções def print_hi(name): print(f'Oi, {name}') # a partir do Python 3 def calcular_area_do_retangulo(largura, comprimento): return largura * comprimento def calcular_area_do_quadrado(lado): return lado ** 2 def calcular_area_do_triangulo(largura, comprimento): return largura * comprimento / 2 def contagem_progressiva(fim): for numero in range(fim): # repetir o bloco de zero até o fim print(numero) # exibir o número def apoiar_candidato(nome, vezes): for numero in range(vezes): # contador = numero + 1 # print(f'{contador} - {nome}') if numero < 9: print(f'00{numero + 1} - {nome}') elif numero < 99: print(f'0{numero + 1} - {nome}') else: print(numero + 1, '-', nome) def brincar_de_plim(fim): for numero in range(fim): if numero % 4 == 0: print('PLIM!') else: print('{:0>3}'.format(numero)) def exibir_dia_da_semana_if(numero): print("Execução com IF") if numero == 1: print('O dia é segunda') elif numero == 2: print('O dia é terça') elif numero == 3: print('O dia é quarta') elif numero == 4: print('O dia é quinta') elif numero == 5: print('O dia é sexta') elif numero == 6: print('O dia é sábado') elif numero == 7: print('O dia é domingo') else: print('Número de dia inválido. Digite um número de 1 a 7') def exibir_dia_da_semana_com_match(numero): print("Execução com MATCH") match numero: case 1: print('O dia é segunda') case 2: print('O dia é terça') case 3: print('O dia é quarta') case 4: print('O dia é quinta') case 5: print('O dia é sexta') case 6: print('O dia é sábado') case 5: print('O dia é domingo') def brincar_de_para_ou_continua(): resposta = 'C' # S aqui significa que continua # while resposta == 'C' or resposta == 'c': while resposta.upper() == 'C': resposta = input("Digite C para continuar ou qualquer outro caracter para parar") print('Você decidiu parar com a brincadeira') # estrutura de identificação/execução if __name__ == '__main__': print_hi('Graziela') # chamar a função de cálculo da área do retângulo resultado = calcular_area_do_retangulo(3, 4) print(f'A área do retângulo é de {resultado} m²') # chamar a função de cálculo da área do quadrado resultado = calcular_area_do_quadrado(5) print(f'A área do quadrado é de {resultado} m²') # chamar a função de cálculo da área do triângulo resultado = calcular_area_do_triangulo(6, 7) print(f'A área do triângulo é de {resultado} m²') # executar uma contagem progressiva contagem_progressiva(12) # exibir o nome do candidato várias vezes apoiar_candidato('Faker', 101) # brincar de plim brincar_de_plim(101) # exemplo de dia da semana com if - elif - else exibir_dia_da_semana_if(5) # exemplo de dia da semana com match - case exibir_dia_da_semana_com_match(1) # exemplo com while - para ou continua brincar_de_para_ou_continua()
from bs4 import BeautifulSoup import html import logging import re def __parseHTML(page_html: str) -> dict: """Function to parse EDGAR page HTML, returning a dict of company info. Arguments: page_html {str} -- Raw HTML of page. Returns: dict -- Structured dictionary of company attributes. """ # Dict for final output company_info = dict() # Parsing HTML parsed = BeautifulSoup(page_html, features='html.parser') # Getting company addresses company_info['addresses'] = __getAddresses(parsed=parsed) # Getting company name company_info['name'] = __getCompanyName(parsed=parsed) # Getting former company names company_info['former_names'] = __getFormerNames(parsed=parsed) # Getting company metadata company_info['metadata'] = __getCompanyMetadata(parsed=parsed) return company_info def __getAddresses(parsed: BeautifulSoup) -> list: """Function to extract company addresses from the parsed HTML EDGAR page. Searches for address information in divs with class name 'mailer'. Arguments: parsed {BeautifulSoup} -- Parsed HTML from company EDGAR filing. Returns: list -- List of addresses. """ # Addresses container address_divs = parsed.find_all('div', class_='mailer') # Building RegEx for phone number # The following RegEx extracts phone numbers in the following formats: # 1. (###) ###-#### # 2. ###-###-#### # 3. ########## phone_number_regex = re.compile( r'(\(\d{3}\) \d{3}-\d{4}|\d{3}-\d{3}-\d{4}|\d{10})') # List for final addresses addresses = list() for address in address_divs: # Create dict for address address_parsed = dict() # Split text by newline address_items = address.text.split('\n') # Removing leading and trailing spaces address_items = [i.strip() for i in address_items] # Variable to store street address street_address = '' # Iterate through each line for idx, address_item in enumerate(address_items): # First line is address type if idx == 0: address_parsed['type'] = address_item continue # Check if line has phone number phone_matches = phone_number_regex.findall(address_item) if len(phone_matches) == 1: # Stripping non-digit characters from phone number phone_number = re.sub('[^0-9]', '', phone_matches[0]) address_parsed['phone'] = phone_number continue # If no number, add to address line street_address += address_item.strip() + ' ' # Adding street address to parsed address address_parsed['street_address'] = street_address.strip() # Adding parsed address to addresses master list addresses += [address_parsed] return addresses def __getCompanyName(parsed: BeautifulSoup) -> str: """Function to extract the company name from the parsed HTML EDGAR page. Searches for company name in a span with class 'companyName'. Arguments: parsed {BeautifulSoup} -- Parsed HTML from company EDGAR filing. Returns: str -- Name of company. """ # Company name container name_container = parsed.find('span', class_='companyName') # Extracting raw text elements name_raw_text = [s for s in name_container.children if isinstance(s, str)] # Getting name (first raw text instance) return name_raw_text[0].strip() def __getFormerNames(parsed: BeautifulSoup) -> list: """Function to extract former company names, and dates through which reports were filed under that name from the parsed HTML EDGAR page. Searches for strings matching format for previous names first, then extracts former name and filings-through date separately. Arguments: parsed {BeautifulSoup} -- Parsed HTML from company EDGAR filing. Returns: list -- List of former names (if any), empty list otherwise. """ # Former names container former_container = parsed.find('p', class_='identInfo') # List for former names former_names = list() # Building RegEx for former name sentence former_sentence_re = re.compile(r'(formerly:.+?\(filings through .+?\))') # Getting sentence matches former_sentences = former_sentence_re.findall(former_container.text) # Building RegEx for name and filings-through date extraction name_and_date_re = re.compile(r'formerly:(.*)\(.*(\d{4}-\d{2}-\d{2})') # Extracting former name and filings-through date for each sentence for sentence in former_sentences: matches = name_and_date_re.findall(sentence) former_name = dict() former_name['former_name'] = matches[0][0].strip() former_name['filings_through'] = matches[0][1] former_names += [former_name] return former_names def __getCompanyMetadata(parsed: BeautifulSoup) -> dict: """Function to extract company Standard Industrial Classification (SIC) code, SIC type (i.e. description), company location, state of incorporation, and the end of its fiscal year. Searches the raw HTML of the company identification section of the page using regular expressions. Arguments: parsed {BeautifulSoup} -- Parsed HTML from company EDGAR filing. Returns: dict -- Company metadata with keys `sic`, `sic_type`, `location`, `incorporation_state`, and `fiscal_year_end`. """ # Company metadata container metadata_container = parsed.find('p', class_='identInfo') # String representation of HTML (used in RegEx) metadata_str = str(metadata_container) # Dictionary for company metadata company_metadata = dict() # RegEx for extracting SIC and SIC type sic_re = re.compile(r'SIC.+?:.+?(\d+?)<\/a> -(.+?)<br') # Getting SIC and SIC type match sic_matches = sic_re.findall(metadata_str) # Saving SIC and stripped, HTML-parsed SIC type company_metadata['sic'] = sic_matches[0][0] company_metadata['sic_type'] = html.unescape(sic_matches[0][1]).strip() # RegEx for extracting company location (state) location_re = re.compile(r'State location:.+?>(\w+?)<\/a>') # Getting company location location_matches = location_re.findall(metadata_str) # Saving company location company_metadata['location'] = location_matches[0].strip() # RegEx for extracting state of incorporation incorp_state_re = re.compile(r'State of Inc\.:.+?>(\w+?)<\/strong>') # Getting state of incorporation incorp_match = incorp_state_re.findall(metadata_str)[0] # Saving state of incorporation company_metadata['incorporation_state'] = incorp_match.strip() # RegEx for extracting end of fiscal year fiscal_year_re = re.compile(r'Fiscal Year End:.+?(\d{4})') # Getting end of fiscal year fiscal_year_match = fiscal_year_re.findall(metadata_str)[0] # Saving end of fiscal year (in mm-dd format) fy_formatted = fiscal_year_match[0:2] + '-' + fiscal_year_match[2:] company_metadata['fiscal_year_end'] = fy_formatted return company_metadata
"""gör om ordet till en lista""" def word_to_list (k): letterno = 0 letter_list = [] while len(letter_list) != len(k): letter_list.append(k[letterno]) letterno = letterno + 1 return letter_list """kollar om bokstav finns med i ordet""" def check_letter(n, b): letterno = 0 while len(n) != letterno: if n[letterno] == b: return letterno else: letterno = letterno + 1 return False """Gr en lista med s mnga tecken som ordet har""" def disp_list (l): disp = [] while len(disp) != len(word): disp.append("_") return disp """hej = word_to_list(word) print hej guess_letter = raw_input("gissa ett ord: ") if check_letter(hej, guess_letter): print "rätt" else: print "fel" """ word = raw_input("Skriv ett ord: ") max_guesses = raw_input("Hur mnga gissningar: ") guesses = 0 list_word = word_to_list(word) display_word = disp_list(len(word)) print display_word while guesses != max_guesses: guess = raw_input("Gissa en bokstav: ") if type(check_letter(list_word, guess)) == int : print "rätt" display_word[check_letter(list_word, guess)] = guess print display_word else: print "fel" print display_word guesses = guesses + 1 print "Du frlorade" hej = raw_input("hej")
#!bin/usr/python class NumberConverter(object): def __init__(self): self.TRANSLATE = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred', 1000: 'thousand' } def __and__(self, s): if s != '': s += ' and ' return s def __space__(self, s): if s != '': s += ' ' return s def to_words(self, n): result = '' ones = n % 10 tens = (n % 100) - ones hundreds = (n % 1000) - tens - ones thousands = n - hundreds - tens - ones if thousands > 0: result += self.TRANSLATE[thousands / 1000] + ' ' \ + self.TRANSLATE[1000] if hundreds > 0: result = self.__space__(result) result += self.TRANSLATE[hundreds / 100] + ' ' \ + self.TRANSLATE[100] if tens == 10: result = self.__and__(result) result += self.TRANSLATE[tens + ones] elif tens > 10: result = self.__and__(result) result += self.TRANSLATE[tens] if tens != 10 and ones > 0: if tens == 0: result = self.__and__(result) else: result = self.__space__(result) result += self.TRANSLATE[ones] return result if __name__ == '__main__': n = 1 converter = NumberConverter() result = '' totalLength = 0 while n < 1001: words = converter.to_words(n) print words words = words.replace(' ', '').replace('-', '') totalLength += len(words) n += 1 result = result.replace(' ', '') print totalLength
from ticket_rule import TicketRule import math file = open("puzzle_input.txt", "r") lines = [line.rstrip('\n') for line in file] # PREPARATION rules = [] nearby_tickets = [] section = 0 for line in lines: if line == "your ticket:" or line == "nearby tickets:": section += 1 continue if line and section == 0: field, bounds = line.split(': ') bounds = bounds.split(' or ') rules.append(TicketRule(field, bounds)) if line and section == 1: your_ticket = [int(x) for x in line.split(',')] if line and section == 2: nearby_tickets.append([int(x) for x in line.split(',')]) # PART ONE def get_invalid_values(ticket): for value in ticket: if not any(rule.validate_value(value) for rule in rules): return value print(sum(get_invalid_values(ticket) for ticket in nearby_tickets if get_invalid_values(ticket) != None)) # PART TWO def get_valid_tickets(tickets): return [ticket for ticket in filter(lambda x: get_invalid_values(x) == None, tickets)] values_per_field = [] rules_index = {i: [] for i in range(len(rules))} for i in range(len(rules)): values_per_field.append([]) for ticket in get_valid_tickets(nearby_tickets): i = 0 for value in ticket: values_per_field[i].append(value) i += 1 i = 0 for value_list in values_per_field: value_list = sorted(set(value_list)) for rule in rules: if all(rule.validate_value(value) for value in value_list): rules_index[i].append(rule.field) i += 1 found_keys = [] while len(found_keys) < len(rules): for key, value in rules_index.items(): if len(rules_index[key]) == 1 and key not in found_keys: rules_index[key] = value[0] print(str(value) + " is " + str(key)) found_keys.append(key) for other_key in rules_index: if other_key != key and value[0] in rules_index[other_key]: rules_index[other_key].remove(value[0]) print(rules_index) break departure_indices = [] for key, value in rules_index.items(): if value[:9] == 'departure': departure_indices.append(key) #1,2,5,11,15,19 print(math.prod(your_ticket[i] for i in departure_indices))
# Java 面向对象编程的 # 设计模式 -----接口 # 接口类: python原生是不支持的 # 抽象类 python 原生支持的 from abc import abstractmethod,ABCMeta class Payment(metaclass=ABCMeta): @abstractmethod # class Payment(): def pay(self,money): raise NotImplemented #没有实现此方法 class Wechat(Payment): def pay(self,money): print ('微信支付%s' %money) class Alipay(Payment): def pay(self,money): print ('支付宝支付%s' %money) class applePay(Payment): def pay(self,money): print ('applepay支付%s' % money) #统一支付接口 def pay(pay_obj,money): pay_obj.pay(money) wechat = Wechat() alipay = Alipay() app = applePay() pay(wechat,100) pay(app,20)
# Hangman(행맨) 미니 게임 재작(1) # 기본 프로그램 제작 및 테스트 import time # csv 처리 import csv # 랜덤 import random # 사운드 처리 import winsound # 처음 인사 name = input("What is your name?") print("Hi, " + name, "Time to play hangman game!") print() time.sleep(0.5) print("Start Loading...") print() time.sleep(0.3) # CSV 단어 리스트 words = [] # 문제 CSV파일 로드 with open('./resource/word_list.csv', 'r') as f: reader = csv.reader(f) # Header Skip (정답,힌트) next(reader) for c in reader: words.append(c) # 리스트 섞기 random.shuffle(words) q = random.choice(words) # 정답 단어 word = q[0].strip() # strip공백제거 # 추측 단어 guesses = '' # 기회 turns = 10 # 핵심 While Loop # 찬스 카운터가 남아 있을 경우 while turns > 0: # 실패 횟수 (단어 매치 수) failed = 0 # print(guesses) # 정답 단어 반복 for char in word: # 정답 단어 내에 추축 문자가 포함되어 있는 경우 if char in guesses: # 추축 단어 출력 print(char, end=' ') else: # 틀린 경우 대시로 처리 print('_', end=' ') failed += 1 # 단어 추측이 성공 한 경우 if failed == 0: print() print() # 성공 사운드 winsound.PlaySound('./sound/good.wav', winsound.SND_FILENAME) print('Congratulation! The Guesses is correct.') # while 문 종료 break print() print() # 힌트 print('Hint : {}'.format(q[1].strip())) # 추측 단어 문자 단위 입력 guess = input("guess a charter.") # 단어 더하기 guesses += guess # 정답 단어에 추측한 문자가 포함되어 있지 않으면 if guess not in word: # 기회 횟수 감소 turns -= 1 # 오류 메세지 print("Oops! Wrong") # 남은 기회 출력 print("You have", turns, "more guesses!") if turns == 0: # 실패 사운드 winsound.PlaySound('./sound/bad.wav', winsound.SND_FILENAME) # 실패 메시지 print("You hangman game failed. Bye!")
# 제너레이터 # iterator객체의 한 종류 (next함수호출) # 만드는 방법 : 제너레이터 함수(function) 제너레이터 표현식(expression) def gen_num(): # 제너레이터 함수정의 print('first number') yield 1 # yield가 하나라도 들어가면 제너레이터가 됩니다. print('second number') yield 2 print('third number') yield 3 # 제너레이터 함수를 호출해도 실행하지 않고 제너레이터객체를 만들어 변수에 담는다. gen = gen_num() # next 함수를 호출하면 첫번째 yield를 만날때 까지 수행하고 멈춘다 print(next(gen)) # 첫번째 yield print(next(gen)) # 두번째 yield print(next(gen)) # 세번째 yield # print(next(gen)) # StopIteration 예외발생 # next 함수가 호출될 때까지 미루는 특성을 lazy evaluation def gen_for(): for i in [1, 2, 3]: yield i g = gen_for() print(next(g)) # 1 print(next(g)) # 2 print(next(g)) # 3 # print(next(g)) # StopIteration 예외발생 # 제너레이터가 갖는 장점 import sys def pows(s): r = [] for i in s: r.append(i ** 2) return r # 미리 st에 값을 미리 전부 만든다 (메모리 호율이 좋지 않다) st = pows(range(1, 1000)) # for i in st: # print(i, end=' ') # 1 4 9 16 25 36 49 64 81 print('getsizeof=', sys.getsizeof(st)) #getsizeof= 9016 def gpows(s): for i in s: yield i ** 2 # 필요할때 만든다 st = gpows(range(1, 1000)) # st는 iterator객체 이면서 iterable객체이므로 for문에 올수 있다 # for i in st: # print(i, end=' ') # 1 4 9 16 25 36 49 64 81 print('getsizeof=', sys.getsizeof(st)) #getsizeof= 112 # lazy evaluation는 필요 할 때 만드는 연산 # map 이나 filter도 제너레이터 함수 # yield from def get_nums(): ns = [0, 1, 0, 1, 0, 1] for i in ns: yield i g = get_nums() print(next(g)) print(next(g)) def get_nums_from(): ns = [0, 1, 0, 1, 0, 1] yield from ns g = get_nums_from() print(next(g)) print(next(g))
import sqlite3 #On cree une connection a la bd et on cree la table si besoin def init(): # Create db if not exist con = sqlite3.connect('hl.db') cur = con.cursor() # Profile table cur.execute("""CREATE TABLE IF NOT EXISTS profile (id integer primary key, name text) """) con.commit()
def common_letter(): str1 = input('enter a string:') str2 = input('enter a string:') s1 = set(str1) s2 = set(str2) lst = s1 & s2 print(lst) common_letter()
from board import Board from player import Player class Game: def __init__(self): self.board = Board(7,6) self.players = [] self.turn = 0 def play_game(self): self.players.append(Player('x')) self.players.append(Player('o')) while True: self.board.disp_board() choice = self.players[self.turn].get_choice(self.board) self.board.add_piece(choice) if self.board.check_win(): print(f"{self.players[self.turn]} wins!") return if self.board.is_full(): self.board.empty_board() return self.turn = (self.turn + 1)% 2 def main(): print("Welcome to Connect 4!") game = Game() while True: game.play_game() if input("Play again?(y)es or (n)o.\n> ") == 'y': return True if input("Play again?(y)es or (n)o.\n> ") == 'n': return False print("Thanks for playing!") if __name__ == "__main__": # test code main()
# To-do # write a piece that throws water master out of the kingdom if he tries to input a negative number # if there is a drought make sure that the first line has a bit that reads in the farmers who rand out of water # add a "run the mode" option! import random import cs50 def print_introductory_message(): print(' __ __ _ __ __ _ ') print(' \ \ / / | | | \/ | | | ') print(' \ \ /\ / /_ _| |_ ___ _ __ | \ / | __ _ ___| |_ ___ _ __ ') print(' \ \/ \/ / _` | __/ _ \ \'__| | |\/| |/ _` / __| __/ _ \ \'__|') print(' \ /\ / (_| | || __/ | | | | | (_| \__ \ || __/ | ') print(' \/ \/ \__,_|\__\___|_| |_| |_|\__,_|___/\__\___|_| ') print(' ') print(' A Game by Spencer Harris ') print(' [email protected] ') print('''\n\nCongratulations, you are the newest water master of San Juanito County, California. You have been elected for a ten year term of office. Your duties are to dispense water, direct farming, and buy and sell land as needed to support your citizens. Watch our for environmental requirements and drought! Water is the general currency, measured in Acre-feet (AC-FT). The following will help you in your decisions:\n * Each citizen needs at least 0.2 AC-FT of water per year to survive\n * Each citizen can farm at most 2 acres of land\n * It takes 2 AC-FT of water to farm an acre of land\n * The market price for land fluctuates yearly\n Rule wisely and you will be showered with appreciation at the end of your term. Rule poorly and you will be thrown out of office!\n''') def ask_to_buy_land(ACFT_in_storage, cost_per_acre): 'Ask user how many ACFT to spend buying land.' acres = cs50.get_int('How many acres will you buy? ') while acres * cost_per_acre > ACFT_in_storage: print ('Hey Water Master, we have but ', ACFT_in_storage,' ACFT of water!') acres = cs50.get_int('How many acres will you buy? ') return acres def ask_to_sell_land(acres_owned, acres, ACFT_in_storage, cost_per_acre): 'Ask user how many acres of land to spend buying water, do not ask if buying land' if acres > 0: print('') acres_to_sell = 0 return acres_to_sell else: acres_to_sell = cs50.get_int('How many acres will you sell? ') while acres_to_sell > acres_owned: print('Hey Water Master, we have but ', acres_owned,'acres of land!') acres_to_sell = cs50.get_int('How many ACFT will you buy? ') return acres_to_sell def ask_to_water_stakeholders(ACFT_in_storage): 'Ask user how many ACFT of water to spend on feeding the stakeholders of the county' ACFT_to_water = cs50.get_int('How many ACFT do you wish to feed your stakeholders? ') while ACFT_in_storage < ACFT_to_water: print('Hey Water Master, we have but', ACFT_in_storage, 'ACFT of water!') ACFT_to_water = cs50.get_int('How many ACFT do you wish to feed your stakeholders? ') return ACFT_to_water def ask_to_water_acres(ACFT_in_storage, acres_owned, population): 'Ask user how many acres of land to water with ACFT of water' acres_to_water = cs50.get_int('How many acres do you wish to water with water? ') while acres_owned < acres_to_water: print('Hey Water Master, we have but ',acres_owned,'acres of land!') acres_to_water = cs50.get_int('How many acres do you wish to water with water? ') while acres_to_water * 2 > ACFT_in_storage: print('Hey Water Master, we have but ',ACFT_in_storage,'ACFT of water!') acres_to_water = cs50.get_int('How many acres do you wish to water with water ? ') while acres_to_water > (population * 10): print('Hey Water Master, we have but ',population,'farmers with which to water acres!') acres_to_water = cs50.get_int('How many acres do you wish to water with water ? ') return acres_to_water #no input functions def drought(): 'generate the chances of there being a drought and then return the number of dead ppl' drought = 'yay' chance_of_drought = (random.randint(1,100)) if chance_of_drought > 90: drought = 'OH_GOD' return drought else: return drought def parched_pop(ACFT_to_water, population): 'lets see how many stakeholders hammurabi parched this year' ACFT_needed = population * 2 if ACFT_to_water >= ACFT_needed: parched = 0 return parched elif ACFT_to_water < ACFT_needed: parched = ((ACFT_needed - ACFT_to_water) / 2) return parched def immigration(ACFT_in_storage, ACFT_to_water, acres_owned, population): 'calculate how many stakeholders immigrated to the county' ACFT_needed = population * 2 if ACFT_to_water >= ACFT_needed: immigrants = ((ACFT_in_storage + (2 * acres_owned))/(100 * population))+1 return immigrants else: immigrants = 0 return immigrants def annual_allocation_1(acres_to_water): 'calculate how many ACFT were annual_allocated in the previous year' yield_1 = acres_to_water * (random.randint(1,8)) return yield_1 def environmentalists(): 'determine how bad, if at all your environmental flows will be' env_chance = (random.randint(1,5)) if env_chance >= 4: environmental_thirst = (random.randint(1,3)) environmental_thirst = environmental_thirst / 10 if env_chance == 4: environmental_actor = '''Looks like the Salmon run this year is going to need some extra flow, we need help them out by giving up some of our storage!''' if env_chance == 5: environmental_actor = '''Groundwater levels have been reach below the mandated level, we need to inject some of our storage to get the levels back into compliance!''' return environmental_thirst, environmental_actor, env_chance else: environmental_thirst = 0 environmental_actor = 'no-one' return environmental_thirst, environmental_actor, env_chance #def environmental_actor(environmental_thirst): def cost_of_land(): cost_per_acre = (random.randint(17,23)) return cost_per_acre # game start) years = [1,2,3,4,5,6,7,8,9,10] def hammurabi(): parched = 0 immigrants = 5 population = 100 annual_allocation = 3000 # total water recieved from statewater project ACFT_per_acre = 3 # amount of water secured for each acre watered environmental_flow = 200 # ACFT taken by environmental flows ACFT_in_storage = 2800 acres_owned = 1000 cost_per_acre = 19 # each acre costs this many ACFT drought_closures = 0 env_chance = 0 print_introductory_message() for year in years: print('Howdy Water Master!\n\n In year ',year,' of your ten year term ',parched, ' citizens ran out of water and left.', immigrants,' citizens entered the county.\n') print('The county now has ',population,' citizens.') print('We secured',annual_allocation,' AC-FT from the aquaduct at ',ACFT_per_acre,' AC-FT per acre.') if env_chance == 4: print(' ><(((\'> ') print(' ><(((\'> ><(((\'>') print(' ><(((\'> ><(((\'>') print(' ><(((\'> ><(((\'>') print(' ><(((\'> ><(((\'>') print(' ><(((\'> ><(((\'>') print(environmental_actor) print(' ><(((\'> ><(((\'>') print('><(((\'> ><(((\'>\n') if env_chance == 5: print(' .-.') print(' | \\') print(' | /\\') print(' ,___| | \\') print(' / ___( ) L') print(' \'-` | | |') print(' | | F') print(' | | /') print(' | |') print(' | |') print(' ____|_|____') print(' [___________]') print(',,,,,/,,,,,,,,,,,,\,,,,,,,,,,,,,') print(environmental_actor) print(' | | ') print(' | | ') print(' | | ') print(' | | ') print('_ | | _ ') print(' \ | | / ') print(' \ | | /') print(' \ | | /') print(' \ | | / ') print(' \ | | / ') print(' \ |___| / ') print(' \_________/ ') print(' ') print('Environmentalists took', environmental_flow,'AC-FT, leaving ', ACFT_in_storage, ' AC-FT in storage.') print('The county owns ', acres_owned,' acres of land.') print('Land is currently trading at ', cost_per_acre,' AC-FT per acre.') print('\n\n') acres = ask_to_buy_land(ACFT_in_storage, cost_per_acre) print('\n\n') ACFT_sold = acres * cost_per_acre ACFT_in_storage = ACFT_in_storage - ACFT_sold acres_owned = acres_owned + acres acres_to_sell = ask_to_sell_land(acres_owned, acres, ACFT_in_storage, cost_per_acre) print('\n\n') ACFT_in_storage = ACFT_in_storage + (acres_to_sell * cost_per_acre) acres_owned = acres_owned - acres_to_sell ACFT_to_water = ask_to_water_stakeholders(ACFT_in_storage) print('\n\n') ACFT_in_storage = ACFT_in_storage - ACFT_to_water acres_to_water = ask_to_water_acres(ACFT_in_storage, acres_owned, population) print('\n\n') result1 = drought() if result1 == 'OH_GOD': population = int(round(population / 2)) # R.I.P. print(' ') print('THERE WAS A DROUGHT!') print(' ') print(' ') print(' vv vv /') print(' ||____M__||/') print(' || || ') print(' /\||_______|| ') print(' (XX) ') print(' (--) ') print(' ') parched = parched_pop(ACFT_to_water, population) if parched > population * 0.45: print('You\'ve parched too many of your citizens!') break population = population - parched immigrants = int(round(immigration(ACFT_in_storage, ACFT_to_water, acres_owned, population))) population = population + immigrants print('\n\n') environmental_thirst, environmental_actor, env_chance = environmentalists() environmental_flow = ACFT_in_storage * environmental_thirst ACFT_in_storage = ACFT_in_storage - (ACFT_in_storage * environmental_thirst) annual_allocation = annual_allocation_1(acres_to_water) ACFT_per_acre = annual_allocation / acres_to_water ACFT_in_storage = ACFT_in_storage + annual_allocation - (acres_to_water * 2) cost_per_acre = cost_of_land() return population , acres_owned # print('your final population is: %s and your final acres_owned is: %s' % (population, acres_owned)) population, acres_owned = hammurabi() def assessment(population, acres_owned): '''Assesses the water master on his job, points based ranking for acres and population''' if 0 < population < 50: ranking = -1 return ranking if 50 < population < 100: ranking = 0 return ranking if 100 < population < 120: ranking = 1 return ranking if 120 < population < 140: ranking = 2 return ranking if 140 < population: ranking = 3 return ranking if 0 < acres_owned < 500: Aranking = -1 return Aranking if 500 < acres_owned < 1000: Aranking = 0 return Aranking if 1000 < acres_owned < 1200: Aranking = 1 return Aranking if 1200 < acres_owned < 1400: Aranking = 2 return Aranking if 1400 < acres_owned: Aranking = 3 return Aranking total = ranking + Aranking return total
#(1) #Raising Exceptions #raise Exception('This is the error message.') #(2) #def boxPrint(symbol, width, height): # if len(symbol) != 1: # raise Exception('Symbol must be a single character string.') # if width <= 2: # raise Exception('Width must be greater than 2.') # if height <= 2: # raise Exception('Height must be greater than 2.') # print(symbol * width) # for i in range(height - 2): # print(symbol + (' ' * (width - 2)) + symbol) # print(symbol * width) #for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)): # try: # boxPrint(sym, w, h) # except Exception as err: # print('An exception happened: ' + str(err)) #(3) #Getting the Traceback as a String #def spam(): # bacon() #def bacon(): # raise Exception('This is the error message.') #spam() #(4) #import traceback #try: # raise Exception('This is the error message.') #except: # errorFile = open('errorInfo.txt', 'w') # Nc=errorFile.write(traceback.format_exc()) # errorFile.close() # print('The traceback info was written to errorInfo.txt.') #(5) #Assertions #ages = [26, 57, 92, 54, 22, 15, 17, 80, 47, 73] #ages.sort() #print(ages) #assert ages[0] <= ages[-1] # Assert that the first age is <= the last age #ages.reverse() #print(ages) #assert ages[0] <= ages[-1] # Assert that the first age is <= the last age. #Note:If you run a Python script with python -O myscript.py instead of python myscript.py, Python will skip assert statements. #(6) #Using an Assertion in a Traffic Light Simulation #market_2nd = {'ns': 'green', 'ew': 'red'} #mission_16th = {'ns': 'red', 'ew': 'green'} #def switchLights(stoplight): # for key in stoplight.keys(): # if stoplight[key] == 'green': # stoplight[key] = 'yellow' # elif stoplight[key] == 'yellow': # stoplight[key] = 'red' # elif stoplight[key] == 'red': # stoplight[key] = 'green' #switchLights(market_2nd) #print(market_2nd) #With assertion #market_2nd = {'ns': 'green', 'ew': 'red'} #mission_16th = {'ns': 'red', 'ew': 'green'} #def switchLights(stoplight): # for key in stoplight.keys(): # if stoplight[key] == 'green': # stoplight[key] = 'yellow' # elif stoplight[key] == 'yellow': # stoplight[key] = 'red' # elif stoplight[key] == 'red': # stoplight[key] = 'green' # assert 'red' in stoplight.values(), 'Neither light is red! ' + str(stoplight) #switchLights(market_2nd) #print(market_2nd) #(7) #Logging #Using the logging Module #import logging #logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s- %(message)s') #logging.debug('Start of program') #def factorial(n): # logging.debug('Start of factorial(%s%%)' % (n)) # total = 1 # for i in range(n + 1): # total *= i # logging.debug('i is ' + str(i) + ', total is ' + str(total)) # logging.debug('End of factorial(%s%%)' % (n)) # return total #print(factorial(5)) #logging.debug('End of program') #(8) #Logging Levels #import logging #logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s -%(levelname)s - %(message)s') #logging.debug('Some debugging details.') #logging.info('The logging module is working.') #logging.warning('An error message is about to be logged.') #logging.error('An error has occurred.') #logging.critical('The program is unable to recover!') #(9) #Disabling Logging #import logging #logging.basicConfig(level=logging.INFO, format=' %(asctime)s -%(levelname)s - %(message)s') #logging.critical('Critical error! Critical error!') #logging.disable(logging.CRITICAL) #logging.critical('Critical error! Critical error!') #logging.error('Error! Error!') #(10) #Logging to a File #import logging #logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') #logging.debug('Start of program') #def factorial(n): # logging.debug('Start of factorial(%s%%)' % (n)) # total = 1 # for i in range(n + 1): # total *= i # logging.debug('i is ' + str(i) + ', total is ' + str(total)) # logging.debug('End of factorial(%s%%)' % (n)) # return total #print(factorial(5)) #logging.debug('End of program') #(11) #Mu’s Debugger #Debugging a Number Adding Program #print('Enter the first number to add:') #first = input() #print('Enter the second number to add:') #second = input() #print('Enter the third number to add:') #third = input() #print('The sum is ' + first + second + third) #(12) # #import random #heads = 0 #for i in range(1, 1001): # if random.randint(0, 1) == 1: # heads = heads + 1 # if i == 500: # print('Halfway done!') #print('Heads came up ' + str(heads) + ' times.')
#(1) #printing list contents #def printspamlist(list): # for i in range (0,4,1): # print(list[i]) #spam = ['cat', 'bat', 'rat', 'elephant'] #printspamlist(spam) #print(spam[0:2]) #print(spam[0:-1]) #print(spam[:2]) #print(spam[1:]) #print(spam[:]) #print(len(spam)) #spam[1] = 'aardvark' #print(spam[1]) #spam[2] = spam[1] #printspamlist(spam) #spam[-1] = 12345 #printspamlist(spam) #(2) #list of lists #spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] #print(spam[0]) #print(spam[-1]) #print(spam[-2]) #print(spam[1]) #print(spam[0][1]) #print(spam[1][1]) #(3) #list concatenation and replication #print([1, 2, 3] + ['A', 'B', 'C']) #print(['X', 'Y', 'Z'] * 3) #spam = [1, 2, 3] #spam = spam + ['A', 'B', 'C'] #print(spam) #spam = ['cat', 'bat', 'rat', 'elephant'] #del spam[2] #del can also be used to delete variables #print(spam) #(4) #a single list and can store any number of cats that the user types in #catNames = [] #while True: # print('Enter the name of cat ' + str(len(catNames) + 1) + # ' (Or enter nothing to stop.):') # name = input() # if name == '': # break # catNames = catNames + [name] # list concatenation #print('The cat names are:') #for name in catNames: # print(' ' + name) #(5) #printing sequence in alist #for i in [1,2,3,4]: # print(i) #(6) #supplies = ['pens', 'staplers', 'flamethrowers', 'binders'] #for i in range(len(supplies)): # print('Index ' + str(i) + ' in supplies is: ' + supplies[i]) #(7) #You can determine whether a value is or isn’t in a list with the in and not in operators #print('howdy' in ['hello', 'hi', 'howdy', 'heyas']) #spam = ['hello', 'hi', 'howdy', 'heyas'] #print('howdy' not in spam) #(8) #myPets = ['Zophie', 'Pooka', 'Fat-tail'] #print('Enter a pet name:') #name = input() #if name not in myPets: # print('I do not have a pet named ' + name) #else: # print(name + ' is my pet.') #(9) #The Multiple Assignment Trick #The number of variables and the length of the list must be exactly equal, #or Python will give you a ValueError #cat = ['fat', 'gray', 'loud'] #size, color, disposition = cat #print(size) #print(color) #print(disposition) #(10) #Using the enumerate() Function with Lists #supplies = ['pens', 'staplers', 'flamethrowers', 'binders'] #for index, item in enumerate(supplies): # print('Index ' + str(index) + ' in supplies is: ' + item) #(11) #Using the random.choice() and random.shuffle() Functions with Lists #import random #pets = ['Dog', 'Cat', 'Moose'] ##print(random.choice(pets)) ##The random.shuffle() function will reorder the items in a list. #people=['Alice', 'Bob', 'Carol', 'David'] #random.shuffle(people) #print(people) #(12) #spam = 'Hello,' #spam += ' world!' #print(spam) #bacon = ['Zophie'] #bacon *= 3 #print(bacon) #(13) #Methods #Finding a Value in a List with the index() Method #spam = ['hello', 'hi', 'howdy', 'heyas'] #print(spam.index('hello')) #When there are duplicates of the value in the list, the index of its first appearance is returned #spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka'] #print(spam.index('Pooka')) #Adding Values to Lists with the append() and insert() Methods #spam = ['cat', 'dog', 'bat'] #append() method call adds the argument to the end of the list #spam.append('moose') #print(spam) #The insert() method can insert a value at any index in the list. #The first argument to insert() is the index for the new value, #and the second argument is the new value to be inserted #spam.insert(1, 'chicken') #print(spam) #Removing Values from Lists with the remove() Method #If the value appears multiple times in the list, #only the first instance of the value will be removed #spam = ['cat', 'bat', 'rat', 'elephant'] #spam.remove('bat') #=del spam[1] #print(spam) #Sorting the Values in a List with the sort() Method #spam = [2, 5, 3.14, 1, -7] #spam.sort() #print(spam) #spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants'] #spam.sort() #print(spam) #You can also pass True for the reverse keyword argument #to have sort() sort the values in reverse order #spam.sort(reverse=True) #print(spam) #sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting strings. #This means uppercase letters come before lowercase letters #spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats'] #spam.sort() #print(spam) #If you need to sort the values in regular alphabetical order, #pass str.lower for the key keyword argument in the sort() method call #spam.sort(key=str.lower) #print(spam) #Reversing the Values in a List with the reverse() Method #spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats'] #spam.reverse() #print(spam) #(14) #import random #messages = ['It is certain', # 'It is decidedly so', # 'Yes definitely', # 'Reply hazy try again', # 'Ask again later', # 'Concentrate and ask again', # 'My reply is no', # 'Outlook not so good', # 'Very doubtful'] #print(messages[random.randint(0, len(messages) - 1)]) #(15) #SEQUENCE DATA TYPES(data types similar to lists) #name = 'Zophie' #print('Zo' in name) #print('z' in name) #print('p' not in name) #for i in name: # print('* * * ' + i + ' * * *') #(16) #The Tuple Data Type(immutable form of the list data type) #you can indicate this by placing a trailing comma #after the value inside the parentheses. #Otherwise, Python will think you’ve just typed a value inside regular parentheses. #The comma is what lets Python know this is a tuple value #print(type(('hello',))) #print(type(('hello'))) #(17) #Type conversion #print(tuple(['cat', 'dog', 5])) #print(list(('cat', 'dog', 5))) #print(list('hello')) #(18) #Referencing #spam = [0, 1, 2, 3, 4, 5] #cheese = spam # The reference is being copied, not the list. #cheese[1] = 'Hello!' # This changes the list value. #print(spam) #print(cheese) # The cheese variable refers to the same list. #Identity and the id() Function #print(id('Howdy') ) #address stored at #eggs = ['cat', 'dog'] #print(id(eggs)) #eggs.append('moose') #print(id(eggs)) #eggs.insert(0,'egg') #print(id(eggs)) #(19) #The copy Module’s copy() and deepcopy() Functions #import copy #spam = ['A', 'B', 'C', 'D'] #print(id(spam)) #cheese = copy.copy(spam) #print(id(cheese)) # cheese is a different list with different identity. #cheese[1] = 42 #print(spam) #print(cheese) #If the list you need to copy contains lists, #then use the copy.deepcopy() function instead of copy.copy(). #(20) # Conway's Game of Life #import random, time, copy #WIDTH = 60 #HEIGHT = 20 # ## Create a list of list for the cells: #nextCells = [] #for x in range(WIDTH): # column = [] # Create a new column. # for y in range(HEIGHT): # if random.randint(0, 1) == 0: # column.append('#') # Add a living cell. # else: # column.append(' ') # Add a dead cell. # nextCells.append(column) # nextCells is a list of column lists. # #while True: # Main program loop. # print('\n\n\n\n\n') # Separate each step with newlines. # currentCells = copy.deepcopy(nextCells) # # # Print currentCells on the screen: # for y in range(HEIGHT): # for x in range(WIDTH): # print(currentCells[x][y], end='') # Print the # or space. # print() # Print a newline at the end of the row. # # # Calculate the next step's cells based on current step's cells: # for x in range(WIDTH): # for y in range(HEIGHT): # # Get neighboring coordinates: # # `% WIDTH` ensures leftCoord is always between 0 and WIDTH - 1 # leftCoord = (x - 1) % WIDTH # rightCoord = (x + 1) % WIDTH # aboveCoord = (y - 1) % HEIGHT # belowCoord = (y + 1) % HEIGHT # # # Count number of living neighbors: # numNeighbors = 0 # if currentCells[leftCoord][aboveCoord] == '#': # numNeighbors += 1 # Top-left neighbor is alive. # if currentCells[x][aboveCoord] == '#': # numNeighbors += 1 # Top neighbor is alive. # if currentCells[rightCoord][aboveCoord] == '#': # numNeighbors += 1 # Top-right neighbor is alive. # if currentCells[leftCoord][y] == '#': # numNeighbors += 1 # Left neighbor is alive. # if currentCells[rightCoord][y] == '#': # numNeighbors += 1 # Right neighbor is alive. # if currentCells[leftCoord][belowCoord] == '#': # numNeighbors += 1 # Bottom-left neighbor is alive. # if currentCells[x][belowCoord] == '#': # numNeighbors += 1 # Bottom neighbor is alive. # if currentCells[rightCoord][belowCoord] == '#': # numNeighbors += 1 # Bottom-right neighbor is alive. # # # Set cell based on Conway's Game of Life rules: # if currentCells[x][y] == '#' and (numNeighbors == 2 or #numNeighbors == 3): # # Living cells with 2 or 3 neighbors stay alive: # nextCells[x][y] = '#' # elif currentCells[x][y] == ' ' and numNeighbors == 3: # # Dead cells with 3 neighbors become alive: # nextCells[x][y] = '#' # else: # # Everything else dies or stays dead: # nextCells[x][y] = ' ' # time.sleep(1) # Add a 1-second pause to reduce flickering
n = int(input()) field = [] for i in range(n): row = [] for j in range(n): row.append(int(input())) field.append(row) k = int(input()) for i in range(k): x = int(input()) y = int(input()) field[y][x] -= 4 for j in range(n): for m in range(n): if (y - 1 <= j <= y + 1) and (x - 1 <= m <= x + 1): field[j][m] -= 4 if field[j][m] < 0: field[j][m] = 0 for row in field: for bacteria in row: print(bacteria, end=" ") print()
line = input().lower() max_entries = 0 count = 0 for char in line: for character in line: if character == char: count += 1 if count > max_entries: max_entries = count count = 0 print(max_entries)
N = int(input()) numbers = [] for i in range(N): numbers.append(int(input())) # Для сортировки воспользуемся алгоритмом Шелла last_index = len(numbers) - 1 step = len(numbers) // 2 while step > 0: for i in range(step, last_index + 1, 1): j = i delta = j - step while delta >= 0 and numbers[delta] < numbers[j]: numbers[delta], numbers[j] = numbers[j], numbers[delta] j = delta delta = j - step step //= 2 for number in numbers: print(number)
M = int(input()) lessons = [] for i in range(M): present_number = int(input()) students_present = [] for j in range(present_number): students_present.append(input()) lessons.append(students_present) for student in lessons[0]: is_always_present = True for i in range(1, len(lessons)): is_always_present *= lessons[i].__contains__(student) if is_always_present: print(student)
try : hour = float(input('Enter Hours:')) rate = float(input('Enter Rate:')) except : print('Error, please enter numeric input') quit() pay = None if hour <= 40 : pay = hour * rate else : pay = 40 * rate + (hour - 40) * 1.5 * rate print('Pay:',pay)
hour = float(input('Enter Hours:')) rate = float(input('Enter Rate:')) pay = None if hour <= 40 : pay = hour * rate else : pay = 40 * rate + (hour - 40) * 1.5 * rate print('Pay:',pay)
string1 = "he's " string2 = "probably " string3 = "pinning " string4 = "for the " string5 = "fjords" print(string1 + string2 +string3 + string4 + string5) print("he's ""probably ""pinning ""for the ""fjords") print("Hello " * 5) today = "saturday" print("day" in today) #True; in operates a lot like the .includes() from java
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Module summary Attempts to detect if a password(s) passed meets requirements according to the The National Institute of Standards and Technology """ #import import re #used to replace non ascii import sys #used to read from stdin import argparse #create a help automagically import time start = time.time() def is_ascii(pwd_string): '''Takes in a string. Checks if ASCII or not. Returns true or false. ''' return all(ord(char) < 128 for char in pwd_string) def remove_non_ascii(pwd_string): '''Takes a string and attempts to replace all non-ASCII with asterisk.''' return re.sub(r'[^\x00-\x7F]','*', pwd_string) def main(): for input in sys.stdin: input = input.strip() input_len = len(input) MIN_INPUT = 8 MAX_INPUT = 64 # 1. Have an 8 character minimum and if (input_len < MIN_INPUT): print("{} -> Error: Too Short".format(input)) # 2. AT LEAST 64 character maximum elif (input_len > MAX_INPUT): print("{} -> Error: Too Long".format(input)) else: # 3. Allow all ASCII characters and spaces (unicode optional) is_ascii_result = is_ascii(input) if is_ascii_result == False: removed=remove_non_ascii(input) print("{} -> Error: Invalid Charaters".format(removed)) else: #4. Not be a common password try: common_pass_set = set(line.strip() for line in open(args.Path)) if (input in common_pass_set): print("{} -> Error: Too Common".format(input)) except IOError: print("Passed File is not accessible") end = time.time() print(end - start) if __name__ == "__main__": parser = argparse.ArgumentParser(description = 'Detect if a password meets requirements') parser.add_argument('Path',metavar='Filepath', help='File path to list') args = parser.parse_args() main()
import urllib.request def download_file(download_url, filename): response = urllib.request.urlopen(download_url) file = open("Downloads/" + filename + ".pdf", 'wb') file.write(response.read()) file.close() if __name__ == "__main__": url = "https://en.unesco.org/inclusivepolicylab/sites/default/files/dummy-pdf_2.pdf" download_file(url, "Test")
import numpy as np from datetime import date ''' module for general purpose utility functions ''' def string_to_value_or_nan(string_value, type): ''' convert string value to a value of type type which can be int, float or date if string cannot be converted the value will be a np.NaN Date format is a string with following format: YYYYMMDD (for example 20181118) :input: string_value - string to be converted :input: type ['int', 'float', 'date'] :output: value of type type ''' try: value = str(string_value) if type == 'date': value = date(int(value[0:4]), int(value[4:6]), int(value[6:8])) elif type == 'int': value = int(value) elif type == 'float': value = float(value) else: assert False, 'invalid input, must be either int, float or date' except ValueError: value = np.NaN return value def average_with_outlier_removed(input_list, allowed_range): ''' calculates average of elements in a list with values within an allowed range. One outlier (i.e. an element with a value that exceeds the allowed range) will be removed. If there is a choice between valid ranges then choose the one with smallest range. If there are no allowed ranges then the funcion returns None Parameter: :input_list: list with values to be averaged :allowed_range: range that is allowed for values to deviate Return: :average: average value of list or None if there are more than one value exceeding the allowed_range ''' input_list.sort() elements = len(input_list) #check if input_list is not empty to avoid index errors if elements == 0: return None # if there is only one element then return this value elif elements == 1: return input_list[0] # if there are 2 elements they must be within allowed_range elif elements == 2: if abs(input_list[1] - input_list[0]) < allowed_range: return sum(input_list)/ 2 else: return None # if all elements are within the allowed_range calculate average elif abs(input_list[-1] - input_list[0]) < allowed_range: return sum(input_list)/ elements # if there is a choice between the two ranges choose the smallest elif abs(input_list[0] - input_list[-2]) < abs(input_list[1] - input_list[-1]): if abs(input_list[0] - input_list[-2]) < allowed_range: return sum(input_list[0:-1])/(elements - 1) else: return None else: if abs(input_list[1] - input_list[-1]) < allowed_range: return sum(input_list[1:])/ (elements - 1) else: return None
from tkinter import * from tkinter import ttk # Tkinter using oriented-object desing class HelloApp: # Constroctor method # single parameter is master, which is the main window def __init__(self, master): self.master = master self.label = ttk.Label(master, text="Hello Tkinter!") self.label.grid(row=0, column=0, columnspan=2) ttk.Button(master, text= "Texas",command = self.texas_hello).grid(row=1, column=0) ttk.Button(master, text= "Hawaii",command = self.hawaii_hello).grid(row=1, column=1) def texas_hello(self): self.label.config(text="Howdy, Tkinter!") def hawaii_hello(self): self.label.config(text="Aloha, Tkinter!") root = Tk() app = HelloApp(root) root.mainloop()
print('Hello...') L= [10,20,30,40,50,60] try: x = int(input('enter the first number')) y = int(input('enter the second number')) s = int(10) s = 10 + 'abc' # import sheetal q = x/y print(q) print(L[1]) except ValueError: print('I got value error') y = int(input('enter the second number')) except ZeroDivisionError: print('I got ZeroDivisionError') except IndexError: print("I got index error") except TypeError: print("I got Type error exception") except Exception: print("I got exception") else: print("i got no exception") finally: print('I do always') print("end of app")
# !/usr/bin/env python3 """Foobar.py: Description of what foobar does. __author__ = "Fu Linke" __pkuid__ = "1800011782 __email__ = "[email protected] """ #定义一个铺砖函数,a,b分别为地面的长和宽,m,n分别为砖的长和宽 #由于m=n且能铺满时,铺法显然只有一种,本函数不予考虑,定义m!=n #method代表铺法,alternative是代表地砖坐标的中间体 #ans是储存所有铺法的列表,gd是墙面/地板 def ocp(a, b, m, n, gd, method, ans, alternative): if a*b%(m*n)!=0: print ("no way, bro") else: count = 0 h = 0 for w in range(a*b): if gd[w] == 0 and h == 0: startrow = w//a + 1 startcol = w%a + 1 #找到第一个未被铺砖的位置,确定其坐标 h = 1 #判断起始到横着铺的区域在没有超出地面的情况下是否全部空白 if (startcol + m) <= (a + 1) and (startrow + n)<=(b + 1): for i in range(startrow, startrow + n) : for j in range(startcol,startcol + m): if gd[(i-1)*a + j - 1] == 0: #此处以及以下的所有‘(i-1)*a + j - 1’均表示第i行,第j列所对应的列表中的一维坐标 count +=1 alternative = [] if count == m*n:#如果全部空白,就可以横着铺 for i in range(startrow, startrow + n): for j in range(startcol,startcol + m): gd[(i-1)*a + j - 1] = 1 #改变砖的状态为1,表示已经铺上 alternative.append((i-1)*a + j - 1) method.append(alternative)#将一块砖的坐标加入method if 0 not in gd: ans.append(method.copy()) else: ocp(a, b, m, n, gd, method, ans, alternative) #拆转 for i in range(startrow, startrow + n): for j in range(startcol,startcol + m): gd[(i-1)*a + j - 1] = 0 del method[-1]#删除砖的坐标 count = 0 #现在开始竖着铺,一切基本同上 alternative = [] if startcol + n <= a+1 and startrow + m <= b+1: for i in range(startrow, startrow + m): for j in range(startcol,startcol + n): if gd[(i-1)*a + j - 1] == 0: count+=1 if count == m*n: for i in range(startrow, startrow + m): for j in range(startcol,startcol + n): gd[(i-1)*a + j - 1] = 1 alternative.append((i-1)*a + j - 1) method.append(alternative) if 0 not in gd: ans.append(method.copy()) else: ocp(a, b, m, n, gd, method, ans, alternative) for i in range(startrow, startrow + m): for j in range(startcol,startcol + n): gd[(i-1)*a + j - 1] = 0 del method[-1] return ans #定义可视化的函数 def draw(a,b,m,n,method): import turtle p = turtle.Pen() p.speed(0) p.pencolor('blue') #画墙面 p.pensize(0.5) p.penup() p.goto(-15*a, -15*b) p.pendown() for i in range(b): #画横线 for j in range(a):#标坐标 p.forward(10) p.write(i*a + j) p.forward(20) p.penup() p.goto(-15*a, -15*b + 30*(i+1)) p.pendown() p.penup()#此处是画出不用标坐标的那一条横线 p.goto(-15*a, -15*b+30*(b)) p.pendown() p.forward(30*a) p.left(90) p.penup() for i in range(a+1):#画竖线 p.goto(-15*a + 30*i, -15*b) p.pendown() p.forward(30*b) p.penup() p.pencolor('black')#画地砖 p.pensize(3) for alternative in method: if alternative[-1] - alternative[0] == m-1 + (n-1)*a: #判断为横着铺的砖 p.goto(-15*a + 30*(alternative[0]%a), -15*b + 30*(alternative[0]//a)) p.pendown() p.forward(30*n) p.right(90) p.forward(30*m) p.right(90) p.forward(30*n) p.right(90) p.forward(30*m) p.right(90) p.penup() else:#竖着来 p.goto(-15*a + 30*(alternative[0]%a), -15*b + 30*(alternative[0]//a)) p.pendown() p.forward(30*m) p.right(90) p.forward(30*n) p.right(90) p.forward(30*m) p.right(90) p.forward(30*n) p.right(90) p.penup() p.hideturtle() turtle.done() def main(): print('显然地砖长宽相等时只有一种铺法,请输入长宽不等的地砖') a = int(input('地板的长度')) b = int(input('地板的宽度')) m = int(input('地砖的长度')) n = int(input('地砖的宽度')) gd = [0]*a*b #构建地面 ans = [] ocp(a, b, m, n, gd, [], ans, []) for i in range(len(ans)): print('第%d种'%(i+1), ans[i]) print('\n') print('共有%d种铺法'%len(ans)) choice = int(input('您选择的方案号:')) draw(a, b, m, n, ans[choice-1]) if __name__ == '__main__': main()
import numpy as np def dice_dist(n, d, p=False): ''' returns a dictionary containing the probability distribution for a given dice combination, assuming fair dice n = number of dice d = number of faces on the dice p = probability distribution of a single dice. if left blank, assumes a fair die ''' if n < 1: raise Exception('invalid input n: the number of dice cannot be less than 1') if d < 1: raise Exception('invalid input d: the number of faces cannot be less than 1') if not p: p = [1/d for _ in range(d)] elif sum(p) != 1: raise Exception('invalid input p: the total probability must equal 1') proba_one = {} for i in range(1, d + 1): proba_one[i] = p[i - 1] if n == 1: return proba_one else: proba_n_minus_one = dice_dist(n - 1, d) return add(proba_n_minus_one, proba_one) def add(o1, o2, *args): def rv_add_rv(A, B): ''' returns a probability distribution representing the sum of random variables a and b \n A, B = dictionaries containing their full probability distributions ''' result = {} for z in range(min(A) + min(B), max(A) + max(B) + 1): p = 0 for a in A: if (z - a) in B: p += A[a] * B[z - a] result[z] = p return result def rv_add_c(A, c): ''' adds constant c to each key in dictionary A, but does not mutate A ''' keys = A.keys() result = {} for k in keys: result[k + c] = A[k] return result if type(o1) == dict and type(o2) == dict: result = rv_add_rv(o1, o2) elif type(o1) == dict: result = rv_add_c(o1, o2) elif type(o2) == dict: result = rv_add_c(o2, o1) else: raise Exception('invalid arg types: add func only takes in dict and constant') for a in args: result = add(result, a) return result def negative(obj): if type(obj) == dict: new_dict = {-x: obj[x] for x in obj.keys()} return new_dict else: return -obj def abs_val(obj): if type(obj) == dict: result = {} for i in obj: if abs(i) in result: result[abs(i)] += obj[i] else: result[abs(i)] = obj[i] elif type(obj) == int: result = abs(obj) return result def get_ac_hit_dist(ac_mod=8, ac_range=range(30)): ac_dist = add(ac_mod, dice_dist(1,20)) ac_hit_dist = {} for i in ac_range: sum_p = np.sum([ac_dist[p] for p in ac_dist.keys() if p >= i]) sum_p = min(sum_p, 1 - ac_dist[max(ac_dist)]) sum_p = max(sum_p, ac_dist[min(ac_dist)]) ac_hit_dist[i] = sum_p return ac_hit_dist
from re import findall ##Question 1 s = "c'est Bien" l1 = findall('[A-Z][a-z]+', s) print(l1) def handscape() s = "Il Fera Beau Demain" l1 = findall('[A-Z][a-z]+', s) l2 = l1[0] l3 = s.split() print(l3) print (l1) print (l2) print(l3) s = "Onze ans déjà que cela passe vite Vous " s += "vous étiez servis simplement de vos armes la " s += "mort n'éblouit pas les yeux des partisans Vous " s += "aviez vos portraits sur les murs de nos villes" l1 = findall('[A-Z][a-z]+', s) print(l1) def hascaps(s): l3 = [] l2 = s.split() # créer une liste for i in l2: # boucle if ord(i[0]) in range(65,91): # condition l3.append(i) # ajoute dans la liste l3 return l3 # on retourne la liste l3 print(hascap(s)) ##Question 2 s = 'Le prix est de 27 euros' s1 = s.split() for i, s in enumerate(s1): print(i,s) s = "Le prix est de 27 euro" z = "je suis ton père" def inflation(s): s1 = s.split() for i, n in enumerate(s1): if n.isnumeric(): s1[i] = int(n)*2 s1[i] = str(s1[i]) s1 = " ".join(s1) return s1 print(inflation(s)) print(inflation(z)) ##Question 3 def ligne(s) : y=[''] x=s.split() for i in x: i+=" " if len(y[-1])+len(i)<=24: y[-1]+=i else: y.append(i) return y print(ligne(s)) ##Question 4 import re def nombre(): a= re.findall('[\-]?[0-9][\.,,]?[0-9]*','les 3,0 maqueraux valent 6.50') print(a) nombre()
import pandas as pd import matplotlib.pyplot as plt import numpy as np iris = pd.read_csv('../input/Iris.csv') iris.head() # creating dependent and independent variables X = iris.iloc[:,[1,2,3,4]] y = iris.iloc[:,5] # creating test and training sets from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0) # lets scale out variables from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Fitting K-NN to the Training set using euclidean distance from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2) classifier.fit(X_train, y_train) # predicting using the trained classifier y_pred = classifier.predict(X_test) #looking at the confusion matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) print(cm) print('the amount of right predictions is {} out of {}'.format(sum(y_test == y_pred), len(y_test)))
from datetime import datetime, timedelta import time def sort_by_start(list_of_periods): if len(list_of_periods) == 0: return [] if len(list_of_periods) == 1: return list_of_periods list_of_periods.sort(key=lambda period: period.start) return list_of_periods def merge(list_of_periods): """ Adds up all the periods from the input list that are overlapping Examples: - merge([]) _> [] - merge([P(1,5)]) -> [P(1,5)] - merge([P(1,4), P(2,5)]) -> [P(1,5)] - merge([P(1,4), P(2,5), P(7,8)]) -> [P(1,5), P(7,8)] """ if len(list_of_periods) == 0: return [] if len(list_of_periods) <= 2: return list_of_periods sorted_periods = sort_by_start(list_of_periods) result = [] temp = sorted_periods[0] for i in range(1, len(sorted_periods)): current = sorted_periods[i] if temp.is_overlapped(current): temp = temp + current temp = temp[0] # we know len == 1 since both are overlapping else: result.append(temp) temp = current if i == len(sorted_periods) - 1: result.append(temp) return result class Period: def __init__(self, start, end): self.start = start self.end = end def __repr__(self): return f"Period('{self.start}', '{self.end}')" @classmethod def fromIsoFormat(cls, start, end): start_datetime = datetime.fromisoformat(start) end_datetime = datetime.fromisoformat(end) return Period(start_datetime, end_datetime) def get_duration(self): return self.end - self.start def is_overlapped(self, other): if max(self.start, other.start) <= min(self.end, other.end): return True else: return False def contains(self, other): if not self.is_overlapped(other): return False else: return self.start <= other.start and self.end >= other.end def get_overlapped_period(self, other: 'Period'): if not self.is_overlapped(other): return if other.start >= self.start: if self.end >= other.end: return Period(other.start, other.end) else: return Period(other.start, self.end) elif other.start < self.start: if other.end >= self.end: return Period(self.start, self.end) else: return Period(self.start, other.end) def __add__(self, other): if self.is_overlapped(other): earliest_start = min(self.start, other.start) latest_end = max(self.end, other.end) period = Period(earliest_start, latest_end) return [period] else: return [self, other] def __radd__(self, other): return self.__add__(other) def __sub__(self, other): if self.contains(other): first = Period(self.start, other.start) second = Period(other.end, self.end) return [first, second] elif other.contains(self): return [] elif self.is_overlapped(other): if self.start < other.start: return [Period(self.start, min(self.end, other.start))] else: return [Period(max(self.start, other.end), self.end)] else: return [self] def subtract(self, others): if len(others) == 0: return [self] if len(others) == 1: return self - others[0] results = [self] for i in range(len(others)): current = others[i] temp = [] for result in results: temp = temp + (result - current) results = temp return results def __eq__(self, other): return self.start == other.start and self.end == other.end
print ("") print ("") print ("") print (''' BEM VINDO A CALCULADORA DO FLAVIO 1,0v''') ide = input("Digite seu nome: ") print (''' Seja bem vindo,''',ide) nome = input (''' Por favor escolha sua operação: ------------------- | + | | - | ------------------- ''') if nome == "+": a = int (input("Digite aqui seu primeiro numero: ")) b = int (input ("Digite seu segundo numero: ")) print ("Resultado:",a + b) elif nome == "-": c = int(input("Digite aqui seu primeiro numero: ")) d = int(input("Digite seu segundo numero: ")) print ( c - d )
#-*- coding:UTF-8 -*- from make_shirt import get_format_name zly = get_format_name('Li','sdd','Yunfei') print(zly) #列表翻转函数实现 list = ['1','2','3','4','5','6'] list.reverse() print list def reverse(names): list = [] while names: list.append(names.pop()) return list list1=reverse(list) print list1
# -*- coding: UTF-8 -*- alien0 = {'color':'green','points':5} print(alien0) print(alien0.keys()) print(alien0['color']) #添加元素 alien0['points_x'] = 0 alien0['points_y'] = 25 print(alien0) alien1 = {'point_x':2,'point_y':25,'speed':'low'} if (alien1['speed'] == 'low'): x_increm = 1 y_increm = 2 elif (alien1['speed'] == 'middle'): x_increm = 2 y_increm = 4 elif (alien1['speed'] == 'fast'): x_increm = 8 y_increm = 5 new_alien1 = {} new_alien1['point_x'] = alien1['point_x'] + x_increm new_alien1['point_y'] = alien1['point_y'] + y_increm print(alien1) print(new_alien1) #del删除键值对 print(alien0) del alien0['points_y'] print(alien0) #使用for循环遍历字典 users = { 'username':'efiram', 'first':'li', 'last_name':'yuenfei', 'age':'20', 'major':'programer', 'do':'20' } for key,value in users.items(): print("\nKey: " + key) print("\nValue: "+ value) for name in users: print(name) print name.title() #按顺序返回键 for name in sorted(users.keys()): print name #遍历字典的值 for value in sorted(users.values()): print value #使用set剔除重复项 for value in sorted(set(users.values())): print value
""" try: for i in ['a', 'b', 'c']: print(i**2) except: print("Something went wrong") finally: print("I always run") """ """ try: x = 5 y = 0 z = x/y except ZeroDivisionError: print("You can't divide by 0") except: print("Something went wroong!") finally: print("I always run!") """ def ask(): x = int(input("Give me integer: ")) result = x ** 2 while True: try: ask() except TypeError: print("It's not an integer!") except: print("Something went wrong!") else: print("Thank you!") break finally: print("Let's do it again!")
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: chris # # Created: 11-10-2017 # Copyright: (c) chris 2017 # Licence: <your licence> #------------------------------------------------------------------------------- from random import randint def main(): print get_guess_count(11,1,20) print get_guess_count(11,1,20) print get_guess_count(11,1,20) print get_guess_count(11,1,20) def get_guess_count(number_to_guess, min_bound, max_bound): number=randint(min_bound,max_bound) guesses=1 if number >= min_bound and number<= max_bound: while number!=number_to_guess: number= randint(min_bound,max_bound) if number==number_to_guess: return "Your number is "+ str(number) + ". It took "+str(guesses)+" guesses to get this number." elif number != number_to_guess: guesses +=1 if number<number_to_guess: min_bound==number+1 if number>number_to_guess: max_bound==number-1 if guesses>=100000: return 'Guesses greater than 100000' if guesses>=100000:break else: continue else: return 0 if __name__ == '__main__': main()
class User: def __init__(self, username, email_address): self.name = username self.email = email_address self.account_balance = 0 def make_deposit(self, amount): self.account_balance += amount return self def make_withdrawal(self, amount): self.account_balance -= amount return self def display_user_balance(self): print(f"{self.name}: {self.account_balance}") return self def transfer_amount(self, target, amount): self.make_withdrawal(amount) target.make_deposit(amount) return self mike = User("mike", "[email protected]") shelbi = User("shelbi", "[email protected]") ryan = User("ryan", "[email protected]") mike.make_deposit(50).make_deposit(150).make_deposit(250).make_withdrawal(100).display_user_balance().transfer_amount(shelbi, 50).display_user_balance() shelbi.make_deposit(500).make_deposit(100).make_withdrawal(50).make_withdrawal(100).display_user_balance().display_user_balance() ryan.make_deposit(1000).make_withdrawal(500).make_withdrawal(100).make_withdrawal(50).display_user_balance()
import time import random # Heading print("\n") print(" *************************** ") print(" * * ") print(" * CHALLENGE YOUR GK * ") print(" * * ") print(" *************************** ") time.sleep(1) # Welcome message print("\nWelcome to my computer quiz!\n") confirm = input("Do you want to play a Game (yes/no): ") confirm = confirm.upper() if confirm in ("Y", "YES"): pass else: print("Thank you! Come back later") quit() """ Enter Name of the user, Game doesnt start without Name details """ # time delay used between displays time.sleep(0.5) while True: name = input("Please Enter your Name: ") if not name: print("please Enter your Name before start the game: ") else: print("Hi " + name + " Let's Start the Game") break time.sleep(0.5) q1 = """ Which Country is Known as the 'Land of Raising Sun'? A. Japan B. New Zealand C. Fiji D. China """ q2 = """ Which Country is known as the 'Playground of Europe? A. Austria B. holland C. Switzerland D. Italy """ q3 = """ What percentage of the human body is water? A. 75% B. 60% C. 69% D. 65% """ questions = {q1: 'A', q2: 'C', q3: 'B'} def start(): """ Score """ score = 0 for i in questions: print(i) answer = input("Enter your Answer(A/B/C/D): ") if answer == questions[i]: print("Correct Answer!, You got 1 point") score += 1 else: print("Incorrect Answer!") score -= 1 display_score(score) def display_score(score): print("Final Score is: ", score) def play_again(): """ Choice given to play again """ response = input("Do you want to Play again:(yes or no): ") response = response.upper() if response in ("Y", "YES"): return True elif response in ("N", "NO"): return False else: print("Please enter Valid answer(yes or no)") return play_again() def mix_questions(): keys = questions.keys() random.shuffle(keys) for key in keys: print(key, questions[key]) start() while play_again(): start() mix_questions()
""" If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? """ import re import functools def wordify_number(n): """ Translate a number from 0 to 1000 into its written component. """ twenty_nums = ["zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen", "eighteen","nineteen"] if n < 20: return twenty_nums[n] elif n == 1000: return "one thousand" else: tens = ["zero","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"] if n < 100: if n % 10 != 0: return tens[n//10] + "-" + twenty_nums[n % 10] else: return tens[n//10] else: hundred = twenty_nums[n//100] + " hundred" if n % 100 != 0: return hundred + " and " + wordify_number(n % 100) else: return hundred if __name__ == "__main__": print(functools.reduce(lambda x,y : x+y,map(lambda n : len(re.sub(r'[\s-]','',wordify_number(n))),range(1,1001))))
""" We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ import math def get_num_of_digits(n): return int(math.log10(n)) + 1 digits = set(range(1,10)) pandigital_numbers = set() # product will have at least as many digits as the smallest multiplicand upper_bound = 10000 for a in range(1,upper_bound): # 2 multiplicands and product must have 9 digits all together lower_digits_in_b = 1 while get_num_of_digits(a) + get_num_of_digits(((10**lower_digits_in_b)-1)*a) + lower_digits_in_b < 9: lower_digits_in_b += 1 upper_digits_in_b = 4 while get_num_of_digits(a) + get_num_of_digits(a*(10**(upper_digits_in_b-1))) + upper_digits_in_b > 9: upper_digits_in_b -= 1 lower_b = max(a+1,int(10**(lower_digits_in_b-1))) upper_b = int(10**upper_digits_in_b) - 1 for b in range(lower_b, upper_b): product = a*b multiplicand_and_product_digits = str(a) + str(b) + str(product) if len(multiplicand_and_product_digits) == 9 and set(map(int,multiplicand_and_product_digits)) == digits: pandigital_numbers.add(a*b) print(sum(pandigital_numbers))
# a collection of functions related to prime numbers def get_primes(n): """ Get all primes less than n. >>> len(get_primes(10)) 4 >>> len(get_primes(10000)) 1229 >>> p_list = get_primes(1000000) >>> len(p_list) 78498 >>> p_list[5] 13 >>> p_list[-6] 999931 """ import math if n < 3: return [] if n < 4: return [2] if n < 5: return [2,3] if n < 7: return [2,3,5] primes = [2,3,5] possible_primes = list(range(n)) is_prime = [False]*n a = {1,13,17,29,37,41,49,53} b = {7,19,31,43} c = {11,23,47,59} for x in range(1,int(math.sqrt(n/2))+1): for y in range(1,int(math.sqrt(n))+1): n_a = 4*x*x+y*y n_b = 3*x*x+y*y n_c = 3*x*x-y*y if n_a < n and (n_a % 60) in a: is_prime[n_a] = not is_prime[n_a] if n_b < n and (n_b % 60) in b: is_prime[n_b] = not is_prime[n_b] if x > y and n_c < n and (n_c % 60) in c: is_prime[n_c] = not is_prime[n_c] for i in possible_primes[5:]: if is_prime[i] is True: primes.append(i) t = i*i non_prime_idx = t while non_prime_idx < n: is_prime[non_prime_idx] = False non_prime_idx += t return primes def factor(n): """ Return the factors of a number. Factors may repeated. The trivial factor 1 is included. >>> factor(12) [1, 2, 2, 3] >>> factor(857643) [1, 3, 263, 1087] >>> factor(1257787) [1, 1257787] >>> factor(234124332234*31) [1, 2, 3, 13, 31, 31, 7919, 12227] """ import math p_list = get_primes(int(math.sqrt(n))+1) factors = [1] for p in p_list: while n % p == 0: factors.append(p) n //= p if n == 1: break if n != 1: factors.append(n) return factors def get_nth_prime(n): """ Get nth prime number >>> get_nth_prime(-1) Traceback (most recent call last): ... ValueError: n is -1 but expected be a positive integer >>> get_nth_prime(4) 7 >>> get_nth_prime(10001) 104743 >>> get_nth_prime(50000) 611953 """ if n < 1 or n != int(n): raise ValueError("n is {0} but expected be a positive integer".format(n)) if n == 1: return 2 if n == 2: return 3 if n == 3: return 5 if n == 4: return 7 if n == 5: return 11 import math upper = n*math.log(n) upper += upper*math.log(n) upper = math.ceil(upper) # use rosser's theorem for upper bound return get_primes(upper)[n-1] def get_n_divisors(n): """ Find the number of divisors using the fact that if n = x^a y^b z^c, the number of divisors is (a+1)(b+1)(c+1). Thus, we include 1 and itself. >>> get_n_divisors(1) 1 >>> get_n_divisors(28) 6 """ if n < 1 or n != int(n): raise ValueError("n must be a positive integer") if n == 1: return 1 factors = factor(n)[1:] counts = [0]*(factors[-1]+1) for f in factors: counts[f] += 1 from functools import reduce return reduce(lambda x, y : x*y, [exp+1 for exp in counts if exp != 0]) def get_divisors(n): """ Find all divisors of n, including 1 and n, itself. >>> get_divisors(1) {1} >>> get_divisors(28).issubset({1, 2, 4, 7, 14, 28}) True >>> get_divisors(28).issuperset({1, 2, 4, 7, 14, 28}) True """ return _factors_to_divisors(factor(n)) def get_proper_divisors(n): """ Get all divisors of n, excluding n. >>> get_proper_divisors(1) set() >>> get_proper_divisors(28).issubset({1, 2, 4, 7, 14, 28}) True >>> get_proper_divisors(28).issuperset({1, 2, 4, 7, 14, 28}) False """ proper_divisors = get_divisors(n) proper_divisors.remove(n) return proper_divisors def _factors_to_divisors(f): res = {1} if f is None or len(f)==0: return res res.update(_factors_to_divisors(f[1:])) for d in list(res): res.add(f[0]*d) return res if __name__ == "__main__": import doctest doctest.testmod()
""" Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ import prime def tabulate(l): res = dict() for n in l: if n in res: res[n] += 1 else: res[n] = 1 return res def find_divisors(f): res = {1} if f is None or len(f)==0: return res res.update(find_divisors(f[1:])) for d in list(res): res.add(f[0]*d) return res def d(n): proper_divisors = find_divisors(prime.factor(n)) proper_divisors.remove(n) return sum(proper_divisors) d_result = list() for n in range(30000): d_result.append(d(n)) amicable_numbers_sum = 0 for a in range(2,10000): if d_result[d_result[a]] == a and d_result[a] != a: amicable_numbers_sum += a print(a) print(amicable_numbers_sum)
Idade_User= int(input("Digite sua idade:")) Sal_User= float(input("Digite seu salrio:")) Adicional_User= Sal_User*0.2 print("Sua idade :", Idade_User) print("Seu salrio : R$", Sal_User) print("Adicional: R$", Adicional_User) print("Total: R$", Sal_User+Adicional_User)
tentativas = 3 correto = False while (tentativas>0) and not (correto): user = input("Qual meu nome? ") if user=="Caio": print('Parabns, voc acertou!') correto = True else: tentativas -= 1 print("Voc errou, suas tentativas restantes so:", tentativas)
#集合的運算 #s1={3,4,5}#大括號 #print(3 in s1)#3在s1中? 有就印出true 沒就印出false #print(10 not in s1)#10不在s1中 #s1={3,4,5} #s2={4,5,6,7} #s3=s1&s2# & : 交集 :取兩個集合中,相同的資料 #s3=s1|s2 # | : 聯集 :取兩個集合中的所有資料,但不重複取 #s3=s1-s2 # - : 差集 : 從s1中,減去和s2重疊的部分 #所以只印出3 #s3=s1^s2 # ^ : 反交集 : 取兩個集合中,不重疊的部分 #所以印出367 #print(s3) #s=set("Hello")#把字串中的字母拆解成集合 : set(字串)重複的部分不會取 所以印出HELO #print(s) #print("a" in s) #字典的運算:key-value配對 #dic={"apple":"蘋果","bug":"蟲蟲"} #dic["apple"]="小蘋果"#更改 #print(dic["apple"]) #print("test" not in dic)#判斷key是否存在 #dic={"apple":"蘋果","bug":"蟲蟲"} #print(dic) #del dic["apple"]#刪除字典中的鑑值對(key-value pair):刪除apple蘋果 #print(dic) dic={x:x*2 for x in [3,4,5]} #從列表的資料產生字典 print(dic)
''' Given two directories as input (folder1 and folder2), the script will compare the files they contain. It will: (1) print to STDOUT the list of the files unique to folder1 (2) print to STDOUT the list of the files unique to folder2 (3) run MD5 hashing on the common files (meaning the files with the same name) (4) delete from folder1 the common files that also had identical content (same md5) (5) print to STDOUT the list of the commong files that have different content RUN LIKE: $ python3 compareFolders.py -1 path/to/folder1 -2 path/to/folder2 The paths can be absolute or relative to CWD ''' import os import subprocess as sp import argparse def editFolderPath(f): ''' function to derive the absolute directory path ''' # get homepath homepath = os.path.expanduser('~') + '/' # get current path currentpath = os.getcwd() + '/' # in case a relative path was given as input if not os.path.commonprefix([homepath, f]): # append to current path f = currentpath + f # add '/' as suffix, if missing if f[-1:] != '/': f = f + '/' return(f) #### Parse and edit command line arguments parser = argparse.ArgumentParser() parser.add_argument('-1', required=True, dest='folder1', action='store', help='path to folder1') parser.add_argument('-2', required=True, dest='folder2', action='store', help='path to folder2') args = parser.parse_args() # derive absolute directory paths folder1 = editFolderPath(args.folder1) folder2 = editFolderPath(args.folder2) # get list of files in folders files1 = os.listdir(folder1) files2 = os.listdir(folder2) # print files unique to folder1 print('\nunique to folder1'.upper()) print('\n'.join([f for f in files1 if f not in files2])) # print files unique to folder2 print('\nunique to folder2'.upper()) print('\n'.join([f for f in files2 if f not in files1])) different = [] # loop over files in folder1 for f in files1: # if the file is also contained in folder2 if f in files2: # run MD5 hashing on the file in folder1 md51 = sp.run('md5sum %s%s' %(folder1, f), shell=True, stdout=sp.PIPE).stdout.decode().split(' ')[0] # run MD5 hashing on the file in folder2 md52 = sp.run('md5sum %s%s' %(folder2, f), shell=True, stdout=sp.PIPE).stdout.decode().split(' ')[0] # if the hash codes are different, append file name to list of different files if md51 != md52: different.append(f) # else, delete file in folder1 else: sp.run('rm %s%s' %(folder1, f), shell=True) # print list of common files with different hashed codes print('\nsame name but different'.upper()) print('\n'.join(different)) ##### END #####
#!/usr/bin/python3 def remove_char_at(str, n): c = str if n < 0: return c c = c[:n] + "" + c[n + 1:] return c
#!/usr/bin/python3 """ 1-square.py Square class """ class Square: """Square Class Class """ def __init__(self, size): """__init__ Contructor Contructor of class Square Args: size (integer): privete attribute for size Square """ self.__size = size
#!/usr/bin/python3 """ Object Square """ from models.rectangle import Rectangle class Square(Rectangle): """ class Square ihnertes Rectangle """ def __init__(self, size, x=0, y=0, id=None): """ constructor """ Rectangle.__init__(self, width=size, height=size, x=x, y=y, id=id) @property def size(self): """ getter width """ return self.width @size.setter def size(self, value): """ setter """ self.width = value self.height = value def __str__(self): """ str square """ return ("[Square] ({}) {:d}/{:d} - {:d}". format(self.id, self.x, self.y, self.width)) def update(self, *args, **kwargs): """ update square atributtes """ if len(kwargs) <= 0 and len(args) != 0: try: self.id = args[0] self.size = args[1] self.x = args[2] self.y = args[3] except IndexError: pass else: for k, v in kwargs.items(): setattr(self, k, v) def to_dictionary(self): """ square dictionary """ dic = {} dic["id"] = self.id dic["size"] = self.size dic["x"] = self.x dic["y"] = self.y return dic
#!/usr/bin/python3 """ My add module add_integer: function that add two numbers Return: the add of two intigers """ def add_integer(a, b=98): """ Return the add of intigers a and b are intigers """ if not isinstance(a, (int, float)) or isinstance(a, bool): raise TypeError("a must be an integer") elif not isinstance(b, (int, float)) or isinstance(b, bool): raise TypeError("b must be an integer") else: a = int(round(a)) b = int(round(b)) return (a + b)
#!/usr/bin/python3 """0 read_file """ def read_file(filename=""): """ Keyword Arguments: filename {file} -- text file (default: {""}) """ with open(filename, mode="r", encoding="utf-8") as f: x = f.read() print(x, end="")
""" agente.py criar aqui as funções que respondem às perguntas e quaisquer outras que achem necessário criar colocar aqui os nomes e número de aluno: 39392, Joana Elias Almeida 39341, Nuno Miguel da Silva Coelho Fernandes """ import time import math #--------------------------------------------------------------------------- #posicao inicial/em que o robô começa + tempo inicial INICIAL X_escada = 180 Y_escada = 40 tempo_inicial = 0 coordenadas_X = 0 coordenadas_Y = 0 Divisoes = [] #--------------------------------------------------------------------------- sala_atual = '' X_ant = 0 Y_ant = 0 #Lista com todos as Salas Visitadas e o qual é o seu tipo de sala (Sala, Tipo de Sala) Tipos_Sala = [] #Lista de obejtos e a sala onde forma encontrados (Nome Objeto, Sala onde foi visto) Objetos_Vistos = [] #Lista de Medicos encontrados e as suas coordenadas (Nome do Medico, X, Y) Medicos_Vistos = [] #Lista de Pessoas encontradas e as salas onde as mesmas foram encontradas (Pessoa, Sala) Pessoas_Encontradas = [] #Lista com todas as divisões encontradas, #+ coordenadas X, Y Divisoes_Encontradas = [] #time.time() dá nos os segundos desde que o tempo começo, para UNIX Janeiro 1, 1970, 00:00:00 a = time.time() #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def work(posicao, bateria, objetos): # esta função é invocada em cada ciclo de clock # e pode servir para armazenar informação recolhida pelo agente # recebe: # posicao = a posição atual do agente, uma lista [X,Y] # bateria = valor de energia na bateria, um número inteiro >= 0 # objetos = o nome do(s) objeto(s) próximos do agente, uma lista # podem achar o tempo atual usando, p.ex. # time.time() global X, Y, X_ant, Y_ant, objeto, objetos_sala, sala_atual, lista_objetos, bat, b, coordenadas_X, coordenadas_Y, inicial_time #X e Y atuais : X = posicao[0] Y = posicao[1] objeto = objetos objetos_sala = [] lista_objetos = [] bat = bateria #tempo atual b = time.time() #Quando o agente se está a mover, verificar as salas e os objetos dentro das mesmas if (X != X_ant) or (Y != Y_ant): #Cada Sala/Corredor é atribuida pelas cordenadas if (85 < X and X < 565) and (30 <= Y and Y <= 135): sala_atual = 'Corredor 1' elif (30 <= X and X <= 85) and (90 <= Y and Y < 330): sala_atual = 'Corredor 2' elif (565 <= X and X <= 635) and (30 <= Y and Y < 330): sala_atual = 'Corredor 3' elif (30 <= X and X <= 770) and (330 <= Y and Y <= 410): sala_atual = 'Corredor 4' elif (130 <= X and X <= 235) and (180 <= Y and Y <= 285): sala_atual = 'Sala 5' elif (280 <= X and X <= 385) and (180 <= Y and Y <= 285): sala_atual = 'Sala 6' elif (430 <= X and X <= 520) and (180 <= Y and Y <= 285): sala_atual = 'Sala 7' elif (680 <= X and X <= 770) and (30 <= Y and Y <= 85): sala_atual = 'Sala 8' elif (680 <= X and X <= 770) and (130 <= Y and Y <= 185): sala_atual = 'Sala 9' elif (680 <= X and X <= 770) and (230 <= Y and Y <= 285): sala_atual = 'Sala 10' elif (30 <= X and X <= 235) and (455 <= Y and Y <= 570): sala_atual = 'Sala 11' elif (280 <= X and X <= 385) and (455 <= Y and Y <= 570): sala_atual = 'Sala 12' elif (430 <= X and X <= 570) and (455 <= Y and Y <= 570): sala_atual = 'Sala 13' elif (615 <= X and X <= 770) and (455 <= Y and Y <= 570): sala_atual = 'Sala 14' else: sala_atual = '' if (X == 100) and (Y == 100): tempo_inicial = time.time() #Adiciona só a divisão quando esta ainda não foi adicionada if ((sala_atual not in Divisoes_Encontradas) and sala_atual != '') : Divisoes_Encontradas.append(sala_atual) #--------------------------------------------- if ((sala_atual not in Divisoes) and 'Sala' in sala_atual) : Divisoes.append(sala_atual) Divisoes.append(X) Divisoes.append(Y) #-------------------------------------------- #Só adiciona quando vê que todos os objetos ainda não foram registados if (bool(set(objetos).intersection(Objetos_Vistos)) == False) : #Objetos encontrados nas salas são adicionados a lista Objetos_Vistos tal como as mesmas for i in range (len(objetos)): Objetos_Vistos.append(objetos[i]) Objetos_Vistos.append(sala_atual) #Só adciona a lista de médicos quando o mesmo ainda não foi registado if (bool(set(objetos).intersection(Medicos_Vistos)) == False) : for i in range (0, len(objetos)): #Problema com o if não encontra o medico mesmo que já tenha sido encontrado if ('medico' in objetos[i]): Medicos_Vistos.append(objetos[i]) Medicos_Vistos.append(X) Medicos_Vistos.append(Y) #-------------------------------------------------------------------------------------------------------------------- #só adiciona à lista de pessoas encontradas quando o mesmo ainda não foi registado if (bool(set(objetos).intersection(Pessoas_Encontradas)) == False): #objetos encontrados são adicionados à lista_de_pessoa encontradas for i in range(0, len(objetos)): #se for médico, doente ou enfermeiro if(('medico' in objetos[i]) or ('doente' in objetos[i]) or ('enfermeiro' in objetos[i])): Pessoas_Encontradas.append(objetos[i]) #-------------------------------------------------------------------------------------------------------------------- Tipos_de_Sala(sala_atual) Y_ant = Y X_ant = X #Probabiliade_Condicionada () #caso o agente tenha sido carregado o tempo tem que começar de novo if bat == 100 : a = time.time() #resp5() #print(sala_atual) #print(X) #print(Y) pass #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #Ver qual é o tipo da sala atual def Tipos_de_Sala(sala): cama = 0 cadeira = 0 mesa = 0 aux_obj = [] #corre a lista de Objetos vistos só nas salas e não corredores if ('Sala' in sala): for i in range (0, len(Objetos_Vistos)): if (Objetos_Vistos[i] == sala): if('cama' in Objetos_Vistos[i-1]): cama = cama + 1 elif('cadeira' in Objetos_Vistos[i-1]): cadeira = cadeira + 1 elif('mesa' in Objetos_Vistos[i-1]): mesa = mesa + 1 #Apenas entra no ciclo quando a sala já consegue ser identificada if (cama > 0 or cadeira > 2 or mesa > 0 ): #Só adiciona a sala quando vê que a mesma ainda não foram registados if (sala not in Tipos_Sala) : #Sala adicionada a lista Tipos_Sala #Tipo de sala adicionado if (cama > 0 ): Tipos_Sala.append(sala) Tipos_Sala.append('Quarto') #-------------- #Tipos_Sala.append(X) #Tipos_Sala.append(Y) #-------------- elif (cama == 0 and cadeira > 0 and mesa > 0): Tipos_Sala.append(sala) Tipos_Sala.append('Sala de Enfermeiros') #-------------- #Tipos_Sala.append(X) #Tipos_Sala.append(Y) #-------------- elif (cadeira > 2 and cama == 0 and mesa == 0): Tipos_Sala.append(sala) Tipos_Sala.append('Sala de Espera') #-------------- #Tipos_Sala.append(X) #Tipos_Sala.append(Y) #-------------- #Se numa sala de espera uma mesa for encontrada (ou seja passar a ser uma sala de Enfermeiros) for i in range (0, len(Tipos_Sala)): #Se a sala for a atual e a mesma for uma Sala de Espera if (Tipos_Sala[i] == sala and Tipos_Sala[i+1] == 'Sala de Espera'): if (mesa > 0): Tipos_Sala[i+1] = 'Sala de Enfermeiros' pass #Fazer a média dos segundos para perder 1 de bateria def Media_Perda_Bateria (bateria, tempo) : media = 0 #A bateria perdida é 100(bateria inicial) - a bateria atual e = 100 - bateria #time.time() dá nos os segundos desde que o tempo começo, para UNIX Janeiro 1, 1970, 00:00:00 #Para saber quanto tempo passou desde que a bateria foi 100 temos que fazer o tempo atual menos o time.time() de quando a bateria era 100 tem = tempo - a #Mostra quantos segundos foram necessários para perder 1 de bateria media = tem / e return media pass #Probabilidade de encontrar um objeto sendo que o outro já foi encontrado def Probabiliade_Condicionada (): cont_obj1 = 0 cont_reuniao = 0 salas = [] for i in range (0, len(Objetos_Vistos)): if ('enfermeiro' in Objetos_Vistos[i]): #Só é contado quando os enfermeiros estão em salas diferentes if (Objetos_Vistos[i+1] not in salas): cont_obj1 = cont_obj1 + 1 aux = 0 #Ver se nessa sala está um Doente for j in range (0, len(Objetos_Vistos)): # A sala tem que ser igual a sala do enfermeiro if (Objetos_Vistos[i+1] == Objetos_Vistos[j]): #Só se conta a reunião uma vez por cada sala if (aux == 0): if ('mesa' in Objetos_Vistos[j-1]): cont_reuniao = cont_reuniao + 1 aux = 1 #Sempre que exite um enfermeiro a sala onde o mesmo foi encontrado salas.append(Objetos_Vistos[i+1]) #resultado = (cont_reuniao / len(Divisoes_Encontradas)) / (cont_obj1/ len(Divisoes_Encontradas)) print(cont_obj1, cont_reuniao, len(Divisoes_Encontradas)) pass def Distancia_sala_Enfermeiro(): #variaveis auxiliares count = 0 distancia = 0 #lista auxiliar distancias_varias = [] #cria uma lista auxiliar para guardar as salas de enfermeiros que vão existindo sala_aux = [] #percorre a lista dos Tipos de Sala que existem for i in range(0, len(Tipos_Sala), 2): #se Sala Enfermeiros estiver na lista dos tipos de Sala, algo que tem que acontecer, pois caso não estivesse o mesmo não "acionava" a função if 'Sala de Enfermeiros' in Tipos_Sala[i+1]: count = count + 1 for j in range(0, len(Divisoes), 3): if(Tipos_Sala[i] in Divisoes[j]): sala_aux.append(Divisoes[j]) sala_aux.append(Divisoes[j+1]) #X sala_aux.append(Divisoes[j+2]) #Y #se só existe 1 sala de enfermeiros if count == 1: X_sala = sala_aux[1] #print(X_sala) Y_sala = sala_aux[2] #print(Y_sala) #calcula a distância da posição em que o dito se encontra até à única sala existente distancia = math.sqrt((X_sala - X)**2 + (Y_sala - Y)**2) Caminho_sala_Enfermeiro(sala_aux[0]) #print(distancia) #se existir mais que 1 sala de enfermeiros else: for i in range(0, len(sala_aux),3): #guardar o X e Y da sala X_sala = sala_aux[i+1] Y_sala = sala_aux[i+2] #calcula a distância da posição em que o dito se encontra até à única sala existente, através do X e Y da posição atual e da sala distancia = math.sqrt((X_sala - X_ant)**2 + (Y_sala - Y_ant)**2) distancias_varias.append(sala_aux[i]) distancias_varias.append(distancia) #sala em concreto aux_distancias = distancias_varias[0] #distancia da posição atual até dita sala distancia_aux = distancias_varias[1] for i in range(3, len(distancias_varias),2): if(distancia_aux > distancias_varias[i]): #sala aux_distancias = distancias_varias[i-1] else: #sala aux_distancias = aux_distancias Caminho_sala_Enfermeiro(aux_distancias) #print(aux_distancias) #acabar o 3 #fazer a cena do deslocamento para a sala de enfermeiros # corredor -> ...., tendo em conta a localização da "porta" -> entrada # se o mesmo se encontrar na sala devolve -> já se encontra na sala pass def Caminho_sala_Enfermeiro(aux_distancias): X_atual = X Y_atual = Y if 'Corredor' in sala_atual: print('Desloque-se para a ', aux_distancias) elif aux_distancias == sala_atual: print('Já se encontra na Sala dos Enfermeiros') else: for i in range (0, len(Divisoes), 3): if (Divisoes[i] == sala_atual): print('Saia da sala atual para o corredor mais próximo e desloque-se para a ', aux_distancias) def Calcula_Distancia_Escadas(): #Variáveis auxiliares distancia = 0 #escadas encontram-se estáticas X_escadas = 180 Y_escadas = 40 distancia = math.sqrt((X_escadas - X)**2 + (Y_escadas - Y)**2) return distancia pass def Media_Tempo_Deslocamento(b): #variáveis auxiliares media = 0 tempo_final = time.time() distancia = 0 tempo_des = 0 distancia = math.sqrt((X - 100)**2 + (Y - 100)**2) if(distancia == 0): return 0 else: tempo_des = tempo_final - b media = tempo_des/distancia return media pass #------------------------------------------------------------------------------------------------------- #Qual foi a penúltima pessoa que viste? #Feito def resp1(): if len(Pessoas_Encontradas) == 1: print("O Robô apenas encontrou uma pessoa") elif len(Pessoas_Encontradas) > 1: print("A Penultima pessoa pessoa -> ", Pessoas_Encontradas[len(Pessoas_Encontradas) - 2]) else: print("O Robô ainda não encontrou nenhuma pessoa") pass #Em que tipo de sala estás agora? #Feito def resp2(): if sala_atual == '': print ("O agente de momento não se encontra em nenhuma sala.") else : for i in range (0, len(Tipos_Sala)): if (Tipos_Sala[i] == sala_atual): print ('A sala onde o agente se encontra de momento é ', Tipos_Sala[i+1], ".") pass #Qual o caminho para a sala de enfermeiros mais próxima? #Feito def resp3(): #indicar o caminho dizendo sala e if len(Tipos_Sala) == 0: print("Ainda não existem salas registadas") elif 'Sala de Enfermeiros' not in Tipos_Sala: print("Ainda não foi registada uma sala de enfermeiros") else: Distancia_sala_Enfermeiro() #print("sala FOUND") pass #Qual a distância até ao médico mais próximo? #Feito def resp4(): aux = [] aux_int = [] dist = 0 nome = '' if not Medicos_Vistos: print ("Ainda nenhum médico foi encontrado") else: #For para o Medicos_Vistos [i] ser sempre o nome do medico ! for i in range (0, len(Medicos_Vistos), 3): X_aux = Medicos_Vistos[i+1] Y_aux = Medicos_Vistos[i+2] a = (X_aux - X)**2 + (Y_aux - Y)**2 dist = math.sqrt(a) aux.append(Medicos_Vistos[i]) aux_int.append(dist) #menor valor da lista min(aux) for i in range (0, len(aux_int)): if (min(aux_int) == aux_int[i]): print('O medico que se encontra mais perto é', aux[i]) pass #Quanto tempo achas que demoras a ir de onde estás até as escadas? def resp5(): deslocamento = Calcula_Distancia_Escadas() #calcular a média do tempo de deslocamento media = Media_Tempo_Deslocamento(b) des_med = deslocamento * media if ((X <= 180) and (30 <= Y and Y <= 45)): print('O robô encontra-se nas escadas') elif (des_med == 0): print('Mova o robô') else: print('Falta aproximadamente ', des_med, ' segundos para chegar às escadas (margem de erro de menos de 2 segundos)') pass #Quanto tempo achas que falta até ficares sem bateria? #Feito def resp6(): #segundos necessários para perder 1 de bateria media = Media_Perda_Bateria (bat, b) tempo_medio = media * bat print ('Falta aproximadamente ', tempo_medio, 'sergundos para ficar sem bateria (margem de erro de menos de 2 segundos)') pass #Qual a probabilidade de encontrar um livro numa divisão, se já encontraste uma cadeira? def resp7(): pass #Se encontrares um enfermeiro numa divisão, qual é a probabilidade de estar lá um doente? def resp8(): pass
# tuple is immmutable sequences of arbitrary objects t = ("Norway", 4.953, 3) print(t[0]) print(len(t)) for item in t: print(item) print(t + (338.0, 123e9)) print(type(t))
# Variable naming in Python # Variables names must start with a letter or and underscore. Variable name may consist of letters, numbers and underscores. Variable name is case sensitive. x = True # valid 9x = False # invalid has_0_in_it = "Still Valid" x=9 y=X*2
# Fixed XOR # input bytes output bytes def xorByteStrings(byteString1,byteString2): # passing an iterable to the bytes constructor => a^b returns an integer xordString = bytes(a^b for a,b in zip(byteString1,byteString2)) return xordString if __name__ == "__main__": # one way to do this is hexString1 = "1c0111001f010100061a024b53535009181c" int1 = int(hexString1,16) hexString2 = "686974207468652062756c6c277320657965" int2 = int(hexString2,16) print(hex(int1^int2)) # but we will be following the cryptopals rule # pretty print using hex or base64 # work on bytes # getting bytes strings byteString1 = bytes.fromhex(hexString1) byteString2 = bytes.fromhex(hexString2) # getting xor of the two byte strings xordString = xorByteStrings(byteString1,byteString2) # hex encoding bytes string for pretty print hexString = xordString.hex() print(hexString)
""" Write a version of a palindrome recogniser that accepts a file name from the user, reads each line, and prints the line to the screen if it is a palindrome. """ import sys def palindrome(word): return word == word[::-1] def main(): file_path = input('Please enter file path:') # raw_input in Python 2 with open(file_path, 'r') as file_handle: for line in file_handle: word = line.rstrip() if palindrome(word): print(word) if __name__ == '__main__': sys.exit(main())