text
stringlengths
37
1.41M
from random import randint from time import sleep from operator import itemgetter jogo = {"jogador1": randint(1, 6), "jogador2": randint(1, 6), "jogador3": randint(1, 6), "jogador4": randint(1, 6)} ranking = list() print("Valores sorteados: ") for k, v in jogo.items(): print(f"{k} tirou {v} no dado") sleep(0.75) ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True) print() print("RANKING DOS JOGADORES!") print() for v, c in enumerate(ranking): print(f"{v + 1} lugar: {c[0]} com {c[1]}") sleep(0.75)
matrix1 = list() matrix2 = list() matrix3 = list() for p in range(0, 3): matrix1.append(input(f"Digite um valor para a posição [0, {p}]")) for b in range(0, 3): matrix2.append(input(f"Digite um valor para a posição [1, {b}]")) for c in range(0, 3): matrix3.append(input(f"Digite um valor para a posição [2, {c}]")) print(matrix1) print(matrix2) print(matrix3)
r = "S" par = impar = 0 while r == "S": n = int(input("Digite um valor:")) r = str(input("Quer continuar? [S/N]")).upper() if n % 2 == 0: par += 1 else: impar += 1 print("Voce digitou {} numeros PARES e {} IMPARES".format(par, impar))
frase = input("Digite uma frase:") c1 = frase.strip().upper() a1 = c1.count("A") a2 = c1.find("A") a3 = c1.rfind("A") print("A letra 'A' aparece {}\nA primeira letra A aoarece na posição {}\nA ultima letra Aparece na posição {}".format(a1, a2, a3))
import random n1 = input('Digite o nome do primeiro aluno:') n2 = input('Digite o nome do segundo aluno:') n3 = input('Digite o nome do terceiro aluno:') n4 = input('Digite o nome do quarto aluno:') lista = (n1, n2 , n3 ,n4) n5 = random.choice(lista) print('O aluno sorteado foi {}'.format(n5))
boletim = list() while True: nome = str(input("Nome do aluno: ")) nota1 = float(input("Primeira nota:")) nota2 = float(input("segunda nota:")) media = (nota1 + nota2) / 2 boletim.append([nome, [nota1, nota2], media]) continuar = " " while continuar not in "SN": continuar = str(input("Dejesa continuar:[S/N] ")).strip().upper() if continuar == "N": break print(boletim) print("=-"*30) print(f"{'NO.':<4}{'NOME':<10}{'MEDIA':>8}") print("=-"*30) for i, a in enumerate(boletim): print(f"{i:<4}{a[0]:<10}{a[2]:>8.1f}") while True: print("-"*25) opc = int(input("Mostrar notas de qual aluno?(999 intenrrompe) ")) if opc == 999: break if opc <= len(boletim) - 1: print(f"Notas de {boletim[opc][0]} São {boletim[opc][1]}")
from random import randint computador = randint(0, 10) print("Seu computador pensou em um numero de 0 a 10 tente adivinhar") acertou = False palpites = 0 while not acertou: jogador = int(input("Tente advinhar:")) palpites += 1 if jogador == computador: acertou = True print("Acertou\nVoce consegui em {} tentativas".format(palpites))
from random import sample texto = print("Ordem de alunos que vão apresentar o trabalho") a1 = input('Primeiro aluno:') a2 = input('Segundo aluno:') a3 = input('Terceiro aluno:') a4 = input('Quarto aluno:') lista = [a1, a2, a3, a4] ordem = sample(lista, k=4) print('A ordem de apresentação será {}'.format(ordem))
# Problem link : https://leetcode.com/problems/first-unique-character-in-a-string/ class FirstUnique: frequency = dict() def __init__(self, nums: List[int]): self.frequency.clear() for item in nums: # Adding all numbers in dictionary if item not in self.frequency: self.frequency[item]=1 else: self.frequency[item]= self.frequency[item]+1 def showFirstUnique(self) -> int: for key,val in self.frequency.items(): if(val==1): return key return -1 def add(self, value: int) -> None: if value not in self.frequency: self.frequency[value]=1 else: self.frequency[value]= self.frequency[value]+1 # Your FirstUnique object will be instantiated and called as such: # obj = FirstUnique(nums) # param_1 = obj.showFirstUnique() # obj.add(value)
from sys import argv script, filename = argv print ("We're going to arase %r." % filename) print ("If you don't want that, hit CTRL-C (^C).") print ("If you do want that, hit return.") input("? ") print ("Opening the file...") target = open(filename, 'w') #进入‘W’模式(打开一个文档若不存在则新建),因为原来的open默认是只读模式(‘r') print ("Truncating the file. Goodbye!") target.truncate() #这货作用是清除,如果文档是新建的,没什么卵用 print ("Now I'm going to ask you for three lines.") line1 = input("line1:") line2 = input("line2:") line3 = input("line3:") print ("I'm going to write these to the file.") a = """%s \n%s \n%s \n""" %( line1,line2,line3) #这样就可以跳过repetition啦。 target.write(a) print ("And finally,we close it.") target.close()
player1 = "" player2 = "" def welcome(): print("Welcome to Tic Tac Toe!") print("Choose your symbol ('X' or 'O') -- ") print("***********************************") while True: global player1 global player2 player1 = input("Player 1 : ").upper() if player1 == "X": player2 = "O" elif player1 == "O": player2 = "X" else: print("Warning! Please choose only 'X' or 'O'") continue break print("") print("") print(f"Player1 chooses {player1}") print(f"Player2 chooses {player2}") print("") print("***INSTRUCTIONS****") print("") print("EXAMPLE BOARD") print("7 | 8 | 9") print("----------") print("4 | 5 | 6") print("----------") print("1 | 2 | 3") print("") def playBoard(position): print("") print(f"{position[7-1]} | {position[8-1]} | {position[9-1]}") print("----------") print(f"{position[4-1]} | {position[5-1]} | {position[6-1]}") print("----------") print(f"{position[1-1]} | {position[2-1]} | {position[3-1]}") print("") def play(): position = ['','','','','','','','',''] global player1 global player2 winner = "" while winner=="": while winner=="": playBoard(position) choice1 = int(input("Player1's turn-- choose your place: ")) if position[choice1-1] == '': position[choice1-1] = player1 if ( position[0] == position[4] == position[8] == player1 or position[6] == position[4] == position[2] == player1 or position[6] == position[3] == position[0] == player1 or position[7] == position[4] == position[1] == player1 or position[8] == position[5] == position[2] == player1 or position[6] == position[7] == position[8] == player1 or position[3] == position[4] == position[5] == player1 or position[0] == position[1] == position[2] == player1 ): winner="player1" break elif ( position[0] != '' and position[1] != '' and position[2] != '' and position[3] != '' and position[4] != '' and position[5] != '' and position[6] != '' and position[7] != '' and position[8] != '' ): winner="draw" break break else: print("") print("WARNING! THE PLACE IS ALREADY TAKEN, Please try again.") print("") while winner=="": playBoard(position) choice2 = int(input("Player2's turn-- choose your place: ")) if position[choice2-1] == '': position[choice2-1] = player2 if ( position[0] == position[4] == position[8] == player2 or position[6] == position[4] == position[2] == player2 or position[6] == position[3] == position[0] == player2 or position[7] == position[4] == position[1] == player2 or position[8] == position[5] == position[2] == player2 or position[6] == position[7] == position[8] == player2 or position[3] == position[4] == position[5] == player2 or position[0] == position[1] == position[2] == player2 ): winner="player2" elif ( position[0] != '' and position[1] != '' and position[2] != '' and position[3] != '' and position[4] != '' and position[5] != '' and position[6] != '' and position[7] != '' and position[8] != '' ): winner="draw" break break else: print("") print("WARNING! THE PLACE IS ALREADY TAKEN, Please try again.") print("") playBoard(position) if winner == "draw": print("********************") print("Match DRAW!") print("********************") else: print("========================") #print("************************") print("OUR WINNER IS: "+winner) #print("************************") print("========================") welcome() play()
# -*- coding: utf-8 -*- """ Created on Wed Mar 25 19:34:47 2020 @author: khare """ f_t= "paris" str1=" " l=list(f_t) if l[0]=="A" or l[0]=="E" or l[0]=="I" or l[0]=="O" or l[0]=="U": l.append("way") else: l.remove(f_t[0]) l.append(f_t[0]) l.append("ay") print(str1.join(l))
import nltk from nltk.tokenize import sent_tokenize def ret_res(text): sent_tokenize_list = sent_tokenize(text) return (sent_tokenize_list) def ret_len_res(text): sent_tokenize_list=sent_tokenize(text) y=len(sent_tokenize_list) return (y) #x=ret_res("whats up. My name is chin. i am expecting this to be 3rd sentence. But you know what, i am confused.ok now tere was no space between full stop and next character.") #print (x)
a = "Evan" arr = list(a) a_list = ['nEva', 'anEv', 'vanE', 'Evan'] count = [] for i in range(len(arr)): arr.insert(0, arr.pop()) joined = ''.join(arr) if joined in a_list: count.append(joined) list(arr) all(x in count for x in a_list) def contain_all(a, b): if a == '': return True arr = list(a) count = [] for i in range(len(arr)): arr.insert(0, arr.pop()) joined = ''.join(arr) print joined if joined in b: count.append(joined) if joined not in b: return False list(arr) #if all(x in count for x in b): #print 'yes, all rotations are included' #print count #print b for item in count: if item not in b: return False return True contain_all('XjYABhR', ["TzYxlgfnhf", "yqVAuoLjMLy", "BhRXjYA", "YABhRXj", "hRXjYAB", "jYABhRX", "XjYABhR", "ABhRXjY"])
""" Dynamic Array * Boyutunu önceden belirlemek zorunda olmadığımız daha sonra eleman ekleyip çıkartabildiğimiz yapılar * Growable and Resizable olarak tanımlanır """ import ctypes # yeni array oluşturmak için kullanacağız class DynamicArray(object): def __init__(self): # initialize (constructor) self.n = 0 # eleman sayısı self.capacity = 1 # kapasite self.A = self.make_array(self.capacity) def __len__(self): # return eleman sayısı return self.n def __getitem__(self, k): # return index k'daki eleman if not 0 <= k < self.n: return IndexError(f'{k} index sınırları içerisinde değil') return self.A[k] def append(self, eleman): # eleman ekler array'e if self.n == self.capacity: self._resize(2*self.capacity) self.A[self.n] = eleman # eleman ekle self.n += 1 # eleman sayısını bir ekler def _resize(self, new_cap): # array kapasitesi arttırılır yeni_array = self.make_array(new_cap) # yeni arrayi yapar # eski array (A) içerisindeki değerleri yeni_array'e taşı for k in range(self.n): yeni_array[k] = self.A[k] self.A = yeni_array # arrayi günceller self.capacity = new_cap # kapasiteyi günceller def make_array(self, new_cap): # return yeni array return (new_cap*ctypes.py_object)() dynamic_array = DynamicArray() # instance oluşturduk dynamic_array.append(1) # element ekle (1) print(dynamic_array[0]) dynamic_array.append(3) # element ekle (1,3) print(dynamic_array[0], dynamic_array[1])
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(6) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(5) root.right.right = TreeNode(7) # if want to traverse BST in increasing order, use the inorder traverse: def increading_BST_traverse(root): if not root: return [] res = [] increading_BST_traverse_util(root, res) return res def increading_BST_traverse_util(node, res): if not node: return increading_BST_traverse_util(node.left, res) res.append(node.val) increading_BST_traverse_util(node.right, res) print(increading_BST_traverse(root)) def descending_BST_traverse(root): if not root: return [] res = [] descending_BST_traverse_util(root, res) return res def descending_BST_traverse_util(node, res): if not node: return descending_BST_traverse_util(node.right, res) res.append(node.val) descending_BST_traverse_util(node.left, res) print(descending_BST_traverse(root))
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import cv2 import math fingertips_touched_flag = np.zeros((10,1)) def touching_detection(tips, hand_mask, depth_image, draw_image=None): ''' by Yuan-Syun ye on 2019/06/17. To detect if the fingertips are touching or not, our algorithm analyzes a 7x7 patch centered on the fingertip's contour position. Each patch of pixels centered on the fingertip's contour position. Each patch is split into S, the set of pixels within the hand + finger mask, and T, the set of pixels outside the mask. The estimated height of the finger is then given by max(Zs|s C S) - min(Zt|t C T) To confirm contact with the surface, the algorithm applies a simple pair of hysteresis thresholds - a fingertip is declared as touching the surface if the smoothed fingertip height descends below 10 mm, and declared to have left the surface if its height laster ascends past 15 mm. ''' global fingertips_touched_flag kernal_size = 7 touch_height = 10#0.02 untouch_height = 15#0.025 # debug image if(draw_image is not None): touched_text = "touched" text_size = 0.5 touched_color = (0, 255, 0) touched_image = draw_image.copy() max_height, max_width = hand_mask.shape # print('max width: %d, height: %d'%(max_width, max_height)) # print('test access: %d'%(hand_mask[170, 223])) for index, tip in enumerate(tips): # this tip is not tracking if(tip[0] == -1): fingertips_touched_flag[index] = False continue # the min hight within the hand+finger mask Zs = (0,0) tip_height = -999 # the max height outside the mask. Zt = (0,0) surface_height = 999 # print ('tip[%d] = (%d, %d)' % (i, tip[0], tip[1])) kernal_range = math.floor(kernal_size/2) for h in range(-kernal_range, kernal_range+ 1, 1): for w in range(-kernal_range, kernal_range + 1, 1): (u, v) = (int(tip[1]+w), int(tip[0]+h)) # check the bounder if(u < 0 or u >= max_height): continue if(v < 0 or v >= max_width): continue # Debug20191031 SkinImg is [0,255] if (hand_mask[u, v] == True or hand_mask[u, v] == 255): if(depth_image[u, v] > tip_height): Zs = (u, v) tip_height = depth_image[u,v] else: if(depth_image[u, v] < surface_height): Zt = (u,v ) surface_height = depth_image[u,v] # if(draw_image is not None): # touched_image[u, v]=touched_color #20191031 Debug : tip/surface not change, put these code outside the for loop if(tip_height!= -999 and surface_height!= 999 and (tip_height - surface_height) < touch_height): fingertips_touched_flag[index] = True print(tip_height,surface_height,(tip_height - surface_height)) # print(depth_image[int(tip[1])-kernal_range:int(tip[1])+kernal_range, int(tip[0])-kernal_range:int(tip[0])+kernal_range] ) # print('finger %d touched'%(index)) if(tip_height == -999 or surface_height == 999 or (tip_height - surface_height) >= untouch_height): fingertips_touched_flag[index] = False # print(tip_height,surface_height,(tip_height - surface_height)) # print(fingertips_touched_flag) # debug image if(draw_image is not None): for i, touched in enumerate(fingertips_touched_flag): if(touched == True): # print('tips[%d], tips size: %d, %d'%(i, tips.shape[0], tips.shape[1])) pos = (int(tips[i][0]), int(tips[i][1])) print('touched pos:', pos) cv2.circle(touched_image, pos, 5 , touched_color , 3) cv2.putText(img=touched_image, text=touched_text, org=pos, fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=text_size, color=touched_color) return fingertips_touched_flag, touched_image # In[2]: # In[ ]:
import pandas as pd import os #set the folder containingall my files as the active directory #os.chdir(r"C:\Users\huwro\Udacity_Projects\Udacity Pgm for DS Proj 2\bikeshare-2") # fishy """----------------------------------------------------------------------------------------------------------------- Section 1 - two functions that take the input passed by the user and produce the output statistics. The first extracts and filters the data set to be consistent with the input parameters passed by the user The second calculates the requested statistics from that filtered data set """ def load_data2(city,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. String for an individual city, a list if you want multiple cities or "all" to see all cities in the dataset. (str) month - name of the month to filter by, or a list of months, or "all" to see statistics for all months values in the data set. (str) day - name of the day of week to filter by, or a list of days, or "all" to see statistics for all day values in the data set. Returns: df - Pandas DataFrame containing data filtered by month, day and city. """ # load the data for the relevant cities # filter by city where necessary if city!=["all"]: # check if New York is in the list of cities provided to resolve the "_" character issue city=pd.Series(city) #get a series of the indicies which relate to new York in the city input list #using the series method, not the string method to replace whole entries in the series, not substrings of entries repl_index=city[city.str.contains("[Nn]ew [Yy]ork[^*]",regex=True)].index #replace the strings in city for the idenfied indecies city[repl_index]="new_york_city" #city=city.replace(to_replace="[Nn]ew [Yy]ork[^*]", value="new_york_city",regex=True) #city = city.map({}) #create the dict that identifies the relevant subset of the overall df based on cities cities_list = [] # now read the csv file from the dir for the cities in the selected dict for c in city: filepath = c+".csv" cities_list.append(pd.read_csv(filepath)) #make a single df from the list of dfs with concat function. # axis = 0 says that concatenate over rows (vertically) df=pd.concat(cities_list, axis= 0, ignore_index=False, keys=city, names=['cities','row index'], sort=True) #create a catagorical variable in the series with the city values against the lines df2 = pd.Series(df.index.get_level_values(0)) df=pd.merge(df,df2, how='inner', on=df.index, sort=True) # delete the index of the previous df and "Unamed: 0", which are unecessary df.drop(columns=["key_0","Unnamed: 0"],inplace=True) else: #loop through all of the .csv files in "input_data_files" file_list = os.listdir() csv_files = [] for f in file_list: if "csv" in f: csv_files.append(f) cities_list =[] # now read the csv file from the dir for all of the cities for which there are data files for f in csv_files: cities_list.append(pd.read_csv(f)) # extract a list of all of the city names in the input data city = [f.split(".")[0].capitalize() for f in csv_files] #make a single df from the list of dfs with concat function. # axis = 0 says that concatenate over rows (vertically) df=pd.concat(cities_list, axis= 0, ignore_index=False, keys=city, names=['cities','row index'], sort=True) #create a catagorical variable in the series with the city values against the lines df2 = pd.Series(df.index.get_level_values(0)) df=pd.merge(df,df2, how='inner', on=df.index, sort=True) # delete the index of the previous df and "Unamed: 0", which are unecessary df.drop(columns=["key_0","Unnamed: 0"],inplace=True) #convert 'Start Time' from object/str dtype to data time df['Start Time']=pd.to_datetime(df['Start Time']) # Extract the month and day components and make new cols in the df using the datetime (denoted dt) class of methods and properties and the month and day properties #note dt object class month property makes 1-12 integers not names df['Month']=df['Start Time'].dt.month df['Day']=df['Start Time'].dt.weekday_name #filter the data for the relevant months and days where necessary # month filter if month!=["All"]: # if supplied one month convert to a list if type(month) is not list: month_list = [] month_list.append(month) month=month_list # convert mnth names to integers month_names=pd.Series(['January','February','March','April','May','June','July','August','September','October','November','December']) # make a list of the repsective integers assoicated with the month names month=list(month_names[month_names.isin(month)].index) # filter df by the relevant months df=df.loc[df['Month'].isin(month)] # now convert the output df's month values to the month names # first make the dict to go into mapping function zip_iterator = zip([i for i in range(1,13)],month_names) #get a list of tuples mnth_mapping_dict = dict(zip_iterator) #do the mapping df['Month']=df['Month'].map(mnth_mapping_dict) else: # get a list of mnth names to convert to integers month_names=pd.Series(['January','February','March','April','May','June','July','August','September','October','November','December']) # now convert the output df's month values to the month names # first make the dict to go into mapping function zip_iterator = zip([i for i in range(1,13)],month_names) #get a list of tuples mnth_mapping_dict = dict(zip_iterator) #do the mapping df['Month']=df['Month'].map(mnth_mapping_dict) # day filter if day !=["All"]: if type(day) is not list: day = [day] df=df.loc[df['Day'].isin(day)] #finally make a column of combinations of start and end stations df['Trip']=pd.Series(zip(df['Start Station'],df['End Station'])).apply(lambda x: "From "+ x[0]+ " to "+x[1]) #note one can also do it as with basic python string operator: #df['Trip']=df['Start Station']+df['End Station'] #we reset the index of the df - note that if you filter out certain rows of a df the original index remains # if you then want to use indexing on rows, .e.g. show me the first five rows, you will see only rows in the filtered df that had an index of 5 or less in the orginal dataframe df.reset_index(inplace=True) # the old index is preserved as a column, thus we must remove it df.drop(columns="index",inplace=True) # UX - clean up the output df #for user experience, replace 'new_york_city' with 'New York City' and rename columns df.rename(columns={"cities":"City"}, inplace=True) df['City'].replace(to_replace={"new_york_city": "New York City","washington":"Washington","chicago":"Chicago"}, inplace=True) return df def calc_stats(df): """ Calculates the output statistics using the dataframe generated by function load_data2 as its domain. Args: dataframe output of load_data2 function Returns: dictionary of stats split by city, user type and gender. """ import statistics as st #1 Popular times of travel # note .droplevel() is used to remove the unecessary hierarchical index travel_time_stats=df.groupby(by=df['City'],as_index=True)[['Month','Day']].apply(pd.DataFrame.mode).droplevel(level=1) #2 Popular stations and trip location_stats=df.groupby(by=df['City'],as_index=True)[['Start Station','End Station','Trip']].apply(pd.DataFrame.mode).droplevel(level=1) #3 Trip duration duration_stats_sum = df.groupby(by=df['City'],as_index=True)[['Trip Duration']].sum().rename(columns={'Trip Duration': 'Total Trip Duration (Mins)'}) duration_stats_avg = df.groupby(by=df['City'],as_index=True)[['Trip Duration']].mean().rename(columns={'Trip Duration': 'Average Trip Duration (Mins)'}) duration_stats = pd.merge(duration_stats_sum, duration_stats_avg, on=duration_stats_avg.index).rename(columns={"key_0": "City"}) #4 User characteristics user_characteristic_stats = df.groupby(['City','User Type','Gender'])[['User Type']].count().rename(columns={'User Type':'User Count'}) #5 User birth yrs earliest_birth_yr = df.groupby(by=df['City'],as_index=True)['Birth Year'].min() latest_birth_yr = df.groupby(by=df['City'],as_index=True)['Birth Year'].max() most_common_birth_yr =df.groupby(by=df['City'],as_index=True)['Birth Year'].apply(pd.Series.mode).droplevel(level=1) # concat the three dfs with a common structure into one over column axis user_birth_stats=pd.concat([earliest_birth_yr, latest_birth_yr, most_common_birth_yr], axis=1,sort=True) #reset column values of the new df user_birth_stats.columns=["Earliest Birth Year","Latest Birth Year","Most Common Birth Year"] bike_stats = {"travel time stats": travel_time_stats, "travel location stats": location_stats, "travel duration stats":duration_stats, "user characteristic stats": user_characteristic_stats,"user birth stats": user_birth_stats} return bike_stats """------------------------------------------------------------------------------------------------------------------------------ Section 2 User input and output provided generated using function calls on the functions listed above. """ """ Section 2.1. Get the input from the user in the necessary format to generate the ouptut. """ print("Please provide values for the main dimensions when prompted. These will filter the data used to calculate the stats.") print("You can write one value or multiple values seperated by a comma.") # define a bool variable whose value is set to prompt the user to reenter if they did not provide input values of the correct type def user_input(i): """ This function handles the user inputs for the main dimensions. It takes a string inputted by the user and returns a list of distinct dimension values that the above function load_data2() takes as the dimension values to filter the raw data on. The user must input a string. If they want to filter on multiple values for a dimension they must seperate each of the values with a comma in the string. """ if i=="city": while True: m = input("Which cities are you interested in? : ") m=[s.strip().lower() for s in m.split(",")] # verify correct data type entered if not all([e in ["chicago","washington", "new york city"] for e in m]) and m[0]!="all": print("Those cities aren't valid unfortunately. Pls try again.") else: break elif i == "mnth": while True: m = input("What months are you interested in? : ") # turn the input into the format that the function load_data2 accepts when filtering on month # First, strip all of the spaces left around the commas the user inputs #Then, convert all to lower case to remove any captialised characters not at the start of the string #Finally, captialise the strings in m so that first character is a capital m=[s.strip().lower().capitalize() for s in m.split(",")] # verify correct data type entered if not all([e in ['January','February','March','April','May','June','July','August','September','October','November','December'] for e in m]) and m[0]!="All": print("Those months aren't valid unfortunately. Pls try again.") else: break elif i == "day": while True: m = input("What days are you interested in? : ") # turn the input into the format that the function load_data2 accepts when filtering on day # First, strip all of the spaces left around the commas the user inputs #Then, convert all to lower case to remove any captialised characters not at the start of the string # Finally, captialise the strings in m so that first character is a capital m=[s.strip().lower().capitalize() for s in m.split(",")] # verify correct data type entered if not all([e in ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] for e in m]) and m[0]!="All": print("Those days aren't valid unfortunately. Pls try again.") else: break elif i == "raw": while True: m = input("Do you want to see the raw data? Pls type yes or no: ").lower() # verify correct data type entered if m.lower() not in ['yes','no']: print("That isn't valid. Pls try again.") else: break return m # Obtain the cities print("Pls choose the cities you want stats for from Chicago, Washington or New York City. Pls input a city ") x = user_input("city") # Obtain the months print("Pls choose the months you want stats for. Pls input a month as a capitalised string or list of strings") y = user_input("mnth") # Obtain the days print("Pls choose the days you want stats for. Pls input a day as a capitalised string or list of strings") z = user_input("day") # Determine if the user wants raw data r = user_input("raw") """ Section 2.2. Calling the functions defined in section 1 on the input variables entered by the user in section 2.1. """ def make_output(x,y,z): """ This function calls first the function load_data2 to produce a dataframe containing the bikeshare input data filtered to include only data points for the cities, days and months specified by the user. It then calls the function calc_stats which takes the dataframe output of load_data2 to produce the output of descriptive statistics. Args: exactly the same as those specified in docustring for function load_data_2. Output: bike_stats dataframe of output stats presented as a table and the dataframe of filtered base data, stats_input_df. """ stats_input_df = load_data2(x,y,z) bike_stats = calc_stats(stats_input_df) return bike_stats, stats_input_df output_dict, raw_data = make_output(x,y,z) check_type = True while check_type == True: print("Which stats do you want to see: Travel Time Stats,Travel Location Stats,Travel Duration Stats, User Characteristic Stats, User Birth Stats") input_str =input("Please enter one of these strings, or multiple strings seperated by a comma: ") print("\n ---------------------------------------------------------------------- \n") # if there are mutliple cities in the input string we now need to split to form a list input_list = [s.strip().lower() for s in input_str.split(",")] # verify correct data type entered if not all([e in ['travel time stats','travel location stats','travel duration stats', 'user characteristic stats', 'user birth stats'] for e in input_list]): print("There was an error in the strings that you entered. Pls try again, writing string names exactly as prompted.") else: for i in input_list: print(output_dict[i]) print("\n ---------------------------------------------------------------------- \n") break if r == "yes": row = 0 print(raw_data.loc[row:row+4]) print("\n ---------------------------------------------------------------------- \n") n = input("Do you want to see another 5 rows of data? Pls type yes or no: ") while n == 'yes': row=+5 print(raw_data.loc[row:row+4]) print("\n ---------------------------------------------------------------------- \n") n = input("Do you want to see another 5 rows of data? Pls type yes or no: ")
temperatures_C = [33, 66, 65, 0, 59, 60, 62, 64, 70, 76, 80, 81, 80, 83, 90, 79, 61, 53, 50, 49, 53, 48, 45, 39] min_temp = min(temperatures_C) max_temp = max(temperatures_C) hot_temps = [] for temp in temperatures_C: if temp >= 70: hot_temps.append(temp) avg_temp = sum(temperatures_C) / len(temperatures_C) #sensor failure at 3am - change the temp at 3am to average temp temperatures_C = [x if x != 0 else int(avg_temp) for x in temperatures_C] print(temperatures_C) print('Min temp is',min_temp) print('max temp is',max_temp) print('Temperatures above 70 are',hot_temps) print('Average temp is',avg_temp) def c_to_f(temp): f = 1.8 * temp + 32 return f #convert temperatures from C to F temperatures_F = [c_to_f(x) for x in temperatures_C] print('Temperatures in Fahrenheit are',temperatures_F) #decision making if len(hot_temps) > 4 or avg_temp > 65 or [True if x > 80 else False for x in temperatures_C]: print('Replace the cooling system') else: print('Do not replace the cooling system')
def partition(elements, start, end): pivot = elements[start] left = start + 1 right = end while True: while left <= right and elements[left] <= pivot: left += 1 while left <= right and elements[right] >= pivot: right -= 1 if left <= right: elements[left], elements[right] = elements[right], elements[left] else: break elements[start], elements[right] = elements[right], elements[start] return right def quick_sort(elements, start, end): if start >= end: return partition_index = partition(elements, start, end) quick_sort(elements, start, partition_index-1) # sort left subarray quick_sort(elements, partition_index+1, end) # sort right subarray def display_elements(elements): for i in elements: print(i, end=" ") print("") def main(): elements = [87, 65, 34, 23, 12, 9] quick_sort(elements, 0, len(elements)-1) display_elements(elements) if __name__ == "__main__": main()
def add_it_up(n): if isinstance(n, int): result = n*(n+1)/2 return int(result) else: return 0 def better_approach(num): try: return sum(range(num+1)) except Exception: return 0 def main(): result = add_it_up(20) print(f"Sum of first 20 numbers is : {result}") print(f"Sum of first 10 is : {better_approach(10)}") print(f"Exception : {add_it_up('ERROR')}") print(f"Exception : {better_approach('ERROR')}") if __name__ == '__main__': main()
# remove duplicate from a list of strings def remove_duplicate(li): return list(set(li)) def main(): li = ['Sourav', 'Ganguly', 'Gourab', 'Ganguly', 'Ratul', 'Rakshit', 'Ratul', 'Mukherjee'] new_list = remove_duplicate(li) print(f"New list : {new_list}") if __name__ == '__main__': main()
def insertion_sort(elements): for i in range(1, len(elements)): j = i - 1 key = elements[i] while j >= 0 and elements[j] > key: elements[j+1] = elements[j] j = j-1 elements[j+1] = key def display_elements(elements): for i in elements: print(i, end=" ") print("") def main(): elements = [3, 20, 6, 9, 99, 12, 21, 2,77] print("Before sorting : ") display_elements(elements) insertion_sort(elements) print("After sorting : ") display_elements(elements) if __name__ == '__main__': main()
[car for car in['a','e','i','o','u'] if car not in('a','i','o')] edad,_peso = 20, 70.5 nombres = 'Jesus Quirumaby' dirDomiciliaria= "Paraiso de la flor " Tipo_sexo = 'M' civil = True usuario = ('jquirumbayr','1234','[email protected]') materias = ['Programa Web','PHP','POO'] docente = {'nombre':'Jesus','edad':19} print("""Mi nombre es {}, tengo {} años""".format(nombres,edad)) print(usuario,materias,docente) import math num1, num2, num, men = 12.572, 15.4, 4, '1234' print(math.ceil(num1), '\t',math.floor(num1)) print(round(num1,1),'\t',type(num),'\t',type(men))
def wages(a): b = 0 c = 0 d = 0 if a <= 1000: b = a * 0.14 c = a * 0.02 d = a - b - c print(d) # ve ya print(int(d)) elif a >= 2500: b = a * 0.20 c = a * 0.05 d = a - b - c print(d) # və ya print(int(d)) else: print("wrong") wages(1000)
#Jared Hinkle #jah87410 #4.8 #This program sorts three integers first,second,third = eval(input("Enter x,y,z:")) small = min(first,second,third) large = max(first,second,third) middle = (first + second + third) - (small + large) print("The numbers in accending order are: ", small, middle, large)
#Jared Hinkle #jah87410 #5.1 #This program will use a while loop and a for loop to find the sum of number between 1 and 15 x = 1 total = 0 while x <= 15: total = total + x x = x + 1 print("Sum using while loop: ", total) total2 = 0 for i in range(1, 16): total2 = total2 + i print("Sum using for loop: ", total2)
#Jared Hinkle #jah87410 #2.17 #This program will calculate the users BMI weightLBs = eval(input("Enter weight in pounds: ")) heightINCH = eval(input("Enter height in inches: ")) weightKG = weightLBs * 0.45359237 heightMeters = heightINCH * 0.0254 BMI = weightKG / (heightMeters * heightMeters) print("BMI is: ", round(BMI,4))
#Jared Hinkle #jah87410 #final exam #program calculates BAC def estimatedBAC(alcohol, bodyWeight, r): if (r == 0): return(((alcohol)/(bodyWeight*(.68)))*100) if (r == 1): return(((alcohol)/(bodyWeight*(.55)))*100) alchol = eval(input("Enter amount of alcohol in grams: ")) bodyWeight = eval(input("Enter body weight in grams: ")) r = eval(input("Enter gender (0 for male, 1 for female): ")) print("Estimated BAC is: ", estimatedBAC(alchol, bodyWeight, r))
import random # Set your random roll range random_number = random.randint(1, 50) print("Your random number is " + str(random_number)) # Create dictionary for items and values gear = {'Arcanum of Wizardry': 10, 'Rib Cage of King Ragmussen': 20, 'Helm of Helia': 30, 'Flametooth Dagger': 40, 'Wand of Zeek': 50} # Check random_number against items in dictionary. def rng(): for key, value in gear.items(): if random_number == value: print("You won the " + key + "!") break else: print("Sorry, you're a noob and win nothing!") rng()
from typing import Optional from enum import Enum from abc import ABC class Display: # This class is given with implementation. And the ONLY one @staticmethod def read_input(display_text: str) -> str: pass @staticmethod def show_error(err_msg: str) -> None: pass @staticmethod def show_message(msg: str) -> None: pass ''' Implement methods below here ''' class AccountStoreRespCode(Enum): USER_NOT_EXIST = 0 USER_ALREADY_EXIST = 1 class AccountStore: @staticmethod def check_user(name: str, address: str) -> AccountStoreRespCode: return AccountStoreRespCode.USER_NOT_EXIST @staticmethod def create_user(name: str, address: str, pin: str) -> Optional[int]: pass @staticmethod def verify_user(uid: int, pin: str) -> bool: pass @staticmethod def withdraw(uid: int, amount: int) -> bool: pass @staticmethod def get_balance(uid: int) -> int: balance = 1000 # balance = Account.get_balance_for_user(uid) return balance @staticmethod def set_balance(uid: int, amount: int) -> None: # balance = Account.set_balance_for_user(uid) return class CardHandler: @staticmethod def create_card(uid: int): pass @staticmethod def read_card() -> Optional[int]: pass @staticmethod def return_card() -> None: pass @staticmethod def lock_card(num): pass class CashDispenser: @staticmethod def dispense(amount: int) -> bool: pass class CashInTake: @staticmethod def take() -> int: pass ''' State design pattern: Actions changes according to internal state, as if the implementation changes dynamically ''' class ATMState(Enum): GREETING = 0 ASK_PIN = 1 AUTHORIZED = 2 MAIN_MENU = 3 WITHDRAW_SELECTED = 10 WITHDRAW_AMOUNT_ENTERED = 11 WITHDRAW_LOW_BALANCE = 13 DEPOSIT_SELECTED = 20 DEPOSIT_ACCEPTED = 21 ENDING_MENU = 30 class ATM: def __init__(self): self.state_obj = None self.withdraw_amount = None self.uid = None self.card = 0 self.pin_error = 0 states_map = { ATMState.GREETING: lambda: GreetingState(), ATMState.ASK_PIN: lambda: AskPinState(), ATMState.MAIN_MENU: lambda: MainMenuState(), } def set_state(self, state: ATMState) -> None: self.state_obj = ATM.states_map[state](self) def insert_card(self): self.state_obj.insert_card() def ask_pin(self) -> int: return self.state_obj.ask_pin() def log_in_user(self, pin: str): self.uid = AccountStore.verify_user(self.card, pin) return self.uid def set_withdraw_amount(self, amount) -> None: self.withdraw_amount = amount def get_withdraw_amount(self) -> int: return self.withdraw_amount def get_balance(self) -> int: return AccountStore.get_balance(self.uid) def set_balance(self, amount: int) -> None: AccountStore.set_balance(self.uid, amount) def create_account(self): name = Display.read_input('Enter your name:') address = Display.read_input('Enter your address:') if AccountStore.check_user(name, address) == AccountStoreRespCode.USER_ALREADY_EXIST: Display.show_error('User already exist!') return pin = Display.read_input('Enter pin:') uid = AccountStore.create_user(name, address, pin) if not uid: return CardHandler.create_card(uid) def get_input(self): self.state_obj.get_input() def ask_deposit_money(self): self.state_obj.ask_deposit_money() def ask_withdraw_amount(self): self.state_obj.ask_withdraw_amount() def lock_card(self): CardHandler.lock_card(self.card) def withdraw(self): self.state_obj.withdraw() def show_menu(self): self.state_obj.show_menu() def show_ending_menu(self): self.state_obj.show_ending_menu() class BaseState(ABC): ''' Class 1. take action 2. store intermediate result to atm 3. change atm to next possible state ''' def __init__(self, atm: ATM = None): self.atm = atm def set_atm(self, atm: ATM): self.atm = atm return self def insert_card(self): pass def ask_pin(self) -> int: pass def ask_withdraw_amount(self): pass def get_input(self) -> int: pass def ask_deposit_money(self): pass def withdraw(self): pass def show_menu(self): pass def show_ending_menu(self): pass class GreetingState(BaseState): def insert_card(self) -> None: card = CardHandler.read_card() if not card: Display.show_error('Card cannot be read') self.atm.card = card self.atm.set_state(ATMState.ASK_PIN) self.atm.ask_pin() class AskPinState(BaseState): def ask_pin(self) -> int: pin = Display.read_input('Enter pin code:') uid = self.atm.log_in_user(pin) if uid: self.atm.set_state(ATMState.MAIN_MENU) self.atm.show_menu() return 0 else: self.atm.pin_error += 1 if self.atm.pin_error == 3: self.atm.lock_card() self.atm.set_state(ATMState.GREETING) else: self.atm.set_state(ATMState.ASK_PIN) self.atm.ask_pin() return -1 class MainMenuState(BaseState): def show_menu(self) -> int: mode = int(Display.read_input('Choose 1. Withdraw 2. Deposit 3. Log out')) if mode == 1: self.atm.set_state(ATMState.WITHDRAW_SELECTED) self.atm.ask_withdraw_amount() elif mode == 2: self.atm.set_state(ATMState.DEPOSIT_SELECTED) self.atm.ask_deposit_money() elif mode == 3: CardHandler.return_card() self.atm.set_state(ATMState.GREETING) return mode class WithdrawSelected(BaseState): def ask_withdraw_amount(self): amount = int(Display.read_input('Enter withdraw amount')) res = self.atm.check_balance(amount) if res == 0: self.atm.set_state(ATMState.WITHDRAW_AMOUNT_ENTERED) self.atm.withdraw_amount(amount) self.atm.set_state(ATMState.ENDING_MENU) self.atm.show_ending_menu() self.atm.set_state(ATMState.WITHDRAW_AMOUNT_ENTERED) class WithdrawExecuteState(BaseState): def withdraw(self) -> int: balance = self.atm.get_balance() if self.atm.withdraw_amount <= balance: CashDispenser.dispense(self.atm.withdraw_amount) self.atm.set_balance(balance - self.atm.withdraw_amount) self.atm.set_state(ATMState.ENDING_MENU) self.atm.show_ending_menu() return 0 else: Display.show_error('Balance is not enough') self.atm.set_state(ATMState.WITHDRAW_LOW_BALANCE) return -1 class WithdrawLowBalance(BaseState): def get_input(self): self.atm.set_state(ATMState.MAIN_MENU) class DepositSelected(BaseState): def ask_deposit_money(self): Display.show_message('Deposit money') amount = CashInTake.take() self.atm.set_balance(self.atm.get_balance() + amount) self.atm.set_state(ATMState.MAIN_MENU) class EndingMenuState(BaseState): def show_ending_menu(self) -> None: mode = int(Display.read_input('Choose 1. Print Receipt 2. Send email 3. Log out 4. Go to main menu')) if mode == 3: self.atm.log_out() self.atm.set_state(ATMState.GREETING) elif mode == 4: self.atm.set_state(ATMState.MAIN_MENU) self.atm.show_menu() def main(): atm = ATM() atm.insert_card() i = 0 res = -1 while i < 3: if atm.ask_pin() < 0: i += 1 else: break if i == 3: return mode = atm.get_input() if mode == 1: atm.ask_withdraw_amount() res = atm.withdraw() if res == 0: atm.show_menu() # It's the user input to drive ATM jump between different states if __name__ == '__main__': main()
import random from collections import OrderedDict, defaultdict from typing import List class Node: def __init__(self, val, next, random): self.val = val self.next = next self.random = random self.prev = self.next = self.child = None class ListNode: def __init__(self, val): self.val = val self.next = None class Solution382: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.head = head def getRandom(self) -> int: """ Returns a random node's value. """ # k = 1 resevoir sampling res = self.head cur = res.next count = 1 while cur: if random.randint(0, count) == 0: #random find a node including cur and check if is < k (k = 1). if so # use it res = cur.val count += 1 cur = cur.next return res class LRUCache: class ListNode: def __init__(self, key=None, val=None): # python func does not support overloading! every same name func # replace previous one. Use default value and factory methord to construct condionally self.key = key # used when try to delete node self.val = val self.pre = self.next = None def __init__(self, capacity: int): self.cap = capacity self.head, self.tail = self.ListNode(), self.ListNode() self.size = 0 self.hm = {} self.head.next = self.tail self.tail.pre = self.head def get(self, key: int) -> int: if key not in self.hm: return -1 res = self.hm[key] self.move_to_head(res) return res.val def put(self, key: int, value: int) -> None: if key in self.hm: x = self.hm[key] x.val = value self.move_to_head(x) else: if self.size == self.cap: del self.hm[self.tail.pre.key] # dont forget to remove from hm self.delete_node(self.tail.pre) self.size -= 1 node = self.ListNode(key, value) self.insert_to_head(node) self.hm[key] = node self.size += 1 def insert_to_head(self, node): if self.head.next == node: return node.next = self.head.next self.head.next.pre = node node.pre = self.head self.head.next = node def move_to_head(self, node): self.delete_node(node) self.insert_to_head(node) def delete_node(self, node): node.pre.next = node.next node.next.pre = node.pre class LFUCache: class Node: def __init__(self, k, v, count): self.k, self.v, self.count = k, v, count def __init__(self, capacity): self.capacity = capacity self.hm_key = {} self.hm_count = defaultdict(OrderedDict) self.minc = None def get(self, key): if key not in self.hm_key: return -1 node = self.hm_key[key] self.bump_node(node) return node.v def put(self, key, value): if self.capacity <= 0: return if key in self.hm_key: node = self.hm_key[key] node.v = value self.bump_node(node) return if len(self.hm_key) == self.capacity: k, v = self.hm_count[self.minc].popitem(last=False) del self.hm_key[k] self.hm_key[key] = self.hm_count[1][key] = self.Node(key, value, 1) self.minc = 1 def bump_node(self, node: Node): del self.hm_count[node.count][node.k] if not self.hm_count[node.count]: del self.hm_count[node.count] if self.minc not in self.hm_count: self.minc += 1 node.count += 1 self.hm_count[node.count][node.k] = node class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head: return head cur = head # 1. copy 1->1' -> 2 -> 2' while cur: node = Node(cur.val, None, None) node.next = cur.next cur.next = node cur = cur.next.next # 2. connect random cur = head while cur: cur.next.random = cur.random.next if cur.random else None cur = cur.next.next # 3. split cur = head dummy = pre = Node(0, None, None) while cur: pre.next = cur.next pre = pre.next cur.next = cur.next.next cur = cur.next return dummy.next def isPalindrome(self, head: ListNode) -> bool: if not head or not head.next: return True slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next pre = None while slow: next = slow.next slow.next = pre pre = slow slow = next while pre: if pre.val != head.val: return False pre, head = pre.next, head.next return True def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1 or not l2: return l1 or l2 dummy = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dummy.next def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1 or not l2: return l1 or l2 dummy = cur = ListNode(0) carry = 0 while l1 or l2 or carry: sum = carry if l1: sum += l1.val l1 = l1.next if l2: sum += l2.val l2 = l2.next cur.next = ListNode(sum % 10) cur = cur.next carry = sum // 10 return dummy.next def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1 or not l2: return l1 or l2 st1, st2 = [], [] while l1: st1.append(l1.val) l1 = l1.next while l2: st2.append(l2.val) l2 = l2.next carry = 0 nextn = None while st1 or st2 or carry: sum = carry if st1: sum += st1.pop() if st2: sum += st2.pop() node = ListNode(sum % 10) carry = sum // 10 node.next = nextn nextn = node return nextn def getIntersectionNode(self, headA, headB): if not headA or not headB: return None # return None if one not exist m, n = 0, 0 curA, curB = headA, headB while curA: m += 1 curA = curA.next while curB: n += 1 curB = curB.next curA, curB = headA, headB while m - n > 0: curA = curA.next m -= 1 while n - m > 0: curB = curB.next n -= 1 while curA != curB: curA, curB = curA.next, curB.next return curA def plusOne(self, head: ListNode) -> ListNode: if not head: return head right, cur = None, head while cur: if cur.val != 9: right = cur cur = cur.next if not right: node = ListNode(1) node.next = head head = right = node else: right.val += 1 # dont forget to plus 1 cur = right.next while cur: cur.val = 0 cur = cur.next return head def oddEvenList(self, head: ListNode) -> ListNode: if not head or not head.next: return head dummyo = curo = ListNode(0) dummye = cure = ListNode(0) i = 1 while head: if i % 2 == 1: curo.next = head curo = curo.next else: cure.next = head cure = cure.next head = head.next i += 1 curo.next = dummye.next cure.next = None return dummyo.next def partition(self, head: ListNode, x: int) -> ListNode: if not head: return head dummy_lt = clt = ListNode(0) dummy_gt = clg = ListNode(0) while head: if head.val < x: clt.next = head clt = clt.next else: clg.next = head clg = clg.next head = head.next clt.next = dummy_gt.next clg.next = None return dummy_lt.next def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return head pre = dummy = ListNode(0) pre.next = head has_dup = False cur = head while cur: while cur.next and cur.val == cur.next.val: has_dup = True cur.next = cur.next.next if has_dup: pre.next = cur.next else: pre = cur cur = cur.next has_dup = False return dummy.next def swapPairs(self, head: ListNode) -> ListNode: if not head: return head dummy = pre = ListNode(0) dummy.next = cur = head while cur and cur.next: next = cur.next.next pre.next = cur.next cur.next.next = cur pre = cur cur = next pre.next = cur return dummy.next def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: if not head: return head dummy = left = ListNode(0) dummy.next = head x = n - m while m > 1: left = left.next m -= 1 cur = left.next pre = None while x >= 0: next = cur.next cur.next = pre pre = cur cur = next x -= 1 left.next.next = cur left.next = pre return dummy.next def reorderList(self, head: ListNode) -> None: if not head or not head.next: return slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next pre = None cur = slow while cur: next = cur.next cur.next = pre pre = cur cur = next t = ListNode(0) n = 1 while head and pre: if n % 2 == 1: t.next = head head = head.next else: t.next = pre pre = pre.next t = t.next n += 1 def detectCycle(self, head: ListNode) -> ListNode: if not head: return head slow = fast = head has_cycle = False while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: has_cycle = True break if not has_cycle: return None slow = head while slow != fast: slow = slow.next fast = fast.next return slow def insert(self, head: 'Node', insertVal: int) -> 'Node': class Node: def __init__(self, val, next): self.val = val self.next = next if not head: head = Node(insertVal, None) head.next = head return head # two pointers, if pre <= insert <= cur, insert it; else if at pivot, insert >= pre or insert <= cur, insert # cyclic, while loop break when cur become head again pre, cur = head, head.next while cur != head: if pre.val <= insertVal <= cur.val: break if pre.val > cur.val and (insertVal >= pre.val or insertVal <= cur.val): break pre, cur = cur, cur.next pre.next = Node(insertVal, cur) return head def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]: # the first N % K sub list will have an extra node. plus the avg of N // K res = [None] * k if not root: return res n = 0 cur = root while cur: n += 1 cur = cur.next avg, ext = n // k, n % k cur = root for i in range(k): res[i] = cur if cur: for j in range(avg + (1 if i < ext else 0) - 1): cur = cur.next t = cur.next cur.next = None cur = t return res def nextLargerNodes(self, head: ListNode) -> List[int]: # maintain a st caching numbers and immmeditely pop once a larger number shows up. store index because number # can duplicate res = [] if not head: return res while head: res.append(head.val) head = head.next st = [] for i in range(len(res)): while st and res[st[-1]] < res[i]: res[st.pop()] = res[i] st.append(i) while st: res[st.pop()] = 0 return res def removeZeroSumSublists1171(self, head: ListNode) -> ListNode: # there are two scenarios: [3, 2, -2, 1, -1] or [3, 2, -1, 1, -2]. two passes, first pass map prefix sum -> node # and always later overwrite the repeating prefix sum. second pass get prefix sum again and directly bypass # all the way to the mapped value if not head: return head hm = {} dummy = cur = ListNode(0) dummy.next = head presum = 0 while cur: presum += cur.val hm[presum] = cur cur = cur.next cur = dummy presum = 0 while cur: presum += cur.val cur.next = hm[presum].next cur = cur.next return dummy.next def flatten430(self, head: 'Node') -> 'Node': def dfs(head: Node): cur = head tail = None while cur: # special case, when a level contain a single node, need go in loop and record tail if not cur.next: tail = cur if cur.child: next = cur.next chead, ctail = dfs(cur.child) cur.next = chead chead.prev = cur cur.child = None ctail.next = next if next: # special case, when single node in level, next is None, need to set tail to child tail next.prev = ctail else: tail = ctail cur = next else: cur = cur.next return head, tail if not head: return head return dfs(head)[0]
import heapq from typing import List, Tuple class Solution: ''' * Order Book Take in a stream of orders (as lists of limit price, quantity, and side, like ["155", "3", "buy"]) and return the total number of executed shares. Rules - An incoming buy is compatible with a standing sell if the buy's price is >= the sell's price. Similarly, an incoming sell is compatible with a standing buy if the sell's price <= the buy's price. - An incoming order will execute as many shares as possible against the best compatible order, if there is one (by "best" we mean most favorable to the incoming order). - Any remaining shares will continue executing against the best compatible order, if there is one. If there are shares of the incoming order remaining and no compatible standing orders, the incoming order becomes a standing order. Example input (more details are in the slide deck): Stream of orders ("150", "10", "buy"), ("165", "7", "sell"), ("168", "3", "buy"), ("155", "5", "sell"), ("166", "8", "buy") Example output: 11 ''' def total_executed_shares(self, orders: List[Tuple[str, str, str]]) -> int: buy, sell = [], [] res = 0 for price, cnt, op in orders: price, cnt = int(price), int(cnt) if op == 'buy': heapq.heappush(buy, [-price, cnt]) else: heapq.heappush(sell, [price, cnt]) while buy and sell and -buy[0][0] >= sell[0][0]: if buy[0][1] >= sell[0][1]: res += sell[0][1] buy[0][1] -= sell[0][1] sell[0][1] -= sell[0][1] else: res += buy[0][1] sell[0][1] -= buy[0][1] buy[0][1] -= buy[0][1] if sell[0][1] == 0: heapq.heappop(sell) if buy[0][1] == 0: heapq.heappop(buy) return res ''' You have N securities available to buy that each has a price Pi. Your friend predicts for each security the stock price will be Si at some future date. But based on volatility of each share, you only want to buy up to Ai shares of each security i. Given M dollars to spend, calculate the maximum value (revenue not profit) you could potentially achieve based on the predicted prices Si (and including any cash you have remaining). Assume fractional shares are possible. * N = List of securities * Pi = Current Price * Si = Expected Future Price * Ai = Maximum units you are willing to purchase * M = Dollars available to invest Example Input: M = $140 available N = 4 Securities - P1=15, S1=45, A1=3 (AAPL) - P2=25, S2=35, A2=3 (SNAP - P3=40, S3=50, A3=3 (BYND - P4=30, S4=25, A4=4 (TSLA Output: $265 3 shares of apple -> 45(15 *3), 135(45 *3) 3 shares of snap -> 75, 105 0.5 share of bynd -> 20, 25 ''' def max_value(self, options: List[List[int]], m: int) -> int: options.sort(key=lambda l: l[1] / l[0], reverse=True) res = 0 i = 0 for p, s, a in options: if s <= p: break shares = m / p if shares >= a: res += s * a m -= p * a else: res += shares * s break return res class InsufficientFunds(Exception): pass def bad_transfer(src_account, dst_account, amount): src_cash = src_account.cash # DB read dst_cash = dst_account.cash # DB read if src_cash < amount: raise InsufficientFunds src_account.cash = src_cash - amount # DB write src_account.send_src_transfer_email() dst_account.cash = dst_cash + amount # DB write dst_account.send_dst_transfer_email() s = Solution() input = [("150", "10", "buy"), ("165", "7", "sell"), ("168", "3", "buy"), ("155", "5", "sell"), ("166", "8", "buy")] # res = s.total_executed_shares(input) # input = [[15, 45, 3], [25, 35, 3], [40, 50, 3], [30, 25, 4]] # input = [[10, 5, 3], [8, 5, 2]] # res = s.max_value(input, 140) # print(res) def t() -> Tuple[int, int, int]: return 1
import random from typing import List ''' Reservoir sampling: When to use: 1. list length is unknown 2. Save space How to use: Loop through entire data stream Use a counter cnt increment when meet target if random.randrange(cnt) == 0: swap into reservoir return the one in reservoir ''' class Solution398: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: # to save space, use reservoir sampling res, cnt = -1, 0 for i in range(len(self.nums)): if self.nums[i] == target: cnt += 1 if random.randrange(cnt) == 0: res = i return res
"""This shows an example of how to use the Generator object to provide more control within loops. This could be used for things such as progress bars or emergency stops.""" from mandelpy import Settings, Generator s = Settings() with Generator(s) as g: blocks = g.blocks for i, block in enumerate(blocks): print(f"Creating block {i + 1} of {len(blocks)}:", block) g.run_block(block) img = g.finished_img()
def product2(num1,num2): p=num1*num2 return p def product3(num1,num2,num3): p=num1*num2*num3 return p print product2(2,3) print product3(2,3,4)
import random def merge_sort(arr): if len(arr) > 1: mid = len(arr)//2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) i = 0 j = 0 k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i = i+1 else: arr[k] = right[j] j = j+1 k = k+1 while i < len(left): arr[k] = left[i] i = i+1 k = k+1 while j < len(right): arr[k] = right[j] j = j+1 k = k+1 def hybrid_sort(arr): if len(arr) > 1: mid = len(arr)//2 left = arr[:mid] right = arr[mid:] if mid > 10: hybrid_sort(left) hybrid_sort(right) elif mid < 10: insertion_sort(left) insertion_sort(right) i = 0 j = 0 k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i = i+1 else: arr[k] = right[j] j = j+1 k = k+1 while i < len(left): arr[k] = left[i] i = i+1 k = k+1 while j < len(right): arr[k] = right[j] j = j+1 k = k+1 def insertion_sort(arr): size = len(arr) for i in range(size): key = arr[i] j = i-1 while j >= 0 and arr[j] > key: arr[j+1] = arr[j] j = j-1 arr[j+1] = key print("insertionSort: ",arr) setA = [] for i in range(2006): setA.append(random.randrange(100)) hybrid_sort(setA) print(setA)
import cs50 import sys if len(sys.argv) == 2: k = int(sys.argv[1]) s = input() ss = "" for symbol in s: if symbol.islower(): ascii = ord(symbol) + k%26 if ascii > 122: ascii = ascii - 122 + 96 buf = chr(ascii) elif symbol.isupper(): ascii = ord(symbol) + k%26 if ascii > 90: ascii = ascii - 90 + 64 buf = chr(ascii) else: buf = symbol ss += buf print(ss) else: print("Please enter one argument next time!")
import random class Unit: HP = 100 STR = 10 LUCK = 5 DEF = 5 name = "" def __init__(self, name): self.name = name def status(self): print("HP: %d, STR = %d, LUCK = %d, DEF = %d" % (self.HP, self.STR, self.LUCK, self.DEF)) class Battle: def attack(unit1,unit2): if random.randrange(0,99) > unit2.LUCK: damage = unit1.STR-unit2.DEF unit2.HP = unit2.HP - damage print("%s(은)는 %s의 공격에 성공하였다! %s는 피가 %d만큼 줄었다!" % (unit1.name, unit2.name, unit2.name, damage)) if unit2.HP < 0 : Battle.endGame(unit1) else: print("%s (은)는 %s의 공격에 실패하였다!" % (unit1.name,unit2.name)) if random.randrange(0,99) > unit1.LUCK : damage = unit2.STR-unit1.DEF unit1.HP = unit1.HP - damage print("%s(은)는 %s의 공격에 성공하였다! %s는 피가 %d만큼 줄었다!" % (unit2.name, unit1.name, unit1.name, damage)) if unit1.HP < 0 : Battle.endGame(unit2) else: print("%s (은)는 %s의 공격에 실패하였다!" % (unit2.name, unit1.name)) def endGame(unit): print("%s의 승리!" % unit.name) quit() unit1 = input("이름을 입력해주세요\n") unit1 = Unit(unit1) print(unit1.status()) unit2 = input("이름을 입력해주세요\n") unit2 = Unit(unit2) print(unit2.status()) print("싸움을 시작하시겠습니까?\m") go = input("Y/N") if go == 'Y': while (1): Battle.attack(unit1,unit2) elif go == 'N': pass else : print("Y 나 N 을 입력주세요")
# File with strings to print HELLO_PRINT = 'Hello! This is Vending Machine!' ENTER_CODE = "Enter code: " INSERT_BN = 'Insert your banknotes value one by one.' STOP_INSERT = 'To stop process - insert 0.' CUST_INSERT = 'Insert: ' CREDIT = 'Your credit is ' CHOOSE_IT = 'Write a number of choice: ' IT_NUM = 'Item number: ' TAKE_CHANGE = "Take your change." IT_DESCRIPTION = ' Description: ' IT_PRICE = ' Price: ' CANT_BUY = "Not enough credit." NUM_OF_IT = ' Available number of item: ' CUST_CHOICE_NUM = 'Your items number: ' LST_PRDCT = " List of available product" CHOOSEN_ITM = "Your choice is:" SEPORATOR = "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" MENU = " Menu" MENU_CODE = [" 1. Insert a banknote", " 2. Show available products", " 3. Select a product", " 4. Get the change"] ERROR_WR = "Error: wrong input." ERROR_IN_BN = " Take the banknote back and insert another one." ERORR_NO_CHANGE_BN = "Take the banknote back. No product with full change." SUP_BN = "Supporting banknotes: " NO_PRDCT = "Not enough product" CUST_PRDCT = "You have bought this: " GOODBYE = "GoodBye and see you later!" CNT = "Press Enter to continue" NO_CHAHGE = "The machine has not enough change" # service print HELLO_SER = "This is service menu" MENU_SER = " Service Menu" MENU_SER_CODE = [" 1. Power OFF", " 2. Return to Main Menu", " 3. Service Operation", " 4. Show all information"] VALUE_BN = "Value banknote: " NUM = "Its number: " VALUE_CN = "Value coin: " ABOUT_PRODUCT_AND_COIN_NUM = "The number of coins and products was updated." NO_COIN = "There isn`t any coin or products.\n Please, call service staff." SHOW_INFO = "The number of banknotes, coins and products:" UPDATED = "You should update coins and products" CREDIT_0 = 'To do this operation the credit should be 0.'
#part 3 file = input("Enter the name of file: ") e=open(file,'w') store_file = input("Enter the contents to be stored in a file: ") e.write(store_file) e.close()
#!/usr/bin/python3 ''' Python tool to hide information inside of text through a key. File: main.py @authors: - David Regueira - Santiago Rocha - Eduardo Blazquez - Jorge Sanchez ''' """ App entry point """ import text_stego, crawler from art import * import colorama as cla import sys, random, signal from os import name, system, remove import text_stego as stego from text_stego import InvalidBitValue, InvalidCharacter def sigint_handler(signum, frame): """ Handler for SIGINT interruption (CTRL+C) """ print("\n\n") print(cla.Fore.RED + "[*]SIGINT received exiting") print("[!]Thanks for using the tool") sys.exit(0) def clear_screen(): """ Different ways from cleaning the screen """ if name == 'nt': _ = system('cls') else: _ = system('clear') def banner(): """ Clean screen and print new banner """ clear_screen() logo = text2art("Kage no Kotoba",font="katakana") print(cla.Fore.GREEN + logo) logo_text = text2art("Kage no Kotoba - Shadow Words",font="fancy") print(cla.Fore.YELLOW + logo_text) author_text = text2art("\n\nBy k0deless",font="fancy2") print(cla.Fore.BLUE + author_text) print("*" * 116 + "\n") def menu(): """ Print menu to the user """ choices = input(""" 1: Hide information 2: Unhide Information 3: Quit/Log Out Please enter your choice: """) if choices == str(1): hideInformation() elif choices == str(2): unhideInformation() elif choices == str(3): sys.exit else: print("You must only select either 1,2 or 3.") print("Please try again") menu() def main(): signal.signal(signal.SIGINT, sigint_handler) cla.init(autoreset=True) banner() menu() def hideInformation(): """ Call to stego library to hide message in a text and finally hide key and url in an image """ clear_screen() logo_text = text2art("Hiding information",font="fancy", decoration="barcode") print(cla.Fore.YELLOW + logo_text) print("*" * 116 + "\n") secret_file = input("[*]Enter file to hide: ") print("[*]Generating cover files...") languages = ["es", "en"] source = crawler.SourceFinding(source_language=random.choice(languages)) url, source = source.generate() print("[*]Cover files fetched from: %s" % url) try: ph = stego.ParagraphsHiding('cover.txt', file_to_hide=secret_file) key = ph.hide_information() print("[*]File %s hidden using cover text words" % (secret_file)) print(cla.Fore.LIGHTRED_EX + "[*]Generated Key: %s" % (key)) ih = stego.ImageHiding('cover.png', key_to_hide=key, url_metadata=url, url_language=source) ih.hide_information() print(cla.Fore.LIGHTRED_EX + "[*]Stego file generated => cover_hide.png") except InvalidBitValue as ibv: print(cla.Fore.RED + "[-]Error hidding message in text: %s" % (str(ibv))) sys.exit(1) except FileNotFoundError as fnf: print(cla.Fore.RED + "[-]Error with file hidding message in text: %s" % (str(fnf))) sys.exit(1) except ValueError as ve: print(cla.Fore.RED + "[-]Error of value hiding message in text: %s" % (str(ve))) sys.exit(1) finally: remove("cover.txt") remove("cover.png") print("[*]Cover files removed!!") def unhideInformation(): """ Extract key and download text to unhide the message """ clear_screen() logo_text = text2art("UnHiding information",font="fancy", decoration="barcode") print(cla.Fore.YELLOW + logo_text) print("*" * 116 + "\n") secret_file = input("[*]Enter file to unhide: ") target_file = input("[*]Enter result file name (whitout extension): ") uh = stego.ImageHiding(secret_file) key, url, language = uh.unhide_information() print("[*]Recovered URL: %s (language: %s)" % (url, language)) print(cla.Fore.GREEN + "[*]Recovered key: %s" % key) print("[*]enerating cover files from recovered data...") uSource = crawler.SourceFinding() if language == "es": uSource.get_source_es(url) elif language == "en": uSource.get_source_en(url) else: uSource.get_source_ru(url) print("[*]Cover files fetched from: %s" % url) try: dh = stego.ParagraphsHiding('cover.txt',key=key, file_to_unhide=target_file) f_name = dh.unhide_information() print(cla.Fore.GREEN + "[*]File unhidden: %s" % (f_name)) except InvalidCharacter as ic: print(cla.Fore.RED + "[-]Error extracting original message from text: %s" % (str(ic))) sys.exit(1) except FileNotFoundError as fnf: print(cla.Fore.RED + "[-]Error with file extracting original message from text: %s" % (str(fnf))) sys.exit(1) finally: remove("cover.txt") remove("cover.png") print("[*]Cover files removed!!") if __name__ == "__main__": main()
""" Entrada de Dados Sempre retorna uma String, independente do valor que seja digitado! """ #nome = input("Qual o seu nome?\n") ##idade = input("Qual sua idade?\n") ###ano_nascimento = 2021 - int(idade) #print(f"Usuário digitou {nome} e o tipo da variável {type(nome)}") #print(f"Tem {idade} anos") ##print(f"Nasceu no ano {ano_nascimento}") """ CALCULADORA DE SOMA """ numero_1 = int(input("Digite um número ")) numero_2 = int(input("Digite outro número ")) print(numero_1 + numero_2)
""" Condições if elif e else """ if False: print('Verdadeira!') elif False: print("Agora é verdadeiro") elif False: print("Sempre verdadeiro") else: print('Não é verdadeira!')
import datetime from .. import db class Blog(db.Model): """Represents a blog model in the database.""" id = db.Column(db.Integer, primary_key=True, nullable=False) path = db.Column(db.String(64), unique=True, nullable=False) name = db.Column(db.String(256), nullable=False) created = db.Column(db.DateTime, default=datetime.datetime.utcnow, nullable=False) owner_id = db.Column(db.Integer, db.ForeignKey('user.id'), unique=True) # Only one blog per user, please posts = db.relationship('Post', backref='blog') @staticmethod def GetById(id): """Get the blog which resides at the given id. Arguments: id: the id of the blog. Returns: the Blog object with the primary key id, or None """ return Blog.query.get(int(id)) @staticmethod def GetByPath(path): """Get the blog which resides at the given path. Arguments: path: the path of the blog. Returns: the Blog object with the corresponding path, or None """ return Blog.query.filter_by(path=path).first() @staticmethod def GetByName(name): """Get the blog which resides at the given name. Arguments: name: the name of the blog. Returns: the Blog object with the corresponding name, or None """ return Blog.query.filter_by(name=name).all() def __init__(self, path, name, owner): """Create a new blog. Note: This blog is not persisted to the database until Persist() is explicitly called. Arguments: path: The desired path for display of the blog. Must be unique. name: The name for the blog. owner: A User object who owns the blog. The Blog must be persisted. """ self.path = path self.name = name self.owner_id = owner.id def Persist(self, db_session=None): """Store the current version of the blog in the database. NOTE: This method commits the database session given by db_session. By default, this will be the session at db.session. If this transaction should be isolated, an explicitly created session must be provided. Arguments: db_session: Optional. A Flask SQLAlchemy session to use. """ if not db_session: db_session = db.session if not self.IsPersisted(): db_session.add(self) db_session.commit() def IsPersisted(self): """Indicates whether the blog has been persisted. Returns: boolean indicating whether the blog was persisted. """ return (self.id is not None) def __str__(self): return self.name def __repr__(self): return "%s: %s (%s)" % (self.name, self.path, self.owner)
# -*- coding: utf-8 -*- """ Created on Tue Aug 3 19:33:57 2021 @author: Estefania """ def crealista(n): lista=[] for i in range(n): lista.append(i) return lista print(crealista(5)) def crealista(n): lista=[] for i in range(n+1): lista.append(i) return lista print(crealista(5)) def crealista(n): lista=[] for i in range(n): lista.append(i) return lista print(crealista(15)) resultado=crealista(20)
# !/usr/bin/python3 import openpyxl import sys import csv def convert_excel(csvFile): # convert from csv to xlsx wb = openpyxl.Workbook() ws = wb.active with open(csvFile) as f: reader = csv.reader(f, delimiter=',') for row in reader: ws.append(row) fileName = csvFile.replace(".csv", ".xlsx") wb.save(fileName) if __name__ == "__main__": inputFile1 = sys.argv[1] inputFile2 = sys.argv[2] # If you have both xlsx files, skip this sentence ########### if inputFile1 != 'total.xlsx': convert_excel(inputFile1) inputFile1 = inputFile1.replace(".csv", ".xlsx") convert_excel(inputFile2) inputFile2 = inputFile2.replace(".csv", ".xlsx") ############ wb1 = openpyxl.load_workbook(inputFile1) ws1 = wb1.active wb2 = openpyxl.load_workbook(inputFile2) ws2 = wb2.active wb = openpyxl.Workbook() ws = wb.active i = 2 while True: if not ws2.cell(row=i, column=1).value: break ws2.cell(row=i, column=3, value="{}".format(0)) i = i + 1 i = 2 while True: if not ws1.cell(row=i, column=1).value: break A_name = ws1.cell(row=i, column=1).value # eng ver # A_name = A_name.lower() # A_name = A_name.capitalize() A_count = int(ws1.cell(row=i, column=2).value) ws.cell(row=i, column=1, value="{}".format(A_name)) ws.cell(row=i, column=2, value="{}".format(A_count)) j = 2 while True: if not ws2.cell(row=j, column=1).value: break B_name = ws2.cell(row=j, column=1).value # eng ver # B_name = B_name.lower() # B_name = B_name.capitalize() B_count = int(ws2.cell(row=j, column=2).value) if A_name == B_name: total_count = A_count + B_count ws.cell(row=i, column=2, value="{}".format(total_count)) ws2.cell(row=i, column=3, value="{}".format(1)) j = j + 1 if ws.cell(row=j, column=2).value == 0: ws.cell(row=i, column=2, value="{}".format(A_count)) i = i + 1 k = 2 while True: if not ws2.cell(row=k, column=1).value: break B_name = ws2.cell(row=k, column=1).value # eng ver # B_name = B_name.lower() # B_name = B_name.capitalize() B_count = int(ws2.cell(row=k, column=2).value) if ws2.cell(row=k, column=3).value == 0: ws.cell(row=i, column=1, value="{}".format(B_name)) ws.cell(row=i, column=2, value="{}".format(B_count)) i = i + 1 k = k + 1 wb.save('total.csv') wb.save('total.xlsx')
def print_elem(letter, count): for i in range(count): print(letter, end = "") def print_group(corner_char, fill_char, fill_count): print_elem(corner_char, 1) print_elem(fill_char, fill_count) def print_line(corner_char, fill_char, fill_count, rep): for i in range(rep): print_group(corner_char, fill_char, fill_count) print_elem(corner_char, 1) print() def print_grids(corner_char, rows, cols): for i in range(rows): print_line('+', '-', 4, cols) for i in range(4): print_line('|', ' ', 4, cols) print_line('+', '-', 4, cols) print_grids('+', 2, 3)
import turtle screen = turtle.Screen() screen.title('Tic-Tac-Toe') screen.setworldcoordinates(-5, -5, 35, 35) pen = turtle.Turtle() for i in range(0, 4): pen.penup() pen.speed(0) pen.goto(0, i*10) pen.pendown() pen.speed(0) pen.forward(30) pen.left(90) for i in range(0, 4): pen.penup() pen.speed(0) pen.goto(i*10, 0) pen.pendown() pen.forward(30) pen.penup() for i in range(4): x = eval(input("Enter x coordinate for X's move: ")) y = eval(input("Enter y coordinate for X's move: ")) pen.goto(x*10+5, y*10+2.5) pen.write("X", align='center', font=('Arial', 80, 'normal')) x = eval(input("Enter x coordinate for X's move: ")) y = eval(input("Enter y coordinate for X's move: ")) pen.goto(x*10+5, y*10+2.5) pen.write("O", align='center', font=('Arial', 80, 'normal')) pen.goto(-2.5, -2.5) pen.write("Thank you for playing!", font=('Arial', 20, 'normal'))
def draw_board(board): print(" " + board[0] + " | " + board[1] + " | " + board[2] + " ") print("---+---+---") print(" " + board[3] + " | " + board[4] + " | " + board[5] + " ") print("---+---+---") print(" " + board[6] + " | " + board[7] + " | " + board[8] + " ") def get_player_move(board): # get a number from 1 to 9 for the board position move = input("Enter your move (position 1-9): ") imove = int(move) if can_make_move(board, imove - 1): return imove - 1 else: print("Sorry, that's not a valid move. Please try again.") return get_player_move(board) def get_board_copy(board): new_board = list(board) return new_board def can_make_move(board, move): if move in range(0,9): if " " == board[move]: return True return False def get_computer_move(board): # first priority, can I win? for m in range(0,9): copy_board = get_board_copy(board) if can_make_move(copy_board, m): make_move(copy_board, m, "O") if has_someone_won(copy_board): return m # second priority, block a win? for m in range(0,9): copy_board = get_board_copy(board) if can_make_move(copy_board, m): make_move(copy_board, m, "X") if has_someone_won(copy_board): return m # third priority, take the middle if can_make_move(board, 4): return 4 # fourth priority, take a corner for m in [0, 2, 6, 8]: if can_make_move(board, m): return m # fifth priority, take a side for m in [1, 3, 5, 7]: if can_make_move(board, m): return m def make_move(board, move, piece): board[move] = piece def has_someone_won(board): winner = False if (board[0] != " " and board[0] == board[1] == board[2]) or \ (board[3] != " " and board[3] == board[4] == board[5]) or \ (board[6] != " " and board[6] == board[7] == board[8]) or \ (board[0] != " " and board[0] == board[3] == board[6]) or \ (board[1] != " " and board[1] == board[4] == board[7]) or \ (board[2] != " " and board[2] == board[5] == board[8]) or \ (board[0] != " " and board[0] == board[4] == board[8]) or \ (board[2] != " " and board[2] == board[4] == board[6]): winner = True return winner def is_it_a_draw(board): if len("".join(board).replace(" ", "")) == 9: return True else: return False print("Welcome to Noughts and Crosses") board = [" "] * 9 while True: draw_board(board) move = get_player_move(board) make_move(board, move, "X") if has_someone_won(board): draw_board(board) print("We have a winner! Well done you!") break elif is_it_a_draw(board): print("Fought to a draw...") break move = get_computer_move(board) make_move(board, move, "O") if has_someone_won(board): draw_board(board) print("We have a winner! But it wasn't you!") break elif is_it_a_draw(board): print("Fought to a draw...") break
numbers = [5, 3, 4, 43, 4, 3, 4, 3, 5, 56] numbers.sort() print(numbers) goodNumbers = [] for num in numbers: if num not in goodNumbers: goodNumbers.append(num) print(goodNumbers)
import math print('Hello again, You must study 2 hours a day! ') firstName = 'Mihail' secondName = 'Hadzhiev' print(f'my first name is {firstName}, and my second name is {secondName}') sum = 200 print(firstName + ' ' + str(sum)) course = "Mihail is cool and he is working Mihail hard cool cooll02 to learn Python" print(course.upper()) print(course) print(course.replace('Mihail', 'Hadzhiev')) print('Mihail' in course) number = 2.2223 print(math.ceil(number)) print(math.log(number)) print(math.floor(number))
is_hot = False is_cold = False if is_hot: print("It's a hot day, drink plenty of water Mihail ") elif is_cold: print("It's very cold, be careful ! ") else: print("It's cold stay home") priceHouse = 100000 has_good_credit = True if has_good_credit: down_payment = 0.1 * priceHouse else: down_payment = 0.2 * priceHouse print(f'Down payment for the house is: ${down_payment}') has_money = True has_perfect_credit = True if has_money and not has_perfect_credit: print('Awesome you are rich') else: print('Sorry no money for you :( ')
''' Michael Borczuk SoftDev K05 - Program to print a random SoftDev student's name 2021-09-27 # SUMMARY OF TRIO DISCUSSION # We decided to send each other the code we had with our original trios. We then chose to pick the parts of the code that would make the program do as little work as possible to give us a random name, while also making the code as easy to read and understand as possible. To this end, we chose to store our names in two seperate arrays, choose a random index and store those results in two variables, and then print out a name from either one of the periods. Each of these three sections of code were taken from our individual programs. # DISCOVERIES # One of the group members did not know Kevin Cao was in period 2, and put Kevin in period 1. That was resolved. # QUESTIONS # None # COMMENTS # The refactoring and combination process was rather fun, mixing and matching code to create a representative program. ''' import random #Lists containing names of people in each period NAMES = { 'pd1': ['Owen Yaggy', 'Haotian Gan', 'Ishraq Mahid', 'Ivan Lam', 'Michelle Lo', 'Christopher Liu', 'Michael Borczuk', 'Ivan Mijacika', 'Lucas Lee', 'Rayat Roy', 'Emma Buller', 'Andrew Juang', 'Renggeng Zheng', 'Annabel Zhang', 'Alejandro Alonso', 'Deven Mahehwari', 'David', 'Aryaman Goenka', 'Oscar Wang', 'Tami Takada', 'Yusuf Elsharawy', 'Ella Krechmer', 'Tomas Acuna', 'Tina Nguyen', 'Sadid Ethun', 'Shyne Choi', 'Shriya Anand'], 'pd2': ['Patrick Ging', 'Raymond Yeung', 'Josephine Lee', 'Alif Abdullah', 'William Chen', 'Justin Zou', 'Andy Lin', 'Rachel Xiao', 'Yuqing Wu', 'Shadman Rakib', 'Liesel Wong', 'Daniel Sooknanan', 'Cameron Nelson', 'Austin Ngan', 'Thomas Yu', 'Yaying Liang Li', 'Jesse Xie', 'Eric Guo', 'Jonathan Wu', 'Zhaoyu Lin', 'Joshua Kloepfer', 'Noakai Aronesty', 'Yoonah Chang', 'Hebe Huang', 'Wen Hao Dong', 'Mark Zhu', 'Kevin Cao'] } #Variables used to hold randomly selected indeces from both lists pd1Chosen = random.randint(0,len(NAMES['pd1'])-1) pd2Chosen = random.randint(0,len(NAMES['pd2'])-1) #Printing a randomly selected name, chosen by the variables above. A name is printed from either period 1's or period 2's list, dictated by the conditionals below. if (random.randint(0, 1) == 0): print("Period 1 Name: " + NAMES['pd1'][pd1Chosen]) else: print("Period 2 Name: " + NAMES['pd2'][pd2Chosen])
# Team Sneakers: Yoonah Chang (Yelena), Kevin Cao (Pipi), Michael Borczuk (Liberty and Baby Yoda) # SoftDev # K10 -- Putting Little Pieces Together # 2021-10-04 from flask import Flask import csv import random app = Flask(__name__) # create instance of class Flask dict = {} with open('occupations.csv', mode='r') as file: # reading the CSV file csvFile = csv.DictReader(file) # add contents to dictionary, multiply by 10 to make probabilities easier for lines in csvFile: dict[lines['Job Class']] = float(lines['Percentage']) * 10 dict.pop('Total') def print_occupations(): return "<br />".join(dict.keys()) def choose(): # generate a random integer num = random.randint(0, 999) counter = 0 # adds to counter, once it passes randomly generated number, it prints the key for key in dict.keys(): if counter + dict[key] > num: return(key) # exit loop once we've found our job break else: counter += dict[key] # continue to next iteration so we don't print Jobless every time continue # if the random int doesn't fall within any range, there is no job return("Other Job") @app.route("/") # assign fxn to route def main(): return heading() + "<br/>" + occupations() def heading(): return "<h2> Team Sneakers: Yoonah Chang (Yelena), Kevin Cao (Pipi), Michael Borczuk (Liberty and Baby Yoda) </h2>" def occupations(): occupations = print_occupations() occupation = "Your occupation is: " + choose() return f"<b>List of occupations:</b> <br/><br/> {occupations} <br/><br/> <b>{occupation}</b>" if __name__ == "__main__": # true if this file NOT imported app.debug = True # enable auto-reload upon code change app.run()
import timeit """ The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def difference_sum_sq_and_sq_sum(n): return sum(xrange(1, n+1))**2 - sum(map(lambda x: x**2, xrange(1, n+1))) def difference_sum_sq_and_sq_sum_better(n): """ Better because it math formula, only arifmetic """ return (n * (n + 1) / 2)**2 - (n * (n + 1) * (2 * n + 1) / 6) if __name__ == '__main__': print timeit.timeit( "print difference_sum_sq_and_sq_sum(100)", setup="from __main__ import difference_sum_sq_and_sq_sum", number=1 ) print timeit.timeit( "print difference_sum_sq_and_sq_sum_better(100)", setup="from __main__ import difference_sum_sq_and_sq_sum_better", number=1 )
def opposite(list): if len(list) == 1: return list else: return opposite(list[1:]) + [list[0]] """ This function revers the list Args: list: list of numbers Returns: opposite: list of int numbers Raises: ValueError Examples: l = [9, 45, 1, 3] >>> print(min_elem(l)) "Data is correct" "3, 1, 45, 9" l = [0, 8, 'c', 7] >>> print(min_elem(l)) Traceback (most recent call last): ... ValueError """ list1 = [int(elem) for elem in input("Введіть список: ").split()] print(opposite(list1))
''' Script for server @author: hao ''' import config import protocol import os from socket import * class server: # Constructor: load the server information from config file def __init__(self): self.port, self.path=config.config().readServerConfig() # Get the file names from shared directory def getFileList(self): return os.listdir(self.path) # Function to send file list to client def listFile(self, serverSocket): serverSocket.send(protocol.prepareFileList(protocol.HEAD_LIST, self.getFileList())) # Function to send a file to client def sendFile(self,serverSocket,fileName): f = open(fileName,'rb') l = f.read(1024) # each time we only send 1024 bytes of data while (l): serverSocket.send(l) l = f.read(1024) # Function for getting Message def getMessage(self,serverSocket): serverSocket.send(protocol.prepareMsg(protocol.HEAD_MSGREC)) # Main function of server, start the file sharing service def start(self): serverPort=self.port serverSocket=socket(AF_INET,SOCK_STREAM) serverSocket.bind(('',serverPort)) serverSocket.listen(20) print('The server is ready to receive') while True: connectionSocket, addr = serverSocket.accept() dataRec = connectionSocket.recv(1024) header,msg=protocol.decodeMsg(dataRec.decode()) # get client's info, parse it to header and content # Main logic of the program, send different content to client according to client's requests if(header==protocol.HEAD_REQUEST): self.listFile(connectionSocket) elif(header==protocol.HEAD_DOWNLOAD): self.sendFile(connectionSocket, self.path+"/"+msg) elif(header==protocol.HEAD_MSGREQUEST): self.getMessage(connectionSocket,msg) elif(head==protocol.HEAD_MSGREC): self.getMessage(connectionSocket,msg) else: connectionSocket.send(protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message")) connectionSocket.close() def main(): s=server() s.start() main()
def rev(x): y = 0 while x > 0: y *= 10 y += x % 10 x = x // 10 return y class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ return (rev(x) == x and x >= 0)
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if not intervals: return [] # Sort intervals based on start intervals.sort(key=lambda x: x.start) # Merge if overlapping end/start res = [] start = intervals[0].start end = intervals[0].end for n in intervals[1:]: if n.start > end: res.append(Interval(start, end)) start = n.start end = n.end else: end = max(n.end, end) res.append(Interval(start, end)) return res
#!/bin/python3 import sys def print_staircase(n): for i in range(n): print( ( " " * ( (n - 1) - i) ) + ( "#" * (i + 1) ) ) n = int(input().strip()) print_staircase(n)
#!/bin/python3 import sys def sockMerchant(n, ar): # Complete this function my_map = {} for sock in ar: try: my_map[sock] += 1 except: my_map[sock] = 1 count = 0 for sock in my_map: count += my_map[sock]//2 return count n = int(input().strip()) ar = list(map(int, input().strip().split(' '))) result = sockMerchant(n, ar) print(result)
class ProductItem: ''' ProductItem constructor, creates an instance of a product that has a name, a price, and sometimes a sale price. ''' def __init__(self, name, reg_price, sale_price=None): self.name = name self.reg_price = reg_price self.sale_price = sale_price ''' The override of the str() method. ''' def __str__(self): if self.sale_price is None: return "Product: " + self.name + "\nPrice: " + self.reg_price + "\n\n" else: return "Product: " + self.name + "\nPrice: " + self.reg_price + "\nSale Price: " + self.sale_price + "\n\n"
import random as rand print("""Правила игры Камень = 0 Ножницы = 1 Бумага = 2 0>1>2>0""") while True: p1 = int(input("камень ножницы бумага")) p2 = rand.randint(0,2) if p1 == p2: print("Ничья") elif (p1 == 0 and p2 == 1) or(p1 == 1 and p2 == 2) or (p1 == 2 and p2 == 0): print("Выиграл игрок") elif (p2 == 0 and p1 == 1) or(p2 == 1 and p1 == 2) or (p2 == 2 and p1 == 0): print("Выиграл компьютер") else: print("При таких условиях играть нельзя") end = int(input("Продолжите играть")) if not end: break
strings a= 'apple is a fruit' a.lower() a.upper() a.title() a.islower() a.isupper() a.istitle() a.startswith('a') a.endswith('e') a.swapcase() a.replace('a','b') a.split() ' '.join(c) range b = list(range(1,11)) for i in b[::-1]: print(i, end =',')
#! python3 # run_tracker.py tracking my monthy stats import shelve def data_entry(): run_data = [] while True: runs = [] month = input('Enter Month:') runs = runs + [month] year = input('Enter year:') runs = runs + [year] dist = input('Enter distance:') runs = runs + [dist] pace = input('Enter pace as minutes.seconds:') runs = runs + [pace] run_data = run_data + [runs] ans = input('Enter more data y/n?') if ans == 'n': break return run_data shelfFile = shelve.open('rundata') deets = data_entry() shelfFile['deets'] = deets shelfFile.close() print(data_entry)
#! python3 def median(seq): seq = sorted(seq) if len(seq) % 2 == 0: num_a = seq[int((len(seq)/2)-1)] print(num_a) num_b = seq[int(len(seq)/2)] print(num_b) return (num_a + num_b) / 2.0 else: i = int(len(seq)/2) return seq[i] seq = [4,5,5,4] print(median(seq))
#! python3 def factorial(x): hold = [] result = 1 for i in range(1,x+1): hold.append(i) for j in hold: result = result * j return result num = input("Enter a number: ") print(factorial(int(num)))
""" Random algorithm Places all houses at a random spot. Constrains for this spot are: - a house doesn't overlap with another house - a house doesn't overlap with water - a house fits on the grid """ import random from classes.structure import House def random_placement(area): """ Places a new set of house-objects on a given area. """ area.create_houses(True) for house in area.houses: place_house(area, house) def place_house(area, house): """ Places a house It picks a random x and y coordinate and then checks if there is room for the new house. If it does not succeed, try new coordinates. """ while_count = 0 valid = False while not valid: # Get random bottom_left coordinates x = int(random.random() * (area.width - house.width + 1)) y = int(random.random() * (area.height - house.height + 1)) house.set_coordinates([x,y], house.horizontal) if area.check_valid(house, x, y): valid = True if while_count == 1000: raise Exception("Something went wrong when placing a house. There was probably too little room to fit an extra house.") while_count += 1 area.structures["House"].append(house) area.update_distances(house)
""" The main program to retrieve the solutions of the case. The user will be requested to give input for: the neighbourhood, amount of houses, algorithm and (optionally) the hill_climber. The result of the area will be shown and the data saved in the csv-ouput file. """ import sys import random from time import time from user_input import user_input from classes.area import Area from algorithms.random import random_placement from algorithms.greedy import place_houses_greedy from algorithms.greedy_random import place_houses_greedy_random from algorithms.hill_climber_steps import hill_climber_steps from algorithms.hill_climber_random import hill_climber_random from algorithms.hill_climber_random_random import hill_climber_random_random from algorithms.evolution import evolution from algorithms.simulated_annealing import simulated_annealing def main(): """ Main function """ start = time() neighbourhood, houses, algorithm, hill_climber = user_input() seed = set_random_seed() area = get_area(neighbourhood, houses, algorithm, hill_climber) end = time() print(f"Seed: {seed} \nRuntime: {end - start}") area.make_csv_output() area.plot_area(neighbourhood, houses, algorithm) def get_area(neighbourhood, houses, algorithm_name, hill_climber_name): """ Runs the specific algorithm with hill_climber, if requested. And returns the generated area. """ print("Creating area...") area = Area(neighbourhood, houses) algorithm(area, algorithm_name) if hill_climber_name: hill_climber(area, hill_climber_name) return area def algorithm(area, algorithm_name): """ Runs the specific algorithm with the given area. """ if algorithm_name == "random": random_placement(area) elif algorithm_name == "greedy": place_houses_greedy(area) elif algorithm_name == "greedy_random": place_houses_greedy_random(area) elif algorithm_name == "evolution": evolution(area) def hill_climber(area, hill_climber_name): """ Runs the specific hill climber with the given area. """ if hill_climber_name == "hill_climber_steps": hill_climber_steps(area) elif hill_climber_name == "hill_climber_random": hill_climber_random(area) elif hill_climber_name == "hill_climber_random_random": hill_climber_random_random(area) elif hill_climber_name == "simulated_annealing": simulated_annealing(area) def set_random_seed(r = random.random()): """ Sets a random seed. This seed can be used with debugging. Use the same seed to get the same results. By default it uses a random seed.""" random.seed(r) return r if __name__ == "__main__": main()
""" Program: -------- Program 5 - Query 2 Description: ------------ This program starts by importing help from other files and libraries. A class is created, which allows the MongoDB Server to be accessed by Pymongo, which has various methods for gathering data from MongoDB. There is also some defined functions used for plotting onto the pygame screen. The program starts by accepting system arguements from the command line. It will accept one which is a radius to be searched, or 6 arguments which can be used to filter search and display results. If one arguement is passed in, upon mouse click the pygame screen will display volcanos in red, earthquakes in blue, and meteorites in green in the radius determined by the arguement, they will show for 3 to 5 seconds and then vanish where the user may click on another area to repeat the process. If more arguements are passed in they can be used to filter search results when clicking on the pygame screen, they will also appear if there are any for 3 to 5 seconds and then vanish allowing the user to click and search again. A screenshot is captured after each search, however it is overwritten each search. Name: Matthew Schenk Date: 5 July 2017 """ import pygame from pygame.locals import * import sys,os import json import math from pymongo import MongoClient import pprint as pp class mongoHelper(object): def __init__(self): self.client = MongoClient() self.db_airports = self.client.world_data.airports self.db_cities = self.client.world_data.cities self.db_countries = self.client.world_data.countries self.db_earthquakes = self.client.world_data.earthquakes self.db_meteorites = self.client.world_data.meteorties self.db_states = self.client.world_data.states self.db_terrorism = self.client.world_data.terrorism self.db_volcanos = self.client.world_data.volcanos def get_nearest_neighbor(self,lon,lat,r): # air_res = self.db_ap.find( { 'geometry' : { '$geoWithin' : { '$geometry' : poly } } }) air_res = self.db_ap.find( { 'geometry': { '$geoWithin': { '$centerSphere': [ [lon, lat ] , r / 3963.2 ] } }} ) min = 999999 for ap in air_res: lon2 = ap['geometry']['coordinates'][0] lat2 = ap['geometry']['coordinates'][1] d = self._haversine(lon,lat,lon2,lat2) if d < min: min = d print(d) print(ap['properties']['ap_name']) closest_ap = ap return closest_ap def get_features_near_me(self,collection,point,radius,earth_radius=3963.2): #km = 6371 """ Finds "features" within some radius of a given point. Params: collection_name: e.g airports or meteors etc. point: e.g (-98.5034180, 33.9382331) must be in longitutde and latitude radius: The radius in miles from the center of a sphere (defined by the point passed in) Usage: mh = mongoHelper() loc = (-98.5034180, 33.9382331) miles = 200 feature_list = mh.get_features_near_me('airports', loc, miles) """ x,y = point res = self.client['world_data'][collection].find( { 'geometry': { '$geoWithin': { '$centerSphere': [ [x, y ] , radius/earth_radius ] } }} ) return self._make_result_list(res) def _haversine(self,lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 3956 # Radius of earth in kilometers. Use 6371 for km return c * r def _make_result_list(self,res): """ private method to turn a pymongo result into a list """ res_list = [] for r in res: res_list.append(r) return res_list RADIUS_KM = 6371 # in km RADIUS_MI = 3959 # in mi def mercX(lon,zoom = 1): """ """ lon = math.radians(lon) a = (256 / math.pi) * pow(2, zoom) b = lon + math.pi return int(a * b) def mercY(lat,zoom = 1): """ """ lat = math.radians(lat) a = (256.0 / math.pi) * pow(2, zoom) b = math.tan(math.pi / 4 + lat / 2) c = math.pi - math.log(b) return int(a * c) def mercToLL(point): lng,lat = point lng = lng / 256.0 * 360.0 - 180.0 n = math.pi - 2.0 * math.pi * lat / 256.0 lat = (180.0 / math.pi * math.atan(0.5 * (math.exp(n) - math.exp(-n)))) return (lng, lat) def toLLtest(point): ans = [] x,y = point for i in range(1,5): print(i) ans.append(mercToLL((x/i,y/i))) ans.append(mercToLL((x/4,y))) return ans def toLL(point): ans = [] x,y = point y += 256 return mercToLL((x/4,y/4)) def clean_area(screen,origin,width,height,color): """ Prints a color rectangle (typically white) to "erase" an area on the screen. Could be used to erase a small area, or the entire screen. """ ox,oy = origin points = [(ox,oy),(ox+width,oy),(ox+width,oy+height),(ox,oy+height),(ox,oy)] pygame.draw.polygon(screen, color, points, 0) if __name__=='__main__': pygame.init() bg = pygame.image.load("./worldmap.png") background_colour = (255,255,255) black = (0,0,0) (width, height) = (1024, 512) screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Query 2') screen.fill(background_colour) #example sys.arg pass in parameters #bob = sys.arg[0] #Passed in Arguments via commandline #Volcanos, Earthquakes, Meteorites if len(sys.argv) != 2: feature = 'volcanos' feature = sys.argv[1] if feature == 'volcanos': color = (255,0,0) elif feature == 'earthquakes': color = (0,0,255) elif feature == 'meteorites': color = (0,255,0) #All of these are in the properties: dictionary #Volcanos: Altitude, Country, Name, Type #Earthquakes: mag, rms, year, depth, time #Meteorites: nametype, recclass, name, year, mass, fall, id field = 'year' field = sys.argv[2] #value in which to compare with field_value = 1900 field_value = int(sys.argv[3]) #Results in a greater than or less than field value ('min' or 'max') minimum_maximum = 'min' minimum_maximum = sys.argv[4] #Number of min or max results, 0 is all min_max_results = 10 min_max_results = int(sys.argv[5]) #Search radius from point/mouse click query_radius = 500 query_radius = int(sys.argv[6]) #Opitional #mx = sys.argv[7] #my = sys.argv[8] else: query_radius = int(sys.argv[1]) mh = mongoHelper() flist = [] plot = [] running = True while running: screen.blit(bg, (0,0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: if len(sys.argv) != 2: mx, my = pygame.mouse.get_pos() print (mx, my) #my = abs(512 - my) point = toLL((mx,my)) print(point) feature_list = mh.get_features_near_me(feature,point,query_radius) #pp.pprint(feature_list) del flist[:] del plot[:] i = 0 for item in feature_list: #print(item['properties']['Country']) if item['properties'][field] != '': if minimum_maximum == 'min': if int(item['properties'][field]) >= field_value: flist.append(item['geometry']['coordinates']) elif minimum_maximum == 'max': if int(item['properties'][field]) <= field_value: flist.append(item['geometry']['coordinates']) #pp.pprint(flist) for item in flist: x = mercX(item[0]) y = mercY(item[1]) plotpoint = [int(x),int(y)-256] #print(plotpoint) plot.append(plotpoint) for p in plot: if min_max_results == 0: pygame.draw.circle(screen, color, p, 1,0) else: if min_max_results > i: pygame.draw.circle(screen, color, p, 1,0) i = i + 1 pygame.image.save(screen,'./screen_shot_query2.png') else: mx, my = pygame.mouse.get_pos() print (mx, my) point = toLL((mx,my)) print(point) vlist = [] del vlist[:] elist = [] del elist[:] mlist = [] del mlist[:] vlist = mh.get_features_near_me('volcanos',point,query_radius) #pp.pprint(vlist) elist = mh.get_features_near_me('earthquakes',point,query_radius) #pp.pprint(elist) mlist = mh.get_features_near_me('meteorites',point,query_radius) #pp.pprint(mlist) i = 0 for x in range(0,3): del flist[:] del plot[:] if x == 0: for item in vlist: flist.append(item['geometry']['coordinates']) color = (255,0,0) elif x == 1: for item in elist: flist.append(item['geometry']['coordinates']) color = (0,0,255) elif x == 2: for item in mlist: flist.append(item['geometry']['coordinates']) color = (0,255,0) for item in flist: x = item[0] y = item[1] x = mercX(x) y = mercY(y) plotpoint = [int(x),int(y)-256] plot.append(plotpoint) #print(plotpoint) for p in plot: if 500 > i: pygame.draw.circle(screen, color, p, 1,0) i = i + 1 pygame.image.save(screen,'./screen_shot_query2.png') pygame.display.flip() pygame.time.wait(5000)
def pop_details(list_details): list_details.pop() #print(list_details) return list_details def remove_details(list_details,val): list_details.remove(val) return list_details def discard_details(list_details,val): list_details.discard(val) return list_details def main(): n = int(input()) n_s_non_int = [] mq = [] main_list = [] s = input() n_s_non_int = s.split(" ") for i in range(0,n): mq.append(int(n_s_non_int[i])) main_list = set(mq) #print(main_list) op_length = int(input()) a = [] le_s = [] for k in range(0,op_length): le = input() a = le.split(" ") stat = a[0] val = 0 if(stat == "pop"): main_list = pop_details(main_list) elif(stat =="remove"): val = int(a[1]) if(val in main_list): main_list = remove_details(main_list,val) else: print('None') elif(stat == "discard"): val = int(a[1]) main_list = discard_details(main_list,val) else: pass main_ans_sum = sum(main_list) print(main_ans_sum) main()
def main(): n = int(input()) s = [] for i in range(0,n): le = input() s.append(le) final_set = set(s) final_set_length = len(final_set) print(final_set_length) main()
text_array = ["x","o","*"] #text that will be used to compose the 3 blooms class Bloom(object): def __init__(self,temp_x,temp_y): max_blossom_spread_x = 80 #maximum width of blossom in pixels max_blossom_spread_y = 80 #maximum height of blossom in pixels max_text_size = 40 #maximum size for char that is each "petal". #No minimum. min_text_lightness = 55 #minimum lightness for char that is each "petal". max_text_lightness = 200 #maximum lightness for char that is each "petal". #0 = pure black. 255 = pure white self.x = temp_x self.y = temp_y self.child_x = [] self.child_y = [] self.child_ts = [] self.child_fill = [] for x in range(36): self.child_x.append(self.x - (max_blossom_spread_x/2) + random(max_blossom_spread_x)) self.child_y.append(self.y - (max_blossom_spread_y/2) + random(max_blossom_spread_y)) self.child_ts.append(random(max_text_size)) self.child_fill.append(random(min_text_lightness,max_text_lightness)) def blossom(self,steps,txt): for x in range(steps): if mousePressed == True: fill(255 - self.child_fill[x]) else: fill(self.child_fill[x]) textSize(self.child_ts[x]) text(txt,self.child_x[x],self.child_y[x]) x = Bloom(100,100) y = Bloom(125,125) z = Bloom(150,150) def setup(): size(400,712) frameRate(24) def draw(): global x,y,z if frameCount % 36 == 0: x = Bloom(random(width),random(height)) if ((frameCount - 24) % 36) == 0: y = Bloom(random(width),random(height)) if ((frameCount - 12) % 36) == 0: z = Bloom(random(width),random(height)) if mousePressed == True: background(0) else: background(255) if frameCount >= 24: x.blossom((frameCount % 36),text_array[0]) y.blossom(((frameCount - 24) % 36),text_array[1]) z.blossom(((frameCount - 12) % 36),text_array[2]) #print frameCount #if frameCount < 744: # saveFrame("output-####.png")
from queue import * class BinaryTree: def __init__(self, value): self.value = value self.left_child = None self.right_child = None def insert_left(self, value): if self.left_child == None: self.left_child = BinaryTree(value) else: new_node = BinaryTree(value) new_node.left_child = self.left_child self.left_child = new_node def insert_right(self, value): if self.right_child == None: self.right_child = BinaryTree(value) else: new_node = BinaryTree(value) new_node.right_child = self.right_child self.right_child = new_node #depth first search def pre_order(self): print(self.value) if self.left_child: self.left_child.pre_order() if self.right_child: self.right_child.pre_order() def in_order(self): if self.left_child: self.left_child.in_order() print(self.value) if self.right_child: self.right_child.in_order() def post_order(self): if self.left_child: self.left_child.post_order() if self.right_child: self.right_child.post_order() print(self.value) def bfs(self): #breadth first search queue = Queue() queue.put(self) while not queue.empty(): current_node = queue.get() print(current_node.value) if current_node.left_child: queue.put(current_node.left_child) if current_node.right_child: queue.put(current_node.right_child) class BinarySearchTree: def __init__(self, value): self.value = value self.left_child = None self.right_child = None def insert_node(self, value): if value <= self.value and self.left_child: self.left_child.insert_node(value) elif value <= self.value: self.left_child = BinarySearchTree(value) elif value > self.value and self.right_child: self.right_child.insert_node(value) else: self.right_child = BinarySearchTree(value) def find_node(self, value): if value < self.value and self.left_child: return self.left_child.find_node(value) if value > self.value and self.right_child: return self.right_child.find_node(value) return value == self.value def remove_node(self, value, parent): if value < self.value and self.left_child: return self.left_child.remove_node(value, self) elif value < self.value: return False elif value > self.value and self.right_child: return self.right_child.remove_node(value, self) elif value > self.value: return False else: if self.left_child is None and self.right_child is None and self == parent.left_child: parent.left_child = None self.clear_node() elif self.left_child is None and self.right_child is None and self == parent.right_child: parent.right_child = None self.clear_node() elif self.left_child and self.right_child is None and self == parent.left_child: parent.left_child = self.left_child self.clear_node() elif self.left_child and self.right_child is None and self == parent.right_child: parent.right_child = self.left_child self.clear_node() elif self.right_child and self.left_child is None and self == parent.left_child: parent.left_child = self.right_child self.clear_node() elif self.right_child and self.left_child is None and self == parent.right_child: parent.right_child = self.right_child self.clear_node() else: self.value = self.right_child.find_minimum_value() self.right_child.remove_node(self.value, self) return True def clear_node(self): self.value = None self.left_child = None self.right_child = None def find_minimum_value(self): if self.left_child: return self.left_child.find_minimum_value() else: return self.value def pre_order_traversal(self): print(self.value) if self.left_child: self.left_child.pre_order_traversal() if self.right_child: self.right_child.pre_order_traversal() def in_order_traversal(self): if self.left_child: self.left_child.in_order_traversal() print(self.value) if self.right_child: self.right_child.in_order_traversal()
class Node: def __init__(self, data): self.item = data self.ref = None class LinkedList: def __init__(self): self.start_node = None def traverse_list(self): if self.start_node is None: print("list has no element") return else: n = self.start_node while n is not None: print(n.item, " ") n = n.ref def insert_at_start(self, data): new_node = Node(data) new_node.ref = self.start_node self.start_node = new_node def insert_at_end(self, data): new_node = Node(data) if self.start_node is None: self.start_node = new_node return n = self.start_node while n.ref is not None: n = n.ref n.ref = new_node def insert_after_item(self, x, data): n = self.start_node print(n.ref) while n is not None: if n.item == x: break n = n.ref if n is None: print("item not in the list") else: new_node = Node(data) new_node.ref = n.ref n.ref = new_node def insert_before_item(self, x, data): if self.start_node is None: print("List has no element") return if x == self.start_node.item: new_node = Node(data) new_node.ref = self.start_node self.start_node = new_node return n = self.start_node print(n.ref) while n.ref is not None: if n.ref.item == x: break n = n.ref if n.ref is None: print("item not in the list") else: new_node = Node(data) new_node.ref = n.ref n.ref = new_node def insert_at_index (self, index, data): if index == 1: new_node = Node(data) new_node.ref = self.start_node self.start_node = new_node i = 1 n = self.start_node while i < index-1 and n is not None: n = n.ref i = i+1 if n is None: print("Index out of bound") else: new_node = Node(data) new_node.ref = n.ref n.ref = new_node def get_count(self): if self.start_node is None: return 0 n = self.start_node count = 0 while n is not None: count = count + 1 n = n.ref return count def search_item(self, x): if self.start_node is None: print("list has no element") return n = self.start_node while n is not None: if n.item == x: print("item found") return True n = n.ref print("item not found") return False def make_new_list(self): nums = int(input("how many nodes do you want to create: ")) if nums == 0: return for i in range(nums): value = int(input("enter the value for the node: ")) self.insert_at_end(value) def delete_at_start(self): if self.start_node is None: print("the list has no element to delete") return self.start_node = self.start_node.ref def delete_at_end(self): if self.start_node is None: print("the list has no element to delete") return n = self.start_node while n.ref.ref is not None: n = n.ref n.ref = None def delete_element_by_value(self, x): if self.start_node is None: print("the list has no element to delete") return if self.start_node.item == x: self.start_node = self.start_node.ref return n = self.start_node while n.ref is not None: if n.ref.item == x: break n = n.ref if n.ref is None: print("item not found in the list") else: n.ref = n.ref.ref def reverse_linkedlist(self): prev = None n = self.start_node while n is not None: next = n.ref n.ref = prev prev = n n = next self.start_node = prev def bub_sort_datachange(self): end = None while end != self.start_node: p = self.start_node while p.ref != end: q = p.ref if p.item >q.item: p.item, q.item = q.item, p.item p = p.ref end = p def bub_sort_linkchange(self): end = None while end != self.start_node: r = p = self.start_node while p.ref != end: q = p.ref if p.item > q.item: p.ref = q.ref q.ref = p if p != self.start_node: r.ref = q else: self.start_node = q p,q = q,p r = p p = p.ref end = p def merge_helper(self, list2): merge_list = LinkedList() merge_list.start_node = self.merge_by_newlist(self.start_node, list2.start_node) return merge_list def merge_by_newlist(self, p, q): if p.item <= q.item: startNode = Node(p.item) p = p.ref else: startNode = Node(q.item) q = q.ref em = startNode while p is not None and q is not None: if p.item <= q.item: em.ref = Node(p.item) p = p.ref else: em.ref = Node(q.item) q = q.ref em = em.ref while p is not None: em.ref = Node(p.item) p = p.ref em = em.ref while q is not None: em.ref = Node(q.item) q = q.ref em = em.ref return startNode def merge_helper2(self, list2): merge_list = LinkedList() merge_list.start_node = self.merge_by_linkChange(self.start_node, list2.start_node) return merge_list def merge_by_linkChange(self, p, q): if p.item <= q.item: startNode = Node(p.item) p = p.ref else: startNode = Node(q.item) q = q.ref em = startNode while p is not None and q is not None: if p.item <= q.item: em.ref = Node(p.item) em = em.ref p = p.ref else: em.ref = Node(q.item) em = em.ref q = q.ref if p is None: em.ref = q else: em.ref = p return startNode
# imports the random library to python import random # greets the user with a message about the game print("Hi, welcome to the 'Guess the Number' game!") print("The CPU will guess a number between 1 - 100 and it's your job to guess it in 5 tries or less.") def numGame(): continue_game = 'y' guess = 0 # continues to run the game while continue_game is 'y' while continue_game == 'y': # gets a random integer between 1 and 100 and stores it as a variable, random_number random_number = random.randint(1,101) print("Okay, we've got the number!\n") # while loop that loops while that stops after the user has guessed 5 times while guess < 5: # prompts the user to guess a number: userGuess = int(input('Which number would you like to guess? ')) # if elif statement that gives user feedback based on their guesses if userGuess == random_number: print('\tWINNER') print('\tTHE NUMBER WAS: ' + str(random_number) + "\n") break elif userGuess > random_number: print('\tTOO HIGH - GUESS AGAIN') elif userGuess < random_number: print('\tTOO LOW - GUESS AGAIN') # increments one to the guesses after every guess: guess += 1 # tells the user how many guesses they've made: print('\tYou have made: ' + str(guess) + " guesses") # tells the user if you've run out of guesses if guess == 5: print("Sorry! You ran out of guesses.") # askes the user to play again. 'y' will continue playing, 'n' will break the while loop continue_game = input("Play again? 'y' or 'n': ") # resets the guesses back to zero incase the user chooses to play again. guess = 0 numGame()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ASCII 一个字节 Unicode 2个字节 UTF-8 一个或者3个字节 print('包含中文的str') # ord()函数获取字符的整数表示 chr()将对应的整数转换成字符 print(ord('A')) # 65 print(ord('中')) # 20013 # 字符和字节的相互转换 'abc'.encode('ascii') 'abc'.encode('utf-8') b'abc'.decode('utf-8') # 字符串格式化 print('Hello ,%s' % 'World')
import turtle as t t.pensize(1) t.penup() t.goto(0,0) t.pendown() for i in range(3,9): for l in range(i): t.forward(20) t.left(360/i)
#Ashley Nkomo #09-10-14 #Question 2 Spot Check FirstName = input("Please enter your first name: ") LastName = input("Please enter your last name: ") Gender = input("Please enter your gender: ") if Gender == "male": print("Mr {0} {1}".format(FirstName, LastName)) elif Gender == "female": print("Ms {0} {1}".format(FirstName, LastName)) else: print("Please enter an appropriate gender")
#Ashley Nkomo #30-09-14 #Revision Exercise 4 number1 = float(input("Please enter a number: ")) number2 = float(input("Please enter a second number: ")) number3 = float(input("Please enter a third number: ")) if number3 > number1 and number2: print("The third number entered is larger") elif number2 > number1 and number3 : print("The second number entered is larger") elif number1 > number2 and number3: print("The first number entered is larger") else: print("The numbers are exactly the same")
def append(self, s): new = LinkedList() curr = self.head while curr != None: new.add(curr.item) curr = curr.next self.remove() self.add(s) curr = new.head while curr != None: self.add(curr.item) curr = curr.next def rotate(self): new = LinkedList() first = LinkedList() first.add(self.head.item) self.remove() curr = self.head while curr != None: new.add(curr.item) curr = curr.next self.remove() self.add(first.head.item) new_curr = new.head while new_curr != None: self.add(new_curr.item) new_curr = new_curr.next def detect_loop(linkedlst): curr = linkedlst.head while curr != None: curr = curr.next if curr == linkedlst.head: return True return False
# Author: Joe Delia # In 2012-2013, I worked on a research project involving space-filling fractals. # I wrote a program in Python 2.7 that would draw out square- and hexagonal-shaped # fractals. # # This project is porting that original project to Python 3.x, and adding additional # functionality and speed to it as well. # Last Edit: 7/31/2018 __author__ = 'Joe' from graphics import * from fractal import * WINDOW_SIZE = 800 # Size of the window MIDPOINT = WINDOW_SIZE / 2 # Midpoint of the window def main(): pt1 = Point(MIDPOINT, MIDPOINT) print("What kind of fractal do you want to draw?") f_type = get_type() scale = get_scale() its = get_iterations() ratio = 0 for i in range(its): ratio = ratio + scale ** i length = MIDPOINT / ratio myWin = GraphWin("Fractal Tree", WINDOW_SIZE, WINDOW_SIZE) if f_type == 4: fractal = FourFractal(scale, its, pt1, length, myWin) else: fractal = SixFractal(scale, its, pt1, length, myWin) for iteration in range(0, fractal.get_iterations()): fractal.point_creator(iteration) try: myWin.getMouse() myWin.close() except GraphicsError: print("Window closed before execution completed") return 0 def get_type(): f_type = "" while f_type != 4 and f_type != 6: f_type = input("Enter '4' for square, or '6' for hexagon: ") try: f_type = float(f_type) except ValueError: f_type = "" return f_type def get_scale(): scale = -1 while scale <= 0.0 or scale >= 1.0: scale = input("Enter a scaling ratio (must be between 0 and 1): ") try: scale = float(scale) except ValueError: scale = -1 return scale def get_iterations(): iterations = -1 while iterations < 0: iterations = input("Enter a number of iterations (higher numbers result in slower results!): ") try: iterations = int(iterations) except ValueError: iterations = -1 return iterations main()
# O uso do Async, Await e AsyncIO no python # O AsyncIO é um módulo que chegou no python 3.4 no qual permite que escrevemos códigos assíncronos # em uma unica thread utilizando Coroutines. # Coroutines # São rotinas cooperativas, ou seja, são rotinas (funções, métodos, procedimentos) que concordam em # parar sua execução permitindo que outra rotina possa ser executada naquele momento esperando que # essa rotina secundária devolva a execução para ela em algum momento, portanto uma coopera com a outra. # # Event Loop # O Event loop é um loop que pode registrar tasks para serem executadas, executa-las, pausa-las e # então torna-las em execução a qualquer momento. # Ele é o responsável por gerenciar todos eventos relacionados a isso. # No Python o Event Loop é responsável por manter o registro de tarefas (coroutines) e # distribui a carga de execução entre elas. import time import asyncio def numeros_consecutivos(lista_inteiros =[]): quantidade_faltante = 0 lista_inteiros = list(set(lista_inteiros)) lista_inteiros.sort() for posicao in range(len(lista_inteiros)-1): quantidade_faltante += ((abs(lista_inteiros[posicao] - lista_inteiros[posicao+1]))-1) return quantidade_faltante def quantidade_consecutiva_sincrona(lista_original, n): print("Calculando quantos numeros faltam para deixar a "+ str(n)+"º lista consecutiva...") time.sleep(0.01) quantidade_faltante = numeros_consecutivos(lista_original) print(quantidade_faltante) return quantidade_faltante async def quantidade_consecutiva_assincrona(lista_original, n): print("Calculando quantos numeros faltam para deixar a "+ str(n)+"º lista consecutiva...") await asyncio.sleep(0.01) quantidade_faltante = numeros_consecutivos(lista_original) print(quantidade_faltante) return quantidade_faltante #----------------------------------------- # Execucao sincrona def main_sincrona(): quantidade_consecutiva_sincrona([5,3,9,75,42],1) quantidade_consecutiva_sincrona([5,3,-10,7,15],2) quantidade_consecutiva_sincrona([0,-20,10,7,12],3) print("\nSincrona:") t0 = time.time() main_sincrona() t1 = time.time() print("Tempo da execucao sincrona: "+str(round((t1-t0)*1000,5))+"ms") #----------------------------------------- #----------------------------------------- # Execucao assincrona async def main_assincrona(): await asyncio.wait([ quantidade_consecutiva_assincrona([5,3,9,75,42],1), quantidade_consecutiva_assincrona([5,3,-10,7,15],2), quantidade_consecutiva_assincrona([0,-20,10,7,12],3)]) print("\nAssincrona:") t2 = time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main_assincrona()) t3 = time.time() print("Tempo da execucao assincrona: "+str(round((t3-t2)*1000,5))+"ms") #-----------------------------------------
# -*- coding: utf-8 -*- import json class CommonHelper(object): @staticmethod def load_city_list_json(json_file): print "loading cities" cities = dict() with open(json_file) as data_file: city_list = json.load(data_file) for city_info in city_list: city_name = city_info.get("name") del city_info["name"] if cities.get(city_name) is None: cities[city_name] = [city_info] else: cities[city_name].append(city_info) return cities
''' velocidade_luzsolar = 300 print(velocidade_luzsolar) ''' salario_mensal = input(' Qual é o seu salário mensal? ') horas_trabalhadas_mensais = input(' Quantas horas você trabalha por mês? ') valor_hora = int(salario_mensal) / int(horas_trabalhadas_mensais) print(valor_hora)
######################### # !!! SOLUTION CODE !!! # ######################### class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root def getHeight(self,root): # CODE HERE left_node = 0 right_node = 0 if root.left is not None: left_node = 1 + self.getHeight(root.left) if root.right is not None: right_node = 1 + self.getHeight(root.right) return max(left_node, right_node) T=int(input())
# example_001 # variable n = 1 x, y = 2, 3 x2 = y2 = 4 s = "hello world" s2 = 'hi' b = True b2 = False print("n:", n) print("x:", x , ", x:", y) print("x2:", x2 , ", y2:", y2) print("s:", s) print("s2:", s2) print("b:", b) print("b2:", b2) print("done") """ [output] ('n:', 1) ('x:', 2, ', x:', 3) ('x2:', 4, ', y2:', 4) ('s:', 'hello world') ('s2:', 'hi') ('b:', True) ('b2:', False) done """
# input a number print ("enter a number") for x in range(int(input())): print (f"the answer is : {x**2}") #the other coding assignment is in # https://github.com/rajsekharau9/codingchallenge/blob/master/cod-week-02%20day-4.py #assiignment is in # https://github.com/rajsekharau9/assignments #sorry for late submisssion as it is new to me and am not completely clear regardind the functioning
import pygame BLACK = (0, 0, 0) def draw_rounded_rectangle(screen, color, x0, y0, width, height, radius): rect1 = [x0, y0+radius, width, height - 2*radius] rect2 = [x0+radius, y0, width - 2*radius, height] pygame.draw.rect(screen, color, rect1) pygame.draw.rect(screen, color, rect2) pygame.draw.circle(screen, color, [x0+radius, y0+radius], radius) pygame.draw.circle(screen, color, [x0 + width - radius, y0 + radius], radius) pygame.draw.circle(screen, color, [x0 + radius, y0 + height - radius], radius) pygame.draw.circle(screen, color, [x0 +width - radius, y0 + height - radius], radius) def draw_ball(screen, color, ball): pygame.draw.circle(screen, color, [int(ball[0]), int(ball[1])], 13) def draw_line(screen, color, x1, y1, x2, y2, width): pygame.draw.line(screen, color, (x1, y1), (x2, y2), width) def draw_help(screen, color, ball, vector, length): x1 = int(ball[0]) y1 = int(ball[1]) x2 = x1+vector[0]*length y2 = y1+vector[1]*length pygame.draw.line(screen, color, (x1,y1), (x2,y2), 4) def draw_background(screen): screen.fill(BLACK) pygame.draw.rect(screen, (255, 255, 255), [46, 23, 800, 480]) # draw the visible part of the screen draw_rounded_rectangle(screen, (67, 46, 14), 46, 23, 800, 480, 30) # draw_rounded_rectangle(screen, (12, 53, 30), 56, 33, 780, 460, 25) # 10 px draw_rounded_rectangle(screen, (0, 96, 41), 86, 63, 720, 400, 0) # 30 px # draw the whole pygame.draw.circle(screen, (0, 0, 0), [86, 63], 16) pygame.draw.circle(screen, (0, 0, 0), [446, 63], 16) pygame.draw.circle(screen, (0, 0, 0), [806, 63], 16) pygame.draw.circle(screen, (0, 0, 0), [86, 463], 16) pygame.draw.circle(screen, (0, 0, 0), [446, 463], 16) pygame.draw.circle(screen, (0, 0, 0), [806, 463], 16) def draw_score(screen, player1, player2): font = pygame.font.SysFont(None, 29) # heigth of 20 text1 = font.render("{:d}".format(player2), True, (255, 255, 0)) text2 = font.render("{:d}".format(player1), True, (255, 0, 0)) screen.blit(text1,(226-text1.get_width()//2, 38)) screen.blit(text2,(626-text2.get_width()//2, 38)) def draw_active_player(screen, player): if player == 2: pygame.draw.rect(screen, (255, 255, 0), [61, 163, 20, 200]) else: pygame.draw.rect(screen, (255, 0, 0), [811, 163, 20, 200])
import board b = [[(i, j) for j in range(8)] for i in range(8)] for row in b: print(row) def direction(sqr1, sqr2): if sqr1[0] == sqr2[0] or sqr1[1] == sqr2[1]: return 's' if ((sqr1[0]-sqr2[0]) / (sqr1[1]-sqr2[1]))**2 == 1: return 'd' def between(sqr1, sqr2, sqr3): if direction(sqr1, sqr2) == direction(sqr1, sqr3) and direction(sqr1, sqr2) is not None: print(1) if ((sqr3[0]-sqr1[0]) * (sqr3[0]-sqr2[0])) < 1 and ((sqr3[1]-sqr1[1]) * (sqr3[1]-sqr2[1])) < 1: return True return False print(between(b[1][0], b[4][3], b[2][1]))
''' equation balencer, that balences your chemical or math equations Created on Jun 23, 2016 @author: Lance Pereira ''' import re import numpy from itertools import chain from fractions import gcd from functools import reduce from builtins import max class Equation(): ''' Takes an equation, splits it into reactants and products, splits thoose compounds into elements, and then treats each element as a linear equation which it uses matricies to solve for ''' def __init__(self,equation,doSolve = True): equation = equation.replace(" ","") self.equation = equation (self.reactants,self.products) = equation.split("=") self.reactantList = (self.reactants).split("+") self.productList = (self.products).split("+") self.compoundList = self.reactantList + self.productList self.lenCompoundList = len(self.compoundList) #Makes each compound an object self.compoundList = [ Compound(compound,True) if self.compoundList.index(compound) < len(self.reactantList) else Compound(compound,False) for compound in self.compoundList] self.balencedEquation = "Not solved yet" if doSolve: self.solve() def solve(self): ''' Solves the linear system ''' #Creates a list of all elements on one side of the reaction ()same on other side as well self.allElements = list(self.compoundList[0].ElementsDict.keys()) for compound in range(1,len(self.reactantList)): compound = self.compoundList[compound] #print (compound) newElementsList = list(compound.ElementsDict.keys()) newElementsList = [x for x in newElementsList if x not in self.allElements] self.allElements = self.allElements + newElementsList self.allElements.sort() #print (self.allElements) self.createMatrix() self.makeWhole() self.outputAnswer() def createMatrix(self): ''' Creates a matrix which then uses numpy to solve ''' #Creates matricies filled with zeros to save memoeary self.CompoundMatrix = numpy.zeros((len(self.allElements),self.lenCompoundList-1)) self.ProductMatrix = numpy.zeros((len(self.allElements),1)) #print(CompoundMatrix) #Assigns the element numercal values into the matrix for compoundIndexes in range(self.lenCompoundList): compound = self.compoundList[compoundIndexes] compoundValueRow = [] for element in self.allElements: #If the element is not in the compound, assigns it a value of 0 if element not in compound.ElementsDict: value = 0 else: value = compound.ElementsDict[element] #For the products so that their values are negative if not compound.isReactant and compoundIndexes != self.lenCompoundList-1: value *= -1 compoundValueRow.append(value) #Catches to see if the compound is the last one, which is given a by default a value of 1 if compoundIndexes != self.lenCompoundList-1: self.CompoundMatrix[:,compoundIndexes] = compoundValueRow else: self.ProductMatrix[:,0] = compoundValueRow #print(self.CompoundMatrix) #print(self.ProductMatrix) #Solves for b in A.b = x, with some complicated math i don't understand self.answerList = numpy.linalg.lstsq(self.CompoundMatrix, self.ProductMatrix)[0] self.answerList = (self.answerList).tolist() self.answerList = list(chain.from_iterable(self.answerList)) #Add the 1 that we used to get the rest of the formula self.answerList.append(1) #print (self.answerMatrix) def makeWhole(self): ''' Takes the decimal value matrix that was solved and turns it into whole numbers ''' factor = max(self.answerList) tempAnswerList = self.answerList if factor != 1: tempAnswerList = [x/factor for x in self.answerList] self.denominatorList = [0]*self.lenCompoundList denominatorsMultiplied =1 #Finds the denominators of all the ratio numbers for i,ratioNumber in enumerate(tempAnswerList): self.denominatorList[i] = (1/ratioNumber) denominatorsMultiplied *= self.denominatorList[i] #print(self.denominatorList, factor) #Puts all the numbers over the same denominator self.multipliedDenominatorList = [round(denominatorsMultiplied/x,6)*factor for x in self.denominatorList] #print(self.multipliedDenominatorList) #test_equation1: [12.0, 18.0, 6.0, 36.0] #Find the greatest common factor greatestCommonFactor = reduce(gcd,self.multipliedDenominatorList) #print(greatestCommonFactor) #test_equation1: 6.0 #Divides all the ratios by the greatest common factor self.answerList = [round(x/greatestCommonFactor) for x in self.multipliedDenominatorList] #print(self.answerList) #test_equation1: [2, 3, 1, 6] def outputAnswer(self): ''' Pairs up the ratios with the numbers and creates a readable output for the user ''' balencedEquation = '' for i,compounds in enumerate(self.compoundList): name = compounds.name #Pairs ratio and compound nameWithNmber = str(self.answerList[i]) + " " + name #Matches the appropriate connector (+ or =) depending on whats on either side if i == 0: balencedEquation = nameWithNmber elif (compounds.isReactant and self.compoundList[i-1].isReactant) or (not compounds.isReactant and not self.compoundList[i-1].isReactant): balencedEquation = balencedEquation + " + " + nameWithNmber elif not compounds.isReactant and self.compoundList[i-1].isReactant: balencedEquation = balencedEquation + " = " + nameWithNmber self.balencedEquation = balencedEquation #print (balencedEquation) return balencedEquation def __repr__(self): return self.balencedEquation class Compound(): ''' Takes compounds, splits them into elements ''' def __init__(self,compound,isReactant): self.name = compound self.isReactant = isReactant self.ElementsDict = {} self.elements() def elements(self): ''' I'll be honest, I made this late at night one day and have no idea how it works, there's probabley some corner cases I missed, byut hey, have fun ''' compound = self.name if re.search("\(", compound): elements = re.findall('[(]*[A-Z]+[a-z]*[1-9]*[)]*[1-9]*',compound) else: elements = re.findall('[(]*[A-Z][a-z]*[1-9]*[)]*[1-9]*',compound) #print(elements) for values in elements: factor = 1 valueList = [] if re.search('\(',values): #print(values) factor = re.findall('\)([1-9]+)',values) #print (factor) try: factor = int(factor[0]) except SyntaxError: print ('You used paranthesis without placing a subscript, add a subscript or remove the parenthis') elements2 = re.findall('[A-Z][a-z]*[1-9]*',values) values = elements2 valueList = list(elements2) else: valueList.append(values) for items in valueList: letter = re.findall('[A-Z]+[a-z]*',items) number = (re.findall('[1-9]',items)) if number == []: number = factor else: #print ('This is number',number) number = int(number[0]) number *= factor #print (letter,number) self.ElementsDict[letter[0]] = number def __repr__(self): return self.name def __str__(self): return self.name def main(): done = False print("To use the equation solver, input the equation without any coefficants. Exmp(Na3PO4 + CaCl2 = Ca3(PO4)2 + NaCl).") print("To exit,type in exit.") while not done: raw_equation = input("\nWhat is your Equation: ") checkExit = raw_equation if (checkExit.strip()).lower() == "exit": done = True break equation = Equation(raw_equation) print ('Answer is: ',equation) print("\nThank you for using Chemical Equation Solver by Lance, please come again.") if __name__ == "__main__": main()
students = [] for _ in range(int(raw_input())): name = raw_input() score = float(raw_input()) students.append([name, score]) second_lowest=sorted(list(set([x[1] for x in students])))[1] second_students=sorted([s for s,g in students if g==second_lowest]) for s in second_students: print(s)
import json import pandas as pd import requests from sklearn.base import BaseEstimator, TransformerMixin class CategoriesExtractor(BaseEstimator, TransformerMixin): """ Extract categories from json string. By default it will only keep the hardcoded categories defined below to avoid having too many dummies. """ misc = "misc" gen_cats = ["music", "film & video", "publishing", "art", "games"] precise_cats = [ "rock", "fiction", "webseries", "indie rock", "children's books", "shorts", "documentary", "video games" ] @classmethod def extract_categories(cls, json_string, validate=True): """ Defines a parameter validate. That is a trick, that allows to decide whether you want to extract all categories or only hard coded initially e.g.gen_cats, precise cats -> which you're intrested in, or default "misc" which I'm not. Helper loads the string using json into dict, getting slug method, and two different values as a tuple. If you set to True validate parameter you'll filter. If the first is not in the list category u care about, then you return default. Way to make sure we don't have too many dummy features later. """ categories = json.loads(json_string).get( "slug", "/").split("/", maxsplit=1) # Only keep hardcoded categories if validate: if categories[0] not in cls.gen_cats: categories[0] = cls.misc if categories[1] not in cls.precise_cats: categories[1] = cls.misc return categories def fit(self, X, y=None): return self def transform(self, X): categories = X["category"] return pd.DataFrame({ "gen_cat": categories.apply( lambda x: self.extract_categories(x)[0]), "precise_cat": categories.apply( lambda x: self.extract_categories(x)[1]) }) class GoalAdjustor(BaseEstimator, TransformerMixin): """ Adjusts the goal feature to USD. """ def fit(self, X, y=None): return self def transform(self, X): return pd.DataFrame({"adjusted_goal": X.goal * X.static_usd_rate}) class TimeTransformer(BaseEstimator, TransformerMixin): """ Builds features computed from timestamps. Takes a pandas DataFrame, and extracts different columns multiplied by some sort of adjustment. Then it's gonna do business logic to find out how many days do we have in between the deadline and launched timestamp. """ def __init__(self, adj=1000_000_000): self.adj = adj def fit(self, X, y=None): return self def transform(self, X): """ Loads dates into datetime object. Multiplying the timestamp by constant value. """ deadline = pd.to_datetime(X.deadline * self.adj) created = pd.to_datetime(X.created_at * self.adj) launched = pd.to_datetime(X.launched_at * self.adj) return pd.DataFrame({ "launched_to_deadline": (deadline - launched).dt.days, "created_to_launched": (launched - created).dt.days }) class CountryTransformer(BaseEstimator, TransformerMixin): """ Transform countries into larger groups to avoid having too many dummies. """ countries = { 'US': 'US', 'CA': 'Canada', 'GB': 'UK & Ireland', 'AU': 'Oceania', 'IE': 'UK & Ireland', 'SE': 'Europe', 'CH': "Europe", 'IT': 'Europe', 'FR': 'Europe', 'NZ': 'Oceania', 'DE': 'Europe', 'NL': 'Europe', 'NO': 'Europe', 'MX': 'Other', 'ES': 'Europe', 'DK': 'Europe', 'BE': 'Europe', 'AT': 'Europe', 'HK': 'Other', 'SG': 'Other', 'LU': 'Europe', } def fit(self, X, y=None): return self def transform(self, X): return pd.DataFrame({"country": X.country.map( self.countries)}).fillna("Other") class CountryFullTransformer(BaseEstimator, TransformerMixin): """ Transformer that is connecting to rest api -> passing country as an argument, parsing result from json and returning region, e.g. for CA gonna produce Canada. """ def get_region_from_code(self, country): url = f"https://restcountries.eu/rest/v2/name/{country}" result = json.loads(requests.get(url)) return result['region'] def fit(self, X, y=None): return self def transform(self, X): return pd.DataFrame( {'country': X.country.map(self.get_region_from_code)})
class Sources: ''' Source class to define News Source Objects ''' def __init__(self,id,name,description,url,category,language,country): self.id = id self.name = name self.description = description self.url = url self.category = category self.language = language self.country = country class News: ''' News class to define News Objects ''' def __init__(self,source,author,title,description,url,urlToImage,publishedAt,content): self.source = source self.author = author self.title = title self.description = description self.url = url self.urlToImage = urlToImage self.publishedAt = publishedAt self.content = content class Headlines: ''' Class that instantiates objects of the headlines categories objects of the news sources ''' def __init__(self,author,title,description,url,urlToImage,publishedAt): self.author = author self.title = title self.description = description self.url = url self.urlToImage = urlToImage self.publishedAt = publishedAt class Category: ''' Class that instantiates objects of the categories objects of the news sources ''' def __init__(self,author,title,description,url,urlToImage,publishedAt): self.author = author self.title = title self.description = description self.url = url self.urlToImage = urlToImage self.publishedAt = publishedAt
#! /usr/bin/env python from collections import Counter from sys import maxsize t = int(input()) for it in range(1, t+1): n, l = [int(x) for x in input().rstrip('\n').split()] outlets = [int(x, 2) for x in input().rstrip('\n').split()] devices = [int(x, 2) for x in input().rstrip('\n').split()] devicesCounter = Counter(devices) best = maxsize """ By XORing each outlet with first device we are getting just bits (buttons) which are in incorrect position. e.g. outlet = 010010 device = 110010 ^ 100000 """ for flips in set((x ^ devices[0]) for x in outlets): flipped = ((y ^ flips) for y in outlets) if Counter(flipped) == devicesCounter: best = min(best, bin(flips).count("1")) print("Case #{}: {}".format(it, "NOT POSSIBLE" if best == maxsize else best))
# Base Converter Program - Converts from any desired base to any base ranging # from 2-64. """ Below are the three main variables for the code, the number to change, the original base the number you are converting is in, and the base you would like to convert to. """ n_to_change = raw_input("Number to change:") base1 = int(raw_input("Original base:")) base2 = int(raw_input("Base you are changing to:")) """ This is a function that converts integers into base 10 from any base provided, over decimal bases, such as hexadecimal bases. """ err = 0 def to10fromlarge(n,b): numbasehex = {"1": 1, "0": 0, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "A": 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, 'I': 18, 'J': 19, 'K': 20, 'L': 21, 'M': 22, 'N': 23, 'O': 24, 'P': 25, 'Q': 26, 'R': 27, 'S': 28, 'T': 29, 'U': 30, 'V': 31, 'W': 32, 'X': 33, 'Y': 34, 'Z': 35} n1 = str(n) new = 0 power = 0 ver = str(n[::-1]) # Checks if number is valid in the given base, prints ERROR, if not. for i in ver: if numbasehex[i] < base1: new = new + numbasehex[i] * (int(b) ** power) power = power + 1 test = 0 else: print "" print i + " is not a valid number in base " + str(base1) + "." print "" new = "ERROR" break return new """ Below is a function that converts the new base 10 number into the arbitrary base chosen by the user. """ def base10toN(num,n): #Change a to a base-n number. #Up to base-36 is supported without special notation. num_rep={10:'A', 11:'B',12:'C',13:'D',14:'E',15:'F',16:'G',17:'H',18: 'I',19:'J',20:'K',21:'L',22:'M',23:'N',24:'O',25:'P',26:'Q',27:'R', 28:'S',29:'T',30:'U',31:'V',32:'W',33:'X',34:'Y', 35:'Z'} # Below is how the computer converts through the numbers. new_num_string='' current=num """ Using a while loop to finder remainders and calculate the correct numbers. Seeing if the base is less than 36, than going through the correct steps. """ if current == "ERROR": print "An ERROR has occurred, you have likely input a number too large for that base!" print "" else: while current!=0: remainder=current%n if 36>remainder>9: remainder_string=num_rep[remainder] elif remainder>=36: remainder_string='('+str(remainder)+')' else: remainder_string=str(remainder) new_num_string=remainder_string+new_num_string current=current/n # Prints the number you are changing, the base it was originally in. Then the number in the new base, with the base. return n_to_change + "(Base:" + str(base1) + ")" + " is " + new_num_string + " in base " + str(base2) + "." """ This checks if the base the original number is in is equal to ten, to make calculations easier. Otherwise, runs to10fromlarge, and etc. """ print base10toN(to10fromlarge(n_to_change,base1),base2)
import speech_recognition as sr class VOCAB(): def __init__(self): self.death_vocab = ["dead", "die", "death", "decease", "passed on", "passed away", "perish"] self.recovered_vocab = ["recover", "cure", "heal", "rehabilitate"] self.confirmed_vocab = ["confirm", "have coronavirus", "coronavirus cases", "infect", "contaminate"] self.today_vocab = ["today", "recently", "lately", "just now", "not long ago"] self.serious_vocab = ["serious", "danger"] def find_vocab_in_speech(speech, vocab): for i in vocab: if speech.find(i) != -1: return True return False def user_demand(speech): speech = speech.lower().replace("corona virus", "coronavirus") vocab = VOCAB() print (speech) try: place = speech.split("in ",1)[1] except: place = "global" print(place) if (find_vocab_in_speech(speech, vocab.death_vocab)): if find_vocab_in_speech(speech, vocab.today_vocab): print("death today") else: print("total death") elif (find_vocab_in_speech(speech, vocab.confirmed_vocab)): if find_vocab_in_speech(speech, vocab.today_vocab): print("confirmed today") else: print("total confirmed") elif (find_vocab_in_speech(speech, vocab.recovered_vocab)): print("cured") elif (find_vocab_in_speech(speech, vocab.serious_vocab)): print("serious") else: print("didn't understand") # obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) # recognize speech using Google Speech Recognition try: speech = r.recognize_google(audio) print(speech) user_demand(speech) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))
from numpy import ndarray import cv2 class Normalizer: @classmethod def crop_make_binary_image(cls, image: ndarray): """ crops the image so that the borders of the picture touch the signature. AND converts image to binary :type image: ndarray :return: numpy.ndarray """ binary_image = cls.to_binary_image(image) original_width = binary_image.shape[1] original_height = binary_image.shape[0] min_width = original_width min_height = original_height max_height = 0 max_width = 0 for i in range(0, original_height): for j in range(0, original_width): if binary_image[i, j] == 0: min_width = j if j < min_width else min_width max_width = j if j > max_width else max_width min_height = i if i < min_height else min_height max_height = i if i > max_height else max_height return binary_image[min_height: max_height, min_width: max_width] @classmethod def to_binary_image(cls, image: ndarray): """ converts image to B&W image :type image: numpy.ndarray :return: numpy.ndarray """ gray_image = cls.to_gray(image) thresh, result = cv2.threshold(gray_image, 200, 255, cv2.THRESH_BINARY) return result @classmethod def to_gray(cls, image: ndarray): """ receives a colored image and returns a gray scale image :type image: ndarray """ if len(image.shape) < 3: return image return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) @classmethod def resize(cls, width, height, image): return Normalizer.to_binary_image( # seems resizing a binary image returns a gray scale image! why?? IDK cv2.resize(image, (width, height)) )
""" import fibo fibo.fib(1000) fibsi=fibo.fib fibsi(500) """ """ from fibo import fib, fib2 fib(500) """ """ from fibo import * fib(500) """ # In most cases Python programmers do not use this facility # since it introduces an unknown set of names into the interpreter, # possibly hiding some things you have already defined. # Note that in general the practice of importing * from a # module or package is frowned upon, since it often causes # poorly readable code. """ import fibo as fib fib.fib(500) import fibo as fibona fibona.fib(500) # fibo.fib(500) # This will not work as the name fibo is undefined """ """ from fibo import fib as fibonacci fibonacci(500) from fibo import fib2 as fiboreturns print(fiboreturns(1000)) """ # Each module is imported only once per interpreter session # To test modules interactively, use importlib.reload()