text
stringlengths
37
1.41M
first_name = "jhon" last_name = "smith" message = f'{first_name} {last_name} is a coder ' print(message) print(len(message)) course = "python basic course" print(course.upper()) print(course.lower()) print(course.find("c")) print(course.replace("p", "C")) print("python" in course) print("cython" in course) print(course.title())
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv import time with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixed line telephones in Bangalore. Fixed line numbers include parentheses, so Bangalore numbers have the form (080)xxxxxxx.) Part A: Find all of the area codes and mobile prefixes called by people in Bangalore. - Fixed lines start with an area code enclosed in brackets. The area codes vary in length but always begin with 0. - Mobile numbers have no parentheses, but have a space in the middle of the number to help readability. The prefix of a mobile number is its first four digits, and they always start with 7, 8 or 9. - Telemarketers' numbers have no parentheses or space, but they start with the area code 140. Print the answer as part of a message: "The numbers called by people in Bangalore have codes:" <list of codes> The list of codes should be print out one per line in lexicographic order with no duplicates. Part B: What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Print the answer as a part of a message:: "<percentage> percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore." The percentage should have 2 decimal digits """ def checkreceivingcall(incall): if incall.startswith('('): area_code = get_codes(incall) return area_code elif incall.startswith('140'): return '140' elif incall.startswith('7') or incall.startswith('8') or incall.startswith('9'): return incall[0:4] def get_codes(phone_number): i = 0 area_code = '' while i < len(phone_number): if phone_number[i] == '(': while phone_number[i] != ')': i += 1 if phone_number[i] == ')': break else: area_code += phone_number[i] i += 1 return area_code start = time.time() out_code_list = [] received_code_list = [] for row in range(len(calls)): out_call = calls[row][0] received_call = calls[row][1] if out_call.startswith('(080)'): received_code_list.append(checkreceivingcall(received_call)) unique_code_list = sorted(set(received_code_list)) area_code_list = [] print("The numbers called by people in Bangalore have codes:") for num in unique_code_list: print(num) # Part B out_calls_080_list = [] received_calls_080_list = [] for row in range(len(calls)): out_call = calls[row][0] received_call = calls[row][1] if out_call.startswith('(080)'): out_calls_080_list.append(out_call) if out_call.startswith('(080)') and received_call.startswith('(080)'): received_calls_080_list.append(received_call) time.sleep(1) end = time.time() num_out_080 = len(out_calls_080_list) num_received_080 = len(received_calls_080_list) percent_080 = (num_received_080/num_out_080)*100 print("{0:1.2f} percent of calls from fixed lines in Bangalore are calls \ to other fixed lines in Bangalore.".format(percent_080)) #print(f"Runtime of the program is {end - start}") 1.0111842155456543
def findmaxnum(a): max_num = a[0] for i in range(len(a) - 1): if max_num < a[i + 1]: # found a new max swap max_num = a[i + 1] return max_num a = [7, 3, 10, 5, 0] print("max num in list=", findmaxnum(a))
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # Often decode JSON into dictionaries # Simple dict person = { 'first_name': 'Adam', 'last_name': 'Parsons', 'age': 32 } # Simple dict using a constructor # person = dict(first_name='Adam', last_name='Parsons', age=32) # Access a single value # print(person['first_name']) # Access a single value using get method # print(person.get('first_name')) # Add a key/value pair person['phone'] = '123-123-123' # Get keys # print(person.keys()) # Get items # print(person.items()) # Make a copy person2 = person.copy() person2['first_name'] = "Hello " # Remove an item # del person['age'] # Remove an item using pop person.pop('phone') # List of dict - similiar to an array of objects in JS people = [{"first_name": 'Bob', "age": 25}, {"first_name": 'Samantha', "age": 56}] # Get specific property print(people[1]['first_name']) # print(people)
import math import time import matplotlib.pyplot as plt # function derivative as a method of the function "f" itself def f_dashx(a,b,f,x): f_dash = a*((f*f*f*f) -b) return(f_dash) #calculation of fucntion value using euler method/ RK-1 # ivc stands for initial value condition def rk1(f_dash,ivc,step,iters,args_const): fun_val = ivc[0] x_val = ivc[1] for i in range(iters): args_fdash = args_const + (fun_val,x_val,) fun_val = fun_val + f_dashx(*args_fdash)*step #moving to new point. x_val = x_val + step #print("\t f=",fun_val,"\t x =",x_val); #loop end #print("\n Final Val = ",fun_val,"\t at x=",x_val,"\t iterations = ",iters) return(fun_val) def rk2(f_dash,ivc,step,iters,args_const): fun_val = ivc[0] x_val = ivc[1] for i in range(iters): sudo_args_fdash1 = args_const + (fun_val,x_val,) slope1 = f_dashx(*sudo_args_fdash1) sudo_fun_val1 = fun_val + slope1*step #moving to new sudo point1. sudo_x_val1 = x_val + step sudo_args_fdash2 = args_const + (sudo_fun_val1,sudo_x_val1,) slope2 = f_dashx(*sudo_args_fdash2) sudo_fun_val2 = sudo_fun_val1 + slope2*step #moving to new sudo point2. sudo_x_val2 = sudo_x_val1 + step #calculation of mean slope slope_mean = (slope1 + slope2)/2 #moving to new point. fun_val = fun_val + slope_mean*step x_val = x_val + step #print("\t f=",fun_val,"\t x =",x_val); #loop end #print("\n Final Val = ",fun_val,"\t at x=",x_val,"\t iterations = ",iters) return(fun_val) #optimal step size finding def optimum_rk(rk,f_dashx,ivc,x_range,const_args): i=0 true_val = 647.57 step_size=0 px=[] py=[] while (1): i=i+1 step_size = (x_range[1] - x_range[0])/i numeric_val = rk(f_dashx,ivc,step_size,i,const_args) #calculation of error err = abs((numeric_val - true_val)/true_val) #print("error = ",err*100,"%") px.append( step_size ) py.append( err*100 ) if(err<0.001): #print("\n ERROR LESS THAN 0.1%, OVER") break print("\n RESULTS FOR OPTIMALITY: step_size = ",step_size,"\t no. of iterations = ",i) print ("\n CPU time: ", time.process_time(),'s') plt.plot(px, py) plt.xlabel('Step Size (h)') plt.ylabel('Error (%)') plt.title('Step Size vs. Error') plt.show() #calling in main program a = -2.2067*pow(10,-12) b = 81*pow(10,8) ivc = (1200,0) x_range = (0,480) const_args = (a,b) #rk2(f_dashx,ivc,120,4,const_args) #optimum_rk(rk1,f_dashx,ivc,x_range,const_args) optimum_rk(rk2,f_dashx,ivc,x_range,const_args)
import time import math #globals g = 9.81 Q = 20 def fun(g_,Q_,y): a = g_*pow(y,3) b = pow ((6+y),3) c = (3+y)*Q_*Q_ fun_val = ((a*b)/8)-c return(fun_val) def bisect_root(guess,g,Q): a= guess[0] b= guess[1] itr = 0 while(1): f_a = fun(g,Q,a) f_b = fun(g,Q,b) m = (a+b)/2 f_m = fun(g,Q,m) if(f_a*f_m > 0): #same signs so they should replace a = m elif(f_b*f_m > 0 ): b = m else: print("\n Problem with elif") if(itr): #erroe err = (m - m_prev)/m if(err<0): err=-1*err print("\n Error is :",err) if(err<0.001): print("\n Process over") break m_prev=m itr = itr +1 print("Solution is:", m ) print("Error is:",err) print("function value is at the solution is:",fun(g,Q,m)) print("Number of iterations",itr) bisect_root((0.5,2.5),g,Q)
#!/usr/bin/env python # read latitude and longitutde from csv file # then calculate the distance and write into new csv file # # updated to calculate the bike distance by using MapQuest api # # Last update: 2/4/2020 # Author: Injung Kim import math import csv from collections import defaultdict from pprint import pprint import json import requests MAPQUEST_APP_KEY = "G7LoGyb0mf68nG7IkORMW9U0LOkPDHeG" def distance_matrix(locations): request_body = { 'locations': [{'latLng': {'lat': location['latitude'], 'lng': location['longitude']}} for location in locations], 'unit': 'k' } request_body['routeType'] = 'bicycle' r = requests.post('http://open.mapquestapi.com/directions/v2/routematrix?key={appkey}'.format(appkey=MAPQUEST_APP_KEY), data=json.dumps(request_body) ) if r.status_code != 200: print("We didn't get a response from Mapquest.") print("We were trying to access this URL: {0}".format(r.url)) print("Status code: {0}".format(r.status_code)) print("Full response headers:") pprint(dict(r.headers)) return result = json.loads(r.content) try: distances = result['distance'] except KeyError: print("We didn't get the response we expected from MapQuest.") print("Here's what we got:") pprint(result) return if len(locations) != len(distances): print("We didn't get enough distances back for the number of locations.") print("Number of locations you supplied: {0}".format(len(locations))) print("Number of distances we received: {0}".format(len(distances))) return # distances are in kilometers, need to convert to meters distances = [int(1000*d) for d in distances] results = [{'start_id': locations[0]['id'], 'end_id': locations[loc_index]['id'], 'distance': distances[loc_index]} for loc_index in xrange(len(locations))] return results def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6373.0 # km lat1 = math.radians(float(lat1)) lat2 = math.radians(float(lat2)) lon1 = math.radians(float(lon1)) lon2 = math.radians(float(lon2)) #print(lat1, lat2, lon1, lon2) dlat = lat2-lat1 dlon = lon2-lon1 a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(lat1) \ * math.cos(lat2) * math.sin(dlon/2) * math.sin(dlon/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = radius * c return d # read csv file having latitude and longitude file1 = open('./latitude_longitude.csv', 'rb') reader = csv.DictReader(file1) columns = defaultdict(list) num = 0 for row in reader: num = num + 1 #print(row) for (k,v) in row.items(): columns[k].append(v) print(columns['station_id']) print(columns['latitude']) print(columns['longitude']) print(num) file1.close() # write csv file to have distance info file2 = open('./bikeDistance.csv', 'wb') writer = csv.writer(file2) data = [''] origin = [] desti = [] distance_data = [] for row in range(num): data.append(columns['station_id'][row]) distance_data.append(data) for i in range(num): data = [columns['station_id'][i]] for j in range(num): origin = [columns['latitude'][i], columns['longitude'][i]] desti = [columns['latitude'][j], columns['longitude'][j]] dis = distance( origin, desti ) #dis = str(dis) data.append(dis) distance_data.append(data) writer.writerows(distance_data) file2.close()
def verifica(entrada,t,v): string = "" tamanho = 0 for todos in range(t): if tamanho == (t-v): break i = str(todos+1) if i not in entrada: string+=i string+=" " tamanho+=1 return string while True: try: t,v = [int(x) for x in input().split()] entrada = input().split() if t == v: print("*") else: entrada.sort() print(verifica(entrada,t,v)) except: break
N = int(input("")) fat = 1 i = 1 while i <= N: fat = fat *i i += 1 print (fat)
n = int(input()) lista = [] aux = 1 for x in range(n+1)[1::]: lista.append([x,x**2,x**3]) for x in range(n): for y in range(3): if y == 2: print(lista[x][y]) else: print(lista[x][y], end=' ')
valores = input() partes = valores.split() A = float(partes[0]) B = float(partes[1]) C = float(partes[2]) if (((abs(B-C)) < A) and (A < (B+C))) or (((abs(A-C)) < B) and (B < (A+C))) or (((abs(A-B)) < C) and (C < (A+B))): perimetro = A+B+C print("Perimetro = %0.1f" % perimetro) else: area = (A+B)*C/2 print("Area = %0.1f" % area)
# Incorporate the random library import random # Print Title print("Let's Play Rock Paper Scissors!") # Specify the three options by defining a list options = ["r", "p", "s"] # Computer Selection computer_choice = random.choice(options) # User Selection user_choice = input("Make your Choice: (r)ock, (p)aper, (s)cissors? ") print(f"computer choice is: {computer_choice}") # Run Conditionals if user_choice == computer_choice: print(f"Both players selected {user_choice}.It is a tie") elif user_choice == "r": if computer_choice == "s": print("Rock smashes the scissors! You win!") else: print("Paper covers rock! You lose.") elif user_choice == "p": if computer_choice == "r": print("Paper covers the rock! You Win!") else: print("Scissors cuts the paper! You lose") elif user_choice == "s": if computer_choice == "r": print("rock smashes scissors! you lose") else: print("scissors cuts the paper! You win!")
''' Euler50.py ' 0.05 on a powerful machine, July 2017 ' (c) Riwaz Poudyal ''' primes = [] def isPrime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False i = 5 while(i*i <= n): if n % i == 0: return False if n % (i + 2) == 0: return False i += 6 return True for i in range(3942): # Requries a bit of tuning to find something that is below 1 million if isPrime(i): primes.append(i) cumPrimes = [0] * len(primes) cumPrimes[0] = primes[0] for i in range(1, len(primes)): cumPrimes[i] = cumPrimes[i-1] + primes[i] longest = 0 longestPrime = -1 # Can do better by remembering which find we have already looked at # Still pretty fast def find(i, j): global longest, longestPrime if j - i <= longest: return if (i > len(primes) or j < 0): return if isPrime((cumPrimes[j] - cumPrimes[i])): longest = j - i longestPrime = cumPrimes[j] - cumPrimes[i] else: find(i+1, j) find(i, j - 1) find(0, len(primes)-1) print(longest) print(longestPrime)
amount = int(input()) p1 = ' _~_ ' p2 = ' (o o) ' p3 = ' / V \\ ' p4 = ' /( _ )\\ ' p5 = ' ^^ ^^ ' print(p1*amount) print(p2*amount) print(p3*amount) print(p4*amount) print(p5*amount)
#is_int #An integer is just a number without a decimal part (for instance, -17, 0, and 42 are all integers, but 98.6 is not). #For the purpose of this lesson, we'll also say that a number with a decimal part that is all 0s is also an integer, such as 7.0. #This means that, for this lesson, you can't just test the input to see if it's of type int. #If the difference between a number and that same number rounded is greater than zero, what does that say about that particular number? #Instructions #1.Define a function is_int that takes a number x as an input. #Have it return True if the number is an integer (as defined above) and False otherwise. def is_int(x): if abs(round(x) - float(x)) == 0: return True else: return False print is_int(5.5)
# TODO: redefine magic numbers as constants import pygame import random # Class for the main player class Enemy(pygame.sprite.Sprite): ''' This class is the enemy class which inherits from pygame.sprite.Sprite class ''' # Class initialization def __init__(self, enemy_img, size, game_window_x, game_window_y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(enemy_img).convert() # Load enemy image self.image = pygame.transform.scale(self.image,size) # Enemy size self.image.set_colorkey((255,255,255)) # Turns white in the image to transparent self.rect = self.image.get_rect() # Get position of the enemy self.size = self.image.get_size() # Get size of the enemy self.direction = [random.random()*random.choice([1,-1]),random.random()*random.choice([1,-1])] #movement direction # Starting position self.x = random.random()*1000 self.y = random.random()*640 # Game window size self.game_window_x = game_window_x self.game_window_y = game_window_y # Movement target self.target_x = int(random.random()*self.game_window_x)-self.size[0] self.target_y = int(random.random()*self.game_window_x)-self.size[1] # Defining speed self.speed = random.choice([1,2,5,7]) # Get sprite rectangle self.rect = self.image.get_rect() self.rect.x = self.x self.rect.y = self.y self.counter = random.randint(0,120) # Store directions to flip sprites accordingly self.last_dir = 'RIGHT' self.last_dir_1 = 'RIGHT' # Redefine target, speed and direction def redefine_target_dir_speed(self): # Restart counter self.counter = random.randint(0,120) # Redefine target self.target_x = random.randrange(0,self.game_window_x-self.size[0]) self.target_y = random.randrange(0,self.game_window_y-self.size[1]) # Set speed self.speed = random.choice([1,2]) # Set direction m = float(self.target_y-self.y)/float(self.target_x-self.x) while m > abs(1.73): self.target_x = random.randrange(0,self.game_window_x-self.size[0]) self.target_y = random.randrange(0,self.game_window_y-self.size[1]) m = float(self.target_y-self.y)/float(self.target_x-self.x) self.direction = [float(self.target_x-self.x)/abs(self.target_x-self.x), (float(self.target_y-self.y)/abs(self.target_y-self.y))*m] # Method for moving the enemy def move(self): # First check to see if enemy is on target and, if True, redefine movement parametres if self.x in range(self.target_x-15, self.target_x+15) and \ self.y in range(self.target_y-15, self.target_y+15) or \ self.counter == 0: self.redefine_target_dir_speed() # Else move the enemy according to its speed else: if 0 < self.x+self.direction[0]*self.speed < 1152-self.size[0]: self.x += self.direction[0]*self.speed self.rect.x = self.x # Update facing sprite direction self.last_dir = self.last_dir_1 if self.direction[0]*self.speed > 0: self.last_dir_1 = 'RIGHT' else: self.last_dir_1 = 'LEFT' if self.last_dir != self.last_dir_1: self.image = pygame.transform.flip(self.image, True, False) else: self.direction[0] = -1*self.direction[0] if 0 < self.y+self.direction[1]*self.speed < 640-self.size[1]: self.y += self.direction[1]*self.speed self.rect.y = self.y else: self.direction[1] = -1*self.direction[1] self.counter -= 1 # Method for growing enemy def grow(self,perry,flag): y=random.choice([0,1]) # Only if future size < max size and flag==collision==True and choice==1 if self.size[1]+int(perry.size[1]/10) < 550 and flag == True and y == 1: # Reload image and scale it and create new rectangle self.image = pygame.image.load('perry.png').convert() self.image = pygame.transform.scale(self.image, ( self.size[0]+int(perry.size[0]/10), self.size[1]+int(perry.size[1]/10) ) ) self.image.set_colorkey((255,255,255)) self.rect = self.image.get_rect() self.rect.x = self.x self.rect.y = self.y self.size = self.image.get_size() def flip(self): self.image = pygame.transform.flip(self.image, True, False)
moves = ["move1","move2",["move11","move21"]] # 导入模块 import neast neast.print_lol(moves) # def创建函数 def print_lol(the_list): for the_list_item in the_list: if isinstance(the_list_item, list): print_lol(the_list_item) else: print(the_list_item) # 函数调用 print_lol(moves) print("函数调用结束。。。。") # for循环 for each_item in moves: if isinstance(each_item,list): for ineach_item in each_item: print(ineach_item) else: print(each_item) # while循环 """ 多行注释 使用这个注释符 """ count = 0 while count<len(moves): print(moves[count]) count=count+1 # isinstance检查是否为某个特定类型的数据(如下面的list列表) result = isinstance(moves, list) print(result) # range()内置函数使用 for num in range(5): print(num)
#Day 1 Report Repair #--- Day 1: Report Repair --- # After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. # Surely, Christmas will go on without you. # # The tropical island has its own currency and is entirely cash-only. The gold coins used there have a little picture of # a starfish; the locals just call them stars. None of the currency exchanges seem to have heard of them, but somehow, # you'll need to find fifty of these coins by the time you arrive so you can pay the deposit on your room. # # To save your vacation, you need to get all fifty stars by December 25th. # # Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second # puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! # # Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input); apparently, # something isn't quite adding up. # # Specifically, they need you to find the two entries that sum to 2020 and then multiply those two numbers together. # # For example, suppose your expense report contained the following: from Parser.Parser import Parser def sum_of_three_bf(input_file): parser = Parser(input_file) input = [int(val) for val in parser.Get_Input()] for i in input: for j in input: for k in input: if i + j + k == 2020: return i*j*k #This is the answer to problem 1 def sum_of_two(input, total): difs = set(input) for val in input: y = total - val if y in difs: return y*val else: difs.add(y) raise Exception("No Sum") def sum_of_three_smarter(input_file): parser = Parser(input_file) input = [int(val) for val in parser.Get_Input()] total = 2020 for i in range(len(input)): x = total - input[i] try: y = sum_of_two(input[i:], x) return input[i]*y except: continue if __name__ == '__main__': print(sum_of_three_bf(r"C:\Users\patfa\PycharmProjects\AdventOfCode\Day1\Day1P1Input")) print(sum_of_three_smarter(r"C:\Users\patfa\PycharmProjects\AdventOfCode\Day1\Day1P1Input"))
print("\t\t Jurusan Sistem Informasi terdapat pada fakultas...") while True: for i in range(5): tebakan= input("Masukkan tebakan mu: ") if tebakan == "FRI": print("Jawaban Benar") break else: print("Jawaban salah") if tebakan == "FRI": break else: print("\t\t=============================") print("KAMU SUDAH MENEBAK SEBANYAK 5 KALI. KAMU GAGAL!") break
#lista zawierajaca liczby całkowite od 0 do 20 liczby = [] for x in range(21): liczby.append(x) print(liczby) #list comprehension #jesli chcemy uworzyc listez elementami w srodku (range, kwadraty liczb itp) #to uzywamy ponizszej składni: numerki = [x for x in range(21)] print(numerki)
file_path = "dane.txt" #try: # with open(file_path, 'r') as file: # print(file.read()) #except FileNotFoundError as e: # print("Podany plik nie istnieje!", e) #except Exception as e: # print("Uuuups, nastąpił jakiś błąd.", e) #finally: # print("Ta funkcja zawsze się wykona") try: print("To jest blok try") raise ValueError("Sam tworzę wyjątek! typ ValueError") print("Dobry kod") except ValueError as e: print("Złapałem wyjątek", e) finally: print("Zawsze się wykona")
pos = {num:-num for num in range(10)} print(pos) ### A partir de una lista creo un diccionario. fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli'] dicFellowship = {elemento:len(elemento) for elemento in fellowship} print(dicFellowship)
# coding=utf-8 x = True print(x) print(type(x)) print(int(x)) listOfList = [["a", "b", "c"], ["d", "f"], ["g", "h", "i", "j"]] print("lengh of the list is: ", len(listOfList)) print("lengh of the second list of the list", len(listOfList[1])) x = [8.3, 3.1, 7, 5, 1] y = [2.2, 4.6, 9.1] print("Max element", max(x)) print("Max element of two lists", max(x, y)) w = x + y print("lista W: ",w) sorted_w = sorted(w, reverse=True) print("Lista ordenada:", sorted_w) print("possition of 7", x.index(7))
# Un while basico offset = -6 while offset != 0 : print('entro') if offset > 0 : offset = offset - 1 else : offset = offset + 1 # Un for basico sobre lista areas = [11.25, 18.0, 20.0, 10.75, 9.50] for elemento in areas: print(elemento) # Un for sobre un Objeto Enumerate. for index, element in enumerate(areas): print("Room " + str(index) + ": " + str(element) ) # Un for sobre lista de lista house = [["hallway", 11.25], ["kitchen", 18.0], ["living room", 20.0], ["bedroom", 10.75], ["bathroom", 9.50]] for elemento in house: print(elemento[0] + " tiene: " + str(elemento[1]) + "m2") # Un for sobre Diccionarios europe = {'spain':'madrid', 'france':'paris', 'germany':'bonn', 'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'australia':'vienna' } for key, value in europe.items(): print("La capital de " + key + " es " + value) # Un for sobre numpy import numpy as np peso_kg = np.array([90, 89, 120, 95, 105]) altura_m = np.array([1.90, 1.95, 2.10, 1.92, 2.01]) basket = ([90, 89, 120, 95, 105], [1.90, 1.95, 2.10, 1.92, 2.01]) for peso in peso_kg: print (peso) np2d_basket = np.nditer(basket) #Un for sobre un numpay array 2D for element in np2d_basket: print(str(element)) #Un for sobre un panda import pandas as pd #Un for sobre un pandas basico import pandas as pd cars = pd.read_csv('cars.csv', index_col=0) for primary_key, fila in cars.iterrows(): print(primary_key) print(fila) #Un for sobre un panda con un campo filtrado for pk, fila in cars.iterrows(): print(pk + ": " + str(fila['cars_per_cap']) ) #Un for sobre un DataFame y agregado de una columna. #loc[] busca una posición en el DataFrame a partir del indice y columna pasada como parámetro #En este caso como no existe esa columna, pero se le esta asignando un valor crea la celda. for pk, fila in cars.iterrows(): pais_minuscula = fila["country"] cars.loc[pk, "COUNTRY"] = pais_minuscula.upper() #Una forma eficiente de agregar campos calculados al DataFrame # aplicandole una funcion "apply" a un objeto Series, y pasando una función como parametro para que sea aplicada a cada elemento. def porMil(x): return x*1000 countries = cars["country"] cars["COUNTRY2"] = cars["country"].apply(str.upper) cars["CPC_in_miles"] = cars["cars_per_cap"].apply(porMil) print(cars)
from unittest import TestCase from timeConversion import timeConversion class TestTimeConversion(TestCase): def test_input_is_midnight(self): self.assertEqual(timeConversion("12:00:00AM"), "00:00:00") self.assertEqual(timeConversion("12:05:15AM"), "00:05:15") def test_input_is_the_morning(self): self.assertEqual(timeConversion("10:00:00AM"), "10:00:00") self.assertEqual(timeConversion("11:50:00AM"), "11:50:00") def test_input_is_midday(self): self.assertEqual(timeConversion("12:00:00PM"), "12:00:00") def test_input_is_noon(self): self.assertEqual(timeConversion("01:00:00PM"), "13:00:00") self.assertEqual(timeConversion("11:00:00PM"), "23:00:00")
# https://www.hackerrank.com/challenges/diagonal-difference/problem import math def diagonalDifference(arr): n = len(arr) - 1 d1 = 0 d2 = 0 for i in range(n + 1): d1 += arr[i][i] d2 += arr[i][n - i] return abs(d1 - d2) if __name__ == '__main__': n = int(input()) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(arr) print(result)
# https://www.hackerrank.com/challenges/birthday-cake-candles/problem def birthdayCakeCandles(ar): maxar = ar[0] count = {} for i in ar: count.setdefault(i, 0) count[i] += 1 if i > maxar: maxar = i return count[maxar] if __name__ == '__main__': ar_count = int(input()) ar = list(map(int, input().rstrip().split())) result = birthdayCakeCandles(ar) print(result)
# https://www.hackerrank.com/challenges/time-conversion/problem import re def timeConversion(s): if re.match("^12(.)+AM$", s): res = '00' + s[2:8] return res if re.match("^(.)+AM$|^12(.)+PM$", s): return s[:8] res = int(s[:2]) + 12 return str(res) + s[2:8]
# autor: Hugo de Jesus Valenzuela Chaparro # curso desarrollo experimental 2 # Universidad de Sonora, agosto 2019 # este programa sirve para evaluar funciones, preguntando al usuario # el valor de x a evaluar, las funciones son # -------------------------------------------------------- # a) 4 - x^2 # b) x^(1/2) # c) ln(1 +2x) # d) Sen(x) # e) exp((-x^2)/2) # f) 1/(1+x^2) # -------------------------------------------------------- # posteriormente se da la opcion de graficar en un intervalo dado # y exportar los datos a un archivo .csv con la etiqueta de la funcion # seleccionada # librerias requeridas para que funcione el programa import numpy as np # llamar a las funciones (subrutinas) from funciones import func_a,func_b,func_c,func_d,func_e,func_f from graficar import graficar # mensaje a usuario print(""" Este programa te sirve para evaluar una de las siguientes funciones: a) 4 - x^2 b) x^(1/2) c) ln(1 +2x) d) Sen(x) e) exp((-x^2)/2) f) 1/(1+x^2) """) #test = func_f(2) #print("la prueba es", test) # leer entrada de eleccion choice = input (""" Por favor elige una tecleando la letra (minuscula) que le corresponda: """) # condicionales para evaluar las funciones if choice == "a": eval = input ("""Elige el valor x0 que deseas evaluar """) func_aux = func_a print("La evaluacion resultante es:", func_aux(float(eval))) elif choice == "b": eval = input ("""Elige el valor x0 que deseas evaluar, usando valores mayores o iguales 0 """) func_aux = func_b print("La evaluacion resultante es:", func_aux(float(eval))) elif choice == "c": eval = input ("""Elige el valor x0 que deseas evaluar, usando valores mayores a -0.5 """) func_aux = func_c print("La evaluacion resultante es:", func_aux(float(eval))) elif choice == "d": eval = input ("""Elige el valor x0 que deseas evaluar """) func_aux = func_d print("La evaluacion resultante es:", func_aux(float(eval))) elif choice == "e": eval = input ("""Elige el valor x0 que deseas evaluar """) func_aux = func_e print("La evaluacion resultante es:", func_aux(float(eval))) elif choice == "f": eval = input ("""Elige el valor x0 que deseas evaluar """) func_aux = func_f print("La evaluacion resultante es:", func_aux(float(eval))) elif choice == "i love you": print("i love you too!") exit() else: print("Por favor, ingresa una opcion valida") exit() # dar opcion para graficar y guardar los datos en csv plot_choice = input ("""Deseas especificar un intervalo para graficar la funcion que seleccionaste (adicionalmente se exportaran las evaluaciones en un archivo csv)? (si/no) """) if plot_choice == "si": cota_inf = input ("Ingresa la cota inferior del intervalo") cota_sup = input ("Ingresa la cota superior del intervalo") a, b = float(cota_inf), float(cota_sup) graficar(a, b, func_aux, choice) #llamar funcion graficadora/exportadora elif plot_choice == "no": pass else: print("teclea 'si' o 'no', sin las comillas")
''' 13. Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: Para homens: (72.7*h) - 58 Para mulheres: (62.1*h) - 44.7 ''' alt= float(input('Qual sua altura em mts: ')) sexo='' while sexo != 'M' or 'F': sexo = str(input('Qual seu sexo [M/F] :')).strip().upper() if sexo == 'M': pesoh= (72.7*alt)-52 print(f'Baseado na sua altura de {alt}mt seu peso ideal é {pesoh :.2f}kg') break elif sexo == 'F': pesom= (62.1*alt)-44.7 print(f'Baseado na sua altura de {alt}mt seu peso ideal é {pesom :.2f}') break else: print('sexo invalido')
''' 04. Faça um Programa que verifique se uma letra digitada é vogal ou consoante ''' letra = str(input('digite uma letra: ')).upper() if letra in 'AEIOU': print('A letra digitada é uma VOGAL!') else: print('A letra digitada é uma CONSOANTE!')
''' 11. Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: o produto do dobro do primeiro com metade do segundo . a soma do triplo do primeiro com o terceiro. o terceiro elevado ao cubo. ''' n1int= int(input('Digite um numero inteiro: ')) n2int= int(input('Digite outro numero inteiro: ')) nreal= float(input('Digite um numero real qualquer: ')) print(f''' Com esses dados faremos os seguintes calculos: a. O produto do dobro do primeiro com metade do segundo : {n1int*2} X {n2int/2} = {(n1int*2)*(n2int/2)} b. A soma do triplo do primeiro com o terceiro : {n1int*3} + {nreal} = {(n1int*3)+nreal} c. O terceiro elevado ao cubo : {nreal}³ = {nreal**3} ''')
''' 15. Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê: salário bruto. quanto pagou ao INSS. quanto pagou ao sindicato. o salário líquido. calcule os descontos e o salário líquido, conforme a tabela abaixo: + Salário Bruto : R$ - IR (11%) : R$ - INSS (8%) : R$ - Sindicato ( 5%) : R$ = Salário Liquido : R$ Obs.: Salário Bruto - Descontos = Salário Líquido. ''' preco= float(input('Digite o valor da hora trabalhada: R$')) horames= float(input('Digite Quantas horas trabalhadas no mes: ')) totalb= horames*preco ir= totalb/100*11 inss= totalb/100*8 sind=totalb/100*5 totdesc= ir+inss+sind totall= totalb-totdesc print(f''' Preço da hora:R${preco} x Horas trabalhadas no mes {horames} hs SALARIO BRUTO :...............R${totalb} IR (Desconto de 11%):.........R$-{ir} INSS (Desconto de 8%):........R$-{inss} SINDICATO (Desconto de 5%):...R$-{sind} TOTAL DE DESCONTOS:...........R$-{totdesc} SALARIO LIQUIDO..............:R${totall} ''')
# To be filled by students import matplotlib.pyplot as plt from dataclasses import dataclass import pandas as pd @dataclass class NumericColumn: col_name: str # series: pd.Series df: pd.DataFrame # def get_name(self): # """ # Return name of selected column # """ # name = self.name # return name def get_unique(self): """ Return number of unique values for selected column """ unique_values = len(self.df[self.col_name].unique()) return unique_values def get_missing(self): """ Return number of missing values for selected column """ missing_values = self.df[self.col_name].isnull().sum() return missing_values def get_zeros(self): """ Return number of occurrence of 0 value for selected column """ zero_values = self.df[self.col_name].isin([0]).sum(axis=0) return zero_values def get_negatives(self): """ Return number of negative values for selected column """ negative_values = (self.df[self.col_name]<0).sum() return negative_values def get_mean(self): """ Return the average value for selected column """ average = self.df[self.col_name].mean() return average def get_std(self): """ Return the standard deviation value for selected column """ std_value = self.df[self.col_name].std() return std_value def get_min(self): """ Return the minimum value for selected column """ min_value= self.df[self.col_name].min() return min_value def get_max(self): """ Return the maximum value for selected column """ max_value= self.df[self.col_name].max() return max_value def get_median(self): """ Return the median value for selected column """ med_value= self.df[self.col_name].median() return med_value def get_histogram(self): """ Return the generated histogram for selected column """ n_rows = self.df.shape[0] if n_rows > 250: fig, ax = plt.subplots() ax.hist(self.df[self.col_name], bins=50) else: fig, ax = plt.subplots() ax.hist(self.df[self.col_name], bins=int(round(n_rows/5,0))) return fig def get_frequent(self): """ Return the Pandas dataframe containing the occurrences and percentage of the top 20 most frequent values """ total_rows = self.df[self.col_name].count() frequency = self.df[self.col_name].value_counts().reset_index() frequency.columns = ['value', 'occurrence'] frequency['percentage'] = frequency['occurrence']/total_rows return frequency.head(20) def construct_table(self): unique_values = self.get_unique() missing_values = self.get_missing() zero_values = self.get_zeros() negative_values = self.get_negatives() average = self.get_mean() std_value= self.get_std() min_value = self.get_min() max_value = self.get_max() med_value = self.get_median() table = { 'number of unique values': [unique_values], 'number of missing values': [missing_values], 'number of rows with zero values': [zero_values], 'number of rows with negative values': [negative_values], 'Average': [average], 'Standard Deviation': [std_value], 'Minimum': [min_value], 'Maximum': [max_value], 'Median': [med_value] } table = pd.DataFrame.from_dict(table).T table.columns = ['value'] return table.astype(str)
# Python内置的sorted()函数就可以对list进行排序: # print(sorted([1,4,-1,8,-3])) #1 # list=[1,4,-1,8,-3] # list2=sorted(list) # print(list2) #2 # sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序: #print(sorted([1,4,-1,8,-3],key=abs)) #[1, -1, -3, 4, 8] key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序 #字符串排序 #1.正常: #print(sorted(['bob', 'about', 'Zoo', 'Credit'])) #结果: ['Credit', 'Zoo', 'about', 'bob'] #2.忽略大小写:传入第二个参数 #print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower)) #结果: ['about', 'bob', 'Credit', 'Zoo'] #3.反向排序:可以传入第三个参数reverse=True: #print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower,reverse=True)) #结果: ['Zoo', 'Credit', 'bob', 'about'] #练习: # 假设我们用一组tuple表示学生名字和成绩: # L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] # 请用sorted()对上述列表分别按名字排序: # from operator import itemgetter # # students = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] # # print(sorted(students, key=itemgetter(0))) #按名字 # print(sorted(students, key=lambda t: t[1])) #按成绩 # print(sorted(students, key=itemgetter(1), reverse=True)) #按成绩降序
# map map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素, # 并把结果作为新的Iterator返回。 # 有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下: # def f(x): # return x*x # # # r=map(f,[2,4,6,8]) # 由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。 # print(list(r)) # 把list所有数字转为字符串: # print(list(map(str,[1,3,5,7,9]))) #['1', '3', '5', '7', '9'] # reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是: # 把序列[1, 3, 5, 7, 9]变换成整数13579 # from functools import reduce # # # def fn(x,y): # return x*10+y # # print(reduce(fn,[1,3,5,7])) #1357 # 练习1:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'], # 输出:['Adam', 'Lisa', 'Bart']: # def normalize(name): # return name.capitalize() # # # L1 = ['adam', 'LISA', 'barT'] # L2 = list(map(normalize, L1)) # print(L2) #['Adam', 'Lisa', 'Bart'] # 练习2:请编写一个prod()函数,可以接受一个list并利用reduce()求积 # from functools import reduce # # # def prod(L): # def multi(x, y): # return x*y # return reduce(multi, L) # # # print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) # if prod([3, 5, 7, 9]) == 945: # print('测试成功!') # else: # print('测试失败!') #练习3:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456: # from functools import reduce # # # def str2float(s): # def fn(x, y): # return x * 10 + y # def char2num(s): # return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] # # 得到字符串中.的索引 # n = s.index('.') # # 根据.的位置将字符串切片为两段 # s1 = list(map(int, [x for x in s[: n]])) # s2 = list(map(int, [x for x in s[n + 1 :]])) # # m ** n表示m的n次方 # return reduce(fn, s1) + reduce(fn, s2) / 10 ** len(s2) # # print('str2float(\'123.456\') =', str2float('123.456')) # if abs(str2float('123.456') - 123.456) < 0.00001: # print('测试成功!') # else: # print('测试失败!')
def insertion_sort(a_list): for index in range(1,len(a_list)): current_value = a_list[index] current_position = index while current_position > 0 and a_list[current_position-1] > current_value: a_list[current_position] = a_list[current_position - 1] current_position = current_position - 1 a_list[current_position] = current_value a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list)
graph = dict() graph['A'] = ['B', 'C'] graph['B'] = ['E','A'] graph['C'] = ['A', 'B', 'E','F'] graph['E'] = ['B', 'C'] graph['F'] = ['C'] #The length of the keys is used to provide the dimensions of the matrix which are stored in #cols and rows. matrix_elements = sorted(graph.keys()) cols = rows = len(matrix_elements) #We then set up a cols by rows matrix, filling it with zeros. adjancency_matrix = [[0 for x in range(cols)] for y in range(rows)] # The edges_list variable will # store the tuples that form the edges of in the graph. For example, an edge between node A # and B will be stored as (A, B). And fill the array of tuple using a nested loop. edges_list= [] for key in matrix_elements: for neighbour in graph[key]: edges_list.append((key,neighbour)) # fill our multidimensional array(matrix) by using 1 to mark the # presence of an edge with the line for edge in edges_list: index_of_first_vertex = matrix_elements.index(edge[0]) index_of_second_vertex = matrix_elements.index(edge[1]) adjancency_matrix[index_of_first_vertex][index_of_second_vertex] = 1 print(adjancency_matrix)
# def basic_small_change(denom, total_amount): # sorted_denom = sorted(denom , reverse= True) # print(sorted_denom) # returned_change = [] # for cash in sorted_denom: # div = total_amount // cash # if div > 0: # total_amount = total_amount % cash # returned_change.append((cash , div)) # return returned_change # print(basic_small_change([5,1,8], 20)) #More optimal solution #O(n) most likely loglinear O(nlogn) research!! def optimal_small_change(denom, total_amount): sorted_denominations = sorted(denom, reverse=True) possible_comb_list = [] for j in range(len(sorted_denominations)): term_list = sorted_denominations[j:] number_of_denoms = [] local_total = total_amount coins = 0 for i in term_list: div = local_total // i if div > 0: local_total = local_total % i coins = coins + div number_of_denoms.append((i, div)) number_of_denoms.append(coins) possible_comb_list.append(number_of_denoms) no_of_coins_list = sorted([x[-1] for x in possible_comb_list]) return no_of_coins_list[0] print(optimal_small_change([5,1,8], 68))
def inverting_a_string(str1): last_index = len(str1)-1 if len(str1) == 1: return str1[0] else: return str1[last_index] + inverting_a_string(str1[:last_index]) print(inverting_a_string("jackson"))
import random position = 0 walk = [position] steps = 100 for step in range(steps): dist = 1 if random.randint(0,1) else -1 position = position + dist walk.append(position) print(walk)
def quick_sort(a_list): #O(n) is O(nlogn) but may degrade to O(nlogn) if the pivot point is completely skewed to either the left or the right quick_sort_helper(a_list,0, len(a_list)-1) def quick_sort_helper(a_list , first, last): #begins with the same base case as the merge sort. If the length of the # list is less than or equal to one, it is already sorted. If it is greater, then it can be partitioned and # recursively sorted. if first < last: #Get the split value split_point = partition(a_list,first,last) #splitting the two lists on the split value quick_sort_helper(a_list,first, split_point -1) quick_sort_helper(a_list, split_point + 1 , last) #getting the split value def partition(a_list, first, last): pivot_value = a_list[first] left_mark = first + 1 right_mark = last done = False while not done: #Find a value bigger than the pivot value while left_mark <= right_mark and a_list[left_mark] <= pivot_value: left_mark = left_mark +1 #Find a value smaller than the pivot value while right_mark >= left_mark and a_list[right_mark] >= pivot_value: right_mark = right_mark -1 #Exit the loop if the right index becomes smaller than the left index if right_mark < left_mark: done = True #Exchenge the right_mark(smaller than the pivot value) with the left_mark(bigger than the pivot value) else: a_list[right_mark] ,a_list[left_mark] = a_list[left_mark], a_list[right_mark] #move the pivot value to the split point a_list[first] , a_list[right_mark] =a_list[right_mark] , a_list[first] return right_mark a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] quick_sort(a_list) print(a_list)
from study_address import Address class Person: def __init__(self, name, age, birth, email): self.name = name self.age = age self.birth = birth self.email = email self.place = [] def add_address(self, street, number, state, country): endereco = Address(street, number, state, country) self.place.append(endereco) def change_name(self, new_name): self.name = new_name def print_person(self): print("Name: " + self.name, "Age: " + str(self.age), "Birth: " + self.birth, "Email: " + self.email #"Place: " + self.print_address_person() ) def print_address_person(self): for end in self.place: print (end.print_address()) person1 = Person("Pessoa 1", 45, '1990-05-23', "person1@email.com") #person2 = Person("Pessoa 2", 21, '2003-11-03', "person2@email.com") person1.add_address("Satoshi Toori", 25, "Tokyo", "Japan") person1.add_address("Kokusai Toori", 123, "Okinawa", "Japan") person1.print_person() person1.print_address_person() #person2.print_person() # if __name__ == "__main__": # app.run() # app.run(debug=True)
"""Simple Dungeons and Dragons 5th Edition Character Generator.""" __author__ = "Nicholas Harrison" # COP 1500 project guidelines commented as "per guidelines." # Below imports math and random for use later. import math import random def continue_key_press(): """Allows user to progress program and add a line break.""" input("Press any key to continue: ") print(" ") # Has range, if/else, for, operator, and in per guidelines. # Formatted this function during conversation with Professor Vanselow. def roll_six_side_die_four_times(roll): """Rolls a six-sided die four times after accepting input.""" NUM_TIMES = 4 dice_rolls = [] if roll == 1: for a in range(NUM_TIMES): n = random.randint(1, 6) dice_rolls.append(n) else: print("Please use your own dice for this part.") return dice_rolls # Program uses float instead of int to catch user input errors. # Made my own solution rather than using the one on the course site. # Multiline docstring formatted via PEP8 site per guidelines. def get_input(output_string): """Sanitizes input with float and floor. Called repeatedly. Designed to push the user through the program while resolving errors. """ try: answer = float(input(output_string)) answer = math.floor(answer) except ValueError: answer = 0 return answer def main(): """Core character creator styled as a conversation.""" # Intro and user input test. Simple print functions. continue_key_press() print("Welcome!\nThis is a Dungeons & Dragons character sheet generator.") print("This is the third version.") continue_key_press() print("This program assumes basic knowledge of Dungeons & Dragons.") print("Your character creation process is interactive.") # Allows user to test keyboard functionality. answer_any = input("Try it out. Type anything here: ") # Adds lines without a function. print(" ") # Concatenate a string per guidelines. print("You said " + answer_any + "? " + "I'm sure that won't matter.") continue_key_press() # Uses function get_input to sanitize input. Used throughout. answer_start = get_input("Are you ready? 1 = Yes, 2 = No: ") # While loop to catch bad input per guidelines. # Operators for less/greater than per guidelines. # Boolean operator or per guidelines. while answer_start < 1 or answer_start > 2: answer_start = get_input("You have to answer with 1 or 2: ") # If-else statement for user input of 1 or 2(else) per guidelines. # Operator for equal per guidelines. if answer_start == 1: print(" ") print("You are in a dim tavern.\nA cloaked figure turns to you.") else: answer_start = get_input("You feel compelled to enter 1: ") # Operator for not equal per guidelines. while answer_start != 1: answer_start = get_input("You have to answer with 1: ") else: print(" ") print("You are in a dim tavern.\nA cloaked figure turns to you.") continue_key_press() # Naming process. print("The cloaked figure has a quill and parchment.\nIt asks...") name_player = input("'What should I call you?' Write your name here: ") print(" ") print("'Ah,", name_player, "- sounds like an adventurer to me.'") answer_name = get_input("Is this your name? 1 = Yes, Other = No: ") # Another version of the while loop from earlier. while answer_name != 1: name_player = input("'What should I call you?' Write your name: ") print(" ") print("'Ah,", name_player, "- sounds like an adventurer to me.'") answer_name = get_input("Happy? 1 = Yes, Other = No: ") else: print(" ") print("The cloaked figure says, 'Very well...'") continue_key_press() print("The cloaked figure takes a closer look at you.\n'What are you?'") print("The figure holds a mirror up and you see...") continue_key_press() print("Half-Orc? Strong.\nHumans, average skills.\nHalflings? Sneaky.") print(" ") print("Select a race.") race_select = get_input("1 = Half-Orc, 2 = Human, 3 = Halfling: ") # Another loop that catches input. while race_select < 1 or race_select > 3: print(" ") print("You didn't pick 1, 2, or 3.") race_select = get_input("1 = Half-Orc, 2 = Human, 3 = Halfling: ") # Nested if-elif-else with trailing else. else: if race_select == 1: print(" ") print("Half-Orc. Strength increases by 2, constitution by 1.") elif race_select == 2: print(" ") print("Human. All ability scores increase by 1.") else: print(" ") print("Halfling. Your dexterity increases by 2.") continue_key_press() if race_select == 1: print("'Aha, I know a half-orc when I see one.'") elif race_select == 2: print("'Oh, a human? How... interesting?'") else: print("'A halfling! I barely saw you down there...'") continue_key_press() print("'Now,' it says, 'I will chant my magic word to find your class.'") continue_key_press() # Multiply the input string by 10. # Should allow for some humor depending on user input. print(answer_any * 10) continue_key_press() # Class selection process. print("That makes sense. You are a...") print(" ") print("Fighters are good with weapons.\nRogues, sneaky.\nWizard? Magic.") print("NOTE: primary ability is what you're good at. Saves... save you.") print(" ") class_select = get_input("1 = Fighter, 2 = Rogue, 3 = Wizard: ") while class_select < 1 or class_select > 3: print(" ") print("Pick 1, 2, or 3.") class_select = get_input("1 = Fighter, 2 = Rogue, 3 = Wizard: ") # More nested loops per guidelines with operators. else: if class_select == 1: print(" ") print("Primary: strength. Save: strength, constitution.") elif class_select == 2: print(" ") print("Primary: dexterity. Save: dexterity, intelligence.") else: print(" ") print("Primary: intelligence. Save: intelligence, wisdom.") continue_key_press() # A summary for the player so far. print("The figure leans back in their chair.\nIt says, 'Let's see.'") # Has sep included per guidelines. summary_early = get_input("Like a summary? 1 = Yes, Other = No: ") if summary_early == 1: print("Your name's ", name_player, ", you're certain.", sep='') if race_select == 1: print("You are a Half-Orc. How scary.") elif race_select == 2: print("You are a Human. How tame.") else: print("You are a Halfling. How tiny.") if class_select == 1: print("Fighter: strength. Saves: strength, constitution.") elif class_select == 2: print("Rogue: dexterity. Saves: dexterity, intelligence.") else: print("Wizard: intelligence. Saves: intelligence, wisdom.") else: print("'Moving on then,' says the figure. 'We can ask again later.'") # Explanation of dice rolling. print(" ") print("The figure produces a bag.") print("'Let's decide your fate.'\n'How strong are you? How smart?'") continue_key_press() print("Out of the bag, the figure pulls four six-sided dice.") print("'You will roll these 6 times.'") continue_key_press() print("'We will add the total of the highest 3 dice six times.'") print("'Each sum can be used as one of your 6 ability scores.'") continue_key_press() # This is due to Dungeons and Dragons etiquette. print("NOTE: You are not allowed to re-roll. No cheating, please.") continue_key_press() # Wanted to give the player an option to use their own dice. print("Use your own dice? Hit any option other than 1.") print("If using your own dice, end results will be blanks.") question_roll = get_input("Roll the dice by pressing 1: ") # Calls the dice roll function and passes the user's request to roll. dice_roll = roll_six_side_die_four_times(question_roll) print(dice_roll) # Asks the user to do their own math in case they use their own dice. roll_one = get_input("Enter the sum of the three highest values: ") continue_key_press() print("The figure says, 'Easy, right?") print("If you are using your own dice, enter anything but 1.") # This is due to Dungeons and Dragons etiquette. print("REMINDER 1: You are not allowed to re-roll.") print("REMINDER 2: If using your own dice, end results will be blanks.") # Same as above process but now does it five times. # Still counts off the rolls if they are using their own dice. # This allows the user to keep track of their rolls regardless. question_roll_two = get_input("Roll five more times by pressing 1: ") dice_roll = roll_six_side_die_four_times(question_roll_two) print(dice_roll) roll_two = get_input("Enter the sum of the three highest values: ") dice_roll = roll_six_side_die_four_times(question_roll_two) print(dice_roll) roll_three = get_input("Enter the sum of the three highest values: ") dice_roll = roll_six_side_die_four_times(question_roll_two) print(dice_roll) roll_four = get_input("Enter the sum of the three highest values: ") dice_roll = roll_six_side_die_four_times(question_roll_two) print(dice_roll) roll_five = get_input("Enter the sum of the three highest values: ") dice_roll = roll_six_side_die_four_times(question_roll_two) print(dice_roll) roll_six = get_input("Enter the sum of the three highest values: ") continue_key_press() print("The figure scoops up the dice.\n'That was the last...'") continue_key_press() print("Your ability rolls are:") print(roll_one, roll_two, roll_three, roll_four, roll_five, roll_six) # Makes sure the user keeps moving through the program regardless. print("NOTE: If you used your own dice, scores of 0 will display.") continue_key_press() print("NOTE: If you mistyped an answer, scroll up to see your rolls.") continue_key_press() print("The figure draws six cards.") print("And it says, 'You have six ability scores.'") print("Strength, dexterity, constitution...") print("... and intelligence, wisdom, & charisma.") print("'You will place each of your rolls into each category.'") continue_key_press() print("It is important to review your current character attributes.") summary_early = get_input("Like a summary? 1 = Yes, Other = No: ") # Summary for review. if summary_early == 1: print("Your name's ", name_player, ", you're certain.", sep='') if race_select == 1: print("You are a Half-Orc. How scary.") elif race_select == 2: print("You are a Human. How tame.") else: print("You are a Halfling. How tiny.") if class_select == 1: print("Fighter: strength. Saves: strength, constitution.") elif class_select == 2: print("Rogue: dexterity. Saves: dexterity, intelligence.") else: print("Wizard: intelligence. Saves: intelligence, wisdom.") print("Again, your ability rolls are:") print(roll_one, roll_two, roll_three, roll_four, roll_five, roll_six) else: print("Moving on... Again, your ability rolls are:") print(roll_one, roll_two, roll_three, roll_four, roll_five, roll_six) print(" ") print("'Enter the desired roll sum in each of the following statistics.'") player_str = get_input("Enter your strength: ") player_dex = get_input("Enter your dexterity: ") player_con = get_input("Enter your constitution: ") player_int = get_input("Enter your intelligence: ") player_wis = get_input("Enter your wisdom: ") player_cha = get_input("Enter your charisma: ") continue_key_press() # Prints the user's unique stats based on race selection. # Uses shortcuts and relational operators per guidelines. if race_select == 1: player_str += 2 player_con += 1 print(" ") print("'Such a strong Half-Orc, aren't we?'") # Contains end to put this all on one line per guidelines. print("Str:", player_str, "Dex:", player_dex, end=" ") print("Con:", player_con, "Int:", player_int, end=" ") print("Wis:", player_wis, "Cha:", player_cha) elif race_select == 2: player_str += 1 player_dex += 1 player_con += 1 player_int += 1 player_wis += 1 player_cha += 1 print(" ") print("'What a jack-of-all trades, eh, Human?'") print("Str:", player_str, "Dex:", player_dex, end=" ") print("Con:", player_con, "Int:", player_int, end=" ") print("Wis:", player_wis, "Cha:", player_cha) else: player_dex += 2 print(" ") print("'I keep losing sight of you, little Halfling...'") print("Str:", player_str, "Dex:", player_dex, end=" ") print("Con:", player_con, "Int:", player_int, end=" ") print("Wis:", player_wis, "Cha:", player_cha) continue_key_press() print("The figure is pleased. It's cloak ruffles.") print("'Now, how much damage can you take?'") print("This is based on your class selection and your constitution.") continue_key_press() if class_select == 1: hit_die = 10 # Greater than, less than, equal to, etc. per guidelines. # All below can be simplified, but must show *and* per guidelines. if player_con < 10: hit_points = hit_die - 1 elif player_con >= 10 and player_con <= 11: hit_points = hit_die elif player_con >= 12 and player_con <= 13: hit_points = hit_die + 1 elif player_con >= 14 and player_con <= 15: hit_points = hit_die + 2 elif player_con >= 16 and player_con <= 17: hit_points = hit_die + 3 elif player_con >= 18 and player_con <= 19: hit_points = hit_die + 4 else: hit_points = hit_die + 5 print("'What a beefy fighter.'") print("Your hit points are: ", hit_points) elif class_select == 2: hit_die = 8 # All below can be simplified, but must show *and* per guidelines. if player_con < 10: hit_points = hit_die - 1 elif player_con >= 10 and player_con <= 11: hit_points = hit_die elif player_con >= 12 and player_con <= 13: hit_points = hit_die + 1 elif player_con >= 14 and player_con <= 15: hit_points = hit_die + 2 elif player_con >= 16 and player_con <= 17: hit_points = hit_die + 3 elif player_con >= 18 and player_con <= 19: hit_points = hit_die + 4 else: hit_points = hit_die + 5 print("'What a lithe rogue.'") print("Your hit points are: ", hit_points) else: hit_die = 6 # All below can be simplified, but must show *and* per guidelines. if player_con < 10: hit_points = hit_die - 1 elif player_con >= 10 and player_con <= 11: hit_points = hit_die elif player_con >= 12 and player_con <= 13: hit_points = hit_die + 1 elif player_con >= 14 and player_con <= 15: hit_points = hit_die + 2 elif player_con >= 16 and player_con <= 17: hit_points = hit_die + 3 elif player_con >= 18 and player_con <= 19: hit_points = hit_die + 4 else: hit_points = hit_die + 5 print("'What a frail wizard.'") print("Your hit points are: ", hit_points) continue_key_press() print("The figure pauses for a moment.") # Not statement per guidelines. # Just a break for humor. x = hit_points if not x > 10: print("It says, 'You'll probably be fine...'") continue_key_press() else: print("It says, 'I'm a bit worried about you...'") continue_key_press() # Remaining operators used below per guidelines to assign equipment. print("The cloaked figure places the cards and dice back in the bag.") print("'You're about ready... but you need some equipment and... help.'") continue_key_press() print("The figure produces a crystal out of thin air.") print("'This is not all I can conjure... I need some information first.'") continue_key_press() print("The cloaked figure is going to ask you some questions.") print("Your answers will determine random boons you get for your quest.") continue_key_press() print("'Let us begin...'") print("'If you give me an incorrect answer, this will sway the results.'") continue_key_press() print("'But everything happens for a reason...'") continue_key_press() player_pet = get_input("Numeric value of your birth month?: ") player_tunic = get_input("What is your age?: ") player_henchman = get_input("How many siblings do you have?: ") player_deity = get_input("How tall are you? Nearest foot?: ") player_star = get_input("Numeric value of your birthdate?: ") continue_key_press() # Below can be simplified, but showing unsimplified per guidelines. # Exponential by 2 per guidelines. player_pet = player_pet ** 2 if player_pet <= 10 and player_pet >= 60: player_pet = "Dog" print("You own a: ", player_pet) else: player_pet = "Cat" print("You own a: ", player_pet) # Below can be simplified, but showing unsimplified per guidelines. # Multiplies by 10 per guidelines. player_tunic = player_tunic * 10 if player_tunic > 240 and player_tunic < 400: player_tunic = "Cold Resistant Tunic" print("You are wearing a: ", player_tunic) else: player_tunic = "Heat Resistant Tunic" print("You are wearing a: ", player_tunic) # Below can be simplified, but showing unsimplified per guidelines. # Divides by 10 per guidelines. player_henchman = player_henchman / 10 if player_henchman > 0: player_henchman = "Demon" print("You are followed by a: ", player_henchman) else: player_henchman = "Spirit" print("You are followed by a: ", player_henchman) # Modulus per guidelines. Gives remainder. player_deity = player_deity * 666 % 10 if player_deity < 5: player_deity = "Tyr" print("You worship: ", player_deity) else: player_deity = "Bane" print("You worship: ", player_deity) # Floor division per guidelines. Returns largest integer. player_star = player_star * 777 // 10 if player_star > 500: player_star = "Northern Hemisphere" print("You were born under the: ", player_star) else: player_star = "Southern Hemisphere" print("You were born under the: ", player_star) # All the player's information has been entered by now. continue_key_press() print("The cloaked figure comes out of it's trance.") print("'Easy as that...'") print("It leans forward in the chair and grabs your hand.") continue_key_press() print("'I hope you are ready for your adventure...'") print("And with a shimmer in the air, the figure is gone.") print("You feel emboldened, like you know yourself better than before.") continue_key_press() # Generates the final character sheet. print("YOUR CHARACTER SHEET") print(" ") print("YOUR NAME:", name_player) if race_select == 1: print("RACE: HALF-ORC") elif race_select == 2: print("RACE: HUMAN") else: print("RACE: HALFLING") if class_select == 1: print("CLASS: FIGHTER") elif class_select == 2: print("CLASS: ROGUE") else: print("CLASS: WIZARD") print("STR: ", player_str, "DEX: ", player_dex, "CON: ", player_con) print("INT: ", player_int, "WIS: ", player_wis, "CHA: ", player_cha) print("HIT POINTS:", hit_points) print("PET:", player_pet) print("TUNIC:", player_tunic) print("HENCHMAN:", player_henchman) print("DEITY:", player_deity) print("BORN UNDER WHICH STARS:", player_star) continue_key_press() print("...") print("A familiar voice says, 'Good luck.'") print("And with that, thank you for generating your character with me.") print("This should be enough to get you started on D&D adventure.") # Final user input that closes the program on their own terms. input("Press any key to close the program, go back to the real world: ") # CALL TO MAIN # main() # PyCharm used for debugging. # Warnings are for simplification. # Ignored warnings are a result of project guidelines.
import tkinter as tk # ColorScale class that creates a slider scale with a color gradient class ColorScale(tk.Canvas): def __init__(self, parent, val=0, height=13, width=80, variable=None, from_=0, to=1, command=None, gradient='hue', **kwargs): tk.Canvas.__init__(self, parent, width=width, height=height, **kwargs) self.parent = parent self.max = to self.min = from_ self.range = self.max - self.min self._variable = variable self.command = command self.color_grad = gradient self._variable = tk.IntVar(self) val = max(min(self.max, val), self.min) self._variable.set(val) self._variable.trace("w", self._update_val) self.gradient = tk.PhotoImage(master=self, width=width, height=height) self.bind('<Configure>', lambda e: self._draw_gradient(val)) #Draws the gradient for the slider def _draw_gradient(self, val): self.delete("gradient") self.delete("cursor") del self.gradient width = self.winfo_width() height = self.winfo_height() self.gradient = tk.PhotoImage(master=self, width=width, height=height) line = [] def f(i): factor = 255 / width r = 255 - (factor * i) b = factor * i tuple = (int(r), 0, int(b)) line.append("#%02x%02x%02x" % tuple) for i in range(width): f(i) line = "{" + " ".join(line) + "}" self.gradient.put(" ".join([line for j in range(height)])) self.create_image(0, 0, anchor="nw", tags="gradient", image=self.gradient) self.lower("gradient") x = (val - self.min) / float(self.range) * width if x < 4: x = 4 if x > width - 4: x = width - 4 self.create_line(x, 0, x, height, width=4, fill='white', tags="cursor") self.create_line(x, 0, x, height, width=2, tags="cursor") #Updates the position of the slider pointer def _update_val(self, *args): val = int(self._variable.get()) val = min(max(val, self.min), self.max) self.set(val) self.event_generate("<<HueChanged>>") #Gets the postition of the slider pointer def get(self): coords = self.coords('cursor') width = self.winfo_width() return round(self.range * coords[0] / width, 2) #Sets the position of the slider pointer def set(self, val): width = self.winfo_width() x = (val - self.min) / float(self.range) * width for s in self.find_withtag("cursor"): self.coords(s, x, 0, x, self.winfo_height()) self._variable.set(val)
#str1 = "hasan" str1 = input() a = str1.islower() if a==True: print("Lowercse") else: print("uppercase")
def check(number): if number%2==0: c= "EVEN" return c else: c ="ODD" return c number = int(input()) print(check(number))
class Car: def __init__(self): self.mil = 10 self.com ="mbw" c1 = Car() c2 = Car() #Car.com = "pjero" print(c1.mil , c1.com) print(c2.mil , c2.com)
def my_function(x): return x[::-1] mytxt=input("Input A string\n") print(my_function(mytxt))
from code_challenges.quick_sort.quick_sort import quick_sort, partition,swap def test_assert_quick_sort(): assert quick_sort def test_quick_sort(): list = [8,4,23,42,16,15] actual = quick_sort(list, 0, len(list)-1) expected = [4,8,15,16,23,42] assert actual == expected def test_quick_sort_with_negatives(): list = [-8,4,23,42,16,15] actual = quick_sort(list, 0, len(list)-1) expected = [-8,4,15,16,23,42] assert actual == expected def test_quick_sort_with_floats(): list = [8,4,23,42,15.5,15.6,60] actual = quick_sort(list, 0, len(list)-1) expected = [4,8,15.5,15.6,23,42,60] assert actual == expected def test_quick_sort_odd_num_of_nums(): list = [8,4,23,42,16,15,60] actual = quick_sort(list, 0, len(list)-1) expected = [4,8,15,16,23,42,60] assert actual == expected def test_quick_sort_with_one_value(): list = [8] actual = quick_sort(list, 0, len(list)-1) expected = [8] assert actual == expected def test_quick_sort_empty_list(): list = [] actual = quick_sort(list, 0, len(list)-1) expected = [] assert actual == expected def test_quick_sort_empty_list(): list = [4,3,2,1] actual = quick_sort(list, 0, len(list)-1) expected = [4,3,2,1] assert actual != expected
import string str1 = string.ascii_lowercase dictionary1 = {char:char for char in str1} dictionary2 = {char:(char+char if i%2 ==0 else char) for i,char in enumerate(str1)} dictionary3 = {'a': 'a', 'e': 'e', 'i': 'i', 'm': 'mm', 'q': 'qq', 'u': 'uu', 'y': 'yy'} def left_join(dictionary1, dictionary2): k2dict = {key:(True if key in dictionary2.keys() else False) for key in dictionary2.keys()} return [[key, dictionary1[key], dictionary2[key]] if k2dict[key] else [key, dictionary1[key], None] for key in dictionary1]
import random mylist = ["rock","paper","scissor"] randnum = random.choice(mylist) def game(user,randnum): if randnum == "rock": if user == "r": print("oops! Match tied computer chose: ",randnum) return 0 elif user == "s": print("oops! you lost computer chose: ",randnum) return 0 elif user == "p": print("Hurray! you won computer chose: ",randnum) return 1 elif randnum == "paper": if user == "s": print("Hurray! you won computer chose: ",randnum) return 1 elif user == "p": print("oops! Match tied computer chose: ",randnum) return 0 elif user == "r": print("oops! you lost computer chose: ",randnum) return 0 elif randnum == "scissor": if user == "p": print("oops! you lost computer chose: ",randnum) return 0 elif user == "r": print("Hurray! you won computer chose: ",randnum) return 1 elif user == "s": print("oops! Match tied computer chose: ",randnum) return 0 finalscore = 0 user = input("Choose Between Rock(r),Paper(p),Scissor(s)\n") score = game(user,randnum) finalscore = finalscore + score i=0 while i<1: play=input("Play Again! (y/n)\n") if(play=="y"): randnum = random.choice(mylist) user = input("Choose Between Rock(r),Paper(p),Scissor(s)\n") score = game(user,randnum) finalscore = finalscore + score else: i+=2 else: print("Thanks for Playing Your Total score is: ",finalscore) print("Game made by Raghav Kohli Thanks to CodeWithHarry")
# Define a list list1 = [1,2,3,4,5,6,7,8,9,10] print(list1) # Define an empty Dictionary for output dict1 = {} # Generating dictionary using for loop # Even numbers (keys) and their respective square (values) for x in list1: if x%2 == 0: dict1[x] = x**2 # Driver Code print(dict1) # Generating dictionary using comprehension dict2 = {x:x**2 for x in list1 if x%2 == 0} print(dict2)
""" Two iterators for a single looping construct: In this case, a list and dictionary are to be used for each iteration in a single looping block using enumerate function. Let us see example. """ # Define Two separate lists lang = ["English", "Hindi", "Marathi", "Arabic"] langtype = ["Business Language", "Native Language"] # Single dictionary holds characters of lang and its langtype. # First three items store characters of lang and next two items store characters of langtype. characters = {1:"26", 2:"44", 3:"53", 4:"28", 5:"26", 6:"44"} # Printing characters of lang for index, c in enumerate(lang, start=1): print ("Language: %s Characters: %s"%(c, characters[index])) # Printing characters of langtype for index, a in enumerate(langtype, start=1): print ("Type: %s Characters: %s"%(a,characters[index+len(lang)]))
#!/usr/bin/python3 # Regex search in file "*.txt" for regular expression import os, re, glob targetDir = "/tmp/python" targetRegex = re.compile(r'thuan') fileType = "*.txt" #suppose search only in current directory os.chdir(targetDir) for file in glob.glob(fileType, recursive=False): with open(file, "r") as fr: for line in fr: if targetRegex.search(line): print(file + ":" + line, end="")
import random as r #flowers, badgers, lions, buffer flowers, buffer badgers, buffer lions, cell version,last flowers, last badgers, last lions def matrix(x,y): out = [] #print(x,y) for i in range(x): out.append([(0,0,0,0,0,0,0,0,0,None)]*y) return(out) def matrix2(x,y): out = [] #print(x,y) for i in range(x): out.append([0]) return(out) #additional info # output on top left is in the format of (dandilion count, badger count, lion count) # this is the same as how the cells are colored, the (r ,g ,b) values are determed by (dandilion count, badger count, lion count) # # config w = 100 #width of matrix h = 100 #height of matrix pw = 500 #width of display ph = 500 #height of display rx = pw/w #width of a grid square ry = ph/h #height of a grid square bdrate = 0 #badger death rate, higher number equals longer living badgers ldrate = 0 #same thing but for lions bstart = 100 #badger starting population lstart = 100 #lion starting population dstart = 100 #dandilion starting population #end of config scene = matrix(w,h) searchR = 5 rpf = 0 badger_count = 0 #variables used for count on top left of screen lion_count = 0 dandelion_count = 0 #distribution functions, they take in a count of a given species and distribute it randomly across the scene def distribute_food(amount): global scene for i in xrange(amount): x = r.randint(0,w-1) y = r.randint(0,h-1) d,b,l,db,bb,lb,v,ld,lab,ll = scene[x][y] d += 1 scene[x][y] = (d,b,l,db,bb,lb,v,ld,lab,ll) def distributeBadgers(amount): global scene for i in range(amount): x = r.randint(0,w-1) y = r.randint(0,h-1) d,b,l,db,bb,lb,v,ld,lab,ll = scene[x][y] b += 1 scene[x][y] = (d,b,l,db,bb,lb,v,ld,lab,ll) def distributeLions(amount): global scene for i in range(amount): x = r.randint(0,w-1) y = r.randint(0,h-1) d,b,l,db,bb,lb,v,ld,lab,ll = scene[x][y] l += 1 scene[x][y] = (d,b,l,db,bb,lb,v,ld,lab,ll) #end of distribution functions def inr(x,y): #detects if a given matrix value is within the matrix, if it is not the given value that is out of range is set the the nearest in range value (ex in a 5x5 matrix (100,100) would be set to (4,4)) if x > w-1: x = w-1 if x < 0: x = 0 if y > h - 1: y = h-1 if y < 0: y = 0 return(x,y) #search functions, they take in an x,y valueand preform a basic raster search def badger_search(x,y): #highly inefficient test search global scene closest = (None,None) rp = (0,0) cdist = 0 for rx in xrange(searchR*2): for ry in xrange(searchR*2): cx = searchR-rx cy = searchR-ry ax = x + cx ay = y + cy ax,ay = inr(ax,ay) d,b,l,db,bb,lb,v,ld,lab,ll = scene[ax][ay] #l += 1 scene[ax][ay] = (d,b,l,db,bb,lb,v,ld,lab,ll) if d+db > 0: clx,cly = closest if clx == None: closest = (ax,ay) cdist = cx**2 + cy**2 rp = (cx,cy) else: cdist1 = cx**2 + cy**2 #print(searchR-rx,searchR-ry) if cdist1 < cdist: closest = (ax,ay) cdist = cdist1 rp = (cx,cy) if cdist1 == cdist and r.randint(0,2) == 1: closest = (ax,ay) cdist = ax**2 + ay**2 rp = (cx,cy) # rpx,rpy = rp mx= 0 my = 0 if rpx != 0: mx = rpx/abs(rpx) if rpy != 0: my = rpy/abs(rpy) if rp == (0,0): mx = r.randint(-1,1) my = r.randint(-1,1) return(mx,my) def lion_search(x,y): #highly inefficient test search global scene closest = (None,None) rp = (0,0) cdist = 0 for rx in xrange(searchR*2): for ry in xrange(searchR*2): cx = searchR-rx cy = searchR-ry ax = x + cx ay = y + cy ax,ay = inr(ax,ay) d,b,l,db,bb,lb,v,ld,lab,ll = scene[ax][ay] #l += 1 scene[ax][ay] = (d,b,l,db,bb,lb,v,ld,lab,ll) if b+bb > 0: clx,cly = closest if clx == None: closest = (ax,ay) cdist = cx**2 + cy**2 rp = (cx,cy) else: cdist1 = cx**2 + cy**2 #print(searchR-rx,searchR-ry) if cdist1 < cdist: closest = (ax,ay) cdist = cdist1 rp = (cx,cy) if cdist1 == cdist and r.randint(0,2) == 1: closest = (ax,ay) cdist = ax**2 + ay**2 rp = (cx,cy) # rpx,rpy = rp mx= 0 my = 0 if rpx != 0: mx = rpx/abs(rpx) if rpy != 0: my = rpy/abs(rpy) if rp == (0,0): mx = r.randint(-1,1) my = r.randint(-1,1) return(mx,my) #end of search functions def badgerAI(x,y): #print("ai ran",r.randint(0,5)) global scene #fill(255) #rect(x*rx,y*ry, 5,5) #rpf += 1 d,b,l,db,bb,lb,v,ld,lab,ll= scene[x][y] k = False mx,my = badger_search(x,y) x1 = x + mx y1 = y + my x1,y1 = inr(x1,y1) #print(mx,my) b -=1 if d > 0: rc = r.randint(0,10) if rc == 1: b += 1 d-=1 else: rc = r.randint(0,100) if rc == 1: #b -= 1 k = True scene[x][y] = (d,b,l,db,bb,lb,v,ld,lab,ll) if k == False: d1,b1,l1,db1,bb1,lb1,v1,ld1,lv1,ll1 = scene[x1][y1] if x1 > x or y1 > y: bb1 += 1 else: b1 += 1 #if v1 < v: # bb1 += 1 #else: # b1 += 1 #b1 += 1 scene[x1][y1] = (d1,b1,l1,db1,bb1,lb1,v1,ld1,lv1,ll1) def LionAI(x,y): #print("ai ran",r.randint(0,5)) global scene #fill(255) #rect(x*rx,y*ry, 5,5) #rpf += 1 d,b,l,db,bb,lb,v,ld,lab,ll= scene[x][y] mx,my = lion_search(x,y) x1 = x + mx y1 = y + my x1,y1 = inr(x1,y1) #print(mx,my) l -=1 if b > 0: rc = r.randint(0,10) #if rc == 1: #l += 1 b-=1 scene[x][y] = (d,b,l,db,bb,lb,v,ld,lab,ll) d1,b1,l1,db1,bb1,lb1,v1,ld1,lv1,ll1 = scene[x1][y1] if x1 > x or y1 > y: lb1 += 1 else: l1 += 1 #if v1 < v: # bb1 += 1 #else: # b1 += 1 #b1 += 1 scene[x1][y1] = (d1,b1,l1,db1,bb1,lb1,v1,ld1,lv1,ll1) def render_matrix(): global badger_count, lion_count,dandelion_count for x in xrange(w): for y in xrange(h): d,b,l,db,bb,lb,v,ld,lab,ll = scene[x][y] #scl = 0 #if (d+b+l) != 0: # scl = 255/(d+(b+bb)+l) if (d != ld) or (b != lab) or (l != ll): if l > 0: fill(0,0,255) elif b > 0: fill(0,255,0) elif d > 0: fill(255,0,0) else: fill(0) if (d < 0) or (b < 0) or (l < 0): print("low") fill(255,0,255) badger_count += b + bb lion_count += l+ lb dandelion_count += d + db rect(x*rx,y*ry,rx,ry) def run_ai(): global scene for x in xrange(w): for y in xrange(h): d,b,l,db,bb,lb,v,ld,lab,ll = scene[x][y] ld = d+db lab = b+bb ll = l+lb #print(b) for i in xrange(b): badgerAI(x,y) for i in xrange(l): LionAI(x,y) #print(x,y) d,b,l,db,bb,lb,v,ld,lab,ll = scene[x][y] if l != 0: print(l) # if b != 0: # print(b) #re_add_buffers(x,y) #d,b,l,db,bb,lb,v,lad,lb,ll = scene[x][y] v += 1 scene[x][y] = (d+db,b+bb,l+lb,0,0,0,v,ld,lab,ll) #print("end") def smc(sx,sy): #screen to matrix coordinate converter mx = int(round(sx/rx)) my = int(round(sy/ry)) mx,my = inr(mx,my) return(mx,my) def mouseClicked(): mx,my = smc(mouseX,mouseY) d,b,l,db,bb,lb,v,ld,lb,ll = scene[mx][my] b += 1 print(mx,my) #scene[mx][my] = (d,b,l,db,bb,lb,v,ld,lb,ll) print(frameRate) def setup(): size(pw,ph) #frameRate(60) noStroke() distributeBadgers(500) distribute_food(50) distributeLions(10) render_matrix() def draw(): global badger_count, lion_count,dandelion_count global rpf #print(rpf) #background(0) #rpf = 0 distribute_food(5) #distributeBadgers(1) #print(frameRate) #stroke(255) #text(str(frameRate),20,20) #noStroke() #print(getFoodChunk(10,10)) run_ai() render_matrix() fill(255,0,255) rect(0,0,150,20 ) fill(0) text(str( dandelion_count )+ "," + str( badger_count ) + "," + str(lion_count ) ,0,10) badger_count = 0 lion_count = 0 dandelion_count = 0 #print(tx,ty) pass
import numpy as np a = np.array([1,2,3,4,5]) print(a) print(np.__version__) arr = np.array([1,2,3,4,5]) print(arr) print(arr.ndim) #ndim checks dimensions of array. arr1 = np.array([[[1,2,3],[1,2,3],[1,2,3]]]) print(arr1) print(arr1.ndim)
print("FILTERING ARRAYS: ") #filterng an array using a boolean index list. import numpy as np a = np.array([12,44,56,45,78,66]) x = [True,True,True,False,True,False] print(a[x]) print("CREATING FILTER ARRAYS: ") ar = np.array([12,34,56,13,23,78,90,10]) #print the numbers those are greatr than 13: ar_filter = [] for elements in ar : if elements>13 : print(ar_filter.append(True)) else: print(ar_filter.append(False)) newAr = ar[ar_filter] print("filtered array :", ar_filter) print(newAr) #2nd method: arr = np.array([22,44,66,88,11,33,55,99,23,45,67,89]) filter_arr = arr>44 newarr = arr[filter_arr] print("new array: ", newarr)
#!/usr/bin/env python # # import unittest class BowlingScoreTests(unittest.TestCase): def test_can_parse_all_strike_score_sheet(self): """Can parse score sheet with all strikes""" roll_count = len(Game('X X X X X X X X X X X X').rolls) self.assertEqual(roll_count, 12) def test_can_parse_no_pickup_score_sheet(self): """Can parse score sheet with no pickup rolls""" roll_count = len(Game('9- 9- 9- 9- 9- 9- 9- 9- 9- 9-').rolls) self.assertEqual(roll_count, 20) def test_can_parse_very_short_game(self): """Can parse a game with only one roll""" roll_count = len(Game('1').rolls) self.assertEqual(roll_count, 1) def test_can_score_very_short_game(self): """Can score a game with only one roll""" self.assertEqual(Game('1').score(), 1) def test_can_score_almost_as_short_game(self): """Can score a game with only two rolls""" self.assertEqual(Game('12').score(), 3) def test_can_score_a_good_frame_then_quit(self): """Can score a game with only one roll""" self.assertEqual(Game('9-').score(), 9) def test_can_score_no_pickup_score_sheet(self): """Can score sheet with no pickup rolls""" self.assertEqual(Game('9- 9- 9- 9- 9- 9- 9- 9- 9- 9-').score(), 90) def test_can_score_one_strike_score_sheet(self): """Can score sheet with a strike""" self.assertEqual(Game('X 9- 9- 9- 9- 9- 9- 9- 9- 9-').score(), 100) def test_can_score_all_strike_score_sheet(self): """Can parse score sheet with all strikes""" self.assertEqual(Game('X X X X X X X X X X X X').score(), 300) def test_can_score_one_strike_score_sheet(self): """Can score sheet with a strike""" self.assertEqual(Game('X 9- 9- X 9- 9- 9- 9- X 9-').score(), 120) def test_can_score_sheet_with_many_spares(self): """Can score a whole sheet full of spares""" self.assertEqual(Game('5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/ 5').score(), 200) class FlattenTests(unittest.TestCase): def test_can_flatten_list(self): """Can flatten a list of lists to a 1-dimensional list""" self.assertEqual(flatten([[1,2], [3,4]]), [1,2,3,4]) def flatten(lst): return [item for sublist in lst for item in sublist] class Game: def __init__(self, scoresheet): scoresheet_by_frame = map(lambda x: list(x), scoresheet.split(' ')) self.rolls = flatten(scoresheet_by_frame) def score(self): def char_to_score(n): if n is 'X' or n is '/': return 10 elif n is '-': return 0 else: return int(n) sum = 0 frames_complete = 0 in_frame = False for i, roll in enumerate(self.rolls): if roll is 'X': sum += char_to_score('X') if i+1 < len(self.rolls): sum += char_to_score(self.rolls[i+1]) if i+2 < len(self.rolls): sum += char_to_score(self.rolls[i+2]) frames_complete += 1 in_frame = False elif roll is '/': sum += char_to_score('/') if i+1 < len(self.rolls): sum += char_to_score(self.rolls[i+1]) frames_complete += 1 in_frame = False else: sum += char_to_score(roll) if in_frame: frames_complete += 1 in_frame = False else: in_frame = not in_frame if frames_complete == 10: break return sum
#1. Fix the 5 syntax errors in the code below so that it runs. It should print the length of myFirstList and print the result of myFirstList * 3. #Then it should set mySecondList to the concatenation of myFirstList and a list containing 321.4. #Then it should print the value of mySecondList. myFirstList = [12,"ape",13] print(len(myFirstList)) print(myFirstList * 3) mySecondList = myFirstList + [321.4] print(mySecondList) #2. It runs and prints the contents of items. def itemLister(items): items[0] = "First item" items[1] = items[0] items[2] = items[2] + 1 print(items) itemLister([2,4,68]) #3. The function returns the average of a list of integers. def gradeAverage(aList): sum = 0 for num in aList: sum = num + sum average = sum/len(aList) return average aList = [99, 100, 74, 63, 100, 100] print(gradeAverage(aList)) #4. Assign the value of the item at index 3 of l to “200” l = ["hi", "goodbye", "python", "106", "506"] l[3] = "200" print(l) #5. Using indexing, retrieve the string ‘willow’ from the list and assign that to the variable plant. data = ['bagel', 'cream cheese', 'breakfast', 'grits', 'eggs', 'bacon', [34, 9, 73, []],[['willow', 'birch', 'elm'], 'apple', 'peach', 'cherry']] data_last = data[-1] print(data_last) plant = data_last[0][0] print(plant) #6. Write a function called countWords that returns a count of how many words in the pased list, lst, have length 5. def countWords(lst): count = 0 for word in lst: if len(word) == 5: count = count + 1 return count #7. Write a function called chop that takes a list lst and modifies it, removing the first and last elements. def chop(lst): del lst[0] del lst[-1] return(lst) #8. see #7 #9. Sum all the elements in the list lst up to but not including the first even number. def sumUntilEven(lst): total = 0 element = 0 while element < len(lst) and lst[element] % 2 != 0: total = total + lst[element] print("tot:",total) element = element + 1 print("ele:",element) return total sumUntilEven([1,3,5,7,9]) #10. Write a function called reverse that returns the reverse of a passed list. def reverse(lst): lst.reverse() return lst
#Q-1: The following segment should print the statement, "So happy 4 you!". emotion = "So happy " print(emotion + str(4) + " you!") #Q-2: The following program segment should print the phrase, "My new book cost $12". item = "new book" price = "12" print("My " + item + " cost $" + price) #Q-3: The following program segment should print the phrase, "Sam likes to code". person = "Sam " thing = "likes to code" print(person + thing) #Q-4: The following program segment should print the phrase, "It takes us 2 hours and 45 minutes to get home from camp". numHours = 2 numMinutes = 45.0 print("It takes us " + str(numHours) + " hours and " + str(int(numMinutes)) + " minutes to get home from camp") #Q-5: The following program segment should print the phrase, "Grace loves grapes". feeling = "loves" print("Grace " + feeling + " grapes") #Q-6: The following program segment should print the phrase, "My sheepdog looks like a Muppet". animal = "sheepdog" print("My " + animal + " looks like a Muppet") #Q-7: The following program segment should print the phrase, "3 + 300 + 7 = 310". num1 = 3 num2 = 300 num3 = 7 print(str(num1) + " + " + str(num2) + " + " + str(num3) + " = " + str(ans)) #Q-8: The following program segment should print the phrase, "I am a CS wizard". var1 = "I am a " var2 = "CS wizard" print(var1 + var2) #Q-9: The following program segment should print the phrase, "'Red' is a primary color, and so is 'blue'".\ col1 = "'Red'" col2 = "'blue'" print(col1 + " is a primary color, and so is " + col2) #Q-10: The following program segment should print the phrase, "Petting dogs makes me happier than anything else". var1 = "dogs" print("Petting " + var1 + " makes me happier than anything else")
import tkinter, tkinter.messagebox # Tkクラス生成 tki = tkinter.Tk() # 画面サイズ tki.geometry('300x200') # 画面タイトル tki.title('ラジオボタン') # ラジオボタンのラベルをリスト化する rdo_txt = ['Python','Java','C#'] # ラジオボタンの状態 rdo_var = tkinter.IntVar() # ラジオボタンを動的に作成して配置 for i in range(len(rdo_txt)): rdo = tkinter.Radiobutton(tki, value=i, variable=rdo_var, text=rdo_txt[i]) rdo.place(x=50, y=30 + (i * 24)) # ボタンクリックイベント def btn_click(): num = rdo_var.get() tkinter.messagebox.showinfo('チェックされた項目', rdo_txt[num]) # ボタン作成 btn = tkinter.Button(tki, text='ラジオボタン取得', command=btn_click) btn.place(x=100, y=170) rdo_var.set('2') tki.mainloop()
# !/usr/bin/python # -*- coding: UTF-8 -*- """ Author: YH.Chen Purpose: Use multiprocessing package to create multiprocessing. Created: 24/6/2020 """ import multiprocessing as mul from multiprocessing import Process import os # 进程信息输出函数 def info(title): print(title) # 输出进程名称 print('module name:', __name__) # 输出进程号 print('process id:', os.getpid()) # 进程对应打印输出函数 def process(name): # 调用info()函数输出进程信息 info('function process') print('hello', name) print('=' * 50) if __name__ == '__main__': info('main line') print('=' * 50) # 利用缓冲池创建多进程 pool = mul.Pool(5) rel = pool.map(process, ['Wayne', 'Grayson', 'Jason', 'Drake', 'Damian']) p = Process(target=process, args=(rel,)) p.start() p.join()
##!/usr/bin/python3 """ Author: ZhengPeng.Han Purpose: Get infomation of the operating system by a built-in function of python,which named platform. Created: 26/6/2020 """ import platform def TestPlatform(): print("----------Operation System Info--------------------------") print('The version of Python is:',platform.python_version())# 获取Python版本 print('The structure of OS executable is:',platform.architecture())# 获取操作系统可执行程序的结构 print('The network name of the computer is:',platform.node())# 计算机的网络名称 print('The name of OS and version number is:',platform.platform())# 获取操作系统名称及版本号 print('The computer processor information is:',platform.processor())# 计算机处理器信息 print('The build date for Python on the OS is:',platform.python_build())# 获取操作系统中Python的构建日期 print('The information about the Python interpreter in the OS is:',platform.python_compiler()) # 获取系统中python解释器的信息 if platform.python_branch() == "": print('The Python implementation is:',platform.python_implementation()) print('The Python implementation SCM revision is:',platform.python_revision()) print('The release information is:',platform.release()) print('The operating system is:',platform.system())#获取此电脑使用什么操作系统 print('The OS version is:',platform.version())# 获取操作系统的版本 print('All the information is:',platform.uname())# 包含上面所有的信息汇总 if __name__ == "__main__": TestPlatform()
#采用Python语言创建多进程;提示:采用Python内置工具包multiprocessing from multiprocessing import Process import os, time # 线程启动后实际执行的代码块 def pr1(process_name): for i in range(5): print (process_name, os.getpid()) # 打印出当前进程的id time.sleep(1) def pr2(process_name): for i in range(5): print (process_name, os.getpid()) # 打印出当前进程的id time.sleep(1) if __name__ == "__main__": print ("main process run...") # target:指定进程执行的函数 # args:传入target参数对应函数的参数,需要使用tuple p1 = Process(target=pr1, args=('process_name1',)) p2 = Process(target=pr2, args=('process_name2',)) p1.start() p2.start() p1.join() p2.join() print ("main process ran all lines...")
##!/usr/bin/python3 # -*- coding: UTF-8 -*- """ Author: ZhengPeng.Han Purpose: Gets the names of all files and folders in the given file directory by a built-in function of python,which named os.path. Created: 26/6/2020 """ import os path = 'D:\VIPworks' # 回调函数 def find_file(arg, dirname, files): for file in files: file_path = os.path.join(dirname, file) if os.path.isfile(file_path): print("找到文件:%s" % file_path) # 调用 print('%s下的所有文件和文件夹为:' %path) os.path.walk("D:\VIPworks", find_file, ()) ''' #有另外的一个不使用os.path.walk的办法是使用os.walk遍历目录 import os def file_name_walk(file_dir): for root, dirs, files in os.walk(file_dir): print("root", root) # 当前目录路径 print("dirs", dirs) # 当前路径下所有子目录 print("files", files) # 当前路径下所有非目录子文件 file_name_walk("D:\VIPworks") #os.listdir()方法可以返回指定路径下所有的文件和文件夹列表,但是子目录下文件不遍历。 def file_name_listdir(file_dir): for files in os.listdir(file_dir): print("files", files) file_name_listdir("D:\VIPworks") '''
""" Author:Chenjiaying Purpose:采用Python语言创建多进程 Created:1/7/2020 """ from multiprocessing import Process import time def f(name): time.sleep(1) print('hello', name, time.ctime()) if __name__ == '__main__': p_list = [] for i in range(3): p = Process(target=f, args=('reid',)) # 创建一个进程对象,再传入一个函数f为参数 p_list.append(p) p.start() for p in p_list: p.join() print('end')
import os def print_list_dir(root_path): dir_files = os.listdir(root_path) for f in dir_files: file_path = os.path.join(root_path, f) if os.path.isfile(file_path): print(file_path) if os.path.isdir(file_path): print_list_dir(file_path) if __name__ == '__main__': dir_path = ' your path' print_list_dir(dir_path)
""" Author: jianxi.li Purpose: homework2:采用python语言实现windows命令行调用;提示:采用Python内置工具包os.system Created: 26/6/2020 """ import os #os.system("calc")#启动计算器 #os.system("appwiz.cpl")#程序和功能 #os.system("certmgr.msc")#证书管理实用程序 #os.system("charmap")#启动字符映射表 #os.system("chkdsk.exe")#Chkdsk磁盘检查(管理员身份运行命令提示符) order = input('imput your order') os.system(order)
import multiprocessing import time # 定义一个空列表 m_list = [] # 定义一个向列表添加元素的函数 def add_list(): # 查看进程id编号 print("add:", id(m_list)) # 循环0,1,2,3,4 for i in range(5): # 把循环的元素添加到列表 m_list.append(i) # 打印列表 print(m_list) # 休息1秒 time.sleep(1) # 定义一个函数对比全局不共享 def get_list(): # 查看进程id编号 print("get:", id(m_list)) # 获取列表 print("current", m_list) # main函数 def main(): # 线程一 add = multiprocessing.Process(target=add_list) add.start() add.join() # 线程二 multiprocessing.Process(target=get_list).start() # 查看进程id编号 print("before", id(m_list)) # 获取现在列表 print("now", m_list) # 主函数 if __name__ == "__main__": main()
# coding=utf-8 ''' Author: By.Zhang Purpose: create multiprocess by python. Created: 28/6/2020 ''' from multiprocessing import Process from multiprocessing import Pool import time import os import random # --------创建函数并将其作为单个进程。-------- # 通过Multiprocessing模块中的Process类,创建Process对象 # 通过对象参数target="需要执行的子进程" # def pro1(interval): # for i in range(3): # print("子进程", i) # print("The time is {0}".format(time.ctime())) # time.sleep(interval) # # # if __name__ == "__main__": # p = Process(target=pro1, args=(2,)) # p.start() # p.join() # 加入该语句是等子进程结束后再执行下面代码 # print("执行主进程内容") # print("p.pid:", p.pid) # print("p.name:", p.name) # print("p.is_alive:", p.is_alive()) # -------子类创建进程------- # 通过继承Process类创建子进程,并进行重写 # class newProcess(Process): # # 继承Process类,必须要调用Process中的init初始化参数, # def __init__(self, interval): # Process.__init__(self) # self.interval = interval # # # 重写run方法 # def run(self): # for i in range(3): # print("子进程", i) # print("The time is {0}".format(time.ctime())) # time.sleep(self.interval) # # # if __name__ == "__main__": # p = newProcess(1) # p.start() # print("执行主进程") # -------使用进程池(非阻塞)------- # Pool可以提供指定数量的进程,供用户调用 # def pro2(msg): # print("msg start:", msg) # start_time = time.time() # time.sleep(random.random()) # end_time = time.time() # print('msg end:{} cost time:{} pid:{}'.format(msg, (end_time - start_time), os.getpid())) # print('\n') # # # if __name__ == "__main__": # pool = Pool(processes=3) # for i in range(4): # msg = "子进程 %d" % i # # 维持执行的进程总数为processes,当一个进程执行完毕后会添加新的进程进去 # pool.apply_async(pro2, (msg, )) # # print("~~~~~~~~~~~~~~~~~~") # pool.close() # 关闭进程池,不允许继续添加进程 # pool.join() # print("All processes done.") # -------使用进程池(阻塞)-------- def pro3(msg): print("%s start:" % msg) start_time = time.time() time.sleep(random.random()*3) end_time = time.time() print('msg end:{} cost time:{} pid:{}'.format(msg, (end_time - start_time), os.getpid())) print("msg end:", msg) print('\n') if __name__ == "__main__": pool = Pool(processes=4) for i in range(4): msg = "子进程 %d" % i # 维持执行的进程总数为processes,当一个进程执行完毕后会添加新的进程进去 pool.apply(pro3, (msg, )) print("~~~~~~~~~~~~~~~~~~") pool.close() # 执行完close后不会有新的进程加入到pool pool.join() # join函数等待所有子进程结束 print("All processes done.")
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') while True: city = input('Would you like to see data for Chicago, New York, or Washington: ') if city not in ('Washington', 'Chicago', 'New York'): print("Not an appropriate choice. This Input Function is case sensitive.") else: break while True: Case_M = input('Would you like to filter the data by month, day, both or not at all? Type "none" for no time filter: ') if Case_M not in ('month', 'day', 'both', 'none'): print("Not an appropriate choice. This Input Function is case sensitive.") else: break # TO DO: get user input for month (all, january, february, ... , june) while True: Month_Temp = input('[If you entered "day" or "none" before just enter a random month now, it will not affect the analysis] Which month? All, January, February, March, April, May, or June?: ') if Month_Temp not in ('All', 'January', 'February', 'March', 'April', 'May', 'June'): print("Not an appropriate choice. This Input Function is case sensitive.") else: break # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) while True: try: while True: Day_Temp = input('[If you entered "month" or "none" before just enter a random day now, it will not affect the analysis] Which day? All, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday: ') if Day_Temp not in ('All', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'): print("Not an appropriate choice. This Input Function is case sensitive.") else: break break except ValueError: print("Not an appropriate choice. This Input Function is case sensitive.") if Case_M in ('both'): month = Month_Temp day = Day_Temp elif Case_M in ('month'): month = Month_Temp day = 'All' elif Case_M in ('day'): month = 'All' day = Day_Temp else: month = 'All' day = 'All' print('-'*40) return city, Case_M, month, day ########################################################################## def load_data(city, Case_M, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ monthh = month dayy = day city = city #city, month, day = get_filters() #df = pd.DataFrame(CITY_DATA) df_w = pd.read_csv('./washington.csv') df_w['City'] = 'Washington' df_n = pd.read_csv('./new_york_city.csv') df_n['City'] = 'New York' df_c = pd.read_csv('./chicago.csv') df_c['City'] = 'Chicago' df_temp = df_w df_temp = df_temp.append(df_n) df_temp = df_temp.append(df_c) # convert the Start Time column to datetime df_temp['Start Time'] = pd.to_datetime(df_temp['Start Time']) # extract month and day of week from Start Time to create new columns df_temp['month'] = df_temp['Start Time'].dt.month df_temp['day_of_week'] = df_temp['Start Time'].dt.weekday_name df_temp['hour'] = df_temp['Start Time'].dt.hour df_temp['Start End Combination'] = df_temp['Start Station'] + df_temp['End Station'] df_temp['Trip Duration Hour'] = df_temp['Trip Duration'] / 3600 # filter by month if applicable monthhh = monthh.lower() if monthhh != 'all': # use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] monthhh = months.index(monthhh) + 1 # filter by month to create the new dataframe df_temp = df_temp[df_temp['month'] == monthhh] #filter by day of week if applicable dayyy = dayy.lower() if dayyy != 'all': #filter bypyt day of week to create the new dataframe df_temp = df_temp[df_temp['day_of_week'] == dayyy.title()] ## city filtern is_city = df_temp['City']==city df = df_temp[is_city] return df ################################################################################# def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # TO DO: display the most common month print('most common month [output as an integer (e.g., 1=Januray)]:', df['month'].mode()[0]) # TO DO: display the most common day of week print('most common day of week:', df['day_of_week'].mode()[0]) # TO DO: display the most common start hour print('most common start hour:', df['hour'].mode()[0]) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) ################################################################################# def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station print('most commonly used start station:', df['Start Station'].mode()[0]) # TO DO: display most commonly used end station print('most commonly used end station:', df['End Station'].mode()[0]) # TO DO: display most frequent combination of start station and end station trip print('most frequent combination of start station and end station trip:', df['Start End Combination'].mode()[0]) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) ################################################################################# def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # TO DO: display total travel time print('total travel time [Hours]:', df['Trip Duration Hour'].sum()) # TO DO: display mean travel time print('mean travel time [Hours]:', df['Trip Duration Hour'].mean()) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) ################################################################################# def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types print('counts of user types:', df['User Type'].value_counts()) while True: try: print('counts of gender:', df['Gender'].value_counts()) # TO DO: Display earliest, most recent, and most common year of birth print('earliest year of birth:', int(df['Birth Year'].min())) print('most recent year of birth:', int(df['Birth Year'].max())) print('most common year of birth:', int(df['Birth Year'].mode()[0])) #while True: #day_temp = input('[If you entered "month" or "none" before just enter a random day now, it will not affect the analysis] Which day? All, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday: ') #if day_temp not in ('All', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'): #print("Not an appropriate choice. This Input Function is case sensitive.") #else: #break break except ValueError: print("THERE ARE NO USER FURTHER GENDER AND BIRTH YEAR STATISTICS FOR CITY: WASHINGTON") break #print('counts of gender:', df['Gender'].value_counts()) # TO DO: Display earliest, most recent, and most common year of birth #print('earliest year of birth:', int(df['Birth Year'].min())) #print('most recent year of birth:', int(df['Birth Year'].max())) #print('most common year of birth:', int(df['Birth Year'].mode()[0])) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) ################################################################################# def main(): while True: city, Case_M, month, day = get_filters() #city = 'Washington' #case_m = 'both' #month = 'All' #day = 'All' df = load_data(city, Case_M, month, day) #print(city) #print(case_m) #print(month) #print(day) #print(df) #df.to_csv(r'.\File Name.csv') time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) count = -5 #print(count) while True: while True: answ = input('Would you like to view indivual trip data? Type "yes" or "no".: ') if answ not in ('yes', 'no'): print("Not an appropriate choice. This Input Function is case sensitive.") else: break if answ.lower() != 'no': count = count + 5 #print(count) print(df.iloc[count]) print(df.iloc[count+1]) print(df.iloc[count+2]) print(df.iloc[count+3]) print(df.iloc[count+4]) #answ = input('Would you like to view indivual trip data? Type "yes" or "no".: ') else: break while True: restart = input('\nWould you like to restart? Enter yes or no.\n') if restart not in ('yes', 'no'): print("Not an appropriate choice. This Input Function is case sensitive.") else: break if restart.lower() != 'yes': break if __name__ == "__main__": main()
print("hello wendy :)") # recursion! # call function within a function! # with every recursion problem # what's the base case! # how do we pass along our issuez # factorialz! def factorial(n): """ calls n factorial - 1 base case? n == 0??? return 1 2! = 2 because 2 * 1 = 2 3! = 6 because 3 * factorial(2) """ if n == 0: return 1 return n * factorial(n-1) print("2 factorial is: " + str(factorial(2))) print("4 factorial is: " + str(factorial(4))) print("6 factorial is: " + str(factorial(6))) class TreeNode: population = 0 def __init__(self, x): self.val = x self.left = None self.right = None TreeNode.population += 1 def searchBST(self, root, val): """ if it's none, return none! called itself for the left left = FUNCTION CALL called itself for the right right = FUNCTION CALL if the node's value equals val, return that node! ^__^ check left, right, and root """ if root == None: return None if root.val == val: return root left = self.searchBST(root.left, val) right = self.searchBST(root.right, val) if left != None: if left.val == val: return left if right != None: if right.val == val: return right return None # print("treenode val" + str(TreeNode.val)) # this is gonna error # bobz print("old pop: " + str(TreeNode.population)) BobJrTree = TreeNode("Alice") left = TreeNode("Bob") right = TreeNode("Carol") # CAROL left2 = TreeNode("Bob Jr.") print("new pop: " + str(TreeNode.population)) BobJrTree.left = left BobJrTree.right = right left.left = left2 print("pop: " + str(BobJrTree.population)) print("val: " + str(BobJrTree.val)) print("===================") BobJrTree.searchBST(BobJrTree, "Carol") assert(1 == 1) hopefullyCarolTree = BobJrTree.searchBST(BobJrTree, "Carol") assert(hopefullyCarolTree.val == right.val) hopefullyBobJrTree = BobJrTree.searchBST(BobJrTree, "Bob Jr.") assert(hopefullyBobJrTree.val == left2.val)
# Initializing Variables in Python # Creating Variables # A variable is created the moment you first assign a value to it. x = 5 y = "John" print(x) print(y) # Variables do not need to be declared with any particular type and can even change type after they have been set. z = 4 # z is of type int z = "Sally" # z is now of type str print(z) # Variable Names # A variable name must start with a letter or the underscore character # A variable name cannot start with a number # A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) # Variable names are case-sensitive (age, Age and AGE are three different variables) # Remember that variables are case-sensitive # Output Variables # The Python print statement is often used to output variables. # # To combine both text and a variable, Python uses the + character: x = "awesome" print("Python is " + x) # You can also use the + character to add a variable to another variable: x = "Python is " y = "awesome" z = x + y print(z) # For numbers, the + character works as a mathematical operator: x = 5 y = 10 print(x + y) # If you try to combine a string and a number, Python will give you an error: x = 5 y = "John" print(x + y)
""" The View class for The Ark. """ import pygame pygame.init() class ArkView(): """ A class that represents the game view of the game, The Ark. """ def __init__(self, ark_game): """ Creates a new ArkController instance. """ self._game = ark_game self._font = pygame.font.SysFont("Consolas", 90) self._font_small = pygame.font.SysFont("Verdana", 20) @property def game(self): """ Return the value of the private attribute, self._game. """ return self._game @property def font(self): """ Return the value of the private attribute, self._font. """ return self._font @property def font_small(self): """ Return the value of the private attribute, self._font_small. """ return self._font_small def set_screen(self): """ Initializes the game screen and creates the screen window's surface. Args: This method has no arguments. Returns: The surface that represents the window screen the game. """ pygame.init() display_surf = pygame.display.set_mode((self.game.SCREEN_WIDTH, self.game.SCREEN_HEIGHT)) display_surf.fill(self.game.WHITE) pygame.display.set_caption("The Ark") return display_surf def update_screen(self, display_surf, all_sprites, movable_sprites): """ Updates and redraws all sprites and text on the screen. Args: display_surf: The window screen surface of the game all_sprites: The Sprite Group that holds all of the sprites movable_sprites: The Sprite Group that holds all of the sprites that have move methods. Returns: This method does not return anything. """ # updates the window screen and the Score and Lives text display_surf.blit(self.game.background, (0,0)) scores = self.font_small.render(f"SCORE: {self.game.score}", True, self.game.WHITE) display_surf.blit(scores, (self.game.SCREEN_WIDTH-100,10)) life = self.font_small.render(f"LIVES: {self.game.lives}", True, self.game.WHITE) display_surf.blit(life, (self.game.SCREEN_WIDTH-100,30)) # updates the sprites for sprite in all_sprites: display_surf.blit(sprite.image, sprite.rect) if sprite in movable_sprites: sprite.move() def game_won(self, display_surf): """ Updates screen background and tells player that they have won the game. Args: display_surf: The window screen surface of the game. Returns: This method does not return anything. """ game_won = self._font.render("You won!", True, self.game.WHITE) img = pygame.image.load("win.jpg") display_surf.blit(img, (0,0)) display_surf.blit(game_won, (130, 150)) pygame.display.update() def game_lost(self, display_surf): """ Updates screen background and tells player that they have lost the game. Args: display_surf: The window screen surface of the game. Returns: This method does not return anything. """ game_over = self._font.render("Game Over", True, self.game.WHITE) img = pygame.image.load("lose.jpg") display_surf.blit(img, (0,0)) display_surf.blit(game_over, (100, 150)) pygame.display.update()
# !usr/bin/env python3 ### Author: Marius Ingebrigtsen ### from sys import path def cmpint(a, b): """ Comparison function for numbers. """ return a - b class EntryIterator: """ Iterator class for map entry. """ def __init__(self, entry = MapEntry): """ Assign entry values. """ self.head = self.entry = entry def next(self): """ Return next entry in sequence. """ try: while True: yield self.entry self.entry = self.entry.next except AttributeError: raise StopIteration def __next__(self): """ Function of both python 2 and 3. """ return self.next() class MapEntry: """ Class for entries into hashmap. """ def __init__(self, key = None, value = None, hashv = None, nextnode = None): """ Create entry and assign values. """ self.key = key self.value = value self.hashv = hashv self.next = nextnode def iter(self): """ Return iterator over entry. """ return EntryIterator(self) def __iter__(self): """ Function of both python 2 and 3. """ return self.iter() class HashMap: """ Hash-Map ADT. Collision strategy is chained addressing with Red-Black Tree structures. """ # Map Create: # def __init__(self, cmpfunc = cmpint, hashfunc = hash, STARTENTRIES = 2**10): """ Hash-Map Structure. """ if STARTENTRIES < 2**10: STARTENTRIES = 2**10 self.table = [None for i in range(STARTENTRIES)] # Essentially calloc(). self.entries = 0 self.maxentries = STARTENTRIES self.cmpfunc = cmpfunc self.hashfunc = hashfunc # Map Destroy: # def clear(self): """ Empties all entries. """ self.table = [None for i in range(self.maxentries)] self.entries = 0 # Map Put: # def _resizeput(self, key = None, value = None): """ Same functionality as 'put()', but without size- or containment-checks. """ hashv = self.hashfunc(key) indx = hashv % self.maxentries if self.table[indx] is None: self.table[indx] = MapEntry(key, value, hashv, None) else: self.table[indx] = MapEntry(key, value, hashv, self.table[indx]) self.entries += 1 def _resize(self): """ Increase scope of map, and re-address each entry. """ self.entries = 0 self.maxentries *= 2 oldtable = self.table self.table = [None for i in range(self.maxentries)] for indx in oldtable: if indx is not None: for entry in indx: self._resizeput(entry.key, entry.value) def put(self, key = None, value = None): """ Maps key to value. If key already in map, value is overwritten by argument-value. Return True if put into map. Return False if value overwritten. """ if self.entries >= self.maxentries: self._resize() hashv = self.hashfunc(key) indx = hashv % self.maxentries if self.table[indx] is None: self.table[indx] = MapEntry(key, value, hashv, None) else: for entry in self.table[indx]: if hashv == entry.hashv and self.cmpfunc(key, entry.key) == 0: entry.value = value return False self.table[indx] = MapEntry(key, value, hashv, self.table[indx]) self.entries += 1 return True # Map Has Key: # def haskey(self, key = None): """ Return True if key is associated with value in map. Return False otherwise. """ hashv = self.hashfunc(key) indx = hashv % self.maxentries if self.table[indx] is not None: for entry in self.table[indx]: if hashv == entry.hashv and self.cmpfunc(key, entry.key) == 0: return True return False # Map Get: # def get(self, key = None): """ Return value associated with key. Return None if key not associated in map. """ hashv = self.hashfunc(key) indx = hashv % self.maxentries if self.table[indx] is not None: for entry in self.table[indx]: if hashv == entry.hashv and self.cmpfunc(key, entry.key) == 0: return entry.value return None # Map Size: # def __len__(self): """ Size / length of map. """ return self.entries if __name__ == "__main__": pass
# !usr/bin/env python3.8 from sys import path path.insert(1, "../bst/") from bst import BinarySearchTree, Node class Node(Node): """ Node for rbt-structure. """ def __init__(self, key = None, item = None, nextnode = None): """ Create and assign value to node. """ self.key = key self.item = item self.color = "red" self.left = None self.right = None self.child = None self.next = nextnode def split(self): """ Attempt to discover 2-3-4-Tree equivalent of 4-node, and then 'split' them. """ try: if self.left.color == "red" and self.right.color == "red": self.color = "red" self.left.color = self.right.color = "black" except AttributeError as NoneNode: return def right_left_case(self, fromright = 0/1): """ Check for Red Right-Left Case on current. """ child = self try: if fromright and current.color == "red" and current.left.color == "red": child = self._rotate_right() except AttributeError as NoneNode: return child finally: return child def left_left_case(self): """ Check for Red Left-Left Case on current. """ child = self try: if self.left.color == "red" and self.left.left.color == "red": child = self._rotate_right() child.color = "black" self.color = "red" except AttributeError as NoneNode: return child finally: return child def left_right_case(self, fromright = 0/1): """ Check for Red Left-Right Case on current. """ child = self try: if not fromright and current.color == "red" and current.right.color == "red": child = self._rotate_left() except AttributeError as NoneNode: return child finally: return child def right_right_case(self): """ Check for Red Right-Right Case on current. """ child = self try: if self.right.color == "red" and self.right.right.color == "red": child = self._rotate_left() child.color = "black" self.color = "red" except AttributeError as NoneNode: return child finally: return child class RedBlackTree(BinarySearchTree): """ Self-balancing binary search tree. """ # Red-Black Tree Insert: # def _insert(self, current = Node, key = None, item = None, fromright = 0/1): """ Recursive bottom-up insert. """ if current is None: self.head = Node(key, item, self.head) # Link new node to next-structure with new node as the new head. return self.head current.split() res = self.cmpfunc(key, current.key) if res < 0: current.left = self._insert(current.left, key, item, 0) current = current.right_left_case(fromright) current = current.left_left_case() elif res > 0: current.right = self._insert(current.right, key, item, 1) current = current.left_right_case(fromright) current = current.right_right_case() else: current.item = item self.inserted = False return current def insert(self, key = None, item = None): """ Add item in RBT according to value of key. Return True if inserted, False otherwise. """ self.inserted = True self.root = self._insert(self.root, key, item, 0) self.root.color = "black" if self.inserted: self.children += 1 return self.inserted # Red-Black Tree; Destroy: # def _percolate(self, current = Node, leftrotate = True, fromright = 0/1): """ Alternate left- and right-rotation until node have one leaf child. """ current.split() if current.left is None: return current.right elif current.right is None: return current.left elif leftrotate: current = current._rotate_left() current.left = self._percolate(current.left, False) current.right_left_case(fromright) current.left_left_case() else: current = current._rotate_right() current.right = self._percolate(current.right, True) current.left_right_case(fromright) current.right_right_case() return current def _remove(self, current = Node, key = None): """ Recursive search for matching key. """ if current is None: return None res = self.cmpfunc(key, current.key) if res < 0: current.left = self._remove(current.left, current, key) elif res > 0: current.right = self._remove(current.right, current, key) else: self.item = current.item current = self._percolate(current, True, 0) self.children -= 1 return current def remove(self, key = None): """ Removes item assosiated with key. """ self.root = self._remove(self.root) self.root.color = "black" def pop(self, key = None): """ Removes and return item assosiated with key. Return None if key not in bst. """ self.item = None self.root = self._remove(self.root, key) self.root.color = "black" return self.item if __name__ == "__main__": pass
from ..util import slice_ def daxpy(N, DA, DX, INCX, DY, INCY): """Adds a vector x times a constant alpha to a vector y Parameters ---------- N : int Number of elements in input vector DA : numpy.double Specifies the scalar alpha DX : numpy.ndarray A double precision real array, dimension (1 + (`N` - 1)*abs(`INCX`)) INCX : int Storage spacing between elements of `DX` DY : numpy.ndarray A double precision real array, dimension (1 + (`N` - 1)*abs(`INCY`)) INCY : int Storage spacing between elements of `DY` Returns ------- None See Also -------- saxpy : Single-precision real adding a scaled vector to a vector caxpy : Single-precision complex adding a scaled vector to a vector zaxpy : Double-precision complex adding a scaled vector to a vector Notes ----- Online PyBLAS documentation: https://nbviewer.jupyter.org/github/timleslie/pyblas/blob/main/docs/daxpy.ipynb Reference BLAS documentation: https://github.com/Reference-LAPACK/lapack/blob/v3.9.0/BLAS/SRC/daxpy.f Examples -------- >>> x = np.array([1, 2, 3], dtype=np.double) >>> y = np.array([6, 7, 8], dtype=np.double) >>> N = len(x) >>> alpha = 5 >>> incx = 1 >>> daxpy(N, alpha, x, incx, y, incy) >>> print(y) [11. 17. 23.] """ if N <= 0: return DY[slice_(N, INCY)] += DA * DX[slice_(N, INCX)]
from ..util import slice_ def zdotu(N, ZX, INCX, ZY, INCY): """Computes the dot-product of a vector x and a vector y. Parameters ---------- N : int Number of elements in input vectors ZX : numpy.ndarray A double precision complex array, dimension (1 + (`N` - 1)*abs(`INCX`)) INCX : int Storage spacing between elements of `ZX` ZY : numpy.ndarray A double precision complex array, dimension (1 + (`N` - 1)*abs(`INCY`)) INCY : int Storage spacing between elements of `ZY` Returns ------- numpy.double See Also -------- sdot : Single-precision real dot product dsdot : Single-precision real dot product (computed in double precision, returned as double precision) sdsdot : Single-precision real dot product (computed in double precision, returned as single precision) ddot : Double-precision real dot product cdotu : Single-precision complex dot product cdotc : Single-precision complex conjugate dot product zdotc : Double-precision complex conjugate dot product Notes ----- Online PyBLAS documentation: https://nbviewer.jupyter.org/github/timleslie/pyblas/blob/main/docs/zdotu.ipynb Reference BLAS documentation: https://github.com/Reference-LAPACK/lapack/blob/v3.9.0/BLAS/SRC/zdotu.f Examples -------- >>> x = np.array([1+2j, 2+3j, 3+4j], dtype=np.complex128) >>> y = np.array([6+7j, 7+8j, 8+9j], dtype=np.complex128) >>> N = len(x) >>> incx = 1 >>> incy = 1 >>> zdotu(N, x, incx, y, incy) (-30+115j) """ if N <= 0: return 0 return (ZX[slice_(N, INCX)] * ZY[slice_(N, INCY)]).sum()
from ..util import slice_ def sswap(N, SX, INCX, SY, INCY): """Swaps the contents of a vector x with a vector y Parameters ---------- N : int Number of elements in input vector SX : numpy.ndarray A single precision real array, dimension (1 + (`N` - 1)*abs(`INCX`)) INCX : int Storage spacing between elements of `SX` SY : numpy.ndarray A single precision real array, dimension (1 + (`N` - 1)*abs(`INCY`)) INCY : int Storage spacing between elements of `SY` Returns ------- None See Also -------- dswap : Double-precision real swap two vectors cswap : Single-precision complex swap two vectors zswap : Double-precision complex swap two vectors Notes ----- Online PyBLAS documentation: https://nbviewer.jupyter.org/github/timleslie/pyblas/blob/main/docs/sswap.ipynb Reference BLAS documentation: https://github.com/Reference-LAPACK/lapack/blob/v3.9.0/BLAS/SRC/sswap.f Examples -------- >>> x = np.array([1, 2, 3], dtype=np.single) >>> y = np.array([6, 7, 8], dtype=np.single) >>> N = len(x) >>> incx = 1 >>> sswap(N, x, incx, y, incy) >>> print(x) [6., 7., 8.] >>> print(y) [1., 2., 3.] """ if N <= 0: return x_slice = slice_(N, INCX) y_slice = slice_(N, INCY) X_TEMP = SX[x_slice].copy() SX[x_slice] = SY[y_slice] SY[x_slice] = X_TEMP
from ..util import slice_ def scopy(N, SX, INCX, SY, INCY): """Copies a vector, x, to a vector, y. Parameters ---------- N : int Number of elements in input vectors SX : numpy.ndarray A single precision real array, dimension (1 + (`N` - 1)*abs(`INCX`)) INCX : int Storage spacing between elements of `SX` SY : numpy.ndarray A single precision real array, dimension (1 + (`N` - 1)*abs(`INCY`)) INCY : int Storage spacing between elements of `SY` Returns ------- None See Also -------- dcopy : Double-precision real copy ccopy : Single-precision complex copy zcopy : Double-precision complex copy Notes ----- Online PyBLAS documentation: https://nbviewer.jupyter.org/github/timleslie/pyblas/blob/main/docs/scopy.ipynb Reference BLAS documentation: https://github.com/Reference-LAPACK/lapack/blob/v3.9.0/BLAS/SRC/scopy.f Examples -------- >>> x = np.array([1, 2, 3], dtype=np.single) >>> y = np.array([6, 7, 8], dtype=np.single) >>> N = len(x) >>> incx = 1 >>> incy = 1 >>> scopy(N, x, incx, y, incy) >>> print(y) [1. 2. 3.] """ if N <= 0: return SY[slice_(N, INCY)] = SX[slice_(N, INCX)]
#元祖和列表很类似 ()包裹的,区别在于列表是可变的,元祖是不可变得 arr = ['hello', '','xiaofeng','lulu',''] nums = (2,3,4,5,6,6,8,7,7,7,7,7,7) print(nums.index(4)) #查询数据第一次出现的位置 print(nums.count(7)) #查询某个元素出现的次数 print(type(nums)) #特殊情况表示元祖中只有一个数据 需要加一个逗号 a =(18,) print(type(a)) print(tuple('hello')) #('h', 'e', 'l', 'l', 'o') #列表转换成为元祖 相互转换 print(tuple(arr)) print(list(nums))
person = {'name':'xiaofeng','age':18,'sex':'男','name':'lulu'} person['name'] = '我爱lulu' # 如果key 不存在的话 则会新增一个 person['xf'] = '小哥哥' print(person.pop('name')) #返回被删除的value print(person)
a =['辛德拉','发条','安妮','卡萨丁','阿狸','拉克丝'] for i in a: print(i) j = 0; while j< len(a) : print(a[j]) j += 1
print(ord('a')) # 使⽤ord⽅法,可以获取⼀个字符对应的编码 print(chr(100)) # 使⽤chr⽅法,可以获取⼀个编码对应的字符
#!/usr/bin/env python3 from typing import List class Solution(object): # Inverview 01.08. Zero Matrix LCCI def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ ind = [] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: ind.append([i, j]) if len(ind) > 0: for i in range(len(ind)): matrix[ind[i][0]][:] = [0 for _ in range(len(matrix[0]))] for j in range(len(matrix)): matrix[j][ind[i][1]] = 0 print(matrix) if __name__ == '__main__': print(Solution().setZeroes(matrix=[[1, 1, 1], [1, 0, 1], [1, 1, 1]]))
#!/usr/bin/env python3 from sys import path path.append('.') from utils.linked_list_utils import LinkedList, ListNode class Solution(object): # 19. Remove Nth Node From End of List def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: cur = head length = 0 while cur: cur = cur.next length += 1 cur = head if n > 1: for _ in range(length - n): cur = cur.next cur.val = cur.next.val cur.next = cur.next.next elif length == 1: head = None else: for _ in range(length - n - 1): cur = cur.next cur.next = None return head def removeNthFromEnd_attempt2(self, head: ListNode, n: int) -> ListNode: # Two pointers slow = head fast = head for _ in range(n): fast = fast.next if fast: # if fast is not None while fast.next: slow = slow.next fast = fast.next slow.next = slow.next.next else: # the last node if slow.next: # if slow.next is not None slow.val = slow.next.val slow.next = slow.next.next else: # only 1 node head = None return head if __name__ == '__main__': linked_list_obj = LinkedList() linked_list = [1, 2, 3, 4] head = linked_list_obj.list2LinkedList(input_list=linked_list) # Solution().removeNthFromEnd(head=head, n=2) Solution().removeNthFromEnd_attempt2(head=head, n=2) print(linked_list_obj.linkedList2List(head=head))
#!/usr/bin/env python3 from typing import List class Solution(object): # 53. Maximum Subarray # Dynamic programming def maxSubArray(self, nums: List[int]) -> int: # OVERTIME maxsum = nums[0] for i in range(len(nums)): sums = nums[i] curr_maxsum = sums for num in nums[i + 1::]: curr_maxsum = max(curr_maxsum, sums + num) sums += num maxsum = max(maxsum, curr_maxsum) return maxsum def maxSubArray_attempt2(self, nums: List[int]) -> int: dp = [nums[0]] for i in range(1, len(nums)): dp.append(max(dp[i - 1], 0) + nums[i]) # equivalent to: # dp.append(max(dp[i - 1] + nums[i], nums[i])) return max(dp) if __name__ == '__main__': print(Solution().maxSubArray_attempt2(nums=[2, 7, 9, 3, 1]))
#!/usr/bin/env python3 from typing import List class Solution(object): # 561. Array Partition I def arrayPairSum(self, nums: List[int]) -> int: nums = sorted(nums) sums = 0 for i in range(0, len(nums), 2): sums += min(nums[i], nums[i + 1]) return sums if __name__ == '__main__': print(Solution().arrayPairSum(nums=[6, 2, 6, 5, 1, 2]))
#!/usr/bin/env python3 from typing import List, Optional from sys import path path.append('.') from utils.binary_tree_utils import TreeNode class Solution(object): # 112. Path Sum def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: # Recurse return self.traverse(root=root, targetSum=targetSum, flag=False) def traverse(self, root: TreeNode, targetSum: int, flag: bool) -> List[int]: if root: if root.val == targetSum and not (root.left or root.right): flag = True else: flag = self.traverse(root.left, targetSum - root.val, flag) flag = flag or self.traverse(root.right, targetSum - root.val, flag) if flag: return True return False if __name__ == '__main__': # root=TreeNode(1,TreeNode(2,None,TreeNode(3)),TreeNode(4,TreeNode(5),TreeNode(6,TreeNode(7)))) root = TreeNode(1, TreeNode(2)) # root=TreeNode(1,TreeNode(2,TreeNode(4),TreeNode(3)),TreeNode(2,TreeNode(3),TreeNode(4))) # root=TreeNode() print(Solution().hasPathSum(root=root, targetSum=1))
#!/usr/bin/env python3 from typing import List class Solution(object): # 198. House Robber def rob(self, nums: List[int]) -> int: if len(nums) <= 2: return max(nums) dp = [nums[0], nums[1]] if len(nums) >= 3: dp.append(dp[0] + nums[2]) for i in range(len(dp), len(nums)): dp.append(max(dp[i - 3:i - 1]) + nums[i]) return max(dp) if __name__ == '__main__': print(Solution().rob(nums=[[2, 7, 9, 3, 1]]))
counties = ["Arapahoe", "Denver", "Jefferson"] if "El Paso" in counties: print("El Paso is in the list of counties") else: print("El Paso is not in the list counties") if "Arapahoe" in counties and "El Paso" in counties: print("Arapahoe and El Paso are in the list of counties.") else: print("Arapahoe or El Paso is not in the list of counties") if "Arapahoe" in counties or "El Paso" in counties: print("Arapahoe or El Paso is in the list of counties.") else: print("Arapahoe and El Paso are not in the list of counties.") if "Arapahoe" in counties and "El Paso" not in counties: print("Only Arapahoe is in the list of counties.") else: print("Arapahoe is in the list of counties and El Paso is not in the list.") for county in counties: print(county) for i in range(len(counties)): print(counties[i]) counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} for county in counties_dict.keys(): print(county) for voters in counties_dict.values(): print(voters) for county in counties_dict: print(counties_dict[county]) for county, voters in counties_dict.items(): print(county, voters) for county, voters in counties_dict.items(): print(county, "county has", voters, "registered voters") voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] for county_dict in voting_data: print(county_dict) for county, voters in counties_dict.items(): print(f"{county} county has {voters} registered voters.") for county, voters in counties_dict.items(): print(f"{county} county has {voters:,} registered voters.") x= [] for county_dict in voting_data: for value in county_dict.values(): x.append(value) print("---------") print(f"{x[0]} county has {x[1]:,} registered voters.") print(f"{x[2]} county has {x[3]:,} registered voters.") print(f"{x[4]} county has {x[5]:,} registered voters.") #for county_dict in voting_data: # for value in county_dict.values(): # print(f"{county_dict['county']} county has {county_dict['registered_voters']:,} registered voters.")
def printboard(board): print('\t\t' + '|' + '\t\t' + '|' + ' ') print(' ' + board[1] + ' ' + '|' + ' ' + board[2] + ' ' + '|' + ' ' + board[3] + ' ') print('\t\t' + '|' + '\t\t' + '|' + '\t\t') print('--------' + '|' + '-------' + '|' + '--------') print('\t\t' + '|' + '\t\t' + '|' + '\t\t') print(' ' + board[4] + ' ' + '|' + ' ' + board[5] + ' ' + '|' + ' ' + board[6] + ' ') print('\t\t' + '|' + '\t\t' + '|' + '\t\t') print('--------' + '|' + '-------' + '|' + '--------') print('\t\t' + '|' + '\t\t' + '|' + '\t\t') print(' ' + board[7] + ' ' + '|' + ' ' + board[8] + ' ' + '|' + ' ' + board[9] + ' ') print('\t\t' + '|' + '\t\t' + '|' + '\t\t') def validInput(board): position = 0 valid = [1, 2, 3, 4, 5, 6, 7, 8, 9] alreadythere = False while position not in valid or alreadythere: alreadythere = False printboard(board) position = input('\n\nPlease choose a space numbered between 1 and 9: ') if not position.isdigit(): print('\n' * 100) print("Sorry you need to choose between 1 and 9") else: position = int(position) if board[position] == 'x' or board[position] == 'o': print('\n' * 100) alreadythere = True print('This position is taken. Choose another. Dont be dumb') elif position not in valid: print("Sorry you need to choose between 1 and 9") print('\n' * 100) print('\n'*100) return position def winnerCheck(boardlist): if boardlist[1] == boardlist[2] == boardlist[3] == 'x' or boardlist[1] == boardlist[2] == boardlist[3] == 'o': return True elif boardlist[4] == boardlist[5] == boardlist[6] == 'x' or boardlist[4] == boardlist[5] == boardlist[6] == 'o': return True elif boardlist[7] == boardlist[8] == boardlist[9] == 'x' or boardlist[7] == boardlist[8] == boardlist[9] == 'o': return True elif boardlist[1] == boardlist[4] == boardlist[7] == 'x' or boardlist[1] == boardlist[4] == boardlist[7] == 'o': return True elif boardlist[2] == boardlist[5] == boardlist[8] == 'x' or boardlist[2] == boardlist[5] == boardlist[8] == 'o': return True elif boardlist[3] == boardlist[6] == boardlist[9] == 'x' or boardlist[3] == boardlist[6] == boardlist[9] == 'o': return True elif boardlist[1] == boardlist[5] == boardlist[9] == 'x' or boardlist[1] == boardlist[5] == boardlist[9] == 'o': return True elif boardlist[7] == boardlist[5] == boardlist[3] == 'x' or boardlist[7] == boardlist[5] == boardlist[3] == 'o': return True else: return False person1 = input('Player 1 please enter your name: ') person2 = input('Player 2 please enter your name: ') play = True while play: print('====================Welcome to TIc Tac TOE!===================='+'\n\n') valid = ['x', 'o'] player1 = 'none' player2 = 'none' while player1 not in valid: player1 = input(person1 + ' please choose either x or o: ') player1 = player1.lower() if player1 not in valid: print("Sorry! You have to choose either x or o. Try again.") print(person1+' is ' + player1) if player1 == 'x': print(person2 + ' is ' + 'o') player2 = 'o' else: print(person2+' is ' + 'x') player2 = 'x' position1 = 0 position2 = 0 turn1 = False turn2 = False boardlist = ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] if player1 == 'x': print(person1+' is x so you will go first') position1 = validInput(boardlist) boardlist[position1] = player1 turn1 = True else: print(person2+' is x so you will go first') position2 = validInput(boardlist) boardlist[position2] = player2 turn2 = True winner = False score1 = 0 score2 = 0 count = 1 while not winner and count != 9: if not turn1: print(person1+' its your turn. Go ahead') position1 = validInput(boardlist) boardlist[position1] = player1 turn1 = True turn2 = False count += 1 else: print(person2+' its your turn. Go ahead') position2 = validInput(boardlist) boardlist[position2] = player2 turn2 = True turn1 = False count += 1 if winnerCheck(boardlist): printboard(boardlist) if turn1: print("===================="+person1+" HAS WON THE GAME!!!====================") score1 += 1 winner = True else: print('===================='+person2+' HAS WON THE GAME!!!====================') score2 += 1 winner = True print(score2) playagain = input('Would you like to play again? y or n: ') playagain = playagain.lower() if playagain == 'n': play = False else: play = True elif count == 9: print('====================THIS WAS A DRAWWWW====================!!!') printboard(boardlist) playagain = input('Would you like to play again? y or n: ') playagain = playagain.lower() if playagain == 'n': play = False else: play = True
# Hopcroft-Karp bipartite max-cardinality matching and max independent set # David Eppstein, UC Irvine, 27 Apr 2002 def bipartiteMatch(graph): """ Find maximum cardinality matching of a bipartite graph (U,V,E). The input format is a dictionary mapping members of U to a list of their neighbors in V. The output is a triple (M,A,B) where M is a dictionary mapping members of V to their matches in U, A is the part of the maximum independent set in U, and B is the part of the MIS in V. The same object may occur in both U and V, and is treated as two distinct vertices if this happens. """ # initialize greedy matching (redundant, but faster than full search) matching = {} for u in graph: for v in graph[u]: if v not in matching: matching[v] = u break while 1: # structure residual graph into layers # pred[u] gives the neighbor in the previous layer for u in U # preds[v] gives a list of neighbors in the previous layer for v in V # unmatched gives a list of unmatched vertices in final layer of V, # and is also used as a flag value for pred[u] when u is in the first layer preds = {} unmatched = [] pred = dict([(u, unmatched) for u in graph]) for v in matching: del pred[matching[v]] layer = list(pred) # repeatedly extend layering structure by another pair of layers while layer and not unmatched: newLayer = {} for u in layer: for v in graph[u]: if v not in preds: newLayer.setdefault(v, []).append(u) layer = [] for v in newLayer: preds[v] = newLayer[v] if v in matching: layer.append(matching[v]) pred[matching[v]] = v else: unmatched.append(v) # did we finish layering without finding any alternating paths? if not unmatched: unlayered = {} for u in graph: for v in graph[u]: if v not in preds: unlayered[v] = None return matching, list(pred), list(unlayered) # recursively search backward through layers to find alternating paths # recursion returns true if found path, false otherwise def recurse(v): if v in preds: L = preds[v] del preds[v] for u in L: if u in pred: pu = pred[u] del pred[u] if pu is unmatched or recurse(pu): matching[v] = u return 1 return 0 # s for v in unmatched: recurse(v) # Find a minimum vertex cover def min_vertex_cover(left_v, right_v): """ Use the Hopcroft-Karp algorithm to find a maximum matching or maximum independent set of a bipartite graph. Next, find a minimum vertex cover by finding the complement of a maximum independent set. The function takes as input two dictionaries, one for the left vertices and one for the right vertices. Each key in the left dictionary is a left vertex with a value equal to a list of the right vertices that are connected to the key by an edge. The right dictionary is structured similarly. The output is a dictionary with keys equal to the vertices in a minimum vertex cover and values equal to lists of the vertices connected to the key by an edge. For example, using the following simple bipartite graph: 1000 2000 1001 2000 where vertices 1000 and 1001 each have one edge and 2000 has two edges, the input would be: left = {1000: [2000], 1001: [2000]} right = {2000: [1000, 1001]} and the ouput or minimum vertex cover would be: {2000: [1000, 1001]} with vertex 2000 being the minimum vertex cover. """ data_hk = bipartiteMatch(left_v) left_mis = data_hk[1] right_mis = data_hk[2] mvc = left_v.copy() mvc.update(right_v) # junta os dicionarios num so for v in left_mis: try: del (mvc[v]) except KeyError: pass for v in right_mis: try: del (mvc[v]) except KeyError: pass return mvc
import errno import os import sys def split_list_in_chunks(lst, chunk_amount): """ Splits list lst in lists of chunk_amount elements and returns them (as a list of lists) """ chunk_amount = max(1, chunk_amount) return [lst[i:i + chunk_amount] for i in range(0, len(lst), chunk_amount)] def generate_dir(path): """ If path doesn't exist, it gets created """ try: os.makedirs(path) print('Directory ' + path + ' created or already existed.') except OSError as error: if error.errno != errno.EEXIST: raise def block_console_print(): """ Disables printing to the console. """ sys.stdout = open(os.devnull, 'w') def enable_console_print(): """ Enables printing to the console. :return: """ sys.stdout = sys.__stdout__
#Функция должна проверить совпадение значений с помощью оператора assert # и, в случае несовпадения, предоставить исчерпывающее сообщение об ошибке. def test_input_text(expected_result, actual_result): assert expected_result == actual_result, "expected {}, got {}".format(expected_result, actual_result)
import threading import time print('Start of program.') def takeANap(m, n): time.sleep(n) print('Wake up!') for i in range(1, 6): threadObj = threading.Thread(target=takeANap, args= (0,i)) threadObj.start() print('End of program.')
from collections import defaultdict food_counter = defaultdict(int) for food in ['spam', 'egg', 'spam', 'spam']: food_counter[food] += 1 for food, counter in food_counter.items(): print(food, counter)
from matplotlib import pyplot as plt import numpy as np from qiskit import * from qiskit.visualization import plot_bloch_vector plt.figure() ax = plt.gca() ax.quiver([3], [5], angles='xy', scale_units='xy', scale=1) ax.set_xlim([-1, 10]) ax.set_ylim([-1, 10]) #plt.draw() #plt.show() plot_bloch_vector([1, 0, 0]) """ Matrices: A unitary matrix is very similar. Specifically, it is a matrix such that the inverse matrix is equal to the conjugate transpose of the original matrix. A Hermitian matrix is simply a matrix that is equal to its conjugate transpose (denoted with a † symbol). """
# Program to determine the frequency of each letter when the input text is split into x piles. # # To run: # $python3 freqAnalysis.py text x # where text is the plaintext or ciphertext and x is a possible length of the key, so also the number of piles to split # the text into. # # Output: # $Frequencies: # $Pile 1 Pile 2 Pile 3 Pile 4 # $char: a char: b char: c char: d # . # . # . # where the column underneath "Pile N" represents the frequencies of letters in that pile. Letters are sorted by # non-increasing frequency import sys # import time # t1=time.time() #Read the input string and an integer, x. The string will be split into x piles. s=sys.argv[1] x=int(sys.argv[2]) #init a list to hold lists of tuples, where each list of tuples is a pile of letters, and each tuple is a letter #with its frequency freqs=[] for pile in range(x): #init a dict of letters d={chr(i+65):0 for i in range(26)} for i in range(len(s)): if i%x==pile: d[s[i]]+=1 #convert the dict to list of tuples for easy operation later, and sort by non-increasing frequency d=sorted(d.items(), key=lambda entry: entry[1], reverse=True) freqs.append(d) #create a tuple to string method for easy printing later def tupleToString(t): return str(t[0]) + ': ' + str(t[1]) print("Frequencies: ") #print the heading of each pile for i in range(x): print('Pile ' + str(i+1), end='\t') print() #print the most frequent letter of each pile in the first row, the second most frequent letter of each pile in the #second letter, etc. for i in range(26): a=[freqs[j][i] for j in range(x)] a=[tupleToString(entry) for entry in a] print('\t'.join(a))