text
stringlengths
37
1.41M
"""Implement quick sort in Python. Input a list. Output a sorted list.""" def quicksort(array): if len(array) <= 1: return array else: # get last item from array as pivot pivot = array[-1] # move elements<pivot in array-{pivot} to the left side small_part = [x for x in array[0:-1] if x < pivot] # move elements>=pivot in array-{pivot} to the right side big_part = [x for x in array[0:-1] if x >= pivot] # recursively quicksort left and right part and combine them together return quicksort(small_part) + [pivot] + quicksort(big_part) def quick_sort(array): return \ array if len(array) <= 1 \ else quick_sort([x for x in array[1:] if x < array[0]]) \ + [array[0]] \ + quick_sort([x for x in array[1:] if x >= array[0]]) test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14] assert quicksort(test) == [1, 3, 4, 6, 9, 14, 20, 21, 21, 25] assert quick_sort(test) == [1, 3, 4, 6, 9, 14, 20, 21, 21, 25]
from math import log import random import time deckList = [] suitList = ['C', 'D', 'H', 'S'] # make a list # make a string with numbers 1-13 + suit(C D H S) # append list with strings for element in suitList: for deckNum in range(1,14): deckList.append(str(deckNum) + element) def createList(): shuffleList = [] while len(shuffleList) < 52: number = random.randint(1,52) if number not in shuffleList: shuffleList.append(number) return shuffleList shuffleList = createList() newdeckList = [] for element in shuffleList: newdeckList.append(deckList[element-1]) card = "5D" card2 = "12D" def parseNumberAndSuit(card): value = int(card[:-1]) suit = card[-1] return value, suit def convertValue(value, suit): if suit == 'C': value += 0 elif suit == 'D': value += 13 elif suit == 'H': value += 26 else: value += 39 return value def sort(unorderedList): orderedList = [] for element in unorderedList: positionToInsert = len(orderedList) for idx in range(0, len(orderedList)): if element < orderedList[idx]: positionToInsert = idx break orderedList.insert(positionToInsert, element) return orderedList value, suit = parseNumberAndSuit(card) unorderedList = [] for element in newdeckList: value, suit = parseNumberAndSuit(element) trueValue = convertValue(value, suit) unorderedList.append(trueValue) # print(unorderedList) #Come up with number of groups necessary #Make lists equal to number of groups #Instead of above, just compare groups of two elements in a list #Come up with solution for odd number of elements #Make lists with groups of elements #Compare and order the groups #Merge the groups #Repeat until done #Start combining lists in comparisons #repeat until fully combined list = [-3, 1, 5, 4, 2, 7, 8, 3] def mergeSort(unorderedList): inputs = [] for element in unorderedList: inputs.append( [element] ) while len(inputs) > 1: inputs.append(mergeTwoLists(inputs[0], inputs[1])) del inputs[0] del inputs[0] return inputs[0] def mergeTwoLists(inorderList1, inorderList2): mergedList = [] ioList1 = 0 ioList2 = 0 while len(mergedList) < len(inorderList1) + len(inorderList2): if ioList1 >= len(inorderList1): mergedList += inorderList2[ioList2:] break elif ioList2 >= len(inorderList2): mergedList += inorderList1[ioList1:] break elif inorderList1[ioList1] < inorderList2[ioList2]: mergedList.append(inorderList1[ioList1]) ioList1 += 1 else: mergedList.append(inorderList2[ioList2]) ioList2 += 1 return mergedList # print(mergeSort(list)) # startTime = time.time() # for i in range(0, 100000): # sort(unorderedList) # endTime = time.time() #print("O(n^2) " + str(endTime - startTime)) # startTime = time.time() # for i in range(0, 100000): # mergeSort(unorderedList) # endTime = time.time() #print("O(nlogn) " + str(endTime - startTime)) randomList = [] for i in range(0, 20000): randomList.append(random.randint(-10000000, 10000000)) print("made the list") startTime = time.time() sort(randomList) endTime = time.time() print("O(n^2) " + str(endTime - startTime)) startTime = time.time() mergeSort(randomList) endTime = time.time() print("O(nlogn) " + str(endTime - startTime)) startTime = time.time() randomList.sort() endTime = time.time() print("python " + str(endTime - startTime))
cont = 0 n = 1 soma = 0 while n <= 6: numero = float(input()) if numero > 0: cont += 1 if numero > 0: soma += numero media = (soma)/cont n += 1 print('%d valores positivos' %(cont)) print('%.1f' %(media))
salario = float(input()) if salario > 0 and salario <= 2000: print('Isento') elif salario >= 2000.01 and salario <= 3000: valor1 = salario - 2000 imposto1 = (valor1 * 0.08) print('R$ %.2f' %imposto1) elif salario > 3000.01 and salario <= 4500: valor2 = salario - 2000 taxa2 = valor2 - 1000 imposto2 = (1000 * 0.08) + (taxa2 * 0.18) print('R$ %.2f' %imposto2) else: valor3 = salario - 2000 taxa3 = valor3 - 1000 excedente3 = taxa3 - 1500 imposto3 = (1000 * 0.08) + (1500 * 0.18) + (excedente3 * 0.28) print('R$ %.2f' %imposto3)
numero = float(input()) if numero < 0 or numero > 100: print('Fora de intervalo') else: if numero >= 0 and numero <= 25: print('Intervalo [0,25]') if numero > 25 and numero <= 50: print('Intervalo (25,50]') if numero > 50 and numero <= 75: print('Intervalo (50,75]') if numero > 75 and numero <= 100: print('Intervalo (75,100]')
salario = float(input()) if salario == 0 or salario <= 400: salario_novo = salario + (salario*0.15) reajuste = salario * 0.15 print('Novo salario: %.2f' %salario_novo) print('Reajuste ganho: %.2f' %reajuste) print('Em percentual: 15 %') elif salario >= 400.001 and salario <= 800: salario_novo = salario + (salario*0.12) reajuste = salario * 0.12 print('Novo salario: %.2f' %salario_novo) print('Reajuste ganho: %.2f' %reajuste) print('Em percentual: 12 %') elif salario >= 800.001 and salario <= 1200: salario_novo = salario + (salario*0.10) reajuste = salario * 0.10 print('Novo salario: %.2f' %salario_novo) print('Reajuste ganho: %.2f' %reajuste) print('Em percentual: 10 %') elif salario >= 1200.001 and salario <= 2000: salario_novo = salario + (salario*0.07) reajuste = salario * 0.07 print('Novo salario: %.2f' %salario_novo) print('Reajuste ganho: %.2f' %reajuste) print('Em percentual: 7 %') else: salario_novo = salario + (salario*0.04) reajuste = salario * 0.04 print('Novo salario: %.2f' %salario_novo) print('Reajuste ganho: %.2f' %reajuste) print('Em percentual: 4 %')
valores = input().split() valor_x = float(valores[0]) valor_y = float(valores[1]) if valor_x == 0 and valor_y == 0: print('Origem') elif valor_x != 0 and valor_y == 0: print('Eixo X') elif valor_x == 0 and valor_y != 0: print('Eixo Y') elif valor_x > 0 and valor_y > 0: print('Q1') elif valor_x < 0 and valor_y > 0: print('Q2') elif valor_x < 0 and valor_y < 0: print('Q3') else: print('Q4')
lista = input().split() codigo = int(lista[0]) quantidade = int(lista[1]) if codigo == 1: total_pagar = quantidade * 4.0 print('Total: R$ %.2f' %total_pagar) elif codigo == 2: total_pagar = quantidade * 4.5 print('Total: R$ %.2f' %total_pagar) elif codigo == 3: total_pagar = quantidade * 5.0 print('Total: R$ %.2f' %total_pagar) elif codigo == 4: total_pagar = quantidade * 2.0 print('Total: R$ %.2f' %total_pagar) elif: total_pagar = quantidade * 1.50 print('Total: R$ %.2f' %total_pagar)
numero1 = int(input()) numero2 = int(input()) soma = numero1 + numero2 print("X = " + str(soma))
n = int(input()) num = n + 1 cont = 0 while cont < 6: if num % 2 != 0: print('%d' %num) cont += 1 num += 1
valores = input().split() numero1 = int(valores[0]) numero2 = int(valores[1]) numero3 = int(valores[2]) if numero1 < numero2 and numero1 < numero3 and numero2 < numero3: print('%d \n%d\n%d' %(numero1, numero2, numero3)) print('%d \n%d\n%d' %(numero1, numero2, numero3)) elif numero1 < numero3 and numero1 < numero2 and numero3 < numero2: print('%d \n%d\n%d' %(numero1, numero3, numero2)) print('%d \n%d\n%d' %(numero1, numero2, numero3)) elif numero2 < numero3 and numero2 < numero1 and numero3 < numero1: print('%d \n%d\n%d' %(numero2, numero3, numero1)) print('%d \n%d\n%d' %(numero1, numero2, numero3)) elif numero2 < numero1 and numero2 < numero3 and numero1 < numero3: print('%d \n%d\n%d' %(numero2, numero1, numero3)) print('%d \n%d\n%d' %(numero1, numero2, numero3)) elif numero3 < numero1 and numero3 < numero2 and numero2 < numero1: print('%d \n%d\n%d' %(numero3, numero2, numero1)) print('%d \n%d\n%d' %(numero1, numero2, numero3)) elif numero3 < numero1 and numero3 < numero2 and numero1 < numero2: print('%d \n%d\n%d' %(numero3, numero1, numero2)) print('') print('%d \n%d\n%d' %(numero1, numero2, numero3))
import pandas as pd import pdf_converter csv_data = r"covid.csv" covid_data = pd.read_csv(csv_data, usecols=['Province/State','Country/Region','Last Update','Confirmed','Deaths','Recovered']) print("First Five rows of data\n", covid_data.head()) print("Data shape: ", covid_data.shape) print("Data columns:\n ", covid_data.columns) covid_data['Last Update'] = pd.to_datetime(covid_data['Last Update']) unique_countries = covid_data.groupby(covid_data['Country/Region']).sum() date_df = covid_data[['Country/Region', 'Last Update']] last_update = date_df.sort_values('Last Update').groupby('Country/Region').last() filtered_data = pd.merge(unique_countries, last_update, on='Country/Region') sorted = filtered_data.sort_values('Confirmed',ascending=False).reset_index() print(sorted) print("Top 20 Countries: \n", sorted.head(20)) #user prompt answer = input(" Do you want a Pdf ?Enter yes or no: ") if answer == "yes": #function to convert the dataframe to PDF pdf_converter.convert_to_pdf(sorted.head(20)," ","Top_20.pdf") elif answer == "no": print("Okey.") else: print("Please enter yes or no.")
class ImgEncryption: """ Purpose: Provides capability to encrypt an image """ _xormap = {('0', '1'): '1', ('1', '0'): '1', ('1', '1'): '0', ('0', '0'): '0'} @staticmethod def xor_encrypt(binary_filename, encrypted_filename, password): """ Purpose: Encrypts secret img data file and stores in new encrypted file Args: binary_filename (str) - filename where unencrypted data is read from encrypted_filename (str) - filename where encrypted data is stored password (str) - password used to encrypt image with using XOR Returns: n/a """ bit_data_file = open(binary_filename, "r") bit_data_encrypted_file = open(encrypted_filename, "w") xor_bit_len = len(password) xor_data = "" # skip XORing password bytes_read = bit_data_file.read(xor_bit_len) bit_data_encrypted_file.write(bytes_read) bytes_read = bit_data_file.read(xor_bit_len) while len(bytes_read) > 0: # last read XOR only necessary amount of password if len(bytes_read) < xor_bit_len: shrt_pass = password[0:len(bytes_read)] xor_data = ''.join([ImgEncryption._xormap[a, b] for a, b in zip(bytes_read, shrt_pass)]) else: xor_data = ''.join([ImgEncryption._xormap[a, b] for a, b in zip(bytes_read, password)]) # new password is XOR_data from previous password password = xor_data bit_data_encrypted_file.write(xor_data) bytes_read = bit_data_file.read(xor_bit_len) bit_data_file.close() bit_data_encrypted_file.close() @staticmethod def xor_decrypt(encrypted_filename, decrypted_filename, password): """ Purpose: Decrypts secret img data file and stores in new encrypted file Args: encrypted_filename (str) - filename to read encrypted file decrypted_filename (str) - filename to write decrypted file to password (str) - password used to encrypt image with using XOR Returns: n/a """ encrypted_data = open(encrypted_filename, "r") decrypted_data = open(decrypted_filename, "w") xor_bit_len = len(password) xor_data = "" # skip XORing password bytes_read = encrypted_data.read(xor_bit_len) decrypted_data.write(bytes_read) bytes_read = encrypted_data.read(xor_bit_len) while len(bytes_read) > 0: # last read XOR only necessary amount of password if len(bytes_read) < xor_bit_len: shrt_pass = password[0:len(bytes_read)] xor_data = ''.join([ImgEncryption._xormap[a, b] for a, b in zip(bytes_read, shrt_pass)]) else: xor_data = ''.join([ImgEncryption._xormap[a, b] for a, b in zip(bytes_read, password)]) # next password is bytes read password = bytes_read decrypted_data.write(xor_data) bytes_read = encrypted_data.read(xor_bit_len) encrypted_data.close() decrypted_data.close()
""" cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4 Implement car and cdr. """ def cons(a, b): def pair(f): return f(a, b) return pair def car(c): def first(a, b): return a return c(first) def cdr(c): def last(a, b): return b return c(last) print (car(cons(3,4))) print (cdr(cons(3,4)))
# Name: Jessica Morton # Evergreen Login: morjes14 # Computer Science Foundations # Programming as a Way of Life # Homework 1 # You may do your work by editing this file, or by typing code at the # command line and copying it into the appropriate part of this file when # you are done. When you are done, running this file should compute and # print the answers to all the problems. import math # makes the math.sqrt function available import hw1_test # makes the variables within hw1_test available # have to use 'hw1_test.a' instead of just 'a' from math import * # imports everything from math module so 'sqrt' # can be used instead of 'math.sqrt' from hw1_test import * # imports everything from hw1_test module so just # 'a' can be used instead of 'hw_test.a' ### ### Problem 1 ### print "Problem 1 solution follows:" # Roots of the quadratic equation ax^2+bx+c are: # b+sqrt(b^2 - 4 * a * c)/2 * 1 and # b-sqrt(b^2 - 4 * a * c)/2 * 1 x1 = (5.86+sqrt(5.86**2-4*1*8.5408))/2*1 x2 = (5.86-sqrt(5.86**2-4*1*8.5408))/2*1 print #line of whitespace print "The square root of the quadratic equation x^2-5.86x+8.5408 is:" print "x1 =", x1, "x2 =", x2 print #line of whitespace ### ### Problem 2 ### print "Problem 2 solution follows:" print #line of whitespace print "a =", str(hw1_test.a) # converts bool to str and prints value print "b =", str(hw1_test.b) print "c =", str(hw1_test.c) print "d =", str(hw1_test.d) print "e =", str(hw1_test.e) print "f =", str(hw1_test.f) print #line of whitespace ### ### Problem 3 ### print "Problem 3 solution follows:" print #line of whitespace print "((a and b) or (not c) and not (d or e or f)) =" print str(((a and b) or (not c) and not (d or e or f))) ### ### Collaboration ### # ... List your collaborators here, as a comment (on a line starting with "#").
import csv from data import * d1 = data() with open('satellite.csv', 'r') as file: reader = csv.reader(file) for row in reader: for i in range(len(row)): name = row[0] operator = row[1] user = row[2] purpose = row[3] OrbitClass = row[4] OrbitType = row[5] perigee = row[6] apogee = row[7] eccentricity = row[8] inclination = row[9] LaunchMass = row[10] LaunchYear = row[11] LifeTime = row[12] LaunchSite = row[13] LaunchVehicle = row[14] d1.add_satellite(OrbitClass,OrbitType,LifeTime,purpose,LaunchVehicle, LaunchSite, LaunchYear, LaunchMass,perigee,apogee,eccentricity,inclination,name,operator,user) print("Details Class Functions:") print("Total number of elements:", d1.count_elements()) print("Remove element by name:", d1.remove_by_name('1HOPSAT')) print("Count after removing:", d1.count_elements()) print("Number of satellites for communication purpose:", d1.count_by_purpose('Communications')) print("Max lifetime of satellite:", d1.max_lifetime()) print("Number of satellites of elliptical orbit:", d1.all_satellites_by_OrbitType('Elliptical')) print("No. of satellites between life range:", d1.count_bw_life_range(2,10)) print("\n") print("Launch Class Functions:") print("Highest mass is:",d1.highest_mass()) print("Lowest mass is:", d1.lowest_mass()) print("Average mass is:", d1.average_mass()) print("Total number of satellites in 2010 is:", d1.total_satellites_in_year(2010)) print("Number of satellites launched by PSLV are:", d1.number_of_satellites_by_vehicle('PSLV')) print("Total satellites launched between 2005 to 2015:",d1. number_of_satellites_bw_years_range(2005,2015)) print("\n") print("Orbit Class Functions:") print("max Perigee:", d1.MaxPerigee()) print("min Perigee:", d1.MinPerigee()) print("Avg Perigee:", d1.AvgPerigee()) print("max Apogee:", d1.MaxApogee()) print("min Apogee:", d1.MinApogee()) print("Avg Apogee:", d1.AvgApogee()) print("Avg Ecentricity:", d1.AvgEcentricity()) print("Avg Inclination:", d1.AvgInclination())
class Expenses(): def __init__(self, incomes_list): self.name_of_incomes_list = incomes_list self.dictionary = {} def expenses_list(self, object_list): x = 0 # Luo sanakirjan olioiden menojen perusteella. for object in object_list: name = object.get_name() expenses = object.get_expenses_list() if not expenses: pass else: sum = 0 for income in expenses: sum = income + sum expenses = sum self.dictionary[name] = expenses return self.dictionary
import sys USAGE = """ Program finds Amstrong numbers in given range. N digit Amstrong number is the number equal sum of N-th power of its digits. Example: 153 = 1^3 + 5^3 + 3^3 Usage: {program} [[start] stop] """ def is_amstrong_number(x: int): digits = list(map(int, str(x))) return sum(map(lambda n: pow(n, len(digits)), digits)) == x def usage(): usage_txt = USAGE.format(program=sys.argv[0]) print(usage_txt) def exercise(_range): for number in _range: if is_amstrong_number(number): print(number) if __name__ == '__main__': if len(sys.argv) == 2: stop = int(sys.argv[1]) _range = range(stop) exercise(_range) elif len(sys.argv) == 3: start = int(sys.argv[1]) stop = int(sys.argv[2]) _range = range(start, stop) exercise(_range) else: usage()
from tkinter import * from tkinter import simpledialog import random # Example of how to use the line below: prompts = ["Enter Wage", "Enter Hours Worked"] prompts = ["Enter a comma separated list of words", "Enter a space separated list of test scores"] fields = [None] * (len(prompts)) values = ["All, fish, play, in, the, blue, ocean", "60 70 80 90 100"] # * (len(prompts)) # Write a program that accepts a comma separated sequence of words as input and prints # the words in a comma-separated sequence after sorting them alphabetically. Suppose the # following input is supplied to the program: without,hello,bag,world Then, the output # should be: bag,hello,without,world def run(): # items = [x for x in simpledialog.askstring("Create Sorted CSV", "Enter comma separated words").split(',')] input = fields[0].get() striped = ''.join(input.split()) # remove all spaces from input items = [x for x in striped.split(',')] items.sort() outputln(','.join(items)) # calculate the average of a comma separated list of test scores scores = [x for x in fields[1].get().split(' ')] scores = [float(i) for i in scores] average = sum(scores) / len(scores) outputln(f'The average of {scores} is {average}') # **************** Put helper methods below ********************* # **************** DO NOT CHANGE ANYTHING BELOW THIS LINE ********************** root = Tk() root.geometry('815x600') root.title('AppBuilder') row_num = 0 for index, prompt in enumerate(prompts): label = Label(root, text=prompt) label.grid(row=row_num, column=0, sticky=W) row_num += 2 fields[index] = Entry(root, textvariable=f"{index}", width=100) fields[index].grid(row=row_num, column=0, padx=4, sticky=W) fields[index].insert(0, values[index]) if index == 0: fields[index].focus_set() row_num += 1 def clearOutput(): display.delete("1.0", "end") def outputln(text_to_output): display.insert(END, f'{text_to_output}\n') def output(text_to_output): display.insert(END, f'{text_to_output}') frame = Frame(root) row_num += 1 runButton = Button(frame, text="Run", command=run) runButton.grid(row=row_num, column=0, ipadx=10, pady=5) clrButton = Button(frame, text="Clear Output", command=clearOutput) clrButton.grid(row=row_num, column=1, ipadx=10, pady=5) frame.grid(row=row_num, column=0) row_num += 1 display = Text(root) display.configure(font=("Courier", 12, "bold")) display.grid(row=row_num, column=0, padx=4) root.mainloop()
x=10 if x>=10: print("hello world") print(x) y=15 print("this is to demonstrate if and else ") if x>y: print(x,y) else : print("we are in else as the condion failed") #this is example for multiple condition in if block if x>y and x==y: print("condition for x and y passed ") if x>y or x==y: print("or condition with if ") #This example is for if and elif if x>y: print("making if false as 10>15 will fail") elif y==x: print("we are in else if block") elif y==10: print("we are here 2") elif y!=15: print ("we are here 3") else: print("the end case") #nested conditions (condition within another condition if y>x: print("outside if got passed") if y==15: print("y value is 15") else: print("y value is not 15") else: print("we are in nested condition else ") name="naveen" len(name) print(len(name)) for i in name: print(i)
#multiple inheritance means getting properties from multiple classes # and it should be only one child class #if nothing is given inside child it will inherit all properties from first super class mentioned class Father(): age=50 haircolour="black" eye="brown" def __init__(self,age,haircolour,eye): self.eye=eye self.haircolour=haircolour self.age=age def isFatherTall(self): print("he is tall") class Mother(): age=48 haircolour="gray" eye="blue" def __init__(self,age,haircolour,eye): self.age=age self.eye=eye self.haircolour=haircolour def isMomTall(self): print("yes i'm ") class child(Father,Mother): def __init__(self,age): #self.age=age # self.eye=Father.eye # self.haircolour=Mother.haircolour pass child=child(12) print(child.eye) print(child.haircolour) print(child.age) child.isMomTall() child.isFatherTall()
class Example(): def __init__(self,name,age): self.name=name self.age=age @classmethod def clsmth(cls,name,age): name="naveen" print("we are in class method") return cls(name,age-2) @staticmethod def sttcmthd(): print("we are in static method") def normal(self): print("we are in normal method") ex=Example("prakash",34) x=Example.clsmth("Naveen",34) print(x.age) #Example.normal() # this will throw error because normal methods are defined to object Example.sttcmthd() #classmethod can change the behaviour of tjhe class #static method can't modify or change the behaviour of the class # apart from that both class method and static method are of CLASS LEVEL AND not object leve;
#Hybrid inheritance is some this whil have diamond shaped relationship #Grandfather #son and daughter in law #grandchildren # this is a combination of heirarichal and multiple inheritance class GrandFather: age=72 colour="brown" def __init__(self): print("i'm in grand father") def healthcondition(self): print("i'm doing good") class Father(GrandFather): age =56 colour = "blue" def __init__(self): print("we are in father") def bankbalance(self): print("My bank balance from father is 2500") class Mother(GrandFather): height=5.6 mothertounge="telugu" def __init__(self): print("i'm his mother") class child(Father,Mother): def __init__(self): print("I'm the child") cld=child() cld.healthcondition() print(cld.height) cld.bankbalance() print(cld.mothertounge)
#In multilevel inheritance you have grandparent and grand cild relationship #grandfather #father #child class GrandFather: age=72 eyecolour="brown" def __init__(self,age,eyecolour): print("we are in grandfather") self.age=age self.eyecolour=eyecolour def healthcondition(self): print("he is doing fine") class Father(GrandFather): age=56 def __init__(self,age): print("we are in father") self.age=age def healthcondition(self): print("father health is fine") class child(Father): def __init__(self): print("we are in child") print(self.age) print(self.eyecolour) chld=child() chld.healthcondition()
def print_old_letter(old_letters_gussed): """bla bla bla""" old_letters_gussed.sort() k=0 i=len(old_letters_gussed) print('X') while (i>0): print(old_letters_gussed[k],end='->') k+=1 i-=1 print("\n") def cheack_valid_input(letter_guessed,old_letters_gussed): """function that get letter from gussed and check it is valid' if it is valid return true, else return false :letter_guessed: letter ftom the user:str :return: print the leester in small if it is true, else return false rtype:bool """ if ((len(letter_guessed)>1) or (not(letter_guessed.isalpha()))): print_old_letter(old_letters_gussed) return False; elif letter_guessed.lower() in old_letters_gussed: print_old_letter(old_letters_gussed) return False; else: if (letter_guessed>='A') and (letter_guessed<='Z'): # cahnge big to small letter print("Guess a lletter: ",letter_guessed.lower()); else: print("Guess a lletter = ", letter_guessed); old_letters_gussed.append(letter_guessed.lower()) return True; def main(): old_letters=list() letter=input("please enter letter from the word: "); while(letter!='5'): chk=cheack_valid_input(letter,old_letters); #cheack_valid_input(letter_guessed,old_letters_gussed): print(chk) letter=input("please enter letter from the word: "); if __name__ == "__main__": main();
#!/bin/python3 import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = SinglyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node self.tail = node def getNode(head, positionFromTail): curr = head temp = head for i in range(positionFromTail): temp = temp.next while (temp.next): curr = curr.next temp = temp.next return curr.data def main(): node1 = SinglyLinkedListNode(1) node2 = SinglyLinkedListNode(2) node3 = SinglyLinkedListNode(3) node1.next = node2 node2.next = node3 print (getNode(node1, 2)) if __name__ == "__main__": main()
#!/bin/python3 import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = SinglyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node self.tail = node def reverse(head): if head == None: return head prev = None curr = head next = None while (curr): next = curr.next curr.next = prev prev = curr curr = next head = prev return head def main(): node1 = SinglyLinkedListNode(1) node2 = SinglyLinkedListNode(2) node3 = SinglyLinkedListNode(3) node1.next = node2 node2.next = node3 curr = reverse(node1) while (curr): print (curr.data) curr = curr.next if __name__ == "__main__": main()
#This is a function to draw a playing board in respect of width and length so that it don't wrap def DrawBoard(rows, col): if rows <= 50 and col <= 50: #rows and columns fit into terminal without wrapping if rows%2 == 1 and col%2 == 0: #Pattern must be rows odd Number and col even Number for row in range(rows): if row%2 == 0: for column in range(1, col): if column%2 == 1: if column != col-1: print(" ",end="") else: print(" ") else: print("|",end="") else: print("-" * col) else: print("rows must be Odd and col must be Even") else: print("Rows and Column must be maximum 50") DrawBoard(19, 20)
# let user input age and country, output is whether the user can drive or not country = input('Which country are you from: ') age = input('Please enter your age:') age = int(age) # casting very important if country == 'Taiwan': if age >= 18: print('You can take driving licence test') else: print('You can not take driving licence test yet') elif country == 'America': if age >= 16: print('You can take driving licence test') else: print('You can not take driving licence test yet') else: print('You can only enter Taiwan or America')
# -*- coding: utf-8 -*- """ Created on Tue May 21 12:38:25 2019 @author: Rai """ """ Code Challenge Name: Exploratory Data Analysis - Automobile Filename: automobile.py Dataset: Automobile.csv Problem Statement: Perform the following task : 1. Handle the missing values for Price column 2. Get the values from Price column into a numpy.ndarray 3. Calculate the Minimum Price, Maximum Price, Average Price and Standard Deviation of Price """ import pandas as pd df = pd.read_csv("Automobile.csv") df = df.fillna(round(df.mean(),0)) ---------------------------------------------------
# -*- coding: utf-8 -*- """ Created on Wed May 8 16:53:16 2019 @author: Rai """ """ # Make a function to find whether a year is a leap year or no, return True or False """ year = 2016 if(year%4)==0 : if(year%100)==0 : if(year%400)==0: print("year is a leap year") else: print("year is not aleap year") else: print("year is a leap year") else: print ("year is not a leap year")
a=21 b=0 while a>b: #print(a) a-=1 if a == 15: print(a) a -= 2 print(a) if a == 11: print(a) print('halfway done') a-=2 if a == 5: a-=1
shopping_list = ['banana','apple'] prices = { 'banana':20, 'apple':30 } stock = { 'banana':40, 'apple':20 } #total = 0 # for key in prices: # print # print key # print 'prices = %s' % prices[key] # print 'stock = %s' % stock[key] # total = prices[key] * stock[key] # print '{} price: {} in total'.format(key,total) # # # total = 0 # for key in prices: # print # total = prices[key]*stock[key]+total # # print total def compute_bill(fruits): total = 0 for item in fruits: total += fruits[item] return total result = compute_bill(shopping_list) print result
__author__ = 'kalyani' class Animal(): is_alive = True def __init__(self, name, number, is_good): self.name = name self.number = number self.is_good = is_good kk = Animal('panda', 12, True) ll = Animal('Monkey', 10, False) print kk.name, kk.number, kk.is_good, kk.is_alive print ll.name, ll.number, ll.is_good, ll.is_alive class Python(): name = "Tutorials" mode = "difficult" print Python.name print Python.mode Python.name ="Classes" print Python.name class Cooking(): object1 = "chicken" object2 = "Fish" def __init__(self,name): self.name = name kk = Cooking('kadja') print Cooking.object1 print Cooking.object2 print kk.name class Phone_book(object): def __init__(self, name): self.name = name def hi(self): print "say Hello", Phone_book.name case = Phone_book("leela") print case.name class Directory(object): def __init__(self,name,number): self.name = name self.number = number def add_data(self, Directory): name = raw_input('enter the name') number = input("enter the number") return name, number data1 = Directory('ll',1212) print data1.__dict__ print data1.__dict__['name'] print data1.__dict__['number'] data2 = data1.add_data() print data2.__dict__
#!/usr/bin/env python3 #import sys.intern with open('enable1.txt') as f: words = f.read().splitlines() def funnel( w, l_prev, l_solutions=[] ): for i in range(len(w)): s = w[0:i] + w[i+1:] if s in words: # s is a valid word, so continue recursion temp = l_prev[:] temp.append(s) funnel(s, temp) else: # not an invalid word, so terminate if l_prev: l_solutions.append(l_prev) return l_solutions def _funnel(w): return funnel( w, [w] ) def test(): for w in ['gnash', 'princesses', 'turntables']: print(w, max_funnel(w)) def max_funnel(w): s = _funnel(w) return map(lambda x: len(x), s) # return map(len, _funnel(w)) #print(max_funnel('princesses')) #test() print(max_funnel('turntables')) #print(_funnel('turntables')) #for s in _funnel('turntables'): # print(s)
def solution(bridge_length, weight, truck_weights): weight_list = [] weight_sum = 0 count = [] finish = len(truck_weights) f_c = 0 sec = 0 while (f_c != finish): sec = sec + 1 if (sec > 2): if (count[0] == bridge_length): count.pop(0) weight_sum = weight_sum - weight_list[0] weight_list.pop(0) f_c = f_c + 1 if(len(truck_weights) != 0): if (weight_sum + truck_weights[0] <= weight): weight_sum = weight_sum + truck_weights[0] weight_list.append(truck_weights.pop(0)) count.append(0) for i in range(0, len(count)): count[i] = count[i] + 1 if (f_c == finish): break answer = sec return answer bridge_length = 2 weight = 10 truck_weights = [7, 4, 5, 6] print(solution(bridge_length, weight, truck_weights)) bridge_length = 100 weight = 100 truck_weights = [10] print(solution(bridge_length, weight, truck_weights))
#!/usr/bin/env python """This is a solver for Problem 1 in projecteuler.net. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ from itertools import takewhile def multiples(n): """Generator which produces the infinite sequence of all multiples of n.""" current = n while True: yield current current += n def merge(s1, s2): """Generator which merges two monotonically increasing sequences of numbers into a single monotonically increasing sequence, while avoiding duplicates.""" current1 = s1.next() current2 = s2.next() while True: if current1 < current2: yield current1 current1 = s1.next() elif current2 < current1: yield current2 current2 = s2.next() else: yield current1 current1 = s1.next() current2 = s2.next() LIMIT = 1000 less_than_limit = lambda x: x < LIMIT multiples_of_3_and_5 = merge(multiples(3), multiples(5)) selected_multiples = takewhile(less_than_limit, multiples_of_3_and_5) solution = sum(selected_multiples) print("The solution is: " + str(solution))
''' function vs method: name = "Mark" len(name) - returns int, length of obj name.upper() - changes name name is an instance of the str type. name is an obj of that type(str) obj is wrapper around data & functionality related to data ie methods methods are defined in a class definition methods live inside of class instead of outside of it ''' class Person(object): species = "Homo sapiens" def __init__(self, name="Unknown",age=18): self.name = name self.age = age def talk(self): return "Hello, my name is {}.".format(self.name) def __str__(self): return "Name: {0},Age: {1}".format(self.name,self.age) def __repr__(self): return "Person('{0}',{1}".fomat(self.name,self.age) def __eq__(self,other): return self.age == other.age class Student(Person): bedtime = 'Midnight' def do_homework(self): import time print("I need to work") time.sleep(5) print("Did I just fall asleep?") class Employee(Person): def __init__(self,name,age,employer): super(Employee,self).__init__(name,age) self.employer = employer def talk(self): talk_str = super(Employee,self).talk() return talk_str + " I work for {}".format(self.employer) class StudentEmployee(Student,Employee): pass nobody = Person() print(nobody.species) print(nobody.talk()) tyler = Student("Tyler",19) print(tyler.species) print(tyler.talk()) tyler.do_homework() fred = Employee("Fred Flinstone",55,"Slate Rock and Gravel Company") print(fred.talk()) ann = StudentEmployee("ann",58,"Family Services") print(ann.talk()) print(ann) #bill = StudentEmployee("bill",20) #crashes because no employer is passed
import datetime import time time1 = time.localtime() #[0:tm_year,1:tm_mon,2:tm_day,3:tm_hour,4:tm_min,5:tm_sec,6:tm_wday,7:tm_yday,8:tm_isdst] hour=time1.tm_hour minute = time1.tm_min second = time1.tm_sec if(hour<=5): print("You should be sleeping!") elif(6<=hour&hour<=10): print("Good Morning!") elif(11<=hour&hour<=14): print("How are those emails going?") elif(15<=hour&hour<=17): print("Almost quitting time!")
import sys if __name__ == '__main__': list1=[] if len(sys.argv)==4: k=1 for i in range(2,4): if(int(sys.argv[i])>int(sys.argv[k])): k=i print "largest of 3 is : ",sys.argv[k] else: print "Enter 3 numbers : " for x in range(0,3): list1.append(int(raw_input())) k=0 for i in range(1,3): if(list1[i]>list1[k]): k=i print "largest of 3 is : ",list1[k]
#!/usr/bin/env python # -*- encoding: utf-8 -*- import os dir = 'E:/Music/1、俄罗斯' # dir = 'E:/Music/2、欧美' # dir = 'E:/Music/3、日韩' # dir = 'E:/Music/4、中国' # dir = 'E:/Music/5、歌手' # dir = 'E:/Music/6、张学友' os.chdir(dir) i = 0 for name in os.listdir(): i += 1 lst = name.split('、') if len(lst) == 1: pre = '{0:0>3}'.format(600 + i) new_name = pre + '、' + name print(new_name) os.rename(name, new_name)
# esercizio 1 cand1 = input("come si chiama il primo candidato?") cand2 = input("come si chiama il secondo candidato?") voti1 = int(input("quanti voti ha ottenuto " + cand1 + "?")) voti2 = int(input("quanti voti ha ottenuto " + cand2 + "?")) somma = voti1 + voti2 percvoti1 = (voti1*100/somma) percvoti2 = (voti2*100/somma) print (percvoti1,"%" , cand1) print (percvoti2,"%", cand2) if percvoti1 > percvoti2: print ("ha vinto " + cand1) elif percvoti1 < percvoti2: print ("ha vinto " + cand2) else: print("mhh ") # esercizio 2 lista = [] cand1 = input("come si chiama il primo candidato?") cand2 = input("come si chiama il secondo candidato?") lista.append (cand1) lista.append (cand2) lista.sort () print (lista) voti1 = int(input("quanti voti ha ottenuto " + cand1 + "?")) voti2 = int(input("quanti voti ha ottenuto " + cand2 + "?")) voti = [] voti.append (voti1) voti.append (voti2) if voti1 > voti2: print("ha vinto " + cand1) elif voti1 == voti2: print("pareggio ") elif voti1 < voti2: print("ha vinto " + cand2) else: print("mhh") voti.reverse () print(voti) # esercizio 3 stipendi_totale = 0 stipendi_numero = 0 while True: stipendio=input("inserire il valore di uno stipendio") if stipendio=="-1": break else: stipendio=int(stipendio) stipendi_totale+=stipendio stipendi_numero+=1 media=int(stipendi_totale/stipendi_numero) print("la media degli stipendi è",media,) # esercizio 4 numero_veicoli = 0 print("digitare 0 per interrompere le domande") While True: flusso_veicoli = int(input("quanti veicoli sono passati dal casello oggi?")) if flusso_veicoli == 0 break print("in totale attraversato il casello " + flusso_veicoli +"veicoli")
# This script checks a book shelf for books and adds to it if the book isn't there current_books = ['musashi', 'the universe in a nutshell', 'man\'s search for meaning', 'pulp fiction'] # defines the initial list print('What book do you want to add?') book = input() # defines the book to add if book not in current_books: # check if the book exists. If not, it will add the book. current_books.append(book) else: print('We already have that book') for i in range(len(current_books)): # prints out the list of books currently on the shelf print(f'Index {str(i)} is {current_books[i]}')
# This is a simple program that takes a birthday in the DD/MM UK format and reverses to US MM/DD format. # There is little error checks here - just a simple program. uk_dob = input('What is your birthday in DD/MM format? ') us_dob = uk_dob[3:] + '/' + uk_dob[0:2] print(f'Your US birthday is {us_dob}')
# This is a short program to round any float (decimal number) to one decimal place. decimal = float(input('Give me a number with decimal digits. ')) rounded_decimal = round(decimal*10)/10 print(f'To one decimal place, your number is {rounded_decimal}')
from pprint import pprint import random # 2018/03/07 ''' ####### 生日问题(birthday problem)#######''' # 有一个足够大的房间,现每次进入一个人,直到进入的人中有两个人的生日相同,则停止进入 # 问题:平均进入多少个人,才能有两个人有相同的生日? # 问题简化:生日在1~365之间(不考虑闰年),房间看做已个列表数组 # 问题的关键是:数组的元素重复的查找,判断一个元素是否在这个数组中(可以用 in 来进行判断) # 代码如下: import random # 获取试验进行次数 times = int(input("试验进行的次数:")) # 定义函数 def birthday_problem(times): # 保存每次试验进入的人数的列表,以及进入人数的求和 number_person = [] sum_person = 0 for i in range(times): # 构建房间数组,进入的人数计数 room = [] persons = 0 while True: person_x = random.randint(1,365) if person_x not in room: room.append(person_x) persons += 1 else: persons += 1 break number_person.append(persons) sum_person += persons # 结果输出 print('一个房间中平均进入{:^5}个人,就会有两个人有相同的生日'.format((sum_person//times)+1)) # print('每次进入的人数结果如下:') # 美化输出结果(5个一行) # for time in range(1,times+1): # print(number_person[time-1],end = ' ') # if time % 5 == 0: # print() # 函数调用 birthday_problem(times)
# 二维数组的应用实例:自回避随机行走(本例所使用的的数组为矩阵,不考虑交错数组) # self-avoiding random walk # 一个城市的道路上,假设该城市的道路网络为矩阵,一只AlphaGo在该城市随机行走,走到已走过的点即为失败,请问AlphaGo走出的概率是多大 # 以交叉路口为节点(False),先行构建一个 m*n 的二维数组,所有的值均为False,在 AlphaGo 经过的节点,修改成True # 自回避:前进的方向上的下一节点为True时(说明该节点已经走过),回避此方向(抛弃这个方向) ''' 与书上的稍有区别,书上的对方向的选择上,会出现回头,但是不做操作 还有在二维的数组构建过程中,出现了一个问题 最初的所写的代码是: roads = [[False for i in range(n)]*m] 得到的结果是一个一维数组 改进后的代码是: roads = [[False for i in range(n)]]*m 得到的解结果虽然是一个二维数组,但是是一维数组的重复(不是复制体),更改其中一行的某个元素,其他的的行的相应位置的元素也同时改变 这应该是python列表的映射机制导致的 分析结果如下: 此二维列表的的第一行是由推导生成的,没有问题,问题出现在由一维扩展到二维的时候出现的 第二行后面的行,在内存中的表现是:保存的元素的对象引用(id,内存地址)是第一行的元素的对象引用 所以,此二维数组的中的行均指向第一行中的元素 故改变其中一行的中的某个元素,其他行的相应位置的元素均发生改变 再次改进后,是通过列表相加的得到的,产生的是全新的列表,与原来的第一行的元素的对象引用是不同的 ''' # 书上的程序放在最下面了 # 2018年1月11日 进行修改,修改后与书上的运行结果差不多了,显得有点长啰嗦,毕竟跟书上不一样 import random # 预设条件 print('Alphago的自回避随机行') m = int(input('请预设该城市的横向道路(行)的数量:\n')) n = int(input('请预设该城市的纵向道路(列)的数量:\n')) walk_times = int(input('请预设行走的次数:\n')) # 死亡计数,走出计数,走出步数列表 death_time_steps = [] walk_out_steps = [] # 开始不回头的随机行走 for times in range(walk_times): # 构建及重置这个城市的道路节点矩阵 roads = [[False]*n for _r in range(m)] # 预设及重置 AlphaGo 在地图的中心点(附近)坐标(m//2, n//2) x = m//2 y = n//2 roads[x][y] = True # 初始化行走次数 steps = 0 # 走出的条件(循环控制条件),AlphaGo 触及边界 while (x > 0) and (x < m - 1) and (y > 0) and (y < n - 1): # 构建移动操作计算字典表 move = { 'east': lambda x : x + 1, 'west': lambda x : x - 1, 'north': lambda y : y + 1, 'south': lambda y : y - 1 } # 初始方向列表 directions = [] # 构建方向列表数据,前进方向方节点没有走过(False),加入方向列表中,自回避 if not roads[x+1][y]: directions.append('east') if not roads[x-1][y]: directions.append('west') if not roads[x][y+1]: directions.append('north') if not roads[x][y-1]: directions.append('south') # 如果方向的列表长度为0,则说明进入了死胡同,终止 while 循环,更新死亡是的步数 if len(directions) == 0: death_time_steps.append(steps) break # 行走方向随机选择 turned = random.choice(directions) # 根据方向 turned 进行坐标运算 if turned == 'east' or turned == 'west': x = move[turned](x) else: y = move[turned](y) # AlphaGo行走至新的坐标节点,及行走步数增加 roads[x][y] = True steps += 1 # 判定是否走出,用于数据分析 if not ((x > 0) and (x < m - 1) and (y > 0) and (y < n - 1)): walk_out_steps.append(steps) print(walk_out_steps) print('在 {} X {} 的网格中,共行走了:{} 次,走出了:{} 次'.format(m,n,walk_times,len(walk_out_steps))) print('平均走出的步数结果是:{:.2f}:'.format(sum(walk_out_steps)/len(walk_out_steps))) print('无法走出的次数:{} 次,无法走出的概率是:{:.2f}'.format(len(death_time_steps),len(death_time_steps)/walk_times*100)) if len(death_time_steps) > 0: print('平均无法的步数结果是:{:.2f}:'.format(sum(death_time_steps)/len(death_time_steps))) ''' # 这是书上的版本 import random print('Alphago的自回避随机行') m = int(input('请预设该城市的横向道路(行)的数量:\n')) n = int(input('请预设该城市的纵向道路(列)的数量:\n')) walk_times = int(input('请预设行走的次数:\n')) death_end = 0 for t in range(walk_times): a = [[False]*n for _r in range(n)] x = y = n//2 while (x > 0) and (x < m - 1) and (y > 0) and (y < n - 1): # Check for dead end and make a random move a[x][y] = True if a[x-1][y] and a[x+1][y] and a[x][y-1] and a[x][y+1]: death_end += 1 break r = random.randrange(1,5) if (r == 1) and (not a[x+1][y]): x += 1 elif (r == 2) and (not a[x-1][y]): x -= 1 elif (r == 2) and (not a[x][y+1]): y += 1 elif (r == 2) and (not a[x][y-1]): y -= 1 print('{}% dead ends'.format(100*death_end/walk_times)) '''
# 两个数的最大公约数是指能同时整除它们的最大正整数 # 欧几里得算法:求取两个数字之间的最大公约数(辗转相除法) # use Euclid's algorithm get two intgrate's Greatest Commom Divisor(GCD) ''' 基本原理: 设两数为a、b(a≥b),求a和b最大公约数 的步骤如下: (1) 用 a 除以 b (a≥b),得 a / b = q...r1 (2) 若 r1 = 0 , 则 (a,b) = b (3) 若 r1 != 0 , 则再用 b 除以 r1 ,得 b / r1 = q1....r2 (4) 若 r2 = 0 则 (a,b) = r2 (5) 若 r2 != 0 则继续用 r1 除以 r2 .... 如此下去,直到能整除为止。 其最后一个余数为0的除数即为 (a,b) 的最大公约数。 ''' print('欧几里得算法:求取两个数字之间的最大公约数(辗转相除法)') a = int(input('请输入第一个数字:\n')) b = int(input('请输入第二个数字:\n')) n = 1 aa,bb = a,b if b > a: a,b = b,a while n > 0: n = a % b a,b = b,n print(' {} 和 {} 的最大公约数是 {} '.format(aa,bb,a))
# text progress bar # 刷新的关键是:之后打印的覆盖之前打印的数据 import time scale = 100 print('start'.center(scale//2,'-')) for i in range(scale + 1): a = '>>' * (i//10) b = ' _' * ((scale - i + 9)//10) c = i/scale print('[{}{}]{:^6.2%}'.format(a,b,c),end = '\r') time.sleep(0.1) print('\n'+'finish'.center(scale//2,'-'))
'''This is a simple python program to create a database of switch name and its corresponding switchport name''' print "This programs will create a switchport list based on the switch name \ which you enter" switch=raw_input("Enter switch name: ") stacks=raw_input("Enter number of stacks: ") stacks=int(stacks) for i in range(1, (stacks+1)): for x in range(1, 49): print switch + " %d/0/%d" % (i,x)
Age= int(input("How old are you? : ")) print ("My age is", Age)
#!/usr/bin/env python3 from slice import Slice pizza = [] jambons = [] # tableau de tuples (x, y) : ou y == line # liste des parts là où il y a du jambon # récupérer le jambon le plus proche, puis le plus proche de l'autre # puis du détermine le carré with open("test_round.in", "r") as f: R, C, H, S = map(int, f.readline().split()) print("%s %s %s %s" % (R, C, H, S)) for line in f: l = line.replace('\r', '').replace('\n', '') print("[%s]" % l) pizza.append(l) print("pizza lines %s, cols %s" % (len(pizza), len(pizza[0]))) y = 0 for line in pizza: x = 0 for col in line: if col == 'H': obj = (x, y) jambons.append(obj) x += 1 y += 1 print(str(jambons)) print("Nb jambons %s" % len(jambons)) # x = colonne # y = ligne slices = [] y = 0 for line in pizza: x = 0 begin = -1 count = 0 for x in range(0, len(line)): if line[x] == 'H': if begin == -1: begin = x else: count += 1 if (x - begin) >= 12: x = begin begin = -1 count = 0 if count == 2 and (x - begin) < 12: slices.append(Slice((y, y), (begin, x))) count = 0 begin = -1 x += 1 y += 1 i = 0 for slice in slices: if i + 1 < len(slices): next = slices[i + 1] if next.line_start == slice.line_start: if (slice.column_end - slice.column_start) < 12: cend = next.column_start - 1 while (cend - slice.column_start) >= 12: cend -= 1 slice.column_end = cend i += 1 def find_first_jambon(x, y): tab = [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] found = [] lvl = 1 while lvl < S and len(found) < H: for i in tab: new_pt = (x * (i[0] * lvl), y * (i[1] * lvl)) if new_pt in jambons: found.append(new_pt) lvl += 1 return found def find_first_ham(x, y): lvl = 1 found = [] def is_ham(_x, _y): return (_x, _y) in jambons found.append((x, y)) jambons.remove((x, y)) while lvl < S and len(found) < H: i = x + lvl j = y + lvl while j >= y - lvl: if is_ham(i, j): found.append((i, j)) jambons.remove((i, j)) # A revoir if len(found) >= H: return found j -= 1 if j < y - lvl: j = y + lvl i -= 1 if i < x - lvl: lvl += 1 break return found print(find_first_ham(10, 19)) #for jambon in jambons: # #with open("output.csv", "w") as text_file: # for s in servers: # print(s.csv(), file=text_file) #with open("output.txt", "w") as text_file: # for s in servers: # if s._x == -1: # print("x", file=text_file) # else: # print("%d %d %d" % (s._y, s._x, s._group), file=text_file) #List of slices #slices = [] #filling with dumb data #slices.append(Slice((1, 1), (5, 5))) #slices.append(Slice((10, 11), (7, 8))) #slices.append(Slice((15, 16), (12, 18))) #slices.append(Slice((18, 19), (18, 18))) #slices.append(Slice((21, 22), (21, 21))) # Write the output file according to the format defined in the subject : # first line is the number of slice # each following line is a slice (first 2 digits are the line, last 2 digits are the columns) def print_output(slices): result = open("result.txt", "w") length = len(slices) print(length) result.write(str(length) + '\n') for slice in slices: slice_output = slice.get_printable_output() print(slice_output) result.write(slice_output + '\n') result.close() print_output(slices)
# setup new document size(600, 740) background('#004477') noFill() stroke('#FFFFFF') strokeWeight(3) xco = 400 yco = 440 ''' 1. Draw a line beginning at an x-coordinate of half the display window width, and y-coordinate of a third of the window height. The endpoint must have an x/y-coordinate equal to xco & yco ''' line(width/2,height/3, xco,yco) ''' 2. Draw a centred ellipse with a width that is an eleventh of the display window width, and a height that is a fourteenth of the window height. 3. Draw a centred ellipse with a width that is a nineteenth of the display window width, and a height that is a twenty-second of the window height. 4. Draw a line beginning at an x/y-coordinate equal to xco & yco respectively. The endpoint must have an x-coordinate of the display window width minus xco, and a y-coordinate equal to yco. 5. Draw a line beginning at an x-coordinate of the display window width minus xco, and y-coordinate equal to yco. The endpoint must have an x-coordinate of half the display window width, and a y-coordinate of a third of the window height. 6. Draw a centred ellipse with a width that is a fifth of the display window width, and height that is a twelfth of the display window height. ''' ellipse(width/2, height/2, width/11, height/14) ellipse(width/2, height/2, width/19, height/22) line(xco,yco, width-xco,yco) line(width-xco,yco, width/2,height/3) ellipse(width/2, height/2, width/5, height/12)
# https://en.wikipedia.org/wiki/Parametric_equation def setup(): size(800,800) background('#004477') strokeWeight(3) def parabola(x): return x*x def circl(t): x = cos(t) y = sin(t) return [x,y] def ellips(t): x = 2 * cos(t) y = 1 * sin(t) return [x,y] def lissajous(t,a,b,kx,ky): # ratio of kx/ky determines curve # so kx=2,ky=1 same as kx=10,ky=5 x = a * cos(kx*t) y = b * sin(ky*t) return [x,y] x = -300.0 y = 0.0 t = 0.0 def draw(): global x,y,t t += 0.01 translate(width/2, height/2) stroke('#0099FF') line(width/2*-1,0, width/2,0) line(0,height/2*-1, 0,height/2) stroke('#FFFFFF') ''' y = parabola(x) x += 1 point(x,y) ''' ''' xy = circl(t) x = xy[0] * 100 y = xy[1] * 100 point(x,y) ''' ''' xy = ellips(t) x = xy[0] * 100 y = xy[1] * 100 point(x,y) ''' ''' xy = lissajous(t,1,1,3,2) x = xy[0] * 100 y = xy[1] * 100 t += 0.01 point(x,y) ''' # mystify-esque screensaver xy1 = lissajous(t,2,1,3,1) x1 = xy1[0] * 100 y1 = xy1[1] * 100 xy2 = lissajous(t,1,5,5,3) x2 = xy2[0] * 100 y2 = xy2[1] * 100 xy3 = lissajous(t,7,3,1,1) x3 = xy3[0] * 100 y3 = xy3[1] * 100 fill(0x66004477) rect(-width/2,-height/2, width,height) colorMode(HSB,360,100,100) stroke(x,100,100) x += 1 if x > 360: x = 0 line(x1,y1, x2,y2) line(x2,y2, x3,y3) line(x3,y3, x1,y1)
#coding:utf-8 import os class Path2Tree(object): def __init__(self, path_list): self.path_list = path_list self.tree_str = '' self.build_tree() def get_space(self, tree_list): if len(tree_list) < 2: return "└─" end = tree_list[-1] front_list = tree_list[0:-1] line = "" for flag in front_list: line += "| " if flag else " " line += "└─ " if end else "├─ " return line def get_new_list(self, tree_list, item): ret_list = [] ret_list.extend(tree_list) ret_list.append(item) return ret_list def generate_tree(self, tree, n=0, tree_list=[]): if not isinstance(tree, dict) and not isinstance(tree, list): self.tree_str += self.get_space(tree_list) + str(tree) + '\n' elif isinstance(tree, list) or isinstance(tree, tuple): length = len(tree) for index, error in enumerate(tree): self.tree_str += self.get_space(self.get_new_list(tree_list, length == index + 1)) + str(tree) + '\n' elif isinstance(tree, dict): length = len(tree) keys = list(tree.keys()) keys.sort() for index, key in enumerate(keys): value = tree[key] self.tree_str += self.get_space(self.get_new_list(tree_list, length == index + 1)) + str(key) + '\n' self.generate_tree(value, n + 1, self.get_new_list(tree_list, length != index + 1)) def build_tree(self): tree_dict = {} sub_tree_dict = None for path in self.path_list: path_sub_list = path.split(os.path.sep) for index, sub_key in enumerate(path_sub_list): if index == 0: tree_dict[sub_key] = tree_dict.get(sub_key, {}) sub_tree_dict = tree_dict[sub_key] else: sub_tree_dict[sub_key] = sub_tree_dict.get(sub_key, {}) sub_tree_dict = sub_tree_dict[sub_key] self.tree_str = '' self.generate_tree(tree_dict, 0) def get_tree(self): return self.tree_str
from urllib.request import urlopen from urllib.error import HTTPError from urllib.error import URLError try: PageUrl = urlopen("https://www.google.in/") except HTTPError: print("HTTP error") except URLError: print("Page not found!") else: print("Page Found") try: PageUrl = urlopen("http://www.notfound.in/") except HTTPError: print("HTTP error") except URLError: print("Page not found!") else: print("Page Found")
import numpy as np A = np.array([4, 7, 3, 4, 2, 8]) print(A == 4) print(A < 5) print(A[4]) print(A[A==4]) #index print(A[A<5]) # booleanlist print(A[3:5]) #slicing
def getNames(): names = ['Christopher', 'Susan', 'Danny'] newName = input('Enter last guest: ') names.append(newName) return names def printNames(names): for name in names: print(name) return printNames(getNames())
subject = input("Sub: ") while: year = int(input("Year: ")) if (year == 2018 or year == 2019): break while: duration = int(input("Duration: ")) if (duration >= 10 and duration <= 14): break
minh = {'1':'minh', '2': 'toan'} for a, b in minh.items(): if a == '1': minh['1'] = 'minhdeptrai' print(minh)
import numpy as np list_input = [1,2,3,4,5,6,7,8] print("Type of list: ", type(list_input)) np_arry = np.array(list_input) # print("Numpy array: ", np_arry) print("Type of numpy array: ", type(np_arry))
print("Tinh tong cac chuc so cua mot so") number = input("Nhap vao mot so nguyen di: ") result =0 for i in list(number): result += int(i) print("Tong cac chu so la: %d" %(result))
import os for folderName, subfolders, filenames in os.walk('C:\\Users\\vanquangcz\\Desktop\\python'): print('The current folder is ' + folderName) for subfolder in subfolders: print('SUBFOLDER OF '+ folderName + ': '+ subfolder) for filename in filenames : print('File inside '+ folderName + ': ' + filename) print('End')
import datetime as dt import math firstDay = input("Moi nhap so ngay dau tien: ") firstDays = dt.datetime.strptime(firstDay, '%d%m%Y').date() sencondDay = input("Moi nhap so ngay thu hai: ") sencondDays = dt.datetime.strptime(sencondDay, '%d%m%Y').date() days = (sencondDays - firstDays) print(days)
def tinhTong(ds): sum= 0 for i in ds : sum += ds return sum number = int(input("Nhap vao so chu so: ")) mang = dict(number) for i in range(0, number): mang[i] = input() tinhTong(mang)
# 3.用三个列表表示三门学科的选课学生姓名(一个学生可以同时选多门课) discipline1 = ['1', '2', '5', '8', '11', '15', '12', '3', '7', '17'] discipline2 = ['11', '7', '9', '14', '6', '8', '4', '1', '34', '17'] discipline3 = ['2', '8', '24', '1', '4', '9', '14', '18', '3', '19'] # a. 求选课学生总共有多少人 num = len(set(discipline1 + discipline2 + discipline3)) print(num) # b. 求只选了第一个学科的人的数量和对应的名字 num2 = set() for x in discipline1: for y in discipline2: if x == y: num2.add(x) for y in discipline3: if x == y: num2.add(x) print(set(discipline1) - num2, '数量:', len(set(discipline1) - num2)) # c. 求只选了一门学科的学生的数量和对应的名字 num2 = set() for x in range(len(discipline1)): for y in range(len(discipline1)): if discipline1[x] == discipline2[y]: num2.add(discipline1[x]) for y in range(len(discipline1)): if discipline1[x] == discipline3[y]: num2.add(discipline1[x]) for y in range(len(discipline1)): if discipline2[x] == discipline3[y]: num2.add(discipline2[x]) num1 = set(discipline1 + discipline2 + discipline3) print(num1 - num2, '数量:', len(num1 - num2)) # d. 求只选了两门学科的学生的数量和对应的名字 num = set(discipline1 + discipline2 + discipline3) dict1 = dict.fromkeys(num, 1) for x in range(len(discipline1)): for y in range(len(discipline1)): if discipline1[x] == discipline2[y]: dict1[discipline1[x]] += 1 for y in range(len(discipline1)): if discipline1[x] == discipline3[y]: dict1[discipline1[x]] += 1 for y in range(len(discipline1)): if dict1[discipline1[x]] == 3: print(dict1[discipline1[x]]) continue if discipline2[x] == discipline3[y]: dict1[discipline2[x]] += 1 num = [] for x in dict1: if dict1[x] == 2: num.append(x) print(num, '数量:', len(num)) # e. 求选了三门学生的学生的数量和对应的名字 num = [] for x in dict1: if dict1[x] == 4: num.append(x) print(num, '数量:', len(num))
"""__author__=余婷""" # 如果一个类继承enum模块中的Enum类,那么这个就是枚举 from enum import Enum from random import shuffle from copy import copy # 5.写一个扑克游戏类, 要求拥有发牌和洗牌的功能(具体的属性和其他功能自己根据实际情况发挥) class PokerNum(Enum): Three = (3, '3') Four = (4, '4') Five = (5, '5') Six = (6, '6') Seven = (7, '7') Eight = (8, '8') Nine = (9, '9') Ten = (10, '10') J = (11, 'J') Q = (12, 'Q') K = (13, 'K') A = (14, 'A') Two = (15, '2') Joker_S = (16, 'Joker') Joker_B = (17, 'JOKER') # print(PokerNum.J, PokerNum.J.value) # # # 获取当前枚举类中所有的数据 # for item in PokerNum.__members__.items(): # print(item, type(item[1])) class Poker: def __init__(self, color: str, num: PokerNum): self.color = color # ♥、♠、♣、♦ self.num = num # 2-10,J,Q,K,A; 大王、小王 def __repr__(self): return '{}{}'.format(self.color, self.num.value[1]) # 让Poker对象可以比较大小(>) # p1 > p2 -> p1.__gt__(p2) def __gt__(self, other): return self.num.value[0] > other.num.value[0] # p1 + p2 -> p1.__add__(p2) def __add__(self, other): return self.num.value[0] + other.num.value[0] # p1 * N -> p1.__mul__(N) def __mul__(self, other): list1 = [] for _ in range(other): list1.append(copy(self)) return list1 class PokerGame: def __init__(self): # 一副牌 self.pokers = [] # 创建牌 nums = PokerNum.__members__.items() colors = ['♥', '♠', '♣', '♦'] for num in nums: if num[1] == PokerNum.Joker_S or num[1] == PokerNum.Joker_B: continue for color in colors: # 创建牌对象 p = Poker(color, num[1]) self.pokers.append(p) self.pokers.append(Poker('', PokerNum.Joker_S)) self.pokers.append(Poker('', PokerNum.Joker_B)) # print(self.pokers) def __shuffle(self): # 方法一: 转换成集合 # print(set(self.pokers)) # 方法二: random.shuffle(列表) shuffle(self.pokers) print(self.pokers) def deal(self): self.__shuffle() poker_iter = iter(self.pokers) p1 = [] p2 = [] p3 = [] for _ in range(17): p1.append(next(poker_iter)) p2.append(next(poker_iter)) p3.append(next(poker_iter)) # 排序 # p1.sort(key=lambda item: item.num.value[0], reverse=True) # p2.sort(key=lambda item: item.num.value[0], reverse=True) # p3.sort(key=lambda item: item.num.value[0], reverse=True) p1.sort(reverse=True) p2.sort(reverse=True) p3.sort(reverse=True) return p1, p2, p3, list(poker_iter) game = PokerGame() # game.shuffle() print(game.deal()) print(game.deal()) print('==============补充:运算符重载=================') # 所有的类型都是类;每个运算符都对应一个固定的魔法方法,使用运算符其实是在调用对应的魔法方法 # 10 + 29 p1 = Poker('♠', PokerNum.A) p2 = Poker('♣', PokerNum.J) # print(p1 > p2) print(p1 + p2) print(p1 < p2) print(p1 * 4) # print(p1 * p2) # TypeError: 'Poker' object cannot be interpreted as an integer
"""__author__=桃花寓酒寓美人""" """ import :在导入模块的时候会检查当前模块之前是否已经导入过,如果已经导入过不会重新导入 include 联系:都是导入文件 区别:import会检查是否已经导入 include不会检查每次都会重新导入 """ dict1 = {'name': 1, 'age': 25} generate = ({key, dict1[key]} for key in dict1) for key in generate: print(key) dict2 = dict((dict1[key], key) for key in dict1) print(dict2)
"""__author__=蒋志颖""" # 1.根据实参的传值方式将实参分为: 位置参数、关键字参数 """ 1)位置参数 - 直接让实参的值和形参一一对应 2)关键字参数 - 调用函数的时候以'形参名1=值1,形参名2=值2,...'的形式传参 3) 位置参数和关键字参数混用 - 混用的时候必须保证位置参数在关键字参数的前面, 同时保证每个参数都有值 """ def func1(a, b, c): # a=10, b=20,c=30 print('a:{},b:{},c:{}'.format(a, b, c)) # 位置参数 func1(10, 20, 30) # a:10,b:20,c:30 # 关键参数 func1(a=100, b=200, c=300) # a:100,b:200,c:300 func1(c=33, a=11, b=22) # a:11,b:22,c:33 # 混用 func1(100, c=300, b=200) # a:100,b:200,c:300 # func1(b=22,a=11, 33) # SyntaxError: positional argument follows keyword argument # func1(10, 20, b=30) # TypeError: func1() got multiple values for argument 'b' print('===================参数默认值=================') # 2. 参数默认值(形参) """ 声明函数的时候,可以通过'参数名=值'的形式给参数默认值; 有默认值的参数在调用的时候可以不传参 关键参数的使用场景: 想要跳过前面有默认值的参数直接给后面参数赋值的时候,必须使用关键字参数 注意: 有默认值的参数必须放在没有默认值参数的后面 """ # 给所有的参数赋默认值 def func2(a=1, b=2, c=3): # a=10, b=20 print('a:{},b:{},c:{}'.format(a, b, c)) print("====================") func2() func2(10) func2(10, 20) func2(b=200) def func3(a, b, c=3): print('a:{},b:{},c:{}'.format(a, b, c)) # 3. 参数类型说明 """ 1)给参数赋默认值 2)形参: 类型名 3)返回值类型说明 -> 类型 """ def func4(z: list, y: str, x=10) -> str: """ 功能; x -> int z是列表 :param x: :return: """ # z.append(10) print(z) # func4('abc', 100) # 4.不定长参数 """ 声明函数的时候,参数个数不确定(不定长参数) 1)声明函数的时候在参数名前加*, 这个参数就会变成一个元组,元组中的元素就是对应的多个实参 注意: a.调用的时候只能使用位置参数 b.不定长参数后面如果有其他的定长参数,那么它后面的其他参数必须使用关键字参数传参 2)声明函数的时候在参数名前加**, 这个参数就会变成字典,字典中的元素-> 关键字:实参值 注意: a.调用的时候只能使用关键字参数 b. *和**同时使用时这个函数参数个数不确定,只能可以同时使用位置参数和关键参数;写的时候*要在**的前面 """ print('=================加*===================') # 写一个函数,求多个数的和 def yt_sum(*x): sum1 = 0 for num in x: sum1 += num print(sum1) yt_sum() yt_sum(10) yt_sum(10, 20) yt_sum(1, 2, 3) yt_sum(1, 23, 4, 5, 6, 7, 8) def func5(name, *scores, gender): print(name, scores, gender) # gender必须使用关键字参数 func5('余婷', gender='男') func5('余婷', 29, 90, 89, 78, gender='女') print('===================加**=================') def func6(**x): print(x) func6(x=100) func6(a=1, b=2) func6(a=10, b=3, x=20, y=100) print('=================同时使用*和**==================') def func7(*args, **kwargs): print(args) print(kwargs) func7() func7(1, 2) func7(a=10, b=20, c=30) func7(12, a=10)
"""__author__=余婷""" from socket import socket from threading import Thread class ConnectionThread(Thread): def __init__(self, connection: socket, address): super().__init__() self.connection = connection self.address = address def run(self): # 实现和一个客户端不断聊天的效果 while True: re_message = (self.connection.recv(1024)).decode(encoding='utf-8') print('%s:%s'%(self.address[0], re_message)) self.connection.send('我是余婷!'.encode()) server = socket() server.bind(('10.7.156.58', 8086)) server.listen(512) while True: print('监听....') connection, address = server.accept() t1 = ConnectionThread(connection, address) t1.start()
"""__author__=桃花寓酒寓美人""" # 1.什么是生成器 """ 生成器就是迭代器中的一种 - 但它是自己生产数据(当程序需要它才会产生数据,之间是没有数据) 生成器作为容器它保存的不是数据,而是产生数据的算法 """ # **2.怎么创建生成器 """ 调用带有yield的关键字的函数,就可以得到一个生成器(只有一种创建方式) **注意:函数只要存在关键字yield无论yield在何方,这个函数都是一个生成器 """ def func1(): print('====') print('++++') yield re = func1() # 生成器 print(re) # <generator object func1 at 0x000001F36244D448> # 3.生成器怎么产生数据(怎么确定生成器中的元素) """ 生成器能产生数据和类型,看执行完成生成器会遇到几次yield 遇到几次yield就可以产生多个数据,每次遇到,yield,yield后面的数据就是产生的元素 """ def func2(): yield 10 yield 100 yield 1000 gen1 = func2() for x in gen1: print('x:', x) # 4.生成器产生数据的规律 """ 生成器对应的函数执行条件,当生成器遇到程序 第一次索要数据的指令时,生成器会执行函数找到第一个yield 并在此函数停止并记录位置,将数据传出 第二次程序索要数据时,生成器在上一次停止位置继续向下运行, 找到下一份yield停止函数,记录位置,将数据传出 ... 直到程序再次索要数据,生成器函数向下再也找不到yield时,程序报错StopIteration """ # 例子:YYYYYYYYYYYYYYY def func3(n): for _ in range(n): yield 100 gen3 = func3(4) next(gen3) for x in gen3: print('x:', x) def func4(n): for x in range(1, n+1): yield x*x gen4 = func4(4) print(next(gen4)) # 练习:写一个生成器,能后产生一个班所有学生的学号,班级人数自己定 def student_number(pre: str, n): length = len(str(n)) for x in range(1, n+1): yield pre + str(x).zfill(length) gen = student_number('python1906', 100) for x in gen: print('student_number:', x)
"""__author__=桃花寓酒寓美人""" # 内置类属性 - 声明类的时候系统提供的属性 class Dog: """狗类""" num = 100 # __slots__是用来约束当前类最多能够拥有的对象属性 # __slots__ = ('name', 'age', 'gender', 'height') # 约束对象属性的范围 def __init__(self, name, age=4, gender='公狗'): self.name = name self.age = age self.gender = gender def func1(self): print('对象方法', self.name) @classmethod def func2(cls): print('类方法') @staticmethod def func3(): print('静态方法') dog1 = Dog('大黄') # 1. 类.__name__ - 获取类的名字 print(Dog) print('类名:', Dog.__name__) # 2. 对象.__class__ - 获取对象对应的类(和type(对象)功能一样) print(type(dog1)) print('对象的类名:', dog1.__class__) # 3. 类.__doc__ - 获取类的说明文档 print('类的说明文档:', dog1.__doc__) print(int.__doc__) # 4. __dict__ # 类.__dict__ - 获取类中所有的字段和字段对应的值,以字典的形式返回 print(Dog.__dict__) # (重要!)对象.__dict__ - 获取对象所有的属性和对应的值,以字典的形式返回 # 注意:如果设置了__slots__,对象的__dict__,那对象.__dict__就不能用 print(dog1.__dict__) # 5.类.__module__ - 获取类所在的模块 print(Dog.__module__) print(int.__module__) # 6. 类.__bases__ - 获取当前类的父类 # object是python的基类 print(Dog.__bases__)
"""__author__=桃花寓酒寓美人""" import time # 1.什么是装饰器 """ 装饰器本质是一个函数 = 返回值高阶函数+实参高阶函数+糖语法 装饰器是python的三大神器之一:装饰器、迭代器、生成器 作用:给已经写好的函数添加新的功能 """ # 给函数添加一个功能:统计函数的执行时间 # 方法一:在每个需要添加功能的函数中加入相应代码 def yt_sum(x, y): start = time.time() # 获取当前时间 sum1 = x + y print(sum1) end = time.time() print('函数执行时间:%fs' % (end - start)) yt_sum(100, 200) def factoeial(n): start = time.time() sum1 = 1 for num in range(1, n+1): sum1 *= num print('%d的阶乘是:%d' % (n, sum1)) # 方法二:注意:这个add_time只能给没有参数的函数添加统计执行时间的功能 def add_time(fn): start = time.time() fn() end = time.time() print('函数执行时间:%fs' % (end - start)) def add_time2(fn, *args, **kwargs): start = time.time() fn(*args, **kwargs) end = time.time() print('函数执行时间:%fs' % (end - start)) def func1(): print('===========') print('+++++++++++') def func2(): print('asdfasdf!') print('asdaafasdfsadfasdfasdfasdf') add_time(func1) add_time(func2) print('============装饰器============') # 2.装饰器 """ 无参装饰器的函数: def 函数名1(参数1): def函数名2(*args, **kwargs): 参数1(*args, **kwargs) 新功能对应的代码段 return 函数名2 说明: 函数名1 - 装饰器的名字;一般根据需要添加的功能命名 参数1 - 需要添加功能的函数, 一般为fn 函数名2 - 随便命名,可以用test """ # 添加统计函数执行时间的装饰器对应的函数 def add_time3(fn): def test(*args, **kwargs): start = time.time() fn(*args, **kwargs) end = time.time() print('函数执行时间:%fs' % (end - start)) return test @add_time3 def func5(x, y): print('start %d') print(x+y) func5(19, 129) # 练习:给所有的返回值是整数的函数添加功能:返回值以16进制形式的数据返回 def add_hex(fn): def test(*args, **kwargs): re = fn(*args, **kwargs) # if type(re) == int: # 判断re是否是整型 if isinstance(re, int): return hex(re) return re return test @add_hex def yt_sum(x, y): return x+y print(yt_sum(1, 2))
"""__author__=桃花寓酒寓美人""" # 1.变量可以作为函数的返回值 def yt_sum(x, y): t = x+y return t yt_sum(10, 20) # 函数可以作为函数的返回值 - 返回值高阶函数 # func1就是一个返回值高阶函数 def func1(): def func2(): print('function2') return func2 print(func1()) print('=====================') print(func1()()) # 2.闭包 - 函数1中声明了一个函数2,并且在函数2中使用了函数1的数据,那么这个函数1就是一个闭包 # 作用(特点):闭包函数中的数据不会因为函数调用结束而销毁 def func3(): a = 10 def func4(): print(a) return func4 print(' ====================================================bi bao') t = func3() print(' ====================================================bi bao') t() # a 没有销毁 # 练习1:python中声明函数不会执行函数体 list1 = [] for i in range(5): list1.append(lambda x: x*i) print(list1[1](2), list1[2](2), list1[3](2)) # 练习2: def func2(seq=[]): seq.append(10) return seq func2() print(func2()) print(func2([1, 2])) print(func2())
"""Draw module for X's and O's This module is able to draw an X's and O's game board or series of moves that comprise a game. The module is specifically intended to be run in a Google Colab notebook and requires that `ColabTurtle` be installed within the notebook environment. This can be installed using the following command: ```!pip3 install ColabTurtle``` This module and contains the following functions: * drawNewBoards - initializes and draws a new blank game board * drawMarker - draws an X or O marker in a position on a game board * drawBoard - draws a complete game board as passed in as a 2D representation * drawGame - draws a complete game board as passed in as a sequence of moves """ from ColabTurtle.Turtle import * import math _BOARDSIZE = 180 _X_COLOUR = 'red' _Y_COLOUR = 'green' def drawNewBoard(size=180, colour='white', margin=30): """Draws a new empty game board Parameters ---------- size : int The size in pixels of one side of the square game board colour : str The colour of the game board margin : int The size of the margin around the board in pixels Returns ------- None """ # Calculate parameters used in this method cellSize = math.floor(size / 3) boardSize = (cellSize * 3, cellSize * 3) canvasSize = (size + (2 * margin), size + (2 * margin)) # Create a new turtle session and clear the canvas initializeTurtle(10, canvasSize) hideturtle() color(colour) # Draw the left vertical line penup() goto(margin + cellSize, margin) pendown() goto(margin + cellSize, margin + boardSize[1]) # Draw the right vertical line penup() goto(margin + boardSize[0] - cellSize, margin) pendown() goto(margin + boardSize[0] - cellSize, margin + boardSize[1]) # Draw the upper horizontal line penup() goto(margin, margin + cellSize) pendown() goto(margin + boardSize[0], margin + cellSize) # Draw the lower horizontal line penup() goto(margin, margin + boardSize[1] - cellSize) pendown() goto(margin + boardSize[0], margin + boardSize[1] - cellSize) def drawMarker(team = 'X', pos = (1,1), size=180, colour='white', margin=30) : """Draws an X or O marker on a game board Parameters ---------- team : string Either 'X' or 'O' pos : tuple Position on the game board (row, col) size : int Size of one side of the square game board colour : str The colour of the marker margin : int The size of the margin around the board in pixels Returns ------- None """ # Calculate parameters used in this method cellSize = math.floor(size / 3) boardSize = (cellSize * 3, cellSize * 3) canvasSize = (size + (2 * margin), size + (2 * margin)) # Calculate offset parameters used to position X's and O's x_offset = math.floor(cellSize * 0.2) o_offset_horizontal = math.floor(cellSize * 0.2) o_offset_vertical = math.floor(cellSize / 2) # Set the drawing parameters hideturtle() color(colour) # Draw instructions for an O if (team.lower() == 'o') : penup() # Go to the start position for drawing the marker goto(margin + (cellSize * pos[1]) + o_offset_horizontal, margin + (cellSize * pos[0]) + o_offset_vertical) pendown() # Draw the O scaled based on the size of the board steps = math.floor(1.4 * cellSize) - (o_offset_horizontal * 2) step_len = 2 for s in range(steps) : for ss in range(step_len) : right(360 / (steps * step_len)) forward(math.floor(1)) # Draw instructions for an X elif (team.lower() == 'x') : # Draw the first line of the X (top-left to bottom-right) penup() goto(margin + (cellSize * pos[1]) + x_offset, margin + (cellSize * pos[0]) + x_offset) pendown() goto(margin + (cellSize * pos[1]) + (cellSize - x_offset), margin + (cellSize * pos[0]) + (cellSize - x_offset)) # Draw the second line of the X (top-right to bottom-left) penup() goto(margin + (cellSize * pos[1]) + (cellSize - x_offset), margin + (cellSize * pos[0]) + x_offset) pendown() goto(margin + (cellSize * pos[1]) + x_offset, margin + (cellSize * pos[0]) + (cellSize - x_offset)) def drawWin(startPos = (0,0), endPos = (2,2), size=180, colour='yellow', margin=30) : """Draws an win line on a game board Parameters ---------- startPos : tuple Start position of win line on the game board (row, col) endPos : tuple End position of win line on the game board (row, col) size : int Size of one side of the square game board colour : str The colour of the win line margin : int The size of the margin around the board in pixels Returns ------- None """ # Calculate parameters used in this method cellSize = math.floor(size / 3) boardSize = (cellSize * 3, cellSize * 3) canvasSize = (size + (2 * margin), size + (2 * margin)) # Calculate offset parameter used to position the win line offset = math.floor(cellSize / 2) # Set the drawing parameters hideturtle() color(colour) # Draw instructions # Go to the start position for drawing the marker penup() goto(margin + (cellSize * startPos[1]) + offset, margin + (cellSize * startPos[0]) + offset) # Draw win line pendown() goto(margin + (cellSize * endPos[1]) + offset, margin + (cellSize * endPos[0]) + offset) def drawBoard(board = [], size=180, board_colour='white', xy_colour={'X':'red', 'O':'green', '':'white'}, margin=30, newBoard = False) : """Draws an entire game board Parameters ---------- board : 2D array [3][3] array of 'X', 'O' or '' representing the game board size : int Size of one side of the square game board board_colour : str The colour of the game board xy_colour : dict Dictionary of markers to colours they should be displayed in margin : int The size of the margin around the board in pixels newBoard : bool Set to true if a new board should be drawn Returns ------- None """ # If en empty board is passed or newBoard is true, draw a new board. if ((len(board) == 0) or newBoard) : drawNewBoard(size=size, colour=board_colour, margin=margin) # If the board is not a 2D array, return if (len(board) < 1) : return if (len(board[0]) < 1) : return # Iterate through the board array and draw the markers in their cells for i in range(len(board) * len(board[0])) : row = math.floor(i / len(board)) col = i % len(board) team = board[row][col] drawMarker(team, (row, col), size, xy_colour[team], margin) #print('[' + str(row) + '][' + str(col) + ']: ' + team) def drawGame(game=[], numMoves=1, size=180, board_colour='white', xy_colour={'X':'red', 'O':'green', '':'white'}, margin=30, newBoard = False) : """Draws an entire game board based on a list of positions Parameters ---------- game : array sequence of tuples of (row, col, team) each representing a sigle move made by one team numMoves : int How many moves to draw, starting from the most recent. Use -1 to indicate all moves. size : int Size of one side of the square game board board_colour : str The colour of the game board xy_colour : dict Dictionary of markers to colours they should be displayed in margin : int The size of the margin around the board in pixels newBoard : bool Set to true if a new board should be drawn Returns ------- None """ # If the game array is empty or newBoard is True, draw a new board. if ((len(game) < 1) or newBoard) : drawNewBoard(size=size, colour=board_colour, margin=margin) # Calculate the indices of the first and last moves to draw firstMove = len(game) - numMoves if (numMoves < 1) : firstMove = 0 lastMove = len(game) # Iterate through the sequence of game moves and draw them in order for i in range(firstMove,lastMove) : row = game[i][0] col = game[i][1] team = game[i][2] drawMarker(team, (row, col), size, xy_colour[team], margin) #print('[' + str(row) + '][' + str(col) + ']: ' + team)
import math # Solution to Project Euler problem 20 result = 0 number = str(math.factorial(100)) for character in number: result += int(character) print(result)
size = int(input()) time = int(input()) for row in range(0, size - 1): if time == 0: if row % 2 == 1: print('?' * row + '* ' *(size - row - 1) + '*' + '?' * row) else: print(' ' * row + '* ' * (size - row - 1) + '*' + ' ' * row) elif time == size: if row % 2 == 1: print('?' * row + '- ' *(size - row - 1) + '-' + '?' * row) else: print(' ' * row + '- ' * (size - row - 1) + '-' + ' ' * row) elif row < time: if row % 2 == 1: print('?' * row + '- ' *(size - row - 1) + '-' + '?' * row) else: print(' ' * row + '- ' * (size - row - 1) + '-' + ' ' * row) elif row > time: if row % 2 == 1: print('?' * row + '* ' *(size - row - 1) + '*' + '?' * row) else: print(' ' * row + '* ' * (size - row - 1) + '*' + ' ' * row) if size % 2 == 0: print('?' * (size - 1) + 'o' + '?' * (size - 1)) for row in range(2, size): if time == 0: if row % 2 == 0: print(' ' * row + '- ' * (size - row - 1) + '-' + ' ' * row) else: print('?' * (size - row - 1) + '- ' * (size - row - 1) + '-' + '?' * (size - row - 1)) elif time == size: if row % 2 == 1: print('?' * row + '- ' * (size - row - 1) + '-' + '?' * row) else: print(' ' * row + '- ' * (size - row - 1) + '-' + ' ' * row) elif row < time: if row % 2 == 1: print('?' * row + '- ' * (size - row - 1) + '-' + '?' * row) else: print(' ' * row + '- ' * (size - row - 1) + '-' + ' ' * row) elif row > time: if row % 2 == 1: print('?' * row + '* ' * (size - row - 1) + '*' + '?' * row) else: print(' ' * row + '* ' * (size - row - 1) + '*' + ' ' * row) else: print(' ' * (size - 1) + 'o' + ' ' * (size - 1))
a = int(input()) tens = '' ones = '' if a == 100: print('one hundred') else: if a <= 20: if a == 1: print('one') elif a == 0: print('zero') elif a == 2: print('two') elif a == 3: print('three') elif a == 4: print('four') elif a == 5: print('five') elif a == 6: print('six') elif a == 7: print('seven') elif a == 8: print('eight') elif a == 9: print('nine') elif a == 10: print('ten') elif a == 11: print('eleven') elif a == 12: print('twelve') elif a == 13: print('thirteen') elif a == 14: print('fourteen') elif a == 15: print('fifteen') elif a == 16: print('sixteen') elif a == 17: print('seventeen') elif a == 8: print('eighteen') elif a == 9: print('nineteen') elif a == 20: print('twenty') else: b = a % 10 c = a // 10 if c == 2: tens = 'twenty' elif c == 3: tens = 'thirty' elif c == 4: tens = 'forty' elif c == 5: tens = 'fifty' elif c == 6: tens = 'sixty' elif c == 7: tens = 'seventy' elif c == 8: tens = 'eighty' elif c == 9: tens = 'ninety' if b == 1: ones = 'one' elif b == 2: ones = 'two' elif b == 3: ones = 'three' elif b == 4: ones = 'four' elif b == 5: ones = 'five' elif b == 6: ones = 'six' elif b == 7: ones = 'seven' elif b == 8: ones = 'eight' elif b == 9: ones = 'nine' print(str(tens) + ' ' + str(ones))
import math r = float(input()) perimeter = 2 * math.pi * r area = math.pi * r * r print(area) print(perimeter)
n = int(input()) type = input() if n < 100: if n >= 20: print(0.09 * n) else: if type == 'day': print(0.7 + 0.79 * n) elif type == 'night': print(0.7 + 0.9 * n) else: print(0.06 * n)
size = int(input()) time = int(input()) for row in range(0, size): if row == size - 1 and row % 2 == 0: print('?' * (size -1) + 'o' + '?' * (size - 1)) if row == size - 1 and row % 2 == 1: print(' ' * (size -1) + 'o' + ' ' * (size - 1)) if time == 0: if row % 2 == 0: print('* ' * (size - 1) + '*') else: print('?' * row + '* ' * (size - row - 1) + '*' + '?' * row)
# To use print function from Python 3 in Python2 # from __future__ import print_function # String word print("hello world") print('this is a string') # this code will get error # print('I'm a string') print("i'm a string") print('"this is a quote"') print('Here is a new line \n and here is the second line') print('Here is a new tab \t and here is the second line') print(len("Hello World")) s = "Hello World" print(s) # indexing # in python index starting on 0 print(s[0]) print(s[1]) # Slicing a string print(s[1:]) # ello World print(s[:5]) # Hello print(s[1:4]) # ell print(s[-1]) # d print(s[:-1]) # Hello Worl # Grab Everything Step size 1 print(s[::1]) # Hello World # Grab Everything Step size 2 print(s[::2]) # HloWrd # Grab Everything reverse Step size 1 print(s[::-1]) # dlroW olleH print(s) # String Properties # String Properties Knows as "immutabillity" # Once a string is created the elements within it can't change or replace # s[0] = 'x' # TypeError:'str' object does not support item assignment # but you can concatenate / adding new string together s = s + " concatenate me!" print(s) letter = 'za' print(letter * 10) # zazazazazazazazazaza s = "Hello python" print(s.upper()) # HELLO PYTHON print(s.capitalize()) # Hello python print(s.lower()) # hello python # Split a string by blank space (this is the default) print(s.split()) # ['Hello', 'python'] # Split by a specific element (doesn't include the element that was split on) print(s.split('o')) # ['Hell', ' pyth', 'n']
x = 0 # while x < 10: # print("x i currently!", x) # x += 1 # while x < 10: # print("x i currently!", x) # x += 1 # else: # print("all done") #break continue pass # while x < 10: # print('x is currently: ', x) # print('x is still less then 10, adding 1 to x') # x +=1 # # if x==3: # print("hey x equals 3!") # else: # print('contuning...') # continue # infinite loop while True: print('infinite')
# for x in range(21): # print(type(x), x) start = 0 stop = 20 stepSize = 2 for x in range(start, stop, stepSize): print(x)
import random # Problem 1 def gensqares(N): for i in range(N): yield i ** 2 for x in gensqares(10): print(x) # Problem 2 print(random.randint(1, 10)) def rand_num(low, high, n): for i in range(n): yield random.randint(low, high) for num in rand_num(1, 10, 12): print(num) # Problem 3 s = 'hello' s = iter(s) print(next(s)) # Problem 4 my_list = [1, 2, 3, 4, 5] gencomp = (item for item in my_list if item > 3) for item in gencomp: print(item)
from collections import namedtuple t = (1,2,3) print(type(t)) print(t[1]) Dog = namedtuple('Dog', 'age breed name') sam = Dog(age=2, breed='lab', name='sammy') print(sam.age) print(sam.breed) print(sam.name) print(sam[0]) print(sam[1]) Cat = namedtuple('Cat', 'fur claws name') c = Cat(fur= 'Fuzzy', claws=False, name='kitty') print(c) print(type(c))
# l = [1, 2, 3] # print(l) # print(len(l)) class Book(object): def __init__(self, title, author, pages): print("A book is created") self.title = title self.author = author self.pages = pages def __str__(self): return "Title:%s, author:%s , pages:%s " %(self.title, self.author, self.pages) def __len__(self): return self.pages # def __del__(self): # print("A book is destroyed") b = Book('Python', 'Raihan', 100) print(len(b)) print(b) # del b print(b.title)
def make_advanced_counter_maker(): """Makes a function that makes counters that understands the messages "count", "global-count", "reset", and "global-reset". See the examples below: >>> make_counter = make_advanced_counter_maker() >>> tom_counter = make_counter() >>> tom_counter('count') 1 >>> tom_counter('count') 2 >>> tom_counter('global-count') 1 >>> jon_counter = make_counter() >>> jon_counter('global-count') 2 >>> jon_counter('count') 1 >>> jon_counter('reset') >>> jon_counter('count') 1 >>> tom_counter('count') 3 >>> jon_counter('global-count') 3 >>> jon_counter('global-reset') >>> tom_counter('global-count') 1 """ "*** YOUR CODE HERE ***" global_count = 0 def make_counter(): count=0 def person_counter(x): nonlocal global_count, count if x=='count': count+=1 print(count) elif x=='global-count': global_count+=1 print(global_count) elif x=='reset': count=0 elif x=='global-reset': global_count=0 return person_counter return make_counter def trade(first, second): """Exchange the smallest prefixes of first and second that have equal sum. >>> a = [1, 1, 3, 2, 1, 1, 4] >>> b = [4, 3, 2, 7] >>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7 'Deal!' >>> a [4, 3, 1, 1, 4] >>> b [1, 1, 3, 2, 2, 7] >>> c = [3, 3, 2, 4, 1] >>> trade(b, c) 'No deal!' >>> b [1, 1, 3, 2, 2, 7] >>> c [3, 3, 2, 4, 1] >>> trade(a, c) 'Deal!' >>> a [3, 3, 2, 1, 4] >>> b [1, 1, 3, 2, 2, 7] >>> c [4, 3, 1, 4, 1] """ m, n = 1, 1 "*** YOUR CODE HERE ***" sum1, sum2=first[0], second[0] while sum1 != sum2 and (m<len(first) or n<len(second)): if sum1<sum2 and m<len(first): sum1+=first[m] m+=1 elif sum1>sum2 and n<len(second): sum2+=second[n] n+=1 elif sum1<sum2 and m>=len(first): m, n=len(first), len(second) elif sum1>sum2 and n>=len(second): m, n=len(first), len(second) if sum1==sum2: first[:m], second[:n] = second[:n], first[:m] return 'Deal!' else: return 'No deal!' def boom(n): sum = 0 a, b = 1, 1 while a <= n*n: while b <= n*n: sum += (a*b) b += 1 b = 0 a += 1 return sum
#Himma, Nyasia, Sophie from tkinter import * import random num = 0 root = Tk() names= ['Himma' ,'Nyasia' ,'Logan' ,'Jonah', 'Aidan','Alex' ,'Nyeema' ,'Zoe','Justin' ,'Phillip','Matthew' ,'Andrew' ,'Sophie' ,'Jack','Ian','Henry' ,'Angelina' ] random.shuffle(names) def pairs(): global num for i in range (num): members= names.pop() print(members) print("\n") def get_item_values(): global num num=int(generator.get()) generator= Spinbox(root, from_=1, to=9, width= 30, command= lambda :(get_item_values())) generator.pack() m= Button(root, text="click me to create", width=30, command= lambda : (pairs())) m.pack() root.mainloop()
from abc import abstractmethod import pygame import os import json import logging from typing import List import random class ImageDrawable: """ an abstract class, for all Drawable surfaces/images that Can been drawn on the window surface """ def __init__(self, x: int, y: int, image_path: str, vel: int, win_size: (int, int)): """ :param x: x position :param y: y position :param image_path: path to image :param vel: velocity of image :param win_size: size of the window surface (width, height) """ try: self.img = pygame.image.load(image_path) except pygame.error as e: logging.error(e) raise self.x = x self.y = y self.win_width, self.win_height = win_size self.vel = vel @abstractmethod def draw(self, window: pygame.Surface) -> None: """ drawing on window surface :param window: window surface (which will be drawn on) :return: None """ pass @abstractmethod def move(self) -> None: """ move the image according to its velocity :return: None """ pass class Parachute(ImageDrawable): def __init__(self, x: int, y: int, image_path: str, vel: int, win_size: (int, int), callback): """ :param x: x position :param y: y position :param image_path: path to image location :param vel: velocity :param win_size: size of window :param callback: callback method, when parachute fall off the screen, callback to para_fall """ super().__init__(x, y, image_path, vel, win_size) # hit box: for collision detection, at the bottom of image self.hit_box = pygame.Rect(self.x, self.y + self.img.get_width() - 10, self.img.get_width(), 10) self.para_fall = callback def move(self): self.y += self.vel self.hit_box = pygame.Rect(self.x, self.y + self.img.get_width() - 10, self.img.get_width(), 10) # checks if parachute is out of window if self.y > self.win_height: self.para_fall(self) def draw(self, window: pygame.Surface): window.blit(self.img, (self.x, self.y)) # pygame.draw.rect(window, (255, 0, 0), self.hit_box, 2) class Airplane(ImageDrawable): def __init__(self, x: int, y: int, image_path: str, vel: int, win_size: (int, int), callback): """ :param x: x position :param y: y position :param image_path: path to image location (Already as string) :param vel: velocity :param win_size: window size (width , height) :param callback: function, add_parachute to para_list """ super().__init__(x, y, image_path, vel, win_size) # this image is too small and flipped, therefor: self.img = pygame.transform.flip(pygame.transform.scale2x(self.img), True, False) self.add_parachute = callback # choose random x for dropping the parachute self.drop_parachute_x = random.randint(0 + self.img.get_width(), self.win_width - self.img.get_width()) self.isDropped = False # ensures only one fall on each new track def move(self): self.x -= self.vel if self.x <= self.drop_parachute_x and not self.isDropped: self.add_parachute(self.x, self.y) # add new para to list self.isDropped = True # and only one! if self.x < -self.img.get_width(): # airplane is out of screen, make it start again from the right self.x = self.win_width self.isDropped = False # dont forget to drop new parachute # get new drop x self.drop_parachute_x = random.randint(0 + self.img.get_width(), self.win_width - self.img.get_width()) def draw(self, window: pygame.Surface): window.blit(self.img, (self.x, self.y)) class Player(ImageDrawable): def __init__(self, x, y, image_path: str, vel: int, win_size: (int, int)): super().__init__(x, y, image_path, vel, win_size) # player should be at the bottom of the screen and centered self.x = (self.win_width - self.img.get_width()) // 2 self.y = self.win_height - self.img.get_height() # hit box for collide detection self.hit_box = pygame.Rect(self.x, self.y + round(self.img.get_height() * 0.67), self.img.get_width(), 20) def move(self): """ player can move base on pressed arrow keys (left, right) :return: None """ keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and self.x > self.vel: self.x -= self.vel if keys[pygame.K_RIGHT] and self.x < self.win_width - self.vel - self.img.get_width(): self.x += self.vel self.hit_box = pygame.Rect(self.x, self.y + round(self.img.get_height() * 0.67), self.img.get_width(), 20) def draw(self, window: pygame.Surface): window.blit(self.img, (self.x, self.y)) class Base(ImageDrawable): def __init__(self, x: int, y: int, image_path: str, vel: int, win_size: (int, int)): super().__init__(x, y, image_path, vel, win_size) # for animation, takes same image twice, and move them together. # when one image gets out of screen, get that image to starting position self.img1 = self.img self.img2 = pygame.transform.flip(self.img1, True, False) self.x1 = x self.x2 = self.img.get_width() def move(self): """ move background (make sure to replace img position when img is out of frame) :return: None """ self.x1 += self.vel self.x2 += self.vel if self.x1 > self.img.get_width(): self.x1 = self.x2 - self.img.get_width() if self.x2 > self.img.get_width(): self.x2 = self.x1 - self.img.get_width() def draw(self, window): window.blit(self.img1, (self.x1, self.y)) window.blit(self.img2, (self.x2, self.y)) class GameLogic: """ contains the logic of the game: status (update live & score) initialize all the components of game (player, parachutes, airplane..) keeps track of lives - for updating end of game and more """ def __init__(self, window: pygame.Surface): self.win = window self.score = 0 self.lives = cfg_logic["lives"] self.images = list() self.PAUSE: bool = False self.END_GAME: bool = False # parachutes list self.para_list: List[Parachute] = list() # player self.player = None def init(self) -> None: """ init all images, and append to list - for iterate later when moving and drawing notice: the parachute list is NOT added, because its not ImageDrawable - it is a List of ImageDrawable :return: None """ # init background: (can write it in one long line - but I prefer make it more readable x = cfg_bg["x"] y = cfg_bg["y"] path = os.path.join(*cfg_bg["path"]) # path is list.. vel = cfg_bg["vel"] # add background to images for moving and drawing self.images.append(Base(x, y, path, vel, self.win.get_size())) # init airplane: (can write it in one long line - but I prefer make it more readable x = self.win.get_width() # should start at the right side (x-axis) of window y = 0 # top of window (y-axis) path = os.path.join(*cfg_airplane["path"]) vel = cfg_airplane["vel"] # add airplane to images for moving and drawing self.images.append(Airplane(x, y, path, vel, self.win.get_size(), callback=self.add_para)) # init player: (can write it in one long line - but I prefer make it more readable # player will start at the middle of window, but its depends of img size! # so, I'll defined the position inside the constructor x = -1 # redefined inside the constructor y = -1 # redefined inside the constructor path = os.path.join(*cfg_player["path"]) vel = cfg_player["vel"] # add airplane to images for moving and drawing self.player = Player(x, y, path, vel, self.win.get_size()) self.images.append(self.player) def move_all(self) -> None: """ moving all images. step 1: all images in images list step 2: all parachutes in parachute list :return: None """ # moving all images except parachutes for img in self.images: img.move() # moving parachutes images for para in self.para_list: para.move() def draw_game(self) -> None: """ drawing window, with all images step 1: all images in images list step 2: all parachutes in parachute list :return: None """ # background: self.win.fill(pygame.Color(cfg_style["bg_color"])) # score font = pygame.font.SysFont(cfg_style["font"], cfg_style["font_bar_size"], bold=True) score = font.render('score: {}'.format(self.score), 1, pygame.Color(cfg_style["font_bar_color"])) # self.win.blit(score, (cfg_style["bar_x"], cfg_style["bar_y"])) self.win.blit(score, (0, 0)) # lives: lives = font.render('lives: {}'.format(self.lives), 1, (0, 0, 0)) self.win.blit(lives, (self.win.get_width() - lives.get_width(), 0)) # images (without parachutes) for img in self.images: img.draw(self.win) # parachutes images for para in self.para_list: para.draw(self.win) pygame.display.update() def draw_pause(self): font = pygame.font.SysFont(cfg_style["font"], cfg_style["font_info_size"]) text = font.render('Paused', 1, pygame.Color(cfg_style["font_info_color"])) # pose at mid of the window x = (self.win.get_width() - text.get_width()) // 2 y = (self.win.get_height() - text.get_height()) // 2 self.win.blit(text, (x, y)) pygame.display.update() def draw_end(self): font = pygame.font.SysFont(cfg_style["font"], cfg_style["font_info_size"]) text = font.render('Score {}'.format(self.score), 1, pygame.Color(cfg_style["font_info_color"])) # pose at mid of the window x = (self.win.get_width() - text.get_width()) // 2 y = (self.win.get_height() - text.get_height()) // 2 self.win.blit(text, (x, y)) pygame.display.update() def game_status(self) -> None: """ check the game status i.e: collisions, end o game. :return: None """ # check end Game (3 strikes) if self.lives <= 0: self.END_GAME = True # check for collisions for para in self.para_list: if self.player.hit_box.colliderect(para.hit_box): self.para_collide(para) def score_update(self, x: int) -> None: """ literally update score :param x: amount to add :return: None """ self.score += x def pause_update(self): self.PAUSE = not self.PAUSE def add_para(self, x: int, y: int) -> None: """ append new parachute to para_list at x,y :param x: x position :param y: y position :return: None """ para = Parachute(x, y, os.path.join(*cfg_para["path"]), cfg_para["vel"], self.win.get_size(), callback=self.para_fall) self.para_list.append(para) def para_fall(self, para: Parachute) -> None: """ when para fall out of screen, remove from para_list, and subtract 1 from lives :param para: parachute to remove :return: None """ self.lives -= 1 self.para_list.remove(para) def para_collide(self, para: Parachute) -> None: """ when parachute collide with player: remove the parachute and add 10 points :param para: :return: None """ self.score_update(cfg_logic["score_update"]) # TODO: magic number - change! self.para_list.remove(para) def game_loop(win, clock, fps): game = GameLogic(win) game.init() # initialize all components for game while True: clock.tick(fps) for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): return if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and not game.END_GAME: game.pause_update() if game.END_GAME: game.draw_end() elif game.PAUSE: game.draw_pause() else: game.move_all() game.draw_game() # check game logic status (update score, update life, remove finished parachutes, check collisions) game.game_status() def draw_pre_game(win: pygame.Surface): font1 = pygame.font.SysFont(cfg_style["font"], 100) font2 = pygame.font.SysFont(cfg_style["font"], 75) font3 = pygame.font.SysFont(cfg_style["font"], 50) cur_y = 0 win.fill((0, 0, 0)) text1 = font1.render('Catch The Penguin', 1, pygame.Color(cfg_style["font_info_color"])) x = (win.get_width() - text1.get_width()) // 2 win.blit(text1, (x, 0)) cur_y += text1.get_height() text = font2.render('KEYS:', 1, pygame.Color(cfg_style["font_info_color"])) x = win.get_width() // 8 win.blit(text, (x, cur_y + text.get_height())) cur_y += text.get_height() * 2 text = font3.render('Press right/left Arrow to move', 1, pygame.Color(cfg_style["font_info_color"])) win.blit(text, (x, cur_y)) cur_y += text.get_height() text = font3.render('Press SPACE to Pause', 1, pygame.Color(cfg_style["font_info_color"])) win.blit(text, (x, cur_y)) cur_y += text.get_height() text = font3.render('Press ESC to Quit', 1, pygame.Color(cfg_style["font_info_color"])) win.blit(text, (x, cur_y)) cur_y += text.get_height() text1 = font2.render('Press SPACE to continue', 1, pygame.Color(cfg_style["font_info_color"])) x = (win.get_width() - text1.get_width()) // 2 win.blit(text1, (x, win.get_height() - text1.get_height())) pygame.display.update() def pre_game_loop(win, clock, fps, callback): while True: clock.tick(fps) for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): return if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: return callback(win, clock, fps) draw_pre_game(win) def main() -> None: """ Responsible for game loops :return: None """ fps = cfg_win["clock"] # frames per second (for making the game animated better) win = pygame.display.set_mode((cfg_win["width"], cfg_win["height"])) # creates window pygame.display.set_caption(cfg_win["caption"]) clock = pygame.time.Clock() # start pre game loop, and if needed start game loop (if player pressed Space) pre_game_loop(win, clock, fps, game_loop) pygame.quit() if __name__ == '__main__': logging.basicConfig(filename='basic.log', level=logging.DEBUG, format='%(asctime)s: %(levelname)s: %(message)s') try: cfg = json.load(open('config.json')) cfg_win = cfg["window"] cfg_logic = cfg["gameLogic"] cfg_player = cfg["player"] cfg_bg = cfg["background"] cfg_airplane = cfg["airplane"] cfg_style = cfg["style"] cfg_para = cfg["parachute"] except OSError: logging.error('config file is missing') raise os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.init() main()
# -*- coding: utf-8 -*- import sys import random def IsCircle(): """ Проверяет попадание точки в радиус круга. Возврат ------- bool Возвращает True если выполняется условие, иначе - False. """ x = random.random() y = random.random() return ((x * x + y * y) <= 1) if __name__ == '__main__': a = sys.stdin.read() count=0 for i in range(int(a)): if (IsCircle()): count+=1 print(count)
# Coded by: Miguel Angel Garcia Acosta # Contact: [email protected] # -------------------------- # MATRIX RECURSIVE REPLACER: # -------------------------- # ----- ----- ----- ----- -- # # ----- ----- ----- IMPORTS ----- ----- ----- # import csv # ----- ----- ----- IMPORTS ----- ----- ----- # # # START # # FILE TO READ DATA ==> .CSV FileReader = "filename.csv" # # INITIALIZE ROWS AND COLUMNS Field = [] Rows = [] # # ============================= # READ FILENAME.CSV # with open(FileReader, 'r') as csvfile: # CREATE CSV OBJECT CSV_READER = csv.reader(csvfile) # # GET FIELD NAMES FROM FIRST ROW Field = next(CSV_READER) # # GET DATA FROM ROWS for Row in CSV_READER: Rows.append(Row) # # GET THE TOTAL NUMBER OF ROWS print("Total Rows: %d" % (CSV_READER.line_num)) # # GET THE FIELD NAMES print("FIELD NAMES: " + ','.join(Field for Field in Field)) # # PRINT ROWS print("\nROWS:") for Row in Rows: print(' , '.join(Row for Row in Row)) print("\n") # END
import sqlite3 def createTable(): conn = sqlite3.connect('contacts.db') conn.execute('DROP table IF EXISTS ABC') conn.execute('''CREATE TABLE ABC (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Phone CHAR(50) NOT NULL)''') print ("Table created successfully") conn.commit() conn.close() def updateTable(name, phn, Id): conn = sqlite3.connect('contacts.db') sql = "UPDATE ABC SET Name='"+name+"' ,Phone='"+phn+"' WHERE id="+str(Id) cur = conn.cursor() cur.execute(sql) conn.commit() conn.close() def delFromTable(Id): conn = sqlite3.connect('contacts.db') sql = 'DELETE FROM ABC WHERE id='+ str(Id) cur = conn.cursor() cur.execute(sql) conn.commit() conn.close() def insertInTable(name, phn): conn = sqlite3.connect('contacts.db') sql = ''' INSERT INTO ABC(Name,Phone) VALUES(?,?) ''' cur = conn.cursor() cur.execute(sql, (name, phn)) conn.commit() conn.close() def readFromTable(Id): conn = sqlite3.connect('contacts.db') cur = conn.cursor() sql = "SELECT Name,Phone FROM ABC WHERE Id=" + str(Id) cur.execute(sql) rows = cur.fetchall() conn.close() for row in rows: return(row) def readAllTable(): conn = sqlite3.connect('contacts.db') cur = conn.cursor() cur.execute("SELECT Name,Phone FROM ABC") rows = cur.fetchall() conn.close() r = [list(ele) for ele in rows] return(r) def insertAllInTable(contactlist): conn = sqlite3.connect('contacts.db') sql = ''' INSERT INTO ABC(Name,Phone) VALUES(?,?) ''' cur = conn.cursor() for a in contactlist: cur.execute(sql, (a[0], a[1])) conn.commit() conn.close() def readByName(name): conn = sqlite3.connect('contacts.db') cur = conn.cursor() sql = "SELECT id FROM ABC WHERE Name= '" + name + "'" cur.execute(sql) rows = cur.fetchall() conn.close() for row in rows: return(int(row[0]))
from random import choice def main(): question = input('Ask a question: ') answers = ['Yes!', 'No!', 'Maybe', 'Do not count on it!', 'It\'s certain', 'No way!', 'Maybe'] print(choice(answers)) if __name__ == "__main__": main()
name = input ("What's your name?").strip().title() print ("Hey " + name) other_name = input("What's the other dude's name?") .strip().title() print ("Please tell {} hello for me".format(other_name)) first_age = input ("How old are you {}?".format(name)).strip().title() other_age = input ("And how old is {}?".format(other_name)).strip() first_age = int (first_age) other_age = int (other_age) years_apart = abs(first_age - other_age) days_apart = 365.242 * years_apart print ("You are {} years apart ({} days).".format(years_apart,days_apart))
def merge_sort(alist): if len(alist) <= 1: return alist mid = int(len(alist)/2) left = merge_sort(alist[:mid]) print("left = " + str(left)) right = merge_sort(alist[mid:]) print("right = " + str(right)) return merge_sorted_array(left, right) def merge_sorted_array(alist, blist): ret = [] l = 0 r = 0 while l < len(alist) and r < len(blist): if alist[l] < blist[r]: ret.append(alist[l]) l += 1 else: ret.append(blist[r]) r += 1 ret += alist[l:] ret += blist[r:] return ret unsortedArray = [6, 5, 3, 1, 8, 7, 2, 4] print(merge_sort(unsortedArray))
import heapq def heap_sort(alist): ret = [] while alist: heapq.heapify(alist) ret.append(heapq.heappop(alist)) return ret arr = [4, 7, 8, 9, 1, 5] print(heap_sort(arr))
age = input("how old are you: ") age = int(age) if age <= 18: print("you are a baby!!!") elif age >= 21: print("you can come and you can drink. ") else: print("you can come and you can drink too.")
def problem1(stop): " solved by katayama" sum = 0 for x in range(1, stop): if (x%3==0) or (x%5==0): sum += x return sum def problem2(stop): " solved by miyoshi " a, b = 1, 2 sum = b while True: a, b = b, a+b if b % 2 == 0: sum += b if a+b > stop: break return(sum) def problem3(num): "Solved by: Katsuro" from sympy import factorint return max(factorint(num).keys()) def problem4(digit): """ https://projecteuler.net/problem=4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. >>> problem4(2) 9009 >>> problem4(3) 906609 """ start = 10**(digit-1) stop = 10**digit cand = [] for x in range(start, stop): for y in range(start, stop): z = x * y s = str(z) if s==s[::-1]: cand.append(z) return max(cand) def problem5(to): """ https://projecteuler.net/problem=5 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? >>> problem5(10) 2520 >>> problem5(20) 232792560 """ from sympy import factorint factor = {} for x in range(1, to+1): for base, exp in factorint(x).items(): factor[base] = max(exp, factor.get(base, 0)) else: result = 1 for base, exp in factor.items(): result *= base ** exp return result def problem10(stop): """ https://projecteuler.net/problem=10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. >>> problem10(10) 17 >>> problem10(2000000) 142913828922 """ from sympy import isprime return sum( x for x in range(2, stop) if isprime(x) ) def problem20(n): """ https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! >>> problem20(10) 27 >>> problem20(100) 648 """ from sympy import factorial return sum( int(char) for char in str(factorial(n)) ) def problem30(exp): """ https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1**4 + 6**4 + 3**4 + 4**4 8208 = 8**4 + 2**4 + 0**4 + 8**4 9474 = 9**4 + 4**4 + 7**4 + 4**4 As 1 = 1**4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. >>> problem30(4) 19316 >>> problem30(5) 443839 """ cand = [] for n in range(2, (9**exp)*exp): powsum = sum( int(digit)**exp for digit in str(n) ) if n == powsum: cand.append(n) else: return sum(cand) def problem40(): """ https://projecteuler.net/problem=40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 >>> problem40() 210 """ s = "".join(str(n) for n in range(1000000)) result = 1 for exp in range(7): result *= int(s[10**exp]) else: return result #%% def test(a,b): return a + b def test2(c, d): return c * d
import sys import re from collections import defaultdict # This is a script to identify pronouns in Japanese # It requires data segmented by KyTea (http://www.phontron.com/kytea/) # # If you have raw Japanese text (with no spaces), use this script like: # cat japanese.txt | kytea | python identify_japanese_pronouns.py > japanese_with_pronouns.txt # # If you have tokenized Japanese text (with lots of spaces), use this script like: # cat segmented_japanese.txt | kytea -in tok | python identify_japanese_pronouns.py > japanese_with_pronouns.txt # # The result will be segmented, where each pronoun X will be surrounded by <<<X>>>_{1,2,3} indicating the # person of the pronoun. # # This heavily references Wikipedia: # https://ja.wikipedia.org/wiki/日本語の一人称代名詞 # https://ja.wikipedia.org/wiki/日本語の二人称代名詞 pronoun_map = { # "Standard" first person '私': 1, 'わたし': 1, '僕': 1, 'ぼく': 1, '俺': 1, 'おれ': 1, '我々': 1, # 1st person plural # Less standard first person 'わたくし': 1, 'あたし': 1, 'あたくし': 1, 'わし': 1, 'わて': 1, 'わい': 1, 'うち': 1, 'おいら': 1, 'おい': 1, '我輩': 1, '吾輩': 1, '我が輩': 1, '吾が輩': 1, # "Standard" second person 'あなた': 2, 'あんた': 2, 'お前': 2, '君': 2, # Less standard second person '貴方': 2, 'アナタ': 2, 'おまえ': 2, 'きみ': 2, 'キミ': 2, # "Standard" third person '彼': 3, # can also mean "boyfriend" 'かれ': 3, # can also mean "boyfriend" '彼女': 3, # can also mean "girlfriend" 'かのじょ': 3, # can also mean "girlfriend" 'あいつ': 3, } missed_pronoun = defaultdict(lambda: 0) for line in sys.stdin: line = line.replace('\ ', ' ') # remove space tokens words = line.strip().split(' ') out = [] for w in words: t = w.split('/') if len(t) != 3: print(f'malformed tag {w}, skipping', file=sys.stderr) out.append(w) elif t[1] == '代名詞': if t[0] in pronoun_map: out.append(f'<<<{t[0]}>>>_{pronoun_map[t[0]]}') else: missed_pronoun[t[0]] += 1 out.append(t[0]) else: out.append(t[0]) print(' '.join(out)) # # Print out missed pronouns to check to make sure none are missed # for k, v in sorted(missed_pronoun.items(), key=lambda x: -x[1]): # print(f'MISSED: {k}\t{v}', file=sys.stderr)