blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
24a9a34002a667ac5063e56f991d803ae112d1ba
mootfowl/dp_pdxcodeguild
/python assignments/lab03_madlib01.py
506
3.609375
4
adjective01 = input("Enter an adjective. > ") noun01 = input("Name a noun. > ") verb_past_tense = input("And now a past tense verb. > ") adverb = input("How about an adverb? > ") adjective02 = input("One more adjective. > ") noun02 = input("And finally, one last noun. > ") print("Today I went to the zoo and saw a " + adjective01 + " " + noun01 + " jumping up and down.") print("He " + verb_past_tense + " " + adverb + " through the large tunnel that led to its " + adjective02 + " " + noun02 + ".")
3967fad907d30a59282306b168bfd3fa032bfaa9
mootfowl/dp_pdxcodeguild
/python assignments/lab10_unit_converter_v3.py
1,466
4.34375
4
''' v3 Allow the user to also enter the units. Then depending on the units, convert the distance into meters. The units we'll allow are inches, feet, yards, miles, meters, and kilometers. ''' def number_crunch(): selected_unit = input("Pick a unit of measurement: inches, feet, yards, miles, meters, or kilometers. > ") selected_number = float(input("And now pick a number. > ")) if selected_unit == 'inches': conversion = selected_number * 0.0254 print(f"{selected_number} {selected_unit} is equal to {conversion} meters.") number_crunch() elif selected_unit == 'feet': conversion = selected_number * 0.3048 print(f"{selected_number} {selected_unit} is equal to {conversion} meters.") number_crunch() elif selected_unit == 'yards': conversion = selected_number * 0.9144 number_crunch() elif selected_unit == 'miles': conversion = selected_number * 1609.34 print(f"{selected_number} {selected_unit} is equal to {conversion} meters.") number_crunch() elif selected_unit == 'meters': conversion = selected_number print(f"{selected_number} {selected_unit} is equal to {conversion} meters. DUH.") number_crunch() elif selected_unit == 'kilometers': conversion = selected_number / 1000 print(f"{selected_number} {selected_unit} is equal to {conversion} meters.") number_crunch() number_crunch()
d900cef1d0915808b0b213a6339636bf2dd3dcd2
mootfowl/dp_pdxcodeguild
/python assignments/lab15_ROT_cipher_v1.py
971
4.15625
4
''' LAB15: Write a program that decrypts a message encoded with ROT13 on each character starting with 'a', and displays it to the user in the terminal. ''' # DP note to self: if a = 1, ROT13 a = n (ie, 13 letters after a) # First, let's create a function that encrypts a word with ROT13... alphabet = 'abcdefghijklmnopqrstuvwxyz ' key = 'nopqrstuvwxyzabcdefghijklm ' def encrypt(word): encrypted = '' for letter in word: index = alphabet.find(letter) # returns the alphabet index of the corresponding letter encrypted += (key[index]) # prints the rot13 letter that correlates to the alphabet index return encrypted def decrypt(encrypted_word): decrypted = '' for letter in encrypted_word: index = key.find(letter) decrypted += (alphabet[index]) return decrypted secret_sauce = input("Type in a word > ") print(encrypt(secret_sauce)) not_so_secret_sauce = input("Type in an encrypted word > ") print(decrypt(not_so_secret_sauce))
363feaccd97bf2220c50d1e26900f1e50514f112
xdexer/ModelowanieKomputerowe
/Lista5/lorenz.py
671
3.515625
4
import numpy as np import matplotlib.pyplot as plt def lorenz(x, y, z, s=10, r=28, b=2.667): x_dot = s*(y - x) y_dot = r*x - y - x*z z_dot = x*y - b*z return x_dot, y_dot, z_dot dt = 0.01 num_steps = 10000 xs = np.empty(num_steps + 1) ys = np.empty(num_steps + 1) zs = np.empty(num_steps + 1) xs[0], ys[0], zs[0] = (0.0, 1.0, 1.05) for i in range(num_steps): x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i]) xs[i + 1] = xs[i] + (x_dot * dt) ys[i + 1] = ys[i] + (y_dot * dt) zs[i + 1] = zs[i] + (z_dot * dt) ax = plt.figure().add_subplot(projection='3d') ax.plot(xs, ys, zs, linewidth=0.5) ax.set_title("Lorenz Attractor") plt.show()
65546b82ba65514c1e0fff178974a325dc270dd4
mabuaisha/gradient-descent-python
/linear_regession.py
2,007
3.515625
4
# Standard imports import os # Third party imports import numpy as np import pandas as pd import matplotlib.pyplot as plt def evaluate_cost_function(data, output, thetas): m = len(output) return np.sum((data.dot(thetas) - output) ** 2) / (2 * m) def evaluate_gradient_descent(data, output, initial_thetas, alpha, iterations): cost_history = [0] * iterations thetas = [] for index in range(initial_thetas.size): thetas.append([]) for iteration in range(iterations): # h represent the hypothesis h = data.dot(initial_thetas) # Loss is the difference between hypothesis and the actual value loss = h - output # gradient value which is going to be used later on with alpha # to compute the new values for thetas gradient = data.T.dot(loss) / len(output) # Compute the new thetas initial_thetas = initial_thetas - alpha * gradient # Aggregate all thetas since we need them later on for plot against # costs for index, item in enumerate(initial_thetas): thetas[index].append(item) # Evaluate cost function using the updated thetas cost = evaluate_cost_function(data, output, initial_thetas) # For each iteration we should register new cost function in order # to plot it later on cost_history[iteration] = cost return initial_thetas, cost_history, thetas def plot_cost_and_iterations(iters, cost, plot_location, plot_name, plot_title): fig, ax = plt.subplots() ax.plot(np.arange(iters), cost, 'r') ax.set_xlabel('Iterations') ax.set_ylabel('Cost') ax.set_title(plot_title) plt.savefig('{0}/{1}.png'.format(plot_location, plot_name)) plt.close(fig) def parse_dataset(dataset_name): return pd.read_csv( os.path.join(os.path.dirname(__name__), dataset_name) )
1a5076cd2d4cb1c987e49461aedc4eac7516d66a
vinicius-m-santiago/python
/aniversario.py
372
3.71875
4
#execricio nascimento meses = ("janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro") data_aniversario = input("Insira a data do aniversario: ") mes_aniversario = data_aniversario[3:5] mes_aniversario_num = int(mes_aniversario) - 1 print("Seu aniversário é no mês: ", meses[mes_aniversario_num])
8982823fd433509659ee3fe1eb6a2414c6195b54
MNabi2015/Kalkulator2000
/calc2.py
1,803
4.0625
4
help1 = input("Добро пожаловать в наш калькулятор введите 1 чтобы включить функцию помощь нажмите 0 чтобы ее не включать") if help1 == "1": print("1 Введите первое число") print("2 Нажмите 'Enter'") print("3 Введите оператор") print("4 Нажмите 'Enter'") print("5 Введите Второе число") print("6 Нажмите 'Enter' чтобы посмотреть на результат ") else: print("Спасибо что заглянули в наш калькулятор") # d = input("Нажмите 1 что бы не показывать больше это сообщение ") # if d == 1: # delete (help1) num1 = int(input("Введите 1 число ")) z = input("Введите оператор (*, /, - ,+ ,% ,# - Корень из n ,^ - В степень n ,! - Факториал) ") num2 = int(input("Введите 2 число ")) if z == "+": print(num1 + num2) elif z == "!": fac = 1 i = 0 while i < num1: i += 1 fac = fac * i fac2 = 1 i = 0 while i < num2: i += 1 fac2 = fac2 * i print("Факториал 1 числа:", fac , ", и факториал 2 числа:", fac2) elif z == "-": print(num1 - num2) elif z == "%": print(num1 * (num2 / 100)) elif z == "*": print(num1 * num2) elif z == "#": print(num1 ** (1 / num2)) elif z == "^": print(num1 ** num2) # elif num2 == "0": # z == "/" # print("Деление на ноль!") elif z == "/": print(num1 / num2) else: print ("Пиши правильно!") print("Спасибо что воспользовались нашим калькулятором")
b7372899cb52561ed987c70a8cf9f675cae945d1
gukexi/LearningPython
/create_tc/src/modules/create_tc_measure_points.py
1,177
3.6875
4
''' Created on Jul 18, 2019 The module contains one function. The function needs two input parameters. The first input parameter is a list. The second input parameter is txt file operating. The function is to handling the list and save the comments to txt file. @author: ekexigu ''' from re import sub as s def creat_comments(current_list, tc_operate): description_list = [] for current_comment in current_list[0]: description_list.append(current_comment.replace("\'", "\"")) branches = current_list[1] continuous = current_list[2] tc_comments = "" if continuous: for description in description_list: for branch in range(branches): comment = s("{%02d}", "%02d" % branch, s("{%d}", "%d" % branch, description)) comment += "\n" tc_comments += comment else: for branch in range(branches): for description in description_list: comment = s("{%02d}", "%02d" % branch, s("{%d}", "%d" % branch, description)) comment += "\n" tc_comments += comment tc_operate.write(tc_comments.strip())
67e5b41de7e06e397f62c9fb8156373d54bf8356
FrancoValenteG/Trabajo2
/Nueva carpeta/minisculas.py
758
3.53125
4
def lectura(): p = open("paises.txt","r") paises = [linea.rstrip() for linea in sorted(set(p))] p.close() c = open("colores.txt","r") colores= [linea.rstrip() for linea in sorted(set(c))] c.close() a = open("animales.txt","r") animales= [linea.rstrip() for linea in sorted(set(a))] a.close() n = open("nombres.txt","r") nombres= [linea.rstrip() for linea in sorted(set(n))] n.close() cap = open("capitales.txt","r") capitales= [linea.rstrip() for linea in sorted(set(cap))] cap.close() return(paises,colores,animales,nombres,capitales) paises, colores, animales, nombres, capitales = lectura() print(paises) print(colores) print(animales) print(nombres)
1c8e6b53453f8050af95f63e889b21be04108124
nclelw/Synonym-by-Association
/thesaurus.py
4,268
3.859375
4
import re def read_common_words(filename): ''' Reads the commmon words file into a set. If the file name is None returns an emtpy set. If the file cannot be opened returnes an empty set: ''' words = set() if filename != None: try: with open(filename) as fp: for line in fp: words.add(line.strip().lower()) except FileNotFoundError: print("Warning: Couldn't read common words file") return words def read_corpus(filename, common_words, test_words): ''' Reads the corpus from the given file. Loads the data into a dictionary that holds the targets and the words that they occur with in a sentence. ''' associations = {} word_counts = {} # regular expression to strip punctuations punctuations = "|".join(re.escape(x) for x in ('{', '}', '(', ')', '[', ']', ',', ' ', '\t',':', ';',"'", '"')) repl1 = re.compile(punctuations) # regular expression to remove -- repl2 = re.compile("--") # regular expression to split the text into sentences. sent_splitter = re.compile("\.|\?\!") # regular expression to split a sentence into words. word_splitter = re.compile("\\s{1,}") try: with open(filename) as fp: data = fp.read() sentences = sent_splitter.split(data.lower()) # now iterate through the sentence. for sentence in sentences: sentence = repl2.sub(" ", repl1.sub(" ", sentence)) words = set([word for word in word_splitter.split(sentence) if word not in common_words]) # having split up the sentence in words, let's go through the words and # find the associations. for word in words: word_count = word_counts.get(word) if not word_count: word_counts[word] = 1 else: word_counts[word] += 1 for other_word in words: if word != other_word: count = associations.get(word) if count == None: associations[word] = {other_word: 1} else: ocount = count.get(other_word) if ocount == None: count[other_word] = 1 else: count[other_word] += 1 return word_counts, associations except FileNotFoundError: print("Error could not read the corpus") def print_status(word_counts, associations): ''' Pretty prints the contents of our data structures ''' print(len(word_counts), "words in words list") print("word_count_dict\nword_word_dict") words = sorted(word_counts.keys(), key=lambda x: -word_counts[x]) for word in words: count = word_counts[word] print(word, count) related = associations[word] related_words = sorted(related.keys()) for related_word in related_words: print(" ", related_word, related[related_word]) def read_test_data(filename): ''' Reads the test data into a set ''' data = set() try: with open(filename) as fp: for line in fp: data.add(line.strip().lower()) except FileNotFoundError: print("Error the test data could not be read") return data def main(corpus_file_name, test_sets_file, commonwords_file_name = None): ''' Program entry point ''' stop_words = read_common_words(commonwords_file_name) test_data = read_test_data(test_sets_file) word_counts, associations = read_corpus(corpus_file_name, stop_words, test_data) print_status(word_counts, associations) if __name__ == '__main__': main('punctuation.txt', 'sample0_set.txt', 'common.txt')
f29f512a17e420939afd3f9899127a43aaa3ae73
tomgprice411/Medium_Article_Tutorial_Bar_Plotly_Python
/graph_article_script.py
22,033
3.515625
4
import pandas as pd import plotly.graph_objects as go import os from plotly.subplots import make_subplots ####################### # Data Transformation # ####################### ########## # Step 1 # ########## os.chdir("/mnt/c/Users/tom_p/Spira_Analytics/Medium_Articles/Plotly_Guide_Bar_Chart") #read data df_raw = pd.read_csv("Pakistan Largest Ecommerce Dataset.csv") #only include columns that we are interested in and drop NA's from those columns df_raw = df_raw[["item_id", "status", "created_at", "price", "qty_ordered", "grand_total", "category_name_1", "discount_amount"]] df_raw.dropna(inplace = True) #convert date to datetime df_raw["created_at"] = pd.to_datetime(df_raw["created_at"]) #only use completed, received or paid orders df_raw = df_raw.loc[df_raw["status"].isin(["complete", "received", "paid"])] #we will make the assumption that grand total should be price multiplied by quantity ordered #minus discount amount df_raw["grand_total_calc"] = (df_raw["price"] * df_raw["qty_ordered"]) - df_raw["discount_amount"] df_raw["grand_total_diff"] = df_raw["grand_total_calc"] - df_raw["grand_total"] #some of the grand total figures look way out compared to our calculation #for the purpose of our visual we will go with our assumed calculation df_raw["grand_total"] = df_raw["grand_total_calc"] df_raw.drop(columns = ["grand_total_calc", "grand_total_diff"], inplace = True) #filter the data so we only have the dates we are interested in df_raw = df_raw.loc[(df_raw["created_at"].between("2017-06-01", "2017-08-28")) | (df_raw["created_at"].between("2018-06-01", "2018-08-28"))].copy() #add in variable indicating this year and last year's data df_raw["season_ind"] = "Last Year" df_raw.loc[df_raw["created_at"] > "2018-01-01", "season_ind"] = "This Year" #transform the data so we can acquire the metrics we want to illustrate df = df_raw.groupby(["season_ind", "category_name_1"]).agg(items_ord = ("qty_ordered", "sum"), sales = ("grand_total", "sum")).reset_index() #transform the dataframe so that the rows shows all the metrics for each individual category df = df.pivot(columns = "season_ind", index = "category_name_1", values = ["items_ord", "sales"]).reset_index() #rename the columns to remove the multi index df.columns = ["category_name", "items_ord_ly", "items_ord_ty", "sales_ly", "sales_ty"] #calculate the average selling price df["avg_rsp_ly"] = df["sales_ly"] / df["items_ord_ly"] df["avg_rsp_ty"] = df["sales_ty"] / df["items_ord_ty"] #calculate the year on year variances df["items_ord_variance_abs"] = df["items_ord_ty"] - df["items_ord_ly"] df["items_ord_variance_%"] = df["items_ord_variance_abs"] / df["items_ord_ly"] df["sales_variance_abs"] = df["sales_ty"] - df["sales_ly"] df["sales_variance_%"] = df["sales_variance_abs"] / df["sales_ly"] df["avg_rsp_variance_abs"] = df["avg_rsp_ty"] - df["avg_rsp_ly"] df["avg_rsp_variance_%"] = df["avg_rsp_variance_abs"] / df["avg_rsp_ly"] #drop \N category df.drop(index = df.loc[df["category_name"] == r"\N"].index, inplace = True) ###################### # Data Visualisation # ###################### ########## # Step 2 # ########## fig = go.Figure() fig.add_trace(go.Bar(x = df["sales_variance_abs"], y = df["category_name"], orientation = "h")) #set orientation to horizontal because we want to flip the x and y-axis fig.show() ########## # Step 3 # ########## # we want to sort the categories from highest to lowest for year on year sales variance CATEGORY_ORDER = df.sort_values(by = "sales_variance_abs")["category_name"].tolist() fig = go.Figure() fig.add_trace(go.Bar(x = df["sales_variance_abs"], y = df["category_name"], orientation = "h", )) fig.update_layout(plot_bgcolor = "white", font = dict(color = "#909497"), title = dict(text = "Year on Year Sales Variance by Category for Pakistan Ecommerce Stores"), xaxis = dict(title = "Sales Variance (Abs)", linecolor = "#909497", tickprefix = "&#8377;"), #tick prefix is the html code for Rupee yaxis = dict(title = "Product Category", tickformat = ",", linecolor = "#909497", categoryorder = "array", categoryarray = CATEGORY_ORDER)) #apply our custom category order fig.show() ########## # Step 4 # ########## #transform the dataframe so that we have access to the absolute variances in sales, items ordered and avg rsp df2 = df.melt(id_vars = ["category_name"], value_vars = ["items_ord_variance_abs", "sales_variance_abs", "avg_rsp_variance_abs"], var_name = "metric") #create a columns to hold the position of each subplot df2["row"] = 1 df2["col"] = 1 df2.loc[df2["metric"] == "items_ord_variance_abs", "col"] = 2 df2.loc[df2["metric"] == "avg_rsp_variance_abs", "col"] = 3 #now use make_subplots to create the plot fig = make_subplots(cols = 3, rows = 1, subplot_titles= ["Sales Variance", "Items Ord Variance", "Avg RSP Variance"]) #loop over each metric in the dataframe and create a seprate graph within the subplot for metric in df2["metric"].unique(): df_plot = df2.loc[df2["metric"] == metric].copy() fig.add_trace(go.Bar(x = df_plot["value"], y = df_plot["category_name"], orientation = "h", name = df_plot["metric"].tolist()[0]), row = df_plot["row"].tolist()[0], #apply the row position we created above col = df_plot["col"].tolist()[0]) #apply the column position we created above fig.update_layout(plot_bgcolor = "white", font = dict(color = "#909497"), title = dict(text = "Year on Year Sales Variance by Category for Pakistan Ecommerce Stores"), yaxis = dict(title = "Product Category", linecolor = "white", categoryorder = "array", categoryarray = CATEGORY_ORDER), xaxis = dict(tickprefix = "&#8377;"), xaxis2 = dict(tickformat = ","), xaxis3 = dict(tickprefix = "&#8377;")) fig.update_xaxes(title = "", linecolor = "#909497") #add a vertical line at x = 0 to act as x-axis fig.add_vline(x = 0, line_color = "#909497", line_width = 1) fig.show() ########## # Step 5 # ########## #transform the df dataframe again and this time include the absolute variance in sales and % variance in sales, #items ordered and avg rsp df3 = df.melt(id_vars = ["category_name"], value_vars = ["sales_variance_abs", "items_ord_variance_%", "sales_variance_%", "avg_rsp_variance_%"], var_name = "metric") #create columns to hold the position of each metric in the subplot df3["row"] = 1 df3["col"] = 1 df3.loc[df3["metric"] == "sales_variance_%", "col"] = 2 df3.loc[df3["metric"] == "items_ord_variance_%", "col"] = 3 df3.loc[df3["metric"] == "avg_rsp_variance_%", "col"] = 4 #create the dataframe that contains the subplot titles and x-axis positions df_subplot_titles = pd.DataFrame({ "titles": ["Sales Variance (Abs)", "Sales Variance (%)", "Items Ord Variance (%)", "Avg RSP Variance (%)"], "column": ["x1", "x2", "x3", "x4"], "x": [-4000000,-1,-1,-1] }) #create the plot fig = make_subplots(cols = 4, rows = 1, shared_yaxes = True) #set the subplots to share the y-axis so it only appears once for metric in df3["metric"].unique(): df_plot = df3.loc[df3["metric"] == metric].copy() fig.add_trace(go.Bar(x = df_plot["value"], y = df_plot["category_name"], orientation = "h", name = df_plot["metric"].tolist()[0]), row = df_plot["row"].tolist()[0], col = df_plot["col"].tolist()[0]) fig.update_layout(plot_bgcolor = "white", font = dict(color = "#909497"), title = dict(text = "Year on Year Sales Variance by Category for Pakistan Ecommerce Stores"), yaxis = dict(title = "Product Category", tickformat = ",", linecolor = "white", categoryorder = "array", categoryarray = CATEGORY_ORDER), xaxis = dict(tickprefix = "&#8377;", range = [-4000000,10000000]), xaxis2 = dict(tickformat = "%", range = [-1,4]), xaxis3 = dict(tickformat = "%", range = [-1,4]), xaxis4 = dict(tickformat = "%", range = [-1,4]), showlegend = False) fig.update_xaxes(title = "", linecolor = "#909497", side = "top") #set the x-axes to appear at the top of the charts #add a vertical line at x = 0 to act as x-axis fig.add_vline(x = 0, line_color = "#909497", line_width = 1) # add subplot titles manually for title in df_subplot_titles["titles"].tolist(): df_text = df_subplot_titles.loc[df_subplot_titles["titles"] == title] fig.add_annotation(text = title, xref = df_text["column"].tolist()[0], yref = "paper", x = df_text["x"].tolist()[0], y = 1.08, showarrow = False, align = "left", xanchor = "left", font = dict(size = 14) ) fig.show() ########## # Step 6 # ########## #create a column for color df3["color"] = "#BDC3C7" df3.loc[df3["category_name"] == "Mobiles & Tablets", "color"] = "#2471A3" #create a column for the widths of each bar plot df3["width"] = 0.15 df3.loc[df3["metric"] == "sales_variance_abs", "width"] = 0.8 fig = make_subplots(cols = 4, rows = 1, shared_yaxes = True, column_widths = [0.4, 0.2, 0.2, 0.2]) #set the widths of each graph in the subplot giving more prominence to the first one #create two different data frames in the for loop one for the Mobile & Tablets category only and another without it for metric in df3["metric"].unique(): df_plot_non_mobile_tablet = df3.loc[(df3["metric"] == metric) & (df3["category_name"] != "Mobiles & Tablets")].copy() df_plot_mobile_tablet = df3.loc[(df3["metric"] == metric) & (df3["category_name"] == "Mobiles & Tablets")].copy() fig.add_trace(go.Bar(x = df_plot_non_mobile_tablet["value"], y = df_plot_non_mobile_tablet["category_name"], width = df_plot_non_mobile_tablet["width"], orientation = "h", marker = dict(color = df_plot_non_mobile_tablet["color"].tolist()[0])), row = df_plot_non_mobile_tablet["row"].tolist()[0], col = df_plot_non_mobile_tablet["col"].tolist()[0]) #add a second trace in to deal with different colored category fig.add_trace(go.Bar(x = df_plot_mobile_tablet["value"], y = df_plot_mobile_tablet["category_name"], width = df_plot_mobile_tablet["width"], orientation = "h", marker = dict(color = df_plot_mobile_tablet["color"].tolist()[0])), row = df_plot_mobile_tablet["row"].tolist()[0], col = df_plot_mobile_tablet["col"].tolist()[0]) fig.update_layout(plot_bgcolor = "white", font = dict(color = "#909497"), title = dict(text = "Year on Year Change in Sales by Category for Pakistan Ecommerce Stores"), yaxis = dict(title = "Product Category", tickformat = ",", linecolor = "white", categoryorder = "array", categoryarray = CATEGORY_ORDER), xaxis = dict(tickprefix = "&#8377;", range = [-4000000,10000000]), xaxis2 = dict(tickformat = "%", range = [-1,4]), xaxis3 = dict(tickformat = "%", range = [-1,4]), xaxis4 = dict(tickformat = "%", range = [-1,4]), showlegend = False) fig.update_xaxes(title = "", linecolor = "#909497", side = "top") #add a vertical line at x = 0 to act as x-axis fig.add_vline(x = 0, line_color = "#909497", line_width = 1) # add subplot titles manually for title in df_subplot_titles["titles"].tolist(): df_text = df_subplot_titles.loc[df_subplot_titles["titles"] == title] fig.add_annotation(text = title, xref = df_text["column"].tolist()[0], yref = "paper", x = df_text["x"].tolist()[0], y = 1.08, showarrow = False, align = "left", xanchor = "left", font = dict(size = 14) ) fig.show() ########## # Step 7 # ########## import numpy as np # create the labels for the y-axis df_xaxis_labels = pd.DataFrame({ "category_name": df["category_name"].tolist(), "yref": np.repeat("y", len(df["category_name"])) }) #set the color of the y-axis labels df_xaxis_labels["color"] = "#909497" df_xaxis_labels.loc[df_xaxis_labels["category_name"] == "Mobiles & Tablets", "color"] = "#2471A3" #create the variable names needed for the hover info df3["hover_info_text"] = "Sales Variance (Abs)" df3.loc[df3["metric"] == "qty_ordered_yoy_%", "hover_info_text"] = "Items Ord Variance (%)" df3.loc[df3["metric"] == "grand_total_yoy_%", "hover_info_text"] = "Sales Variance (%)" df3.loc[df3["metric"] == "average_selling_price_yoy_%", "hover_info_text"] = "Avg RSP Variance (%)" #create the size of the item range information for mobiles and tablet category df_price_commentary = df_raw.loc[df_raw["category_name_1"] == "Mobiles & Tablets", ["item_id", "price", "season_ind"]].copy() #how many mobiles and tables in each season all together df_price_commentary_range = df_price_commentary.groupby("season_ind").agg(range_size = ("item_id", "nunique")).reset_index() #how many mobiles and tables in each season over 40,000 rupees df_price_commentary_high_price_point = df_price_commentary.loc[df_price_commentary["price"] >= 40000, ["season_ind", "item_id"]].groupby("season_ind").agg(range_size = ("item_id", "nunique")).reset_index() #create the range size variables to be used in the commentary MT_RANGE_LY = int(round(df_price_commentary_range.loc[df_price_commentary_range["season_ind"] == "Last Year", "range_size"].tolist()[0]/1000, 0)) MT_RANGE_TY = round(df_price_commentary_range.loc[df_price_commentary_range["season_ind"] == "This Year", "range_size"].tolist()[0]/1000, 1) MT_RANGE_PERC_HIGH_PRICE_POINT_LY = df_price_commentary_high_price_point.loc[df_price_commentary_high_price_point["season_ind"] == "Last Year", "range_size"].tolist()[0]/1000 / MT_RANGE_LY MT_RANGE_PERC_HIGH_PRICE_POINT_TY = df_price_commentary_high_price_point.loc[df_price_commentary_high_price_point["season_ind"] == "This Year", "range_size"].tolist()[0]/1000 / MT_RANGE_TY #create the plot fig = make_subplots(cols = 4, rows = 1, shared_yaxes = True, column_widths = [0.4, 0.2, 0.2, 0.2]) for metric in df3["metric"].unique(): df_plot_non_mobile_tablet = df3.loc[(df3["metric"] == metric) & (df3["category_name"] != "Mobiles & Tablets")].copy() df_plot_mobile_tablet = df3.loc[(df3["metric"] == metric) & (df3["category_name"] == "Mobiles & Tablets")].copy() fig.add_trace(go.Bar(x = df_plot_non_mobile_tablet["value"], y = df_plot_non_mobile_tablet["category_name"], width = df_plot_non_mobile_tablet["width"], orientation = "h", marker = dict(color = df_plot_non_mobile_tablet["color"].tolist()[0]), text = df_plot_non_mobile_tablet["hover_info_text"], hovertemplate = "Category: %{y}<br>" + "%{text}: %{x}<extra></extra>"), row = df_plot_non_mobile_tablet["row"].tolist()[0], col = df_plot_non_mobile_tablet["col"].tolist()[0]) #add a second trace in to deal with different colored category fig.add_trace(go.Bar(x = df_plot_mobile_tablet["value"], y = df_plot_mobile_tablet["category_name"], width = df_plot_mobile_tablet["width"], orientation = "h", marker = dict(color = df_plot_mobile_tablet["color"].tolist()[0]), text = df_plot_mobile_tablet["hover_info_text"], hovertemplate = "Category: %{y}<br>" + "%{text}: %{x}<extra></extra>"), row = df_plot_mobile_tablet["row"].tolist()[0], col = df_plot_mobile_tablet["col"].tolist()[0]) fig.update_layout(plot_bgcolor = "white", font = dict(color = "#909497"), yaxis = dict(title = "Category", categoryorder = "array", categoryarray = CATEGORY_ORDER, visible = False), xaxis = dict(tickprefix = "&#8377;", range = [-4000000,10000000]), xaxis2 = dict(tickformat = "%", range = [-1,4]), xaxis3 = dict(tickformat = "%", range = [-1,4]), xaxis4 = dict(tickformat = "%", range = [-1,4]), showlegend = False, margin = dict(l = 120, t = 140)) fig.update_xaxes(title = "", linecolor = "#909497", side = "top") fig.update_yaxes(categoryorder = "array", categoryarray = CATEGORY_ORDER) fig.add_vline(x = 0, line_color = "#909497", line_width = 1) # add subplot titles manually for title in df_subplot_titles["titles"].tolist(): df_text = df_subplot_titles.loc[df_subplot_titles["titles"] == title].copy() fig.add_annotation(text = title, xref = df_text["column"].tolist()[0], yref = "paper", x = df_text["x"].tolist()[0], y = 1.1, showarrow = False, align = "left", xanchor = "left", font = dict(size = 13, color = "#242526") ) # add y axis labels manually for label in df_xaxis_labels["category_name"].tolist(): df_xaxis = df_xaxis_labels.loc[df_xaxis_labels["category_name"] == label].copy() fig.add_annotation(text = label, xref = "paper", yref = df_xaxis["yref"].tolist()[0], x = 0, y = label, showarrow = False, align = "right", xanchor = "right", font = dict(size = 11, color = df_xaxis["color"].tolist()[0]) ) # add y axis title fig.add_annotation(text = "Product Category", xref = "paper", yref = "paper", x = -0.095, y = 1.06, showarrow = False, align = "left", xanchor = "left", font = dict(size = 11) ) # add title manually fig.add_annotation(text = '<span style="color:#2471A3">Mobiles & Tablets</span> Experienced Largest Sales Growth...', xref = "paper", yref = "paper", x = -0.095, y = 1.37, showarrow = False, align = "left", xanchor = "left", font = dict(size = 18, color = "#242526") ) # add sub title fig.add_annotation(text = "E-commerce data from various merchants in Pakistan", xref = "paper", yref = "paper", x = -0.095, y = 1.315, showarrow = False, align = "left", xanchor = "left", font = dict(size = 11) ) #add in commentary fig.add_annotation(text = '...year-on-year in Q3 2018 at <span style="color:#2471A3">+&#8377;9.5M</span> (<span style="color:#2471A3">+28%</span>). The entire growth was driven by a significant increase in the avg RSP YoY (<span style="color:#2471A3">+356%</span>). ' + 'Between Q3 2017 and 2018, two notable changes in the <span style="color:#2471A3">Mobiles & Tablets</span> category <br>impacted the avg RSP. The first one being a severe reduction in the range of products sold, dropping from 6k to 2.2k. The second notable change was a significant move into higher price point items with 9.2% of <br>products sold above the &#8377;40k price point in Q3 2018 compared to only 0.4% in Q3 2017.', xref = "paper", yref = "paper", x = -0.095, y = 1.255, showarrow = False, align = "left", xanchor = "left", font = dict(size = 13, color = "#242526")) #add author of the graph fig.add_annotation(text = "Author: Tom Price", xref = "paper", yref = "paper", x = 1.005, y = -0.11, showarrow = False, font = dict(size = 11), align = "right", xanchor = "right") #add the data source of the graph fig.add_annotation(text = "Data Source: kaggle.com", xref = "paper", yref = "paper", x = -0.095, y = -0.11, showarrow = False, font = dict(size = 11), align = "left", xanchor = "left") fig.show()
ad395106bc1da74199adb7776213842c504f7787
embarced/micro-moves
/modules/chess-diagrams/draw.py
4,961
3.734375
4
import PIL.Image import PIL.ImageDraw import PIL.ImageFont SQUARE_SIZE = 32 BORDER_SIZE = int(SQUARE_SIZE / 2) BOARD_SIZE = int(SQUARE_SIZE * 8 + 2 * BORDER_SIZE) BOARD_COLOR_LIGHT = 'white' BOARD_COLOR_DARK = 'lightgray' BOARD_COLOR_BORDER = 'darkgray' BOARD_COLOR_KEY = 'white' FONT_PATH = 'fonts/' FONT_FILENAME = 'arial.ttf' IMAGE_PATH = 'images/pieces/32' ALL_PIECES = ( 'bb', 'bk', 'bn', 'bp', 'bq', 'br', 'wb', 'wk', 'wn', 'wp', 'wq', 'wr') piece_images = {} for piece in ALL_PIECES: filename = IMAGE_PATH + '/' + piece + '.png' image = PIL.Image.open(filename) piece_images[piece] = image def create_image (width, height, color='white'): """ Creates an empty image. :param width: image width :param height: image height :param color: background color :return: the image """ image = PIL.Image.new("RGBA", (width, height), color) return image def draw_board (image, square_size, start_x, start_y, light=BOARD_COLOR_LIGHT, dark=BOARD_COLOR_DARK): """ Draw a checkered 8x8 chess board into a given images. :param image: target image :param square_size: size of a single square (width and height) :param start_x: x position of upper left corner of board :param start_y: y position of upper left corner of board :param light: light square color :param dark: dark square color """ img_draw = PIL.ImageDraw.Draw(image) x = 0 y = 0 for square in range(64): rect = (start_x + x * square_size, start_y + y * square_size, start_x + x * square_size + square_size, start_y + y * square_size + square_size) if (x+y) % 2 == 0: img_draw.rectangle(rect, fill=light) else : img_draw.rectangle(rect, fill=dark) x += 1 if x == 8: y += 1 x = 0 return image def draw_key(image, square_size, start_x, start_y): """ Draw a key (a..h, 1..8) for the squares into a given images. :param image: target image :param square_size: size of a single square (width and height) :param start_x: x position of upper left corner of board :param start_y: y position of upper left corner of board """ font_size = int(square_size / 2.5) font_dy = int((start_y - font_size) / 2) font_dx = int((start_x - font_size/2)/2) font = PIL.ImageFont.truetype(FONT_PATH + FONT_FILENAME, font_size) img_draw = PIL.ImageDraw.Draw(image) rank_names = "87654321" pos_x_1 = font_dx pos_x_2 = font_dx + 8.5 * square_size pos_y = start_y + int(square_size / 6) for rank in rank_names: img_draw.text((pos_x_1, pos_y), rank, font=font, fill=BOARD_COLOR_KEY) img_draw.text((pos_x_2, pos_y), rank, font=font, fill=BOARD_COLOR_KEY) pos_y += square_size file_names = "abcdefgh" pos_x = start_x + int (square_size/4) + font_dx pos_y_1 = font_dy pos_y_2 = start_y + 8 * square_size + font_dy for file in file_names: img_draw.text((pos_x, pos_y_1), file, font=font, fill=BOARD_COLOR_KEY) img_draw.text((pos_x, pos_y_2), file, font=font, fill=BOARD_COLOR_KEY) pos_x += square_size def piece_image_for_letter(c): """ Return a graphic representation for the given piece. 'K' is a white king, 'p' is a black pawn (lower case means black) :param c: :return: the image for the piece """ if c.islower(): piece = 'b' + c else: piece = 'w' + c.lower() return piece_images.get(piece) def draw_pieces(image, square_size, start_x, start_y, pieces): """ Draws chess pieces into a given image. :param image: target image :param square_size: size of a single square (width and height) :param start_x: x position of upper left corner of board :param start_y: y position of upper left corner of board :param pieces: pieces on the bord (1st FEN group) """ ranks = pieces.split('/') rank_no = 0 file_no = 0 for rank in ranks: for character in rank: if character.isdigit(): file_no += int(character) else: piece_image = piece_image_for_letter(character) pos = (start_x + square_size * file_no, start_y + square_size * rank_no) image.paste(piece_image, pos, piece_image) file_no += 1 rank_no += 1 file_no = 0 def draw_diagram_for_fen(fen): """ Creates an image for the given FEN position. :param fen: game position in FEN notation as string """ image = create_image(BOARD_SIZE, BOARD_SIZE, color=BOARD_COLOR_BORDER) draw_board(image, SQUARE_SIZE, BORDER_SIZE, BORDER_SIZE, light=BOARD_COLOR_LIGHT, dark=BOARD_COLOR_DARK) draw_key(image, SQUARE_SIZE, BORDER_SIZE, BORDER_SIZE) fen_groups = fen.split(" ") pieces = fen_groups[0] draw_pieces(image, SQUARE_SIZE, BORDER_SIZE, BORDER_SIZE, pieces) return image
5390daf4169e82d71c1fa59a7ae42aa706fd7681
OnyiegoAyub/SENDIT-API
/app/api/v1/models/user_models.py
627
3.5
4
class User: users = [] def create(self, username, role, email, password): new_user = {"user_id": len(User.users) + 1, "username": username, "role": role, "email":email, "password":password } User.users.append(new_user) # save user """ get single user """ def get_all_users(self): return User.users def get_one_users(self, user_id): for one_user in User.users: if one_user['user_id'] == "user_id": return one_user return False
e13cc147ffdbc71ac3b178974cfc8cf1e9b9f54d
Tonoyama/2020AB
/regular/112/a.py
237
3.5
4
from typing import List, Dict T = int(input()) case: List[int] = [list(map(int, input().split())) for _ in range(T)] for i in range(T): R: List[int] = case[i][1] L: List[int] = case[i][0] for j in range(R): print(j)
e2c6e14a312b34b85b6e5f65f01ff0b5642ad418
GioPan04/tools
/resistenze.py
1,214
3.71875
4
from tabulate import tabulate COLORS = ['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'purple', 'grey', 'white', 'gold', 'silver'] TOLL = { 'gold': 5.0, 'silver': 10.0, 'brown': 1.0, 'red': 2.0, 'orange': 3.0, 'green': 0.5, 'blue': 0.25, 'purple': 0.1, 'grey': 0.05, } HEADER = ['Colors', 'Result', 'Tolleranza', 'Tot OHM', 'Min OHM', 'Max OHM'] def calculate(colorList): result = '' colorList.reverse() tolleranza = TOLL[colorList[0]] moltiplic = colorList[1] colorList.reverse() moltiplic = COLORS.index(moltiplic) colorList.pop() colorList.pop() for color in colorList: result += str(COLORS.index(color)) result = int(result) value = result * (10 ** moltiplic) totOhm = (value / 100) * tolleranza table = [[', '.join(colorList), value, str(tolleranza) + '%', totOhm, value - totOhm, value + totOhm]] print(tabulate(table, HEADER, tablefmt="pretty")) if __name__ == "__main__": res = input('Write the colors in order separated by a space: ') resColors = res.split(' ') if not all(elem.lower() in COLORS for elem in resColors): print('A color is not allowed') exit(1) if not len(resColors) >= 3: print('Not enough colors') exit(1) calculate(resColors)
cc9dcf38f7b7285a08d4a92b894ea9b7ee103ea8
DEEPESH98/Basic_Python_Programs
/reverse_string.py
779
3.953125
4
''' Given a string S, check if it is palindrome or not. Input: The first line contains 'T' denoting the number of test cases. T testcases follow. Each testcase contains two lines of input. The first line contains the length of the string and the second line contains the string S. Output: For each testcase, in a new line, print "Yes" if it is a palindrome else "No". (Without the double quotes) Constraints: 1 <= T <= 30 1 <= N <= 100 Example: Input: 1 4 abba Output: Yes ''' def reverse(b): str = "" for i in b: str = i + str return str a=int(input()) b=[] c=[] for i in range(0,a): d=int(input()) x=input() b.append(x) c.append(reverse(x)) for i in range(0,a): if c[i]==b[i]: print('Yes') else: print('No')
0d5ba0b5e7961f60e977a9f0f476ad6da232dfdb
MAHESHRAMISETTI/My-python-files
/mon.py
506
4.0625
4
num1=int(input('enter a numb\t')) num2=int(input('enter a number\t')) print(type(num1)) print(type(num2)) print(num1+num2) num=int(input('enter a number\t')) if num%2==0: print(num,'is an even number') else: print(num,'is an odd number') num=int(input('enter a number\t')) if num>=0: if num==0: print('zero num') else: print(''+ ve) else: print('- ve') num=int(input('enter a number\t')) if num>=0: if num==0: print('zero num') else: print(''+ ve) else: print('- ve')
757561a712817637e4ed8606863076259be38ece
MAHESHRAMISETTI/My-python-files
/time.py
311
3.609375
4
# num=int(input('enter the value')) # for a in range (1,11): # print(num,'x',a,'=',num*a) # import time # print(dir(time)) # print(time.asctime()) # import math # print(dir(math)) # print(math.factorial(5)) import calendar # print(dir(calendar)) print(calendar.calendar(2018,8)) # # print('dasdasd')
4471df91a50681366a7f8d154aa5815a71bfb82b
goussous0/old_scripts
/iterexample.py
696
3.71875
4
from itertools import product def gen_sets(set1, set2): x1 = len(set1) y1 = len(set2) tmp_lst = [] for item in set1: x = set1.index(item) set1[x]=int(item) for item in set2: x = set2.index(item) set2[x]=int(item) ## reverse the places of the set1 and set2 to get the right result ## output should be as a tuple not as a list for i in range (y1): tmp_lst.append(set2[i]) tmp =list(product(set1,tmp_lst)) for item in tmp: print (item, end=" ") return if __name__ == '__main__': set1 = input().split() set2 = input().split() gen_sets(set1, set2)
858422c01e9d9390216773f08065f38a124cb579
monicaneill/PythonNumberGuessingGame
/guessinggame.py
1,724
4.46875
4
#Greetings print("Hi there! Welcome to Monica's first coding project, 'The Python Number Guessing Game'!") print("Let's see if you can guess the number in fewer steps than the computer openent. Let's begin!") #Computer Function def computerGuess(lowval, highval, randnum, count=0): if highval >= lowval: guess = lowval + (highval - lowval) // 2 # If guess is in the middle, it is found if guess == randnum: return count #If 'guess' is greater than the number it must be #found in the lower half of the set of numbers #between the lower value and the guess. elif guess > randnum: count = count + 1 return computerGuess(lowval, guess-1, randnum, count) #The number must be in the upper set of numbers #between the guess and the upper value else: count + 1 return computerGuess(guess + 1, highval, randnum, count) else: #Number not found return -1 #End of function #Generate a random number between 1 and 100 import random randnum = random.randint(1,101) count = 0 guess = -99 while (guess != randnum): #Get the user's guess guess = (int) (input("Enter your guess between 1 and 100:")) if guess < randnum: print("You need to guess higher") elif guess > randnum: print("Not quite! Try guessing lower") else: print("Congratulations! You guessed right!") break count = count + 1 #End of while loop print("You took " + str(count) + " steps to guess the number") print("The computer guessed it in " + str(computerGuess(0,100, randnum)) + " steps")
6b23ea66355b94f81be58d2bd546499225c173fa
peterhchen/800_MachineLearning
/09_feature_selection/01_UnivarSelection.py
1,108
3.5625
4
# Univariable Selection from pandas import read_csv from numpy import set_printoptions from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 path = r'..\csv_data\pima-indians-diabetes.csv' headernames = ['preg', 'glucos', 'pres', 'skin', 'insulin', 'mass', 'diabetes', 'age', 'class'] dataframe = read_csv (path, skiprows=9, names = headernames) array = dataframe.values # separate array into input X and output Y X = array[:, 0:8] # 0 .. 7 Y = array[:, 8] # 8: class # Select the best features form dataset # select teh best fit feature = 2 out of 8 features test = SelectKBest (score_func=chi2, k=2) fit = test.fit(X, Y) # set precision = 2 set_printoptions(precision=1) print("\nX.shape\n", X.shape) # (768,8) print("\nX:\n", X[0:5, 0:8]) print("\nY.shape:\n", Y.shape) # (768,) print("\nY[:10]:\n", Y[0:5]) print("\nfit.scores_\n", fit.scores_) # R^2 score of each column # transform: calc mean and fill missing data featured_data = fit.transform (X) print("\nFeatured data:\n", featured_data[0:5]) # display 2 features x 0..5
0a517656681efc1b179ca047ed54e2e210567824
tnaswin/PythonPractice
/Aug18/recursive.py
406
4.21875
4
def factorial(n): if n <= 1: return 1 else: return n * (factorial(n - 1)) def fibonacci(n): if n <= 1: return n else: return (fibonacci(n - 1) + (fibonacci(n - 2))) n = int(raw_input("Enter a number: ")) if n <= 0: print("Plese enter a positive integer") else: print "Factorial: ", factorial(n) print "Fibonacci: ", for i in range(n): print(fibonacci(i)),
75049954b1f4fdaf4acf1d414e3e57ba942e256e
tnaswin/PythonPractice
/Aug17/files.py
408
3.578125
4
my_list = [i ** 2 for i in range(1, 11)] my_file = open("text.txt", "w") for item in my_list: my_file.write(str(item) + "\n") my_file.close() ### my_file = open("text.txt", "r") print my_file.readline() print my_file.readline() print my_file.readline() my_file.close() with open("text.txt", "w") as my_file: my_file.write("My Data!") if not file.closed: file.close() print my_file.closed
71d2b99011c006646b6fe9d40fb0a8ffc162bf05
aisaav/ML-mini-projects
/Forest-Fire-Forecast/Module4.py
3,339
3.6875
4
import numpy import pandas from matplotlib import pyplot as plt # region Making Printing more visible from pandas.plotting import scatter_matrix pandas.set_option('display.max_columns', None) pandas.set_option('display.max_rows', None) # endregion # region Loading Our Data filename = 'forestfires.csv' names = ['X', 'Y', 'month', 'day', 'FFMC', 'DMC', 'DC', 'ISI', 'temp', 'RH', 'wind', 'rain', 'area'] df = pandas.read_csv(filename, names=names) # endregion # region Analyzing Our Data # outputs shape of our data- data dimensions (records x columns) print("**************Data Shape**************") print(df.shape) # tells us what are the underlying data types are in our dataframe # note: pandas interprets strings as objects print("**************Data Types**************") print(df.dtypes) # shows the head of our data- specifically one record print("**************Inspecting the head of the data**************") print(df.head(1)) # as month and day are not numerical values its good practice to replace with numerical values- known as encoding df.month.replace(('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), inplace=True) df.day.replace(('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'), (1, 2, 3, 4, 5, 6, 7), inplace=True) print("**************Inspecting the head of the data after replacement**************") print(df.head(1)) print("**************Data Types Again**************") print(df.dtypes) # shows descriptive statistics about our data - shows stats for all columns of the data # stats shown: count, mean, std, min, 25-percentile, 50-percentile, 75-percentile, max # be careful with month & day stats as they were originally categorical data that we have encoded print("**************Data Stats**************") print(df.describe()) # shows us metrics for correlations among the data- we use this to determine what algorithm best fits our data # intersection btw columns and rows gives us linear correlation among variables, disregard correlations on encoded data print("**************Correlation**************") print(df.corr(method='pearson')) # endregion # region Visualzing Our data # region Univariant # histograms df.hist(sharex=False, sharey=False, xlabelsize=3, ylabelsize=3) plt.suptitle("Histograms", y=1.00, fontweight='bold') plt.show() # density df.plot(kind='density', subplots=True, layout=(4, 4), sharex=False, fontsize=8) plt.suptitle("Density", y=1.00, fontweight='bold') plt.show() # box and whisker plots df.plot(kind='box', subplots=False, layout=(4, 4), sharex=False, sharey=False, fontsize=12) plt.suptitle("Box and Whisker", y=1.00, fontweight='bold') plt.show() # endregion # region Bivariant # scatter plot matrix scatter_matrix(df) plt.suptitle("Scatter Matrix", y=1.00, fontweight='bold') plt.show() # correlation matrix fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(df.corr(), vmin=-1, vmax=1, interpolation='none') fig.colorbar(cax) ticks = numpy.arange(0, 13, 1) ax.set_xticks(ticks) ax.set_yticks(ticks) ax.set_xticklabels(names) ax.set_yticklabels(names) plt.suptitle("Correlation Matrix", y=1.00, fontweight='bold') plt.show() # endregion # endregion
0c47ce184534d698be92f724929ae23e17976754
yiclwh/System-Design
/7_1_1_Geohash II.py
1,440
3.640625
4
""" This is a followup question for Geohash. Convert a Geohash string to latitude and longitude. Try http://geohash.co/. Check how to generate geohash on wiki: Geohash or just google it for more details. Example Given "wx4g0s", return lat = 39.92706299 and lng = 116.39465332. Return double[2], first double is latitude and second double is longitude. """ class GeoHash: """ @param: geohash: geohash a base32 string @return: latitude and longitude a location coordinate pair """ def decode(self, geohash): # Write your code here _base32 = "0123456789bcdefghjkmnpqrstuvwxyz" b = "" for c in geohash: b += self.i2b(_base32.find(c)) odd = ''.join([b[i] for i in range(0, len(b), 2)]) even = ''.join([b[i] for i in range(1, len(b), 2)]) location = [] location.append(self.get_location(-90.0, 90.0, even)) location.append(self.get_location(-180.0, 180.0, odd)) return location def i2b(self, val): b = "" for i in range(5): if val % 2: b = '1' + b else: b = '0' + b val //= 2 return b def get_location(self, start, end, string): for c in string: mid = (start + end) / 2.0 if c == '1': start = mid else: end = mid return (start + end) / 2.0
235b284c39e646997ba74bc4d7ac2539bd07786f
yiclwh/System-Design
/2_1_2_Memcache.py
3,856
4.0625
4
""" Implement a memcache which support the following features: 1. get(curtTime, key). Get the key's value, return 2147483647 if key does not exist. 2. set(curtTime, key, value, ttl). Set the key-value pair in memcache with a time to live (ttl). The key will be valid from curtTime to curtTime + ttl - 1 and it will be expired after ttl seconds. if ttl is 0, the key lives forever until out of memory. 3. delete(curtTime, key). Delete the key. 4. incr(curtTime, key, delta). Increase the key's value by delta return the new value. Return 2147483647 if key does not exist. 5. decr(curtTime, key, delta). Decrease the key's value by delta return the new value. Return 2147483647 if key does not exist. It's guaranteed that the input is given with increasingcurtTime. Clarification Actually, a real memcache server will evict keys if memory is not sufficient, and it also supports variety of value types like string and integer. In our case, let's make it simple, we can assume that we have enough memory and all of the values are integers. Search "LRU" & "LFU" on google to get more information about how memcache evict data. Try the following problem to learn LRU cache: http://www.lintcode.com/problem/lru-cache Example get(1, 0) >> 2147483647 set(2, 1, 1, 2) get(3, 1) >> 1 get(4, 1) >> 2147483647 incr(5, 1, 1) >> 2147483647 set(6, 1, 3, 0) incr(7, 1, 1) >> 4 decr(8, 1, 1) >> 3 get(9, 1) >> 3 delete(10, 1) get(11, 1) >> 2147483647 incr(12, 1, 1) >> 2147483647 """ class Node: def __init__(self, v, e): self.value = v self.exp_time = e class Memcache: def __init__(self): # do intialization if necessary self.errorValue = 2147483647 self.map = {} """ @param: curtTime: An integer @param: key: An integer @return: An integer """ def get(self, curtTime, key): # write your code here if key not in self.map: return self.errorValue v = self.map[key].value e = self.map[key].exp_time if e != 0 and e < curtTime: return self.errorValue else: return v """ @param: curtTime: An integer @param: key: An integer @param: value: An integer @param: ttl: An integer @return: nothing """ def set(self, curtTime, key, value, ttl): # write your code here exp_time = curtTime + ttl - 1 if ttl == 0: exp_time = 0 n = Node(value, exp_time) self.map[key] = n """ @param: curtTime: An integer @param: key: An integer @return: nothing """ def delete(self, curtTime, key): # write your code here if key in self.map: del self.map[key] """ @param: curtTime: An integer @param: key: An integer @param: delta: An integer @return: An integer """ def incr(self, curtTime, key, delta): # write your code here if key not in self.map: return self.errorValue v = self.map[key].value e = self.map[key].exp_time if e != 0 and e < curtTime: return self.errorValue else: n = Node(v + delta, e) self.map[key] = n return v + delta """ @param: curtTime: An integer @param: key: An integer @param: delta: An integer @return: An integer """ def decr(self, curtTime, key, delta): # write your code here if key not in self.map: return self.errorValue v = self.map[key].value e = self.map[key].exp_time if e != 0 and e < curtTime: return self.errorValue else: n = Node(v - delta, e) self.map[key] = n return v - delta
38c175384378c0872e846afc2f625e596dbcc0cd
nadahalli/algorithm-puzzles
/heapsort.py
791
3.546875
4
a = [1, 10, 15, 20] b = [2, 3, 5, 10, 11, 14] c = [100] d = [10, 20, 30, 40, 50] e = [1, 2, 3, 4, 5, 6, 7, 8] arr = [a, b, c, d, e] def heapify(arr, i, n): left = 2 * i right = 2 * i + 1 large = None if left < n and arr[left] > arr[i]: large = left else: large = i if right < n and arr[right] > arr[large]: large = right if large != i: arr[i], arr[large] = arr[large], arr[i] heapify(arr, large, n) x = [10, 11, 12, 2, 3, 4, 100, 120, 40] def make_heap(arr): i = (len(arr) - 1) / 2 while i >= 0: heapify(x, i, len(arr)) i -= 1 def heap_sort(arr): make_heap(arr) for i in range(len(arr)): n = len(arr) - i - 1 arr[0], arr[n] = arr[n], arr[0] heapify(arr, 0, n)
35844bacab782c0d4e39c65c5aadf4f85c542723
nadahalli/algorithm-puzzles
/mergesort.py
761
3.84375
4
def mergesort(a, b, start, end): if start + 1 == end: return else: mid = (start + end)/2 mergesort(a, b, start, mid) mergesort(a, b, mid, end) i = start j = mid k = start while i < mid and j < end: if a[i] < a[j]: b[k] = a[i] i += 1 else: b[k] = a[j] j += 1 k += 1 if i == mid: tailstart = j tailend = end else: tailstart = i tailend = mid while tailstart < tailend: b[k] = a[tailstart] k += 1 tailstart += 1 for i in range(start, end): a[i] = b[i] a = [10, 11, 8, 0, 1, 2, 9, 4] b = [-1 for i in range(len(a))] mergesort(a, b, 0, len(a)) print a
efb37f6b9022f9476258753e835768075e989a56
nadahalli/algorithm-puzzles
/manual_stack_recursions.py
733
3.84375
4
from collections import deque def factorial(n): stack = deque() stack.appendleft(n) fact = 1 while len(stack): i = stack.popleft() if i == 0: fact *= 1 break fact *= i stack.appendleft(i - 1) return fact print factorial(5) def binsearch(a, i, j, x): stack = deque() stack.appendleft((i, j)) while len(stack): i, j = stack.popleft() if i >= j: return -1 mid = (i + j) / 2 if a[mid] == x: return mid if x > a[mid]: stack.appendleft((mid + 1, j)) else: stack.appendleft((i, mid)) a = [1, 2, 3, 4, 5, 6, 7, 8] print binsearch(a, 0, len(a), 10)
0e5c69430dcddf93721e19e55a54d131394ca452
montoyamoraga/nyu-itp
/reading-and-writing-electronic-text/classes/class_02/cat.py
2,211
4.125
4
# import sys library import sys # this is a foor loop #stdin refers to the lines that are input to the program #typical python styling is indenting with four spaces for line in sys.stdin: #strip() removes whitespace at the end of the line #strip() is a method of a line object line = line.strip() if "you" in line: #print prints to the console print line # python follows the pemdas order of precedence ## stands for parenthesis, exponents, multiplication, addition, substraction #this is a string variable tofu = "delicious" #this is for printing it to the screen #notice that this it doesn't include quotes print tofu #to check the length of the string, use len() print len("ok thx bye") #operator in has two arguments, one to the left and one to the right #it returns True if the string on the left can be found on the one to the right #and False otherwise print "foo" in "buffoon" print "foo" in "reginald" #strings have the method startswith that returns True or False #if the string on the argument is found on the original string #it is case-sensitive print "tofu".startswith("to") print "tofu".startswith("soy") #ther is an analog method called endswith, to check for endings print "tofu".endswith("fu") print "tofu".endswith("soy") #the find() method looks for a string inside of another string #it returns the position in the string where it found the first match #return -1 if nothing is found print "tofu".find("u") print "tofu".find("x") #the lower() method evaluates to lowercase and upper() to uppercase #they don't change the original value, they return the evaluated value #most python functionalities don't affect the original one #there is also titlecase, with method title() print "tofu is awesome".lower() print "tofu is awesome".upper() print "tofu is awesome".title() # the strip() method removes at beginning and end print " t o f u yeah ".strip() #the replace method replaces the first argument for the second argument #in the original string, print "what up, this is weird weird oh no".replace("i", "o"); #string indexing #you can access subsets of the strings with [i:j] #where i and j stand from ith to (j-1)th character
47c9f72baa7577f726046a80f338e40fd199bb61
montoyamoraga/nyu-itp
/reading-and-writing-electronic-text/assignments/assignment_04/this.py
2,031
4.1875
4
#assignment 04 #for class reading and writing electronic text #at nyu itp taught by allison parrish #by aaron montoya-moraga #february 2017 #the digital cut-up, part 2. write a program that reads in and creatively re-arranges the content of several source texts. what is the unit of your cut-up technique? (the word, the line, the character? something else?) how does your procedure relate (if at all) to your choice of source text? feel free to build on your assignment from last week. your program must make use of at least one set or dictionary. choose one text that you created with your program to read in class. #my program takes two texts, lyrics for two different songs (javiera plana's invisible and flaming lips' bad days) and remixes them taking different random words from each of them, producing #import sys, random and string module from os import system import random import string # read files text01 = open("./text_original_01.txt").read() text02 = open("./text_original_02.txt").read() #split the texts in lists with all of the words list01 = text01.split() list02 = text02.split() #construct a set of every word in the texts set01 = set() set02 = set() for word in list01: set01.add(word) for word in list02: set02.add(word) #construct a dictionary with words as keys and number of times in values dict01 = dict() dict02 = dict() for word in list01: if word in dict01: dict01[word] += 1 else: dict01[word] = 1 for word in list02: if word in dict02: dict02[word] += 1 else: dict02[word] = 1 for i in range(10): #empty string for the current line currentLine = "" #make a random decision decision = random.randint(1,2) if decision == 1: word = random.choice(dict01.keys()) for i in range(dict01[word]): currentLine = currentLine + word + " " elif decision == 2: word = random.choice(dict02.keys()) for i in range(dict02[word]): currentLine = currentLine + word + " " print currentLine
3c662f42d4491fe70972bb45bb28cdc9668ba90a
littleironical/HackerRank_Solutions
/Python/Text Wrap.py
304
3.8125
4
import textwrap def wrap(string, max_width): for i in range(0, len(string), max_width): newLine = [string[i:i+max_width]] print(newLine[0]) return "" if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
c77eea14ca502183ed0b6eb51e7e8c01041384b3
littleironical/HackerRank_Solutions
/Python/Lists.py
597
3.515625
4
n = int(input()) lis = [] temp1, temp2 = 0, 0 for _ in range(n): line = input().split() if line[0] == "print": print(lis) elif line[0] == "sort": lis.sort() elif line[0] == "pop": lis.pop() elif line[0] == "reverse": lis.reverse() elif line[0] == "append": temp1 = int(line[1]) lis.append(temp1) elif line[0] == "remove": temp1 = int(line[1]) lis.remove(temp1) else: temp1 = int(line[1]) temp2 = int(line[2]) lis.insert(temp1, temp2) temp1 = 0 temp2 = 0 line = ""
393e43f1550a44dc57f3527e5665a7b5db4e9097
VelmirS/lesson2
/while1.py
585
4.0625
4
""" Домашнее задание №1 Цикл while: ask_user * Напишите функцию ask_user(), которая с помощью input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” """ def ask_user(): while True: user_input = input('Как дела?\n') if user_input == 'Хорошо': return ('Если у вас все хорошо, то это супер. Прекрасного дня!') break result_ask = ask_user() print(result_ask)
e7f50e19dbf531b0af4ae651759d714278aac06b
ribeiroale/rita
/rita/example.py
498
4.21875
4
def add(x: float, y: float) -> float: """Returns the sum of two numbers.""" return x + y def subtract(x: float, y: float) -> float: """Returns the subtraction of two numbers.""" return x - y def multiply(x: float, y: float) -> float: """Returns the multiplication of two numbers.""" return x * y def divide(x: float, y: float) -> float: """Returns the division of two numbers.""" if y == 0: raise ValueError("Can not divide by zero!") return x / y
048180879cef5c8d0b4ae185904d72a836d195f0
Dhinessplayz/Python
/chess/minimax.py
2,716
4
4
import random class MinimaxState(object): """ Abstract base class of game states suitabe for minimax. Games that fit this model have two players, and a set of terminal states with well-defined values. One player tries to minimize the final value (min), and one tries to maximize it (max). The game state includes the player whose turn it is. Each nonterminal state has a set of moves that can be taken by the player whose turn it is, and each move deterministically results in a new game state. """ def __init__(self): raise NotImplementedError def value(self): """ Get the value of a state. Returns the final score corresponding to this state if it's terminal, or a heuristic estimate if not. """ raise NotImplementedError def moves(self): raise NotImplementedError def do(self, move): raise NotImplementedError def is_terminal(self): raise NotImplementedError MAX = 1 MIN = -1 def minimax(state, player=MAX, maxdepth=-1): """ Return a (value, move) tuple representing the action taken by player. """ better = max if player == MAX else min results = [] for move, result in state.moves(): # result = state.do(move) if maxdepth == 0 or result.is_terminal(): results.append((result.value(), move)) else: value = minimax(result, player=(-player), maxdepth=(maxdepth - 1))[0] results.append((value, move)) random.shuffle(results) best = better(results, key=(lambda a: a[0])) return best # The alpha-beta pruning function will only work with chess # due to the generate_legal_moves method. def max_value(state, alpha, beta, depth, player): if state.is_terminal() or depth == 0: return (None, state.value()) v = float("-inf") * player best = None worse = (lambda a, b: a < b) if (player == MAX) else (lambda a, b: a > b) for move in state.generate_legal_moves(): state.push(move) _, result = max_value(state, alpha, beta, (depth-1), -player) state.pop() if result is not None and worse(v, result): v = result best = move if not worse(v, beta if player == MAX else alpha): return (move, v) if worse(alpha, v) and player == MAX: alpha = v if worse(beta, v) and player == MIN: beta = v return (best, v) def alphabeta(state, player=MAX, maxdepth=6): v, move = max_value(state, float("-inf"), float("inf"), maxdepth, player) return move, v
ed6df28cd4ffe946d3e4cb93f856b9f0f93e2cb6
NritiNy/AdventOfCode2020
/Day01.py
910
3.609375
4
#!/usr/bin/python import sys def part1(): with open(filename, "r") as f: lines = f.readlines() numbers = [int(str(line).strip()) for line in lines] for i in range(len(numbers)-2): for j in range(i+1, len(numbers)-1): if numbers[i] + numbers[j] == 2020: return (numbers[i] * numbers[j]) def part2(): with open(filename, "r") as f: lines = f.readlines() numbers = [int(str(line).strip()) for line in lines] for i in range(len(numbers)-2): for j in range(i+1, len(numbers)-1): for k in range(j+1, len(numbers)): if numbers[i] + numbers[j] + numbers[k] == 2020: return (numbers[i] * numbers[j] * numbers[k]) if __name__ == "__main__": filename = sys.argv[1] print(f"Part 01: {part1()}") print(f"Part 02: {part2()}")
a3d5fb2f9f597dc7e0cab5691a5a4bbd4cc4a964
rohankokkula/streamlit-sandbox
/python-scripts/hello-streamlit-world.py
543
3.84375
4
# Angelo's first python script in Spyder import streamlit as st # To make things easier later, we're also importing numpy and pandas for # working with sample data. st.title('LiRA - The Linear Regression App') st.header('H1') st.write("Hello Streamlit World") st.write('To start with we will simulate a Linear Function which will be used to generate our data. In order to do so please select the number of samples:') # Number of Samples n = st.slider('Number of samples', 50, 100) st.write("The number of data points generated will be", n)
299cc5fc729fef69fea8e96cd5e72344a1aa3e12
voyeg3r/dotfaster
/algorithm/python/getage.py
1,075
4.375
4
#!/usr/bin/env python3 # # -*- coding: UTF-8 -*-" # ------------------------------------------------ # Creation Date: 01-03-2017 # Last Change: 2018 jun 01 20:00 # this script aim: Programming in Python pg 37 # author: sergio luiz araujo silva # site: http://vivaotux.blogspot.com # twitter: @voyeg3r # ------------------------------------------------ """ One frequent need when writing interactive console applications is to obtain an integer from the user. Here is a function that does just that: This function takes one argument, msg . Inside the while loop the user is prompt- ed to enter an integer. If they enter something invalid a ValueError exception will be raised, the error message will be printed, and the loop will repeat. Once a valid integer is entered, it is returned to the caller. Here is how we would call it: """ def get_int(msg): while True: try: i = int(input(msg)) return i except ValueError as err: print(err) age = get_int("Enter your age ") print("Your age is", age)
00c75c7761a99938db0045e90ef7b8228a83fa45
TonySteven/Python
/upper.py
375
3.578125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2018/7/27 10:40 # @Author : StevenL # @Email : stevenl365404@gmail.com # @File : UUID.py a = input("请输入字符:") b = [] for n in a : if "a"<= n <= "z": b.append(n.upper()) # elif"A" <= n <= "Z" : # b.append(n.lower()) elif n == " " : b.append('_') else: b.append(n) print("".join(b))
099a230b32ffd60a2d1b8c2732ba7ba7ba162b50
jesadrperez/Fundamentals-of-Computing
/An Introduction to Interactive Programming in Python/Mini-project #2 - Guess the Number.py
2,505
4.0625
4
#http://www.codeskulptor.org/#user42_umEoHc2oUY_7.py import random import simplegui num_range = 100 remaining = 7 def set_remaining(): global num_range global remaining if num_range == 100: remaining = 7 else: remaining = 10 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global secret_number global guess global num_range global remaining set_remaining() secret_number = random.randrange(0, num_range) print '' print "New Game Started!" print " Range Set to", str(num_range)+'.' print " You have", str(remaining), "guesses remaining." # remove this when you add your code #pass # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global num_range global remaining remaining = 7 num_range = 100 new_game() # remove this when you add your code #pass def range1000(): # button that changes the range to [0,1000) and starts a new game global num_range global remaining remaining = 10 num_range = 1000 new_game() #pass def input_guess(guess): # main game logic goes here global secret_number global remaining remaining -= 1 print " Guess was", guess guess = int(guess) if guess == secret_number: print "****You Win!****" new_game() elif guess > secret_number: print " Guess Lower" print " You have", str(remaining), "guesses remaining." else: print " Guess Higher" print " You have", str(remaining), "guesses remaining." if remaining == 0: print " Secret Number was", str(secret_number) print "****You Lose!****" new_game() # remove this when you add your code #pass # create frame frame = simplegui.create_frame('Guessing game', 200, 200) frame.add_button('New Game', new_game, 100) frame.add_button('Range is [0,100)', range100, 100) frame.add_button('Range is [0,1000)', range1000, 100) frame.add_input('Guess:', input_guess, 50) # register event handlers for control elements and start frame frame.start() # call new_game new_game() # always remember to check your completed program against the grading rubric
a2b3e4e9aadfb289399d5ed98fae73126a77aa23
jesadrperez/Fundamentals-of-Computing
/Algorithmic Thinking/Project-1.py
3,566
4.40625
4
''' Python code that creates dictionaries corresponding to some simple examples of graphs. Implement two short functions that compute information about the distribution of the in-degrees for nodes in these graphs. ''' # Representing Directed Graphs EX_GRAPH0 = {0:set([1,2]), 1:set([]), 2:set([]) } EX_GRAPH1 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3]), 3:set([0]), 4:set([1]), 5:set([2]), 6:set([]) } EX_GRAPH2 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3,7]), 3:set([7]), 4:set([1]), 5:set([2]), 6:set([]), 7:set([3]), 8:set([1,2]), 9:set([0,3,4,5,6,7]) } #print 'EX_GRAPH0', EX_GRAPH0 #print 'EX_GRAPH1', EX_GRAPH1 #print 'EX_GRAPH2', EX_GRAPH2 def make_complete_graph(num_nodes): ''' Takes the number of nodes and returns a dictionary corresponding to a complete directed graph with the specified number of nodes. ''' if num_nodes == []: return dict([]) else: # creates empty dictonary for storing complete_graph = dict([]) # generates the nodes node_list = range(num_nodes) # loops over nodes and generates path for node in node_list: # creates dummy node list used for paths dummy_node_list = node_list[:] # removes node from dummy_node_list dummy_node_list.remove(node) # saves paths to dict complete_graph[node] = set(dummy_node_list) return complete_graph # Computing degree distributions def compute_in_degrees(digraph): ''' Takes a directed graph (represented as a dictionary) and computes the in-degrees for the nodes in the graph. The function returns a dictionary with the same set of keys (nodes) as whose corresponding values are the number of edges whose head matches a particular node. ''' # Gathers all paths into a single list path_list = [path for path_set in digraph.values() for path in path_set] # Creates dict for storing in degrees by node in_degrees_dict = dict([]) # Loops over nodes for node in digraph.keys(): # Calculates the in degree of node in_degrees_dict[node] = path_list.count(node) return in_degrees_dict def in_degree_distribution(digraph): ''' Takes a directed graph (represented as a dictionary) and computes the unnormalized distribution of the in-degrees of the graph. The function returns a dictionary whose keys correspond to in-degrees of nodes in the graph. The value associated with each particular in-degree is the number of nodes with that in-degree. In-degrees with no corresponding nodes in the graph are not included in the dictionary. ''' # Computes the in_degree of each node in_degrees_dict = compute_in_degrees(digraph) # Gathers all the in_degree values in a list in_degree_list = [in_degree for in_degree in in_degrees_dict.values()] # Finds all the unique in degrees in_degrees = list(set(in_degree_list)) # Creates dict for storing values in_degree_dist_dict = dict([]) # Loops over in degrees for in_degree in in_degrees: # Computes the distribution of in_degree in_degree_dist_dict[in_degree] = in_degree_list.count(in_degree) return in_degree_dist_dict
6f15774dca28c6a77b829fd983f57d46e8f183d1
karinamonetti/curso_universidadPython
/clases.py
2,778
3.78125
4
class Persona: pass # se utiliza para no agregar contenido. print(type(Persona)) # class MiPersona: # def __init__(self): #objeto inicializador # parámetro <--- self.nombre="Karina" ---> atributo # self.edad=26 # self.nacionalidad="ARG" # self.estudios="Universitarios en curso" # persona1= MiPersona() # print(persona1.nombre) #accedo al atributo class Perro: def __init__(self, nombre, edad, raza, dueño, prueba, *args, **kwargs): # *args cuando queremos pasar n atributos y **kwargs cuando queremos pasar un diccionario de valores. self.nombre=nombre # self = this (JS) self.edad=edad self.raza=raza self.dueño=dueño self._prueba=prueba #el _ indica que no se puede modificar fuera de la clase def mostrar_detalle(self): print(f"Perro: Nombre: {self.nombre} Edad: {self.edad} Raza: {self.raza} Dueño/a: {self.dueño} Prueba: {self._prueba}") kimba=Perro("Kimba", 12, "Mestizo","Karina Monetti", "Prueba") # print(kimba.nombre, kimba.edad, kimba.raza, kimba.dueño) kimba.mostrar_detalle() kimba.edad=11 #modificar los atributos print(kimba.edad) ## - sasha=Perro("Sasha", 8,"Mestizo", "Karina Monetti", "Prueba") sasha.glotona=True #le agrego otro atributo pero esta vez sería a la "sub-clase" sasha sasha.mostrar_detalle() print(sasha.glotona) sasha._prueba="Otra cosa" #aunque lo trate de cambiar no cambia. # -- métodos GET (para obtener/recuperar atributos) y SET (para colocar/modificar atributos) class Localidad: def __init__(self, nombre, provincia, pais, cantidadDeHabitantes): self._nombre=nombre self._provincia=provincia self._pais=pais self._cantidadDeHabitantes=cantidadDeHabitantes @property #GET: con property puedo acceder al atributo sin necesidad de llamarlo con () -o sea, nos impide poder llamarlo como método- def nombre(self): #esto se debería hacer con todos los métodos para evitar que sean modificados/llamados libremente return self._nombre @nombre.setter #SET: esta línea me permitirá modificar el contenido. def nombre(self,nombre): self._nombre=nombre # -- read Only # Si quito la parte del setter no se podrá modificar el atributo (read Only) #¿Cómo utilizar una clase desde otro archivo? --> ver. clases-pruebaModulo.py # Para evitar que el código de este archivo se ejecute en el otro debo encapsular todo el código ejecutable en un if: if __name__ == "__main__": miLocalidad=Localidad("Ramos Mejía", "Buenos Aires", "Argentina", 150000) print(miLocalidad.nombre) miLocalidad.nombre="Chacarita" print(miLocalidad.nombre) print(__name__)
89ab7388f9fc37df596b50753ecb5562392d1737
karinamonetti/curso_universidadPython
/ejercicio_calificaciones.py
727
3.96875
4
def tuCalificacion(): calificacion=int(input("Ingresa una calificación entre 0 y 10: ")) nota=None if calificacion>=0 and calificacion <6: nota="F" print(f"Tu calificación es de {nota}") elif calificacion >=6 and calificacion <7: nota="D" print(f"Tu calificación es de {nota}") elif calificacion >=7 and calificacion <8: nota="C" print(f"Tu calificación es de {nota}") elif calificacion >=8 and calificacion <9: nota="B" print(f"Tu calificación es de {nota}") elif calificacion ==9 or calificacion== 10: nota="A" print(f"Tu calificación es de {nota}") else: print("Valor desconocido") tuCalificacion()
e09c64d065f889680dacc7f98bc63a247935ef94
karinamonetti/curso_universidadPython
/notas_universidadPython.py
599
3.875
4
x=2 print(type(x)) title=input("Tell me the title of the book: ") author=input("Tell me the author of the book: ") print(title, "was write for ", author) print(f"{title} was write for {author}") # --> idem que ${} en JS alto=int(input("Dime el alto del rectángulo...:")) ancho=int(input("Dime el ancho del rectángulo...:")) area=alto*ancho perimetro=(alto+ancho)*2 print(f"el area del rectángulo es de {area} y su perimetro es de {perimetro}") # -- operador ternario (NO ES RECOMENDABLE) numero=int(input("Dime un número: ")) print("Mayor a 5") if numero>5 else print("Menor o igual a 5")
b5f3d831f2ad273bf1f29e2e3fdd657e556bbb81
mohitrocky/Maze-Genarator
/maze-generation/maze/visualizers.py
520
3.515625
4
import time def visualize_algorithm(maze, canvas, generator, speed): def inner(): maze.draw(canvas) for action, (c1, c2) in generator(maze): if action == 'connect': maze.connect(c1, c2) maze.draw_line_between(canvas, c1, c2, color='white') elif action == 'disconnect': maze.disconnect(c1, c2) maze.draw_line_between(canvas, c1, c2, color='black') time.sleep(speed) canvas.do(inner)
4d0147222d8383348fbb2760eada34089a4df4da
praveenvenkata21/pythonex
/question11.py
243
4.03125
4
num=input("Enter a number:") size=len(num) num=int(num) temp=num sum1=rem=0 while temp!=0: rem=temp%10 sum1+=rem**size temp//=10 if sum1==num: print(num,"is a armstrong number") else: print(num,"is not a armstrong number")
61abbd616bd21aa13fa6f7d68159154e851da3ad
livochka/domain-independent-planning
/problems_generator/map.py
4,778
3.78125
4
from random import randint import networkx as nx import matplotlib.pyplot as plt from math import floor, sqrt class Connection: """ Represents a connection between two nodes in a graph """ FACT_CONNECTED = "(connected {} {})" FACT_DISTANCE = "(= (distance {} {}) {})" def __init__(self, nodes, distance): self.nodes = nodes self.distance = distance if self.distance == 0: self.distance += 1 def get_initial_state(self): """ Generating initial state, the fact of connection and distance between two nodes :return: list(str1, str2...) in form ["(connected n1 n2)" ... ] """ return [Connection.FACT_CONNECTED.format(str(self.nodes[0]), str(self.nodes[1])), Connection.FACT_CONNECTED.format(str(self.nodes[1]), str(self.nodes[0])), Connection.FACT_DISTANCE.format(str(self.nodes[0]), str(self.nodes[1]), str(self.distance)), Connection.FACT_DISTANCE.format(str(self.nodes[1]), str(self.nodes[0]), str(self.distance))] class Node: """ Represents a node in the graph """ ID = 0 CHAR = "n" def __init__(self): self.ID = Node.ID Node.ID += 1 self.objs = [] def add_obj(self, obj): self.objs.append(obj) def is_empty(self): return len(self.objs) == 0 def __str__(self): return Node.CHAR + str(self.ID) class Map: def __init__(self, nodes=None, connections=None): self.nodes = nodes self.connections = connections self.nodes_coordinates_mapping = None self.graph = None def __len__(self): return len(self.nodes) def get_node(self, number): for node in self.nodes: if node.ID == number: return node def get_objects(self): return self.nodes def get_distance(self, n1, n2): node1, node2 = self.get_node(n1), self.get_node(n2) return nx.dijkstra_path_length(self.graph, node1, node2) def get_initial_state(self): return [connection.get_initial_state() for connection in self.connections] def visualize(self): nx.draw(self.graph, nx.get_node_attributes(self.graph, 'pos'), with_labels=True, node_size=100, node_color='yellow') labels = nx.get_edge_attributes(self.graph, 'weight') nx.draw_networkx_edge_labels(self.graph, nx.get_node_attributes(self.graph, 'pos'), edge_labels=labels, font_size=7) plt.show() def generate_nodes(self, nnodes, scale): coordinates, nodes = [], [] map_size = scale * nnodes def assign_coordinate(size, coordinates): candidate = (randint(0, size), randint(0, size)) while candidate in coordinates: candidate = (randint(0, size), randint(0, size)) return candidate for node_id in range(nnodes): coordinate = assign_coordinate(map_size, coordinates) nodes.append(Node()) coordinates.append(coordinate) coordinates_map = dict(zip(nodes, coordinates)) self.nodes = nodes self.nodes_coordinates_mapping = coordinates_map return coordinates_map def generate_connections(self, rate=2, scale=50): coordinates = self.nodes_coordinates_mapping.items() sorted_coordinates = sorted(list(coordinates), key=lambda x: sqrt(x[1][0]**2 + x[1][1]**2)) connections = [] def calculate_distance(pos1, pos2): return sqrt((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2) / (scale / 2) for node_i in range(len(sorted_coordinates)): ncon = randint(1, rate) + 1 node1 = sorted_coordinates[node_i] for node_j in range(node_i + 1, node_i + ncon): node2 = sorted_coordinates[node_j % len(sorted_coordinates)] distance = floor(calculate_distance(node1[1], node2[1])) connections.append(Connection([node1[0], node2[0]], distance)) self.connections = connections def generate_random_configuration(self, nnodes=10, scale=50): self.generate_nodes(nnodes, scale) self.generate_connections(scale=scale) G = nx.Graph() for node in self.nodes_coordinates_mapping: G.add_node(node, pos=self.nodes_coordinates_mapping[node]) for connection in self.connections: G.add_edge(connection.nodes[0], connection.nodes[1], weight=connection.distance) self.graph = G return self if __name__ == "__main__": map = Map().generate_random_configuration(4) map.visualize() print("Distance:", map.get_distance(0, 1))
d9eddfd175dd379bd8453f908a0d8c5abeef7a29
bbullek/ProgrammingPractice
/bfs.py
1,536
4.1875
4
''' Breadth first traversal for binary tree ''' # First, create a Queue class which will hold nodes to be visited class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self): return self.queue.pop(0) def isEmpty(self): return len(self.queue) == 0 # Define a Node class that holds references to L/R children, value, and 'visited' boolean class Node: def __init__(self, value = None): self.value = value self.left = None self.right = None self.visited = False # Define a Binary Tree class full of nodes class BinTree: def __init__(self): self.root = None # Now the BFS algorithm def BFS(root): if root is None: # Edge case where we're passed a null ref return queue = Queue() # Initialize queue root.visited = True queue.enqueue(root) while queue.isEmpty() == False: v = queue.dequeue() # Some node containing a value print(v.value) # for all vertices adjacent to v... if v.left is not None and v.left.visited == False: v.left.visited = True queue.enqueue(v.left) if v.right is not None and v.right.visited == False: v.right.visited = True queue.enqueue(v.right) # The main function where everything comes together def main(): tree = BinTree() # Populate the tree with nodes tree.root = Node(50) tree.root.left = Node(20) tree.root.right = Node(30) tree.root.left.left = Node(10) tree.root.left.right = Node(5) tree.root.right.left = Node(3) # Perform BFS to visit the nodes of this tree BFS(tree.root) main()
85d04146fea3cdcab3872fe34e247c7fc4b6372d
Evymendes/Modulo3
/randomsorteio.py
359
3.921875
4
import random sorteio = random.randint(1,30) tentativas = 0 while tentativas < 3 : tente = int(input('Digite um número de 1 à 30: ')) print(sorteio) tentativas = tentativas + 1 if tente == sorteio: print('Você acertou na ' + str(tentativas) + ' tentativa!') break else: print('Não foi desta vez... O número sorteado foi: ' + str(sorteio))
7697cd46b036d982721cb4ce4d2ca85e498469ca
Evymendes/Modulo3
/dictionary.py
672
3.703125
4
''' sammy = { 'username': 'sammy-shark', 'online': true, 'followers': 987 } 1- Escreva um dicionário sobre o perfil de um usuário do Gitbub. 2- Adicione novos campos a esse dicionários 3- Exiba esse dicionário mostrando cada chave e valor. ''' username = { 'username': 'Evelyn', 'repositorios': '19', 'followers': '1' } print('username') username = { 'username': 'Evelyn', 'repositorios': '19', 'followers': '1' } username ['following'] = '1' print(username) username = { 'username': 'Evelyn', 'repositorios': '19', 'followers': '1' } del username['repositorios'] print(username) for key in username: print(key + ':\t' + username[key])
4b8238566ade0eebf17e864b2d2c13cee28ff1f2
Evymendes/Modulo3
/cachorroquente.py
266
3.515625
4
preço = int(input('Valor do Hot-Dog?\n')) cliente = input('Nome do cliente?\n') quant = int(input('Quantos Hot-Dog?\n')) pagar = preço * quant print('O cliente ' + cliente + ' comprou ' + str(quant) + ' cachorros quentes e vai pagar R$ ' + str('%.2f'% pagar ))
e8dd510d9976126d0e835a93c8335bfb13913600
leoua7/clu-clu-game
/game/sprites/text.py
4,214
3.546875
4
import pygame as pg from game.sprites.sprite_sheet import SpriteSheet import game.tools.constants as c class PointsSprite(pg.sprite.Sprite): """Create a sprite of the 100 points text. Attributes: pointsImage: A Surface object to be used as the sprite's image. passingDirection: A Directions Enum instance of the direction the player was facing upon colliding with this sprite. Should only be one of the four cardinal directions. Setting this to CLOCKWISE or COUNTER will cause unexpected and undesired results. """ def __init__(self, pointsImage, passingDirection=c.Directions.RIGHT): """Init PointsSprite using the Surface pointsImage and the Directions Enum passingDirection. Instance variables: coordinates: A tuple location to blit the sprite on the screen. isHorizontal: A boolean storing whether or not passingDirection is horizontal. frameCount: An integer that increases whenever the update method is called. Used to control when other methods should be called. """ super().__init__(c.textGroup) self.image = pointsImage self.image.set_colorkey(c.BLACK) self.coordinates = (0, 0) self.passingDirection = passingDirection self.isHorizontal = False self.frameCount = 0 def update(self): """Increase frameCount. Moves the sprite two pixels forward for the first six frames, and disappears once frameCount is 40. """ self.frameCount += 1 positionOffset = 2 if self.passingDirection in [c.Directions.UP, c.Directions.LEFT]: positionOffset = -2 if self.frameCount < 7: if self.isHorizontal: self.coordinates = (self.coordinates[0], self.coordinates[1] + positionOffset) else: self.coordinates = (self.coordinates[0] + positionOffset, self.coordinates[1]) if self.frameCount == 40: self.kill() class GameOverTextSprite(pg.sprite.Sprite): """Create a sprite of the game over text. Attributes: playerNumber: An integer representing whether the object represent player 1, 2, 3, or 4. """ def __init__(self, playerNumber=1): """Init GameOverTextSprite using the integer playerNumber. Instance variables: spriteSheet: The SpriteSheet object for the display sprite sheet image. image: The current image to be drawn for the sprite. Always is the one image from spriteSheet. coordinates: A tuple location to blit the sprite on the screen. frameCount: An integer that increases whenever the update method is called. Used to control when other methods should be called. """ super().__init__(c.textGroup) spriteSheet = SpriteSheet("display.png") self.image = spriteSheet.getSheetImage(404, 536, 62, 32) self.image.set_colorkey(c.RED) self.coordinates = (20, 478) self.playerNumber = playerNumber self.frameCount = 0 def initialize(self): """Set the base coordinates of the sprite. If playerNumber is 1, or the total number of players is at least 3 and playerNumber is 2, the coordinates are set near the left edge of the screen. Otherwise, they are set near the right edge of the screen. This ensures that the first half of the players' list (rounded down) have their game over text spawn on the left edge of the screen, and the second half have it spawn on the right edge. """ if self.playerNumber == 1 or self.playerNumber == 2 and len(c.playerGroup) > 2: self.coordinates = (20, 478) else: self.coordinates = (430, 478) def update(self): """Increase frameCount. Moves the sprite four pixels up for the first 37 frames, and disappears once once frameCount is 300. """ self.frameCount += 1 if self.coordinates[1] > 38: self.coordinates = (self.coordinates[0], self.coordinates[1] - 4) if self.frameCount == 300: self.kill()
755b7474f1481fdf7867cca3f6b5c96e32b6d387
leoua7/clu-clu-game
/game/tools/scores.py
1,267
3.703125
4
import os import game.tools.constants as c def getHighScore(): """Get the current high score saved in a text file in the game folder. This function only acknowledges the six rightmost digits of a high score (i.e., it reads 1234567 as 234567, or 6 as 000006). If highScoreFile does not exist, this function creates a new highScoreFile with a saved score of 0. If there is a ValueError in casting the saved high score to an int, the score defaults to 0. Returns: highScore: An integer showing the current high score. """ try: with open(os.path.join(c.RESOURCE_FOLDER, "clu_high_score.txt"), "r") as highScoreFile: highScore = int(highScoreFile.read()[-6:]) except ValueError: highScore = 0 setHighScore(highScore) except FileNotFoundError: highScore = 0 setHighScore(highScore) return highScore def setHighScore(highScore): """Write the passed score to a text file, creating the file if it does not already exist. Args: highScore: An integer of the score which should be written to highScoreFile. """ with open(os.path.join(c.RESOURCE_FOLDER, "clu_high_score.txt"), "w") as highScoreFile: highScoreFile.write(str(highScore))
334ecf7709cf5c968f60bed07508c489dc6eb0a4
heoun/RPADevCourse
/libraries_and_os.py
825
3.828125
4
# Python RPA Developer Course # Reading and Writing Files, OS utilities, and Libraries # first lets define a valid file path mypath = r"C:\Users\david\Desktop\new_file.txt" f = open(mypath, "w") f.write("HELLO. THIS IS A TEST") f.close() import os # Get current working directory os.getcwd() # libraries can have sub-modules # os.path has functions related to directory and folder paths os.path.exists(mypath) # glob is another usefull library for scannign files in folders # you can use a file path and * to search for every single file type in a folder and have the paths # returned as individual strings in a python list import glob desktop = "C:\Users\david\Desktop\*.txt" glob.glob(desktop) for f in glob.glob(desktop): print("File Path: %s" % f) print("File Contents:") print(open(f, "r").read())
e06b62fbeb573314195b22ab32b994c9a4e2ea06
ssalamancacruz/Proyecto
/proyecto.py
688
3.703125
4
#Ejemplo 1 def mostrar_lista(nodo): for i in 5: print(nodo) nodo = nodo.siguiente def mostrar_backward(list): if list is None:return cabeza = list cola = list.siguiente mostrar_backward(cola) print(cabeza, end=" ") class Nodo: def __init__( self , dato=None , siguiente=None ): self.dato = dato self.siguiente = siguiente def __str__( self ): return str( self.dato ) #Comprobando su funcionalidad: nodo5 = Nodo( "Viernes" ) nodo4 = Nodo( "Jueves" ,nodo5) nodo3 = Nodo( "Miercoles" ,nodo4) nodo2 = Nodo( "Martes" ,nodo3) nodo1 = Nodo( "lunes" ,nodo2) print(nodo1) mostrar_lista(nodo1) mostrar_backward(nodo1)
6feab9def4c2650d2ee732b1be131306906a1b29
guandai/ud120-projects
/datasets_questions/explore_enron_data.py
1,987
3.5
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 """ import matplotlib.pyplot as plt import pickle enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r")) ll = len(enron_data["SKILLING JEFFREY K"]) count = 0 for person in enron_data: if enron_data[person]["poi"]==1: count += 1 print(count) stc = enron_data["PRENTICE JAMES"]["total_stock_value"] print(stc) wc = enron_data["COLWELL WESLEY"]["from_this_person_to_poi"] print(wc) sjk = enron_data["SKILLING JEFFREY K"]["exercised_stock_options"] print(sjk) sjk_value = enron_data["SKILLING JEFFREY K"]["total_payments"] lk_value = enron_data["LAY KENNETH L"]["total_payments"] af_value = enron_data["FASTOW ANDREW S"]["total_payments"] print(sjk_value) print(lk_value) print(af_value) print enron_data["SKILLING JEFFREY K"] salary_count = 0 email_count = 0 non_payment_count = 0 poi_non_pay = 0 poi_count = 0 for person in enron_data: if enron_data[person]["salary"] != "NaN": salary_count += 1 if enron_data[person]["email_address"] != "NaN": email_count += 1 if enron_data[person]["total_payments"] == "NaN": non_payment_count += 1 if enron_data[person]["total_payments"] == "NaN" and enron_data[person]["poi"] == True: poi_non_pay += 1 if enron_data[person]["poi"] == True: poi_count += 1 print salary_count print email_count print non_payment_count print non_payment_count / float(len(enron_data)) print poi_non_pay print poi_count print poi_non_pay / float(poi_count) total = len(enron_data) print total
d113dd76991f1423658901abc9b886dffed3bf94
cooolkiddoo/python-codes
/beginner/sum of n.py
163
4.09375
4
number=int(input("Enter a number: ")) sum46 = 0 while(number > 0): sum46=sum46+number number=number-1 print("The sum of first n natural numbers is",sum46)
47af0ac443a0453c600cf0e8d14952e4887656b7
cooolkiddoo/python-codes
/beginner/alpha.py
122
3.875
4
b=raw_input() print(b) if(b>='a'):ot an Alphabe print"Alphabet" elif(b>='A'): print"Alphabet" else: print"No"
17f30d9b41e3bac84534424877c3fc81791ef755
jibachhydv/bloomED
/level1.py
498
4.15625
4
# Get the Number whose index is to be returned while True: try: num = int(input("Get Integer: ")) break except ValueError: print("Your Input is not integer") # List of Number numbers = [3,6,5,8] # Function that return index of input number def returnIndex(listNum, num): for i in range(len(listNum)): if listNum[i] == num: return i return -1 # Run the Function print(f"Index of {num} in {numbers} is {returnIndex(numbers, num)}")
6ee949d690435e1d6d9d4e95b0d5b9dc0ab47a79
Blindshooter/lits-dp-003
/hw1/t2.py
384
4.03125
4
def check_parenthesis(string): pars = 0 for s in string: #print pars if s in ('(','[','{'): pars+=1 elif s in (')',']','}'): pars-=1 if pars==0: print '('+string.translate(None, '[](){}')+')' return True else: return False str1 = '((((((((((((((2, 3))))))))))))))' print check_parenthesis(str1)
68351e4e9525343707014cb2ea5141caf43d6c35
Palash1999/Encryption-and-Verification-of-Message
/RSA.py
605
3.703125
4
def rsa_encrypt(e:int, n:int, msg: str): # Convert Plain Text -> Cypher Text cypher_text = '' # C = (P ^ e) % n for ch in msg: # convert the Character to ascii (ord) ch = ord(ch) # convert the calculated value to Characters(chr) cypher_text += chr((ch ** e) % n) return cypher_text def rsa_decrypt(d:int, n:int, cipher_t: str): # Convert Plain Text -> Cypher Text plain_text = '' # P = (C ^ d) % n for ch in cipher_t: # convert it to ascii ch = ord(ch) plain_text += chr((ch ** d) % n) return plain_text
499b7a62a8a995c977ec1832d8aa1a239cf2627f
xinetzone/XinetStudio
/XinetModel/Python学习/histogram.py
1,732
3.5
4
#----------------------------------------------------------------------- # histogram.py #----------------------------------------------------------------------- import sys import stdarray import stddraw import stdrandom import stdstats #----------------------------------------------------------------------- class Histogram: # Construct self such that it can store n frequency counts. def __init__(self, n): # Frequency counts. self._freqCounts = stdarray.create1D(n, 0) # Add one occurrence of the value i to self. def addDataPoint(self, i): self._freqCounts[i] += 1 # Draw self. def draw(self): stddraw.setYscale(0, max(self._freqCounts)) stdstats.plotBars(self._freqCounts) #----------------------------------------------------------------------- # Accept integer n, float p, and integer trialCount as command-line # arguments. Perform trialCount experiments, each of which counts the # number of heads found when a biased coin (heads with probability p # and tails with probability 1 - p) is flipped n times. Then, draw # the results to standard draw. def main(): n = int(sys.argv[1]) # number of biased coin flips per trial p = float(sys.argv[2]) # heads with probability p trialCount = int(sys.argv[3]) # number of trials histogram = Histogram(n + 1) for trial in range(trialCount): heads = stdrandom.binomial(n, p) histogram.addDataPoint(heads) stddraw.setCanvasSize(500, 200) stddraw.clear(stddraw.LIGHT_GRAY) histogram.draw() stddraw.show() if __name__ == '__main__': main() #----------------------------------------------------------------------- # python histogram.py 50 .5 1000000
649407eaeb8fc12a32b493a1afe60182dd2d4d5e
xinetzone/XinetStudio
/XinetModel/Python学习/tenhellos.py
593
3.5625
4
#----------------------------------------------------------------------- # tenhellos.py #----------------------------------------------------------------------- import stdio # Write 10 Hellos to standard output. stdio.writeln('1st Hello') stdio.writeln('2nd Hello') stdio.writeln('3rd Hello') i = 4 while i <= 10: stdio.writeln(str(i) + 'th Hello') i = i + 1 #----------------------------------------------------------------------- # python tenhellos.py # 1st Hello # 2nd Hello # 3rd Hello # 4th Hello # 5th Hello # 6th Hello # 7th Hello # 8th Hello # 9th Hello # 10th Hello
823845e68fa0996387193309d60e42b2036a5cae
xinetzone/XinetStudio
/XinetModel/Python学习/grayscale.py
974
3.75
4
#----------------------------------------------------------------------- # grayscale.py #----------------------------------------------------------------------- import sys import stddraw import luminance from picture import Picture #----------------------------------------------------------------------- # Accept the name of a JPG or PNG file as a command-line argument. # Read an image from the file with that name. Create and show a # gray scale version of that image. pic = Picture(sys.argv[1]) for col in range(pic.width()): for row in range(pic.height()): pixel = pic.get(col, row) gray = luminance.toGray(pixel) pic.set(col, row, gray) stddraw.setCanvasSize(pic.width(), pic.height()) stddraw.picture(pic) stddraw.show() #----------------------------------------------------------------------- # python grayscale.py mandrill.jpg # python grayscale mandrill.png # python grayscale.py darwin.jpg # python grayscale.py darwin.png
0e1c7ec440fa2e1b389466da5716f73849074703
GrahamOHagan/python_sandbox
/dictionary_test.py
640
3.90625
4
stuff = ["abc", "def", "ghi", "jkl", "mno", "pqr"] def example(i, x={}): x[i] = stuff[i] print(x) return x def another(i): x = {} x[i] = stuff[i] print(x) return x if __name__ == "__main__": for i in range(6): mydict = example(i) print() for i in range(6): mydict2 = another(i) """ Output: {0: 'abc'} {0: 'abc', 1: 'def'} {0: 'abc', 1: 'def', 2: 'ghi'} {0: 'abc', 1: 'def', 2: 'ghi', 3: 'jkl'} {0: 'abc', 1: 'def', 2: 'ghi', 3: 'jkl', 4: 'mno'} {0: 'abc', 1: 'def', 2: 'ghi', 3: 'jkl', 4: 'mno', 5: 'pqr'} {0: 'abc'} {1: 'def'} {2: 'ghi'} {3: 'jkl'} {4: 'mno'} {5: 'pqr'} """
e4a48078d125102f2a154d5c7cf387b0f087b7a8
ScroogeZhang/Python
/day03字符串/04-字符串相关方法.py
1,185
4.21875
4
# 字符串相关方法的通用格式:字符串.函数() # 1.capitalize:将字符串的首字母转换成大写字母,并且创建一个新的字符返回 str1 = 'abc' new_str = str1.capitalize() print(new_str) # 2.center(width,fillerchar):将原字符串变成指定长度并且内容居中,剩下的部分使用指定的(字符:长度为1的字符串)填充 new_str = str1.center(7,'!') print(str1,new_str) # 3.rjust(width,fillerchar) new_str = str1.rjust(7,'*') print(new_str) number = 19 # py1805009 #str(数据):将其他任何的数据转换成字符串 num_str = str(number) print(num_str, type(num_str)) # 让字符串变成宽度为3,内容右对齐,剩下部分使用'0'填充 new_str = num_str.rjust(3, '0') print(new_str) new_str = 'py1805' + new_str print(new_str) # 4.ljust(width,fillerchar):左对齐 str1 = 'py1805' new_str = str1.ljust(10, '0') print(new_str) new_str = new_str + num_str print(new_str) # 5.字符串1.join(字符串2): 在字符串2中的每个字符间插入一个字符串1 new_str = '123'.join('bbb') print(new_str) print('---------------') # 6.maketrans() new_str = str.maketrans('abc', '123') print(new_str)
29ce22bbee4710c4d2357f0eaea7cb73588aac38
ScroogeZhang/Python
/day02语法基础/04-运算符.py
3,431
4.34375
4
# 数学运算符,比较运算符,逻辑运算符,赋值运算符,位运算符 # 1.数学运算符(+,-,*,/,%,**,//) # +: 求和 # 注意:求和操作,+两边必须是数字类型 # True --> 1 , False --> 0 print(10+20.4,True+1) number = 100 + 11 print(number) # - :求差 print(100-12) # * : 求乘积 print('chengji:'+str(3.12*2)) number = 3 * 9 # / : 求商 print(4/2) print(5/2) # % : 取余 print(3%2) print(101%10) # ** : 幂运算 # x ** y : 求x的y次方 # 浮点数在计算中存储的时候,有的时候会有一定的误差 number = 2 ** 3 print(number) # // : 整除 # 求商,但是只取商的整数部分 print(5//2) # 取一个二位整数的十位数(78) print(78//10) # 取2345中的4: print(2345%100//10) print(2345//10%10) # 2.比较运算符 ''' >,<,==,!=,>=,<= 比较运算符的结果全是布尔值:True,False ''' ''' 1.> x > y : 判断x是否大于y,如果是结果为True,否则是False ''' result = 10 > 20 print(result,100 > 20) #2.< print(10 < 20) # 3. == # x == y: 如果x和y相等,结果九尾True,否则是False number = 12.5 number2 = 12 print(number == number2) # 4.>= ,<= 10 >= 5 #True 10 >= 10 #True # 5.!= # x != y : 如果x和y不相等,结果是True,否则是False #6. number = 15 result = 10 < number <20 #判断number是否在10到20之间 print(result) #3. 逻辑运算符 ''' 与(and), 或(or), 非(not) 逻辑运算符的运算数据是布尔值,结果也是布尔值 布尔1 and 布尔2 :两个都为True结果才是True ,只要有一个是False,结果就是False 并且 需要两个或者多个条件同时满足,就是用逻辑与(and) 布尔1 or 布尔2 :只要有一个是True,结果就是True。两个都是False结果才是False。 或者 需要两个或者多个条件满足一个就可以,就是用逻辑或(or) not 布尔1: 如果是 False,结果就是True;如果是True,结果就是False。 需要不满足某个条件的时候才为True # 写一个条件,判断一个人的年龄是否满足青年的条件(10<age<20) ''' age = 30 print(age>18 and age<28 and age != 20) #平均成绩大于90,或者操评分大于100,并且英语成绩还不能低于80分 score = 80 score2 = 90 english = 70 print('===:',score > 90 or score2 > 100 and english >= 80) #成绩不低于60分 score = 70 print(score >= 60) print(not score < 60) #4.赋值运算符 ''' =,+=,-=,*=,/=,%=,**=,//== 赋值运算符的作用,将赋值符号右边的表达式的值赋给左边的变量 表达式:有结果的语句,例如:10,'abc',10+20,30>10.5等 赋值符号的左边必须是变量 赋值符号,是先算右边的结果,然后再把结果赋给左边的变量 ''' number = 100 number += 10 # 相当于number = number + 10 print(number) number *= 2 # 相当于number = number *2 print(number) #5.运算符的优先级 ''' 10+20*3-5/2=10+60-2.5 ---数学运算顺序 优先级从低到高: 赋值运算符 < 逻辑运算符 < 比较运算符 < 算术运算符 算术运算符中:先幂运算在乘除取余取整再加减 如果你不确定运算顺序,可以通过添加括号来改变运算顺序。有括号就先算括号里边的 ''' result = 10 + 20 > 15 and 7 * 8 < 30 + 60 #result 30>15 and 56< 90 #result True and True #result = True print(result) print(10 + 20 * 3 / 2 - 10 % 3) #10+30-1 #39 print(10 + 20 * 3 / (2 - 10) % 3)
037b5264c6d0e8be1fcc98b978a6829b4e7523d8
ScroogeZhang/Python
/day06 列表,元祖,字典,集合/复习.py
985
3.734375
4
# -*- coding: UTF-8 -*- # @Time : 2018/7/24 8:52 # @Author :Hcy # @Email : 297420160@qq.com # @File : 复习.py # @Software : PyCharm ''' 列表:[1,3,'a','12abc'] 元素 in 列表 +:链接 *:列表重复 都是创建一个新的列表 ''' for item in [{'a':10}, {'b':100}, {'a':1}]: print(item) ''' 元祖:不可变,有序 (1,'yu') ''' a = (1, 2) print(a, type(a)) b = (10,) # 当元祖的元素只有一个的时候,需要在元素的后面加一个逗号表示这个值是一个元祖 print(b, type(b)) ''' 字典:{key:value,key1:value} 字典的增,删,改,查 del 字典[key] 字典.pop(key) key in 字典 字典1.update(字典2) ''' for key in student_dict: print(key, student_dict[key]) ''' 集合:{1,'ss'}无序,可变,不会重复 增删改查 集合.add(元素) 集合.update(集合) 集合.remove(元素) 集合.pop() 数学集合运算:1.包含(<=,>=) 2.并集(|),交集(&),差集(-),补集(^) '''
61cc074563240c4e6f6835b1bf6be450b76956a9
ScroogeZhang/Python
/day04 循环和分支/04-while循环.py
951
4.1875
4
# while循环 ''' while 条件语句: 循环体 其他语句 while:关键字 条件语句: 结果是True,或者False 循环体:重复执行的代码段 执行过程:判断条件语句是否为True,如果为True就执行循环体。 执行完循环体,再判断条件语句是否为True,如果为True就在执行循环体.... 直到条件语句的值为False,循环结束,直接执行while循环后面的语句 注意:如果条件语句一直都是True,就会造成死循环。所以在循环体要有让循环可以结束的操作 python 中没有do-while 循环 ''' # 死循环 # while True: # print('aaa') flag = True while flag: print('aaa') flag = False #使用while 循环计算1到100的和: sum1 = 0 count = 1 while count <= 100: sum1 += count count += 1 print(sum1) #练习: 计算100以内偶数的和 sum1 = 0 count = 0 while count <= 100: sum1 += count count += 2 print(sum1) #
b4fe332072fd7009bf1e921226829a130c458d45
ScroogeZhang/Python
/day12 面向对象基础1/01-迭代器和生成器.py
1,471
3.828125
4
# -*- coding: utf-8 -*- # @Time : 2018/7/31 8:52 # @Author :Hcy # @Email : 297420160@qq.com # @File : 01-迭代器和生成器.py # @Software : PyCharm """ 生成器:a.可以看成一个可以西存储多个数据的容器。 需要里面的数据的时候就生成一个,里面的数据只能从前往后一个一个的生成 不能跳跃,也不能从后往前。生成的数据,不能再生成了 b.获取生成器里面的数据,需要使用__next__()方法 c.只要函数生命中有yield关键字,函数就不在是一个单纯的函数,而变成一个生成器 和列表比较:列表存数据,数据必须是是实实在在存在的数据,一个数据会占一定的内存空间 生成器存数据,存的是数据的算法,没有数据去占内存空间 """ # 1,1,2,3,5,8,13,21 def xulie(n): pre_1 = 1 pre_2 = 1 for x in range(1, n+1): if x==1 or x ==2: current = 1 # print(current) yield current continue current = pre_1 + pre_2 pre_1, pre_2 = pre_2, current # print(current) yield current xulie = xulie(10) print(xulie.__next__()) print(xulie.__next__()) print(xulie.__next__()) if __name__ == '__main__': x = (i for i in range(10)) # x就是一个生成器,用来产生数据 print(x) print(x.__next__()) print(x.__next__()) list1 = list(i for i in range(10)) print(list1)
79c4584eb2cae10c882162f315f213dcaa734949
ScroogeZhang/Python
/day03字符串/05-if语句.py
1,131
4.5
4
# if语句 # 结构: # 1. # if 条件语句: # 条件语句为True执行的代码块 # # 执行过程:先判断条件语句是否为True, # 如果为True就执行if语句后:后面对应的一个缩进的所有代码块 # 如果为False,就不执行冒号后面的一个缩进中的代码块,直接执行后续的其他语句 # # 条件语句:可以使任何有值的表达式,但是一般是布尔值 # # # if : 关键字 if True: print('代码1') print('代码2') print('代码3') print('代码4') # 练习:用一个变量保存时间(50米短跑),如果时间小于8秒,打印及格 time = 7 if time < 8: print('及格') # 只有条件成立的时候才会执行 print(time) #不管if语句的条件是否,这个语句都会执行 ''' if 条件语句: 语句块1 else: 语句块2 执行过程:先判断条件语句是否为True,如果为True就执行语句块1,否则就执行语句块2 练习:用一个变量保存成绩,如果成绩大于等于60,打印及格,否则打印不及格 ''' score = 70 if score >= 60: print('及格') else: print('不及格')
d7785df08f821469f287bfe9854fc977a539c425
ScroogeZhang/Python
/day05 练习和列表/01-作业.py
2,697
3.671875
4
# 1. number = 1 for i in range(0,20): number *= 2 print(number) # for 循环中,如果for后面的变量在循环体中不需要,这个变量命名的时候可以用'_'命名 # for _ in range(20) # 2的20次方 # 2. # sum1 = 0 # num = 1 # while num <= 100: # if ((num%3==0) or (num%7==0)) and (num%21 != 0): # sum1 += 1 # num += 1 # print(num) # 能被3或7整除 且不能被21整除得数 # 1.求1到100之间所有数的和,平均值 sum1 = 0 for x in range(1,101): sum1 += x print(sum1,sum1/100) sum1 = 0 count = 1 while count <= 100: sum1 += count count += 1 print(sum1,sum1/100) # 2.计算1-100之间能被3整除的数的和 sum1 = 0 for x in range(1,101): if x % 3 == 0: sum1 += x print(sum1) sum1 = 0 count = 1 while count <= 100: count += 1 if count % 3 ==0: sum1 += count print(sum1) # 3.计算1到100之间不能被7整除的数的和 sum1 = 0 for x in range(1,101): if x % 7 != 0: sum1 += x print(sum1) sum1 = 0 count = 0 while count <= 100: # count += 1 if count % 7 != 0: sum1 += count count += 1 print(sum1) # 1.兔子问题 斐波那锲数 ''' a = 1 = 1 while count <= 7 ''' # 2.判断101-200之间有多少个素数,并输出所有素数。 #判断素数的方法:用一个数分别除2到sqrt(这个数), #如果能被整除,则表明此数不是素数,反之是素数。 for x in range(101,201): flag = True for y in range(2,x): num = x % y if num == 0: flag = False # 只要在2~number-1之间有一个被num整除,那么这个num就确定不是素数 break # 循环嵌套的时候,遇到break和continue结束的是包含的最近的那个循环 if flag == True: print(x,end=' ') print() #3.打印出所有的水仙花数,所谓水仙花数是指一个三位数,其各位数字立方和等于该数本身。 # 例如:153是一个水仙花数,因为153 = 1^3 + 5^3 + 3^3 for x in range(100,1000): a = x // 100 b = x // 10 % 10 c = x % 10 if x == a**3 + b**3 + c**3: print(x,end=' ') print() #4.有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的第20个分数 ''' 1 2 1 2 3 2 3 5 3 4 8 5 分子:上一个分数的分子加分母 分母: 上一个分数的分子 fz = 2 fm = 1 fz+fm / fz ''' a=1 b=2 for x in range(1,20): c = b b = b + a a = c print('第20个分数是%d/%d' % (b,a)) # 5.给一个正整数,要求:1、求它是几位数 2.逆序打印出各位数字 import random num = random.randint(1,1000) print(num) count = 1 while num // 10 != 0: count += 1 print(num%10,end='') #逆序打印例如 789 打印89 剩下7,单独打印 num //= 10 print(num) #输出原数最高位7,即个位数 print(count)
fca406d84960938a40a1d2216983f2c07efa374e
Suraj-S-Patil/Python_Programs
/Simple_Intrst.py
246
4.125
4
#Program to calculate Simple Interest print("Enter the principal amount, rate and time period: ") princ=int(input()) rate=float(input()) time=float(input()) si=(princ*rate*time)/100 print(f"The simple interest for given data is: {si}.")
ee361861525868e58f690106aa7c13ce67850a80
26point2Newms/data-structures-and-algorithms
/python/CNLRUCache.py
1,278
3.796875
4
''' Created on July 15, 2020 @author: charles newman https://github.com/26point2Newms ''' from collections import OrderedDict class LRUCache(object): ''' Implementation of a Least Recently Used Cache (LRU Cache) which discards the least recently used items first. ''' def __init__(self, capacity): self.cache = OrderedDict() self.capacity = capacity def get(self, key): ''' Returns the value associated with the key if found (cache hit) and moves the key to the end to show it was recently used. Returns -1 if the key is not found (cache miss). ''' if key not in self.cache: return -1 else: self.cache.move_to_end(key) return self.cache[key] def put(self, key, value): ''' Adds/updates the value and moves the key to the end to show it was recently used. Checks the length of the ordered dictionary against the capacity specified in the 'constructor'. Remove the first key (the least recently used) if capacity is exceeded. ''' self.cache[key] = value self.cache.move_to_end(key) if len(self.cache) > self.capacity: self.cache.popitem(last = False)
f6cc44b114538fec05ab11e704eb441deb8a7d86
26point2Newms/data-structures-and-algorithms
/python/testQuickSort.py
551
3.796875
4
''' Created on Aug 3, 2020 @author: charles newman https://github.com/26point2Newms ''' import unittest import CNQuickSort class Test(unittest.TestCase): def setUp(self): self.numbers = [54, 789, 1, 44, 789, 321, 852, 32456, 2, 88, 741, 258, 369, 951, 753] def testQuickSort(self): print("Before sort:") print(self.numbers) CNQuickSort.sort(self.numbers) print("After sort:") print(self.numbers) for i in range(len(self.numbers)-1): self.assertLessEqual(self.numbers[i], self.numbers[i+1]) if __name__ == "__main__": unittest.main()
c74d43ba97660057da398e186e9abca78cd381ec
dvisionst/quiz-game-start
/main.py
737
3.640625
4
from question_model import Question from data import question_data from quiz_brain import QuizBrain # Creating variables in order to loop through the question_data list # loop will populate a new list with Question object and respective attributes question_bank = [] for dictionary in question_data: text_q = dictionary["question"] text_a = dictionary["correct_answer"] question_bank.append(Question(text_q, text_a)) quiz = QuizBrain(question_bank) # while loop that will keep populating the next question until there are no more questions left in the set while quiz.still_has_questions(): quiz.next_question() print(f"You've completed the quiz.") print(f"Your final score was: {quiz.score}/{quiz.question_number}")
f315e9320453868c93587bf014d8d0751b90633d
FeuerFeuer/2015Computing-Lab-Practice2
/q05_find_month_days.py
534
3.859375
4
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"] n = int(input("Enter year: ")) m = int(input("Enter month: ")) n1 = n % 4 n2 = n % 100 n3 = n % 400 if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m == 10 or m == 12: print(months[m-1],n,"has 31 days") elif m == 4 or m == 6 or m == 9 or m == 11: print(months[m-1],n,"has 30 days") else: if (n1 == 0 and n2 != 0) or n3 == 0: print(months[m-1],n,"has 29 days") else: print(months[m-1],n,"has 28 days")
d552de01cad51b019587300e6cf5b7cbc5d3122f
Cherol08/finance-calculator
/finance_calculators.py
2,713
4.40625
4
import math #program will ask user if they want to calculate total investment or loan amount option = """ Choose either 'investment' or 'bond' from the menu below to proceed:\n Investment - to calculate the amount of interest you'll earn on interest Bond - to calculate the amount you'll have to pay on a home loan\n """ print(option) choice = input("Enter option:\t").lower() # lower method used to convert input to lowercase characters # while loop used if user doesn't enter either of the 2 options specified, program will keep asking # user to enter correct option. if user does enter either option #break statement will discontinue the loop and continue with the next statement while (choice != "investment") and (choice != "bond"): print("Invalid option.\n") choice = input("Enter option:\t").lower() if (choice == "investment") or (choice == "bond"): break # if user chooses investment, program will ask user to enter the following values: # P- principal investment amount, r - interest rate, t - time planned to invest in years # and the type of interest they'd like to use. The conditional statement executed if user chooses investment, # will calculate user's investment depending on the type of interest user chooses. # A- total investment amount with interest. Each outcome is rounded off to 2 decimal places if choice == "investment": P = float(input("Enter amount to deposit:\t")) r = float(input("Enter the percentage of interest rate:\t")) t = int(input("Enter number of years planned to invest:\t")) interest = input("Simple or compound interest:\t").lower() if interest == "simple": A = round(P*(1+r*t), 2) #simple interest formula print(f"\nThe total amount of your investment with simple interest is R{A}") elif interest == "compound": A = round(P*math.pow((1+r), t), 2) #compund interest formula print(f"\nThe total amount of your investment with compound interest is R{A}") # if user chooses bond, program will ask user for the following values: # p-present value amount, i-interest rate, n -number of months to repay bond # x - the total bond repayment per month #the final answer is rounded of to two decimal places and displayed elif choice == "bond": bond = True p = float(input("Enter present value of the house:\t")) i = float(input("Enter the percentage of interest rate:\t")) if i: i = i/12 #interest in the bond formula is divided by 12 n = int(input("Enter period planned to repay the bond(in months):\t")) x = round((i*p)/(1 - math.pow((1+i), -n)), 2) #bond formula print(f"\nThe total bond repayment is R{x} per month")
f8249149f1eede2fa7e00b129bb427c2383b8f2f
jasonskipper/CompetitiveProgramming
/AlgoExpert/python/ValidateSubsequence.py
281
3.546875
4
def isValidSubsequence(array, sequence): array_index = 0 sequence_index = 0 while array_index < len(array) and sequence_index < len(sequence): if array[array_index] == sequence[sequence_index]: sequence_index += 1 array_index += 1 return sequence_index == len(sequence)
53ff749da41ea256ca021cee5b8247da41ad81b1
gkanishk44/Python-Projects
/temperature converison.py
115
4
4
celsius=int(input("Enter the temperature in celcius:")) f=(celsius*1.8)+32 print("Temperature in farenheit is:",f)
7c8d1c98423ee1839302522f2071155f1f7cfd98
gkanishk44/Python-Projects
/rockpaperscissors.py
2,113
3.828125
4
from tkinter import * import random root = Tk() root.geometry('400x400') root.resizable(0,0) root.title('DataFlair-Rock,Paper,Scissors') root.config(bg ='seashell3') Label(root, text = 'Rock, Paper ,Scissors' , font='calibri 20 bold', bg = 'violet').pack() user_take = StringVar() Label(root, text = 'choose any one: rock, paper ,scissors' , font='arial 11 bold', bg = 'yellow').place(x = 30,y=70) Entry(root, font = 'arial 15', textvariable = user_take , bg = 'white').place(x=70 , y = 130) comp_pick = random.randint(1,3) if comp_pick == 1: comp_pick = 'rock' elif comp_pick ==2: comp_pick = 'paper' else: comp_pick = 'scissors' Result = StringVar() def play(): user_pick = user_take.get() if user_pick == comp_pick: Result.set('tie,you both select same') elif user_pick == 'rock' and comp_pick == 'paper': Result.set('you lose,computer selected paper') elif user_pick == 'rock' and comp_pick == 'scissors': Result.set('you win,computer selected scissors') elif user_pick == 'paper' and comp_pick == 'scissors': Result.set('you lose,computer selected scissors') elif user_pick == 'paper' and comp_pick == 'rock': Result.set('you win,computer selected rock') elif user_pick == 'scissors' and comp_pick == 'rock': Result.set('you lose,computer selected rock') elif user_pick == 'scissors' and comp_pick == 'paper': Result.set('you win ,computer selected paper') else: Result.set('invalid: choose any one -- rock, paper, scissors') def Reset(): Result.set("") user_take.set("") def Exit(): root.destroy() Entry(root, font = 'arial 10 bold', textvariable = Result, bg ='white',width = 50,).place(x=10, y = 250) Button(root, font = 'arial 13 bold', text = 'PLAY' ,padx =5,bg ='Green' ,command = play).place(x=150,y=190) Button(root, font = 'arial 13 bold', text = 'RESET' ,padx =5,bg ='blue' ,command = Reset).place(x=70,y=310) Button(root, font = 'arial 13 bold', text = 'EXIT' ,padx =5,bg ='Red' ,command = Exit).place(x=230,y=310) root.mainloop()
520890a37552ea6c4cc3c2ef12daa6f432b93de4
gargchirayu/Algorithmic-Toolbox
/week3_greedy_algorithms/1_ change.py
476
3.53125
4
# Uses python3 import sys def get_change(m): n = 0 iter = 0 while (m != 0): if iter == 2: n = n + m m = 0 elif iter == 1: fives = m // 5 n = n + fives m = m % 5 iter = 2 else: tens = m // 10 n = n + tens m = m % 10 iter = 1 return n if __name__ == '__main__': m = int(sys.stdin.read()) print(get_change(m))
8efede982b64c7276e24e6d6db21cc04583f81be
amithjkamath/codesamples
/python/lpthw/ex8.py
529
4.03125
4
# This is an example with more text manipulation than before. # Amith, 01/02 formatter = "%r %r %r %r" print formatter % (1,2,3,4) # This prints numbers using %r print formatter % ('one', "two", 'three', "Four") # This prints numbers as text using %r print formatter % (True, False, True, False) # This prints boolean values using %r print formatter % (formatter, formatter, formatter, formatter) print formatter % ( "I had this thing.", "That you could type up right.", "But it didn't sing.", "So I'm saying goodnight." )
90c6247ac1d1a579952fb0a9900e3ce93ead122e
amithjkamath/codesamples
/python/lpthw/ex11.py
438
4.0625
4
# This exercise introduces command line inputs. # Amith, 01/03 print "How old are you?" age = raw_input() print "How tall are you (in centimeters)?" height = raw_input() print "How much do you weigh (in lbs)?" weight = raw_input() print "So, you're %r years old, %r centimeters tall, and %r lbs heavy!" % ( age, height, weight) BMI = float(weight) * 703.0 * (2.54*2.54)/(float(height)*float(height)) print "and your BMI is %f." % BMI
462321abc830736f71325221f81c4f5075dd46fb
amithjkamath/codesamples
/python/lpthw/ex21.py
847
4.15625
4
# This exercise introduces 'return' from functions, and hence daisy-chaining them. # Amith, 01/11 def add(a, b): print "Adding %d + %d" % (a,b) return a + b def subtract(a, b): print "Subtracting %d - %d" % (a,b) return a - b def multiply(a,b): print "Multiplying %d * %d" % (a,b) return a*b def divide(a,b): print "Dividing %d / %d" % (a,b) return a/b print "Let's do some math with just functions!" age = add(30,5) height = subtract(78,4) weight = multiply(90,2) iq = divide(100,2) # Example of how "string %x" % variable is combined with "string", variable, "string again" ... print "Age: %d, Height: %d, Weight:" % (age, height), weight, ", IQ: %d" % iq print "Here's a puzzle" what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print "That becomes: ", what, " Can you do it by hand?"
d0479ee3d6fbce482ccebef07edc9814564baed3
SAV2288/card-game-21
/21_oop.py
4,732
3.640625
4
import importlib from random import shuffle class Croupier: """Модель Крупье""" cards = importlib.import_module('cards').cards dict_cards_points = importlib.import_module('cards').points def shuffle_the_deck(self): """Перетасовать колоду""" shuffle(self.cards) def give_card(self): """Выдать карту""" return self.cards.pop() сroupier = Croupier() class Gamer: """Модель игрока""" cards_in_the_game = len(сroupier.cards) def __init__(self, name): self.point = 0 # Количество очков в руке self.hand = [] # Список карт в руке self.turn_completed = False # Ход завершен self.name = name # Имя игрока def check(self): """Проверка руки на перебор""" return self.point < 22 def get_card(self): """Взять следующую карту""" if self.check(): card, point = сroupier.give_card() self.hand.append(card) self.point += point Gamer.cards_in_the_game -= 1 return (f'{self.name} вытащил карту: {card}', point) else: self.pass_the_move() def pass_the_move(self): """Присвоить метке завершения хода игрока значение 'True'""" self.turn_completed = True class Computer(Gamer): """Модель игрока компьютер""" # Минимальная вероятность получить хорошую карту, при котором компьютер сделает ход minimum_probability_of_a_good_card = 0.3 def the_likelihood_of_a_good_card(self): """Подсчет вероятности вытащить карту и при этом не перебрать""" # Получаем количество очков, позволяющих не перебрать max_point = 21 - self.point # Подсчет количества карт, номиналом не более max_point count_number_of_good_cards = 0 for nominal_value in сroupier.dict_cards_points: if nominal_value <= max_point: count_number_of_good_cards += сroupier.dict_cards_points[nominal_value] return count_number_of_good_cards/Computer.cards_in_the_game \ >= Computer.minimum_probability_of_a_good_card def possibility_of_action(check_funck): """Определение возможности сделать действие. Принимает проверяющую функцию""" def decorator(func): def wrapper(self): if check_funck(self): func(self) else: self.end = True return wrapper return decorator @possibility_of_action(the_likelihood_of_a_good_card) def get_card(self): card, point = Gamer.get_card(self) сroupier.dict_cards_points[int(point)] -= 1 gamer = Gamer(input('Введите имя: ')) comp = Computer('Гена') def print_game_result(): """Печать результата игры""" if not gamer.check(): name = gamer.name game_result = 3 elif not comp.check(): name = comp.name game_result = 3 elif gamer.point == comp.point: game_result = 2 elif gamer.point - comp.point >0: name = gamer.name game_result = 1 elif gamer.point - comp.point <0: name = comp.name game_result = 1 result = { 1: f'Победил {name}!', 2: 'Ничья!', 3: f'{name} Перебрал!', } print(f'Счет {comp.point}: {gamer.point}. {result[game_result]}') def game(): """Игра в 21 с компьютером""" сroupier.shuffle_the_deck() while True: if gamer.check() and comp.check(): if not gamer.turn_completed: answer = input( 'Взять карту?( Нет(нажми "3"), Да(нажми любую другую кнопку) )' ) if answer == '3': gamer.pass_the_move() else: print(gamer.get_card()[0]) elif not comp.turn_completed: comp.get_card() else: break else: break print_game_result() if __name__ == '__main__': game()
f0b314804a12280947dcc7ffeeb6282e11c4df22
asantinc/practice_algos
/sorting/sorting/binary_search.py
1,132
4.09375
4
def binary_search_recursive(array, item, low=None, high=None): low = low if low is not None else 0 high = high if high is not None else len(array) mid = (low+high)/2 if low<mid: if array[mid] > item: return binary_search_recursive(array, item, low=low, high=mid) elif array[mid] < item: return binary_search_recursive(array, item, low=mid, high=high) else: return mid return -1 def binary_search_iterative(array, item, low=None, high=None): low = 0 high = len(array) mid = (low+high)/2 while low<mid: if array[mid] > item: low=low high=mid elif array[mid] < item: low=mid high=high else: return mid mid = (low+high)/2 return -1 if __name__ == '__main__': a = [-2, 4, 5, 5,6, 7] print binary_search_recursive(a, 6) print binary_search_iterative(a, 6) b = [-2, 4, 5,6, 7] print binary_search_recursive(b, 6) print binary_search_iterative(b, 6) print binary_search_recursive(b, 7) print binary_search_iterative(b, 7) print binary_search_iterative(b, 77) c = [-2, 4,6,12,17,99,100,100,109] print binary_search_recursive(c, 109)
5819eeef3987a90dc81a2e1a18be309406266cb1
lisuizhe/algorithm
/leetcode/python/Q0133_Clone_Graph.py
720
3.703125
4
import queue # Definition for a Node. class Node(object): def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors class Solution(object): def cloneGraph(self, node): """ :type node: Node :rtype: Node """ visited = dict() def dfs(target): if not target: return None cloned = Node(target.val, []) for neighbor in target.neighbors: if neighbor.val in visited: cloned.neighbors.append(visited[neighbor.val]) else: cloned.neighbors.append(dfs(neighbor)) return cloned return dfs(node)
588b68b13395c2753c0e78a92ef36ed6f2c03617
lisuizhe/algorithm
/lintcode/python/Q0038_Search_a_2D_Matrix_II.py
750
3.859375
4
class Solution: """ @param matrix: A list of lists of integers @param target: An integer you want to search in matrix @return: An integer indicate the total occurrence of target in the given matrix """ def searchMatrix(self, matrix, target): # write your code here count = 0 if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0: return count row = 0; column = len(matrix[0]) - 1; while row < len(matrix) and column >= 0: if matrix[row][column] == target: count += 1 row += 1 elif matrix[row][column] < target: row += 1 else: column -= 1 return count;
2e44cccb057aa7d0934d477bb9c521b21359a17b
lisuizhe/algorithm
/lintcode/python/Q0124_Longest_Consecutive_Sequence.py
545
3.640625
4
class Solution: """ @param num: A list of integers @return: An integer """ def longestConsecutive(self, num): # write your code here numSet = set(num) maxLength = 0 for i in numSet: if (i - 1) not in numSet: currentNum = i currentLength = 1 while (currentNum + 1) in numSet: currentLength += 1 currentNum += 1 maxLength = max(maxLength, currentLength) return maxLength
9231f612a25f7efff978e90a571d335ef86c7970
lisuizhe/algorithm
/lintcode/python/Q1172_Binary_Tree_Tilt.py
701
3.84375
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the root @return: the tilt of the whole tree """ def findTilt(self, root): # Write your code here self.totalTilt = 0 self.getNodeSum(root) return self.totalTilt def getNodeSum(self, node): if not node: return 0 leftSum = self.getNodeSum(node.left) rightSum = self.getNodeSum(node.right) tilt = abs(leftSum - rightSum) self.totalTilt += tilt return leftSum + rightSum + node.val
0d0af8973a5fb1eee0d42781bbb72f0a8a3f4319
lisuizhe/algorithm
/lintcode/python/Q0024_LFU_Cache.py
1,922
3.515625
4
from collections import OrderedDict class MyValue: def __init__(self, value, frequency): self.value, self.frequency = value, frequency class LFUCache: """ @param: capacity: An integer """ def __init__(self, capacity): # do intialization if necessary self.capacity = capacity self.minFreq = 0 self.myValues = {} self.freqToKey = { 1: OrderedDict() } """ @param: key: An integer @param: value: An integer @return: nothing """ def set(self, key, value): # write your code here if self.capacity <= 0: return if key in self.myValues: myValue = self.myValues[key] myValue.value = value self.myValues[key] = myValue self.get(key) return if len(self.myValues) >= self.capacity: self._evict() self.minFreq = 1 myValue = MyValue(value, 1) self.myValues[key] = myValue self.freqToKey[1][key] = key def _evict(self): if len(self.myValues) > 0: evictKey, tmp = self.freqToKey[self.minFreq].popitem(last=False) del self.myValues[evictKey] """ @param: key: An integer @return: An integer """ def get(self, key): # write your code here if key in self.myValues: myValue = self.myValues[key] del self.freqToKey[myValue.frequency][key] if self.minFreq == myValue.frequency and len(self.freqToKey[self.minFreq]) == 0: self.minFreq += 1 myValue.frequency += 1 self.myValues[key] = myValue if not (myValue.frequency) in self.freqToKey: self.freqToKey[myValue.frequency] = OrderedDict() self.freqToKey[myValue.frequency][key] = key return myValue.value else: return -1
f7fec4f76f44ec7f0d295176a10288d983f16ab2
PreferredNerd/CMPSC132
/Recursive Triangle.py
1,472
4.0625
4
#Lab #7 #Due Date: 02/22/2019, 11:59PM ######################################## # # Name: Nicholas C. Birosik # Collaboration Statement: Just Me, and my day off in this Happy Valley! # ######################################## #### DO NOT modify the triangle(n) function in any way! def triangle(n): return recursive_triangle(n, n) ################### def recursive_triangle(k, n): if n > 0 and k > 0: if k <= n: #Define the base case, which is we are reducing the problem to the k = 1 if k == 1: returnString = "" for numberOfSpaces in range(n-1): returnString += " " returnString += "*" return returnString #If it has not reduced to this point then we wiull reduce it further to the number of spaces and asteriks and continue to amend the return string. else: returnString = "" for numberOfSpaces in range(n-k): returnString += " " for numberofAsterisks in range(k): returnString += "*" returnString+="\n" #Take what we have added onto what is at each deeper iteration return returnString + recursive_triangle(k-1, n) else: return "Error invalid dimensions" else: return "Error Please submit a valid psoitive non-zero entry"
e896cb10efafca03e2bec2c1c69acb05d2e9f17f
PreferredNerd/CMPSC132
/Max Heap Priority Queue.py
6,202
3.625
4
#Lab #12 #Due Date: 03/24/2019, 11:59PM ######################################## # # Name: Nicholas C. Birosik # Collaboration Statement: None, just me and TA Larry. # ######################################## class MaxHeapPriorityQueue: def __init__(self): self.heap=[] self.size = 0 def __len__(self): return len(self.heap) def parent(self,index): #Take the supplied index and ensure that it is not the root or smaller and that it is not larger than the size #of the heap array itself if index <= 1 or index > len(self): return None else: return self.heap[(index // 2)-1] def swap(self, index1, index2): self.heap[index1 - 1], self.heap[index2 - 1] = self.heap[index2 - 1], self.heap[index1 - 1] def leftChild(self,index): #Determine weather or not the requested child is out of the bounds of the array, if so return None. if 2*index < len(self): return self.heap[(2 * index) - 1] else: return None def rightChild(self,index): # Determine weather or not the requested child is out of the bounds of the array, if so return None. if (2*index) - 1 < len(self): return self.heap[(2 * index)] else: return None def insert(self,x): # Determine how long the size of the list is; if zero, start off by just appending it if self.size == 0: self.heap.append(x) self.size += 1 else: #Insert and start the sorting methodology self.heap.append(x) newNodeIndex = self.heap.index(x) if newNodeIndex == 1: newNodeParentIndex = 1 parentNode = self.heap[0] else: # Otherwise, utilze floor division calculations to find where parent is. newNodeParentIndex = ((newNodeIndex + 1) // 2) parentNode = self.heap[newNodeParentIndex - 1] while parentNode < x: # Commece the switching operations between parents and children until the condition for MAX heap is satisfied self.swap(newNodeParentIndex, newNodeIndex + 1) newNodeIndex = self.heap.index(x) # Determine if it lies at the root and terminate the while loop -- Beware infinte looping if newNodeIndex == 0: break # Update Parent indec newNodeParentIndex = ((newNodeIndex + 1) // 2) parentNode = self.heap[newNodeParentIndex - 1] self.size += 1 def deleteMax(self): # Determine if there is actually anything to delete if self.size <= 0: return None # Determine if there is 1 element and address special case elif self.size == 1: self.size = 0 maximumValue = self.heap[0] self.heap = [] return maximumValue # Work with general case or 2 or more elements else: # Swap first and last element, pop last element, grab return value into max value heapLength = len(self.heap) childValue = self.heap[heapLength - 1] childIndex = self.heap.index(childValue) + 1 self.swap(1, childIndex) maximumValue = self.heap.pop(heapLength - 1) # decrease the size of the heap by one, Becasue we just got rid of the maximum number. self.size -= 1 #Set Left and right childrens popstions in terms of their list positions. leftChild = 1 rightChild = 2 # Lets check if there even are right and left children to begin with! if leftChild and rightChild in range(len(self.heap)): currentRight = self.heap[leftChild] currentLeft = self.heap[rightChild] #Determine with sibling is the largest. if currentRight > currentLeft: currentMax = currentRight # Handle Empty Heap condition else: currentMax = currentLeft # Compare children to root, if they exist elif leftChild and not rightChild in range(len(self.heap)): currentMax = self.heap[rightChild] elif rightChild and not leftChild in range(len(self.heap)): currentMax = self.heap[rightChild] else: self.size = 0 self.heap = [] return maximumValue # I don't know about you but this whole working with an appended list +1 for the trees is hard, store list positons for clarity currentIndex = self.heap.index(currentMax) while currentMax > childValue: self.swap(currentIndex + 1, self.heap.index(childValue) + 1) #Again for clarity purposes newIndex = currentIndex + 1 #update right and left child for current swapping iteration rightChild = newIndex * 2 leftChild = newIndex * 2 - 1 #Are we actually holding the child, like Mrs. Griselda and her kid, or is the variable holding type(None); if so define it as such... if leftChild in range(len(self.heap)): currentRight = self.heap[leftChild] else: currentRight = None if rightChild in range(len(self.heap)): currentLeft = self.heap[rightChild] else: currentLeft = None if currentRight and currentLeft is not None: if currentRight > currentLeft: currentMax = currentRight else: currentMax = currentLeft # Ensure that any sibling that contains something and the other none, returns the other by default elif currentRight and not currentLeft is None: currentMax = currentLeft elif currentRight and not currentLeft is not None: currentMax = currentRight elif currentRight is None and currentLeft is None: break currentIndex = self.heap.index(currentMax) return maximumValue
15650e95e626831dd3fa569fb6fe8128e5529a15
PreferredNerd/CMPSC132
/Merge Sort.py
3,259
4.0625
4
#LAB 15 #Due Date: 04/05/2019, 11:59PM ######################################## # # Name: Nicholas C. Birosik # Collaboration Statement: Just me and Larry Lee. I also consulted Arron for help with the floor division aspect of the # Second part of the assignment. I thought I had seen this concept dealt with in the heap sorting algorithm! # ######################################## def merge(list1, list2): # write your code here # Explicate (instantiate) our variables, first index, second index, current count and our output merged array indexOne, indexTwo, currentCount = 0,0,0 outputList = [] #Control the number of iterations bassed on the length of the two lists as a maximum number of iterations #Better to use a while statement than a for loop with a break statement! while currentCount < len(list1) + len(list2): #Ensure that the input that we are given is within the bounds of the passed in parameters if indexOne < len(list1) and indexTwo < len(list2): #Determine the values at the current index of each of the lists and append the smaller of the two. if list1[indexOne] < list2[indexTwo]: outputList.append(list1[indexOne]) indexOne += 1 #Take appropriate action if value of list one at the current index is greater than that of list two else: outputList.append(list2[indexTwo]) indexTwo += 1 #Advance the current count of the output list by one currentCount += 1 #Now, if we passed through the entierty of the list, take specific action to merege the two halves. else: #Take care of having passed through all of list1 and add list2 to it if indexOne >= len(list1): #Operate between current value fo indexTwo and the len(of the list) for x in range(indexTwo, len(list2)): outputList.append(list2[x]) currentCount += 1 #Otherwise, add list one to list 2 elif indexTwo >= len(list2): # Operate between current value fo indexTwo and the len(of the list) for x in range(indexOne, len(list1)): outputList.append(list1[x]) currentCount += 1 #return the compounded list as the completed list. return outputList def mergeSort(numList): # write your code here #Find the middle of the input array; so that we can send half of it into the mergeSort again. middleOfInput = len(numList) // 2 #Create a base case so we can work down to the bottom of our expression if len(numList) == 1: return numList elif len(numList) < 1: return "An error occurred" #Call mergeSort function repeatedly scanning and selecting the first half the list after each iteration firstComponent = mergeSort(numList[:middleOfInput]) # Call mergeSort function repeatedly scanning and selecting the second half the list after each iteration secondComponent = mergeSort(numList[middleOfInput:]) #Return a sorted list to each iteration call, until it reaches the base case where there is only one element left return merge(firstComponent, secondComponent)
ccd06d530f018d9471124a1b274ac5871dc75726
Lucas210996/noyadeseche
/Exemple sans interface.py
5,370
3.546875
4
from math import* def jourexist(): #on crée une fonction qui permet de définir si le jour entré existe if (jour >31 or jour <1): return False print("Veuillez saisir un jour correct") return True # Retourne True si la date saisie existe def dateExist(): if (jour['value'] == "31"): if (mois['value'] == "avril" or mois['value'] == "juin" or mois['value'] == "septembre" or mois ['value'] == "novembre"): return False if (mois['value'] == "février"): # Si le jour saisi pour le mois de février est=31 ou =30 ou =29 alors que l'année n'est pas bissextile alors --> false if (jour['value'] == "31" or jour['value'] == "30" or (jour['value'] == "29" and bissextile(getYear()) == False)): return False return True # Sinon --> true # Retourne true si l'année est bissextile def bissextile(annee): bissextile = False # Par défaut, on considére l'année saisie comme non bissextile, sauf: if (annee % 400 == 0) or ( annee % 4 == 0 and not annee % 100 == 0): # Si l'année est divisible par 400, divisible par 4 mais pas par 100 bissextile = True return bissextile # Retourne true si le mois saisit est janvier ou février def monthJanuaryOrFebruary(): if (mois['value'] == 'janvier' or mois['value'] == 'février'): return True else: return False # Retourne true si l'année saisie est comprise entre 1600 et 2200 (sinon aucun nombre n'est associé au siècle) def checkYear(): try: if (int(entryYear.get()) >= 1600 and int(entryYear.get()) < 2200): return True except: return False # Retourne l'année sous le format integer def getYear(): return int(annee) # Retourne le nombre à ajouter selon le mois transmis en paramètre def getNumberToAddMonth(): try: mois= mois['value'] if Month == 'janvier': return 0 elif Month == 'février': return 3 elif Month == 'mars': return 3 elif Month == 'avril': return 6 elif Month == 'mai': return 1 elif Month == 'juin': return 4 elif Month == 'juillet': return 6 elif Month == 'août': return 2 elif Month == 'septembre': return 5 elif Month == 'octobre': return 0 elif Month == 'novembre': return 3 elif Month == 'decembre': return 5 except: # Message d'erreur si le mois n'a pas été saisi entryText.set("Veuillez sélectionner un mois") # Convertis le numéro de jour du mois en integer (nomre entier) def getNumberToAddDay(): try: return int(comboDay['value']) except: # Message d'erreur si la journée n'a pas été saisie entryText.set("Veuillez sélectionner un jour") # Retourne le nombre à ajouter selon le siècle de l'année entrée def getNumberToAddCentury(): century = int(str(getYear())[:2]) if century == 16: return int(6) elif century == 17: return int(4) elif century == 18: return int(2) elif century == 19: return int(0) elif century == 20: return int(6) elif century == 21: return int(4) # Retourne le jour de la semaine selon le nombre transmis en paramètre def getDayOfWeek(number): if number == 0 or number == 7: return 'Dimanche' elif number == 1: return 'Lundi' elif number == 2: return 'Mardi' elif number == 3: return 'Mercredi' elif number == 4: return 'Jeudi' elif number == 5: return 'Vendredi' elif number == 6: return 'Samedi' def dayOfWeek(): if (checkYear()): if dateExist(): # On récupère les deux derniers chiffres de la date saisie last2Character = int(str(getYear())[-2:]) # On divise par 4 sans se soucier du reste numberDivBy4 = last2Character + int(last2Character / 4) # On ajoute la journée du mois addedDay = numberDivBy4 + getNumberToAddDay() # On ajoute selon le mois addedMonth = addedDay + getNumberToAddMonth() if (bissextile(getYear()) and monthJanuaryOrFebruary()): addedMonth = addedMonth - 1 addedCentury = addedMonth + int(getNumberToAddCentury()) moduloBy7 = addedCentury % 7 dayOfWeek = getDayOfWeek(moduloBy7) print('Cette date correspond à : ' + dayOfWeek) else: # Message d'erreur si l'année est mal saisie print("La date entrée n'existe pas.") print ("Ce programme permet le calcul du jour exact d'une date saisie, il fonctionne pour les dates comprises entre l'année 1600 et 2200") jour=int(input("Veuillez saisir le jour :")) mois= str(input("Veuillez saisir le mois (en lettre):")) annee= int(input("Veuillez saisir l'année (sous forme '1XXX' s'il vous plait):")) print(dayOfWeek())
bbc1d886fefc5e253fc83cf6abc507ba923af8c3
lowks/ubelt
/ubelt/util_list.py
1,976
4.09375
4
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import itertools as it def take(items, indices): r""" Selects a subset of a list based on a list of indices. This is similar to np.take, but pure python. Args: items (list): some indexable object indices (list OR slice OR int): some indexing object Returns: iter or scalar: subset of the list SeeAlso: ub.dict_subset Example: >>> import ubelt as ub >>> items = [0, 1, 2, 3] >>> indices = [2, 0] >>> ub.take(items, indices) [2, 0] Example: >>> import ubelt as ub >>> items = [0, 1, 2, 3] >>> index = 2 >>> ub.take(items, index) 2 Example: >>> import ubelt as ub >>> items = [0, 1, 2, 3] >>> index = slice(1, None, 2) >>> ub.take(items, index) [1, 3] """ try: return [items[index] for index in indices] except TypeError: return items[indices] def compress(items, flags): r""" Selects items where the corresponding value in flags is True This is similar to np.compress and it.compress Args: items (iterable): a sequence flags (iterable): corresponding sequence of bools Returns: list: a subset of masked items Example: >>> import ubelt as ub >>> items = [1, 2, 3, 4, 5] >>> flags = [False, True, True, False, True] >>> ub.compress(items, flags) [2, 3, 5] """ return list(it.compress(items, flags)) def flatten(nested_list): r""" Args: nested_list (list): list of lists Returns: list: flat list Example: >>> import ubelt as ub >>> nested_list = [['a', 'b'], ['c', 'd']] >>> ub.flatten(nested_list) ['a', 'b', 'c', 'd'] """ return list(it.chain.from_iterable(nested_list))
cd935299254d7686c7faa052bc3a45ec874e7660
frazermills/GCSE-Computer-Science-Homework
/Practicle-2/GUI-Calculator/Menu_System.py
15,500
3.984375
4
# Author: Frazer Mills # Date: 05/03/21 # program name: 'Menu_System.py' # Python 3.9.2 # Description: This module contains the Menu class, which handles the buttons and text rendering and processing. import pygame # ------------------------------------------- Menu Class ----------------------------------------- # class Menu: """ A class to represent a menu. Attributes ---------- screen: <class 'pygame.Surface'> The pygame surface where everything is rendered. clock: <class 'Clock'> Maintains a constant frame rate. button_colour: tuple Colour of the buttons. text_colour: tuple Colour of text. font: <class 'pygame.font.Font'> Style and size of text. result: int, float Result from a calcualtion. Methods ------- setup(): Initilises all of the buttons' attributes. draw(): Displays all of the buttons, with their text, to the screen. draw_text(text: <string>, x: <int>, y: <int>): draws the text string so that the centre is at the x and y locations. is_clicked(): Checks if the user clicks on a button. """ # ------------------------------------- Initialises Attributes ----------------------------------- # def __init__(self, screen, clock, button_colour, text_colour, font, result, clicked_button_colour): """ Constructs all of the necessary attributes for the Menu object. Parameters ---------- screen: <class 'pygame.Surface'> The pygame surface where everything is rendered. clock: <class 'Clock'> Maintains a constant frame rate. screen_colour: tuple Colour of the buttons. text_colour: tuple Colour of text. font: <class 'pygame.font.Font'> Style and size of text. result: int, float Result from a calcualtion. click: bool Keeps track of whether the mouse is clicked or not. button_size: int Defines the size of the buttons. option: str, optional Used to store the user's options. Can take on any value from button_command. button_command: list Stores all possible button commands """ self.screen = screen self.clock = clock self.text_colour = text_colour self.font = font self.button_colour = button_colour self.result = result self.click = False self.button_size = 90 self.option = None self.button_command = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "*", "/", "calc"] self.button_colours = [self.button_colour for i in self.button_command] self.clicked_button_colour = clicked_button_colour self.screen_colour = button_colour # --------------------------------------- Sets up Calculator ------------------------------------- # def setup(self): """ Sets each buttons' x,y positions. Parameters ---------- None Returns ------- None """ self.button_1_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) - 150, (self.screen.get_height() // 2) - 100) self.button_1 = pygame.Rect(self.button_1_xy[0], self.button_1_xy[1], self.button_size, self.button_size) self.button_2_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) - 50, (self.screen.get_height() // 2) - 100) self.button_2 = pygame.Rect(self.button_2_xy[0], self.button_2_xy[1], self.button_size, self.button_size) self.button_3_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) + 50, (self.screen.get_height() // 2) - 100) self.button_3 = pygame.Rect(self.button_3_xy[0], self.button_3_xy[1], self.button_size, self.button_size) self.button_4_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) - 150, (self.screen.get_height() // 2)) self.button_4 = pygame.Rect(self.button_4_xy[0], self.button_4_xy[1], self.button_size, self.button_size) self.button_5_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) - 50, (self.screen.get_height() // 2)) self.button_5 = pygame.Rect(self.button_5_xy[0], self.button_5_xy[1], self.button_size, self.button_size) self.button_6_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) + 50, (self.screen.get_height() // 2)) self.button_6 = pygame.Rect(self.button_6_xy[0], self.button_6_xy[1], self.button_size, self.button_size) self.button_7_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) - 150, (self.screen.get_height() // 2) + 100) self.button_7 = pygame.Rect(self.button_7_xy[0], self.button_7_xy[1], self.button_size, self.button_size) self.button_8_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) - 50, (self.screen.get_height() // 2) + 100) self.button_8 = pygame.Rect(self.button_8_xy[0], self.button_8_xy[1], self.button_size, self.button_size) self.button_9_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) + 50, (self.screen.get_height() // 2) + 100) self.button_9 = pygame.Rect(self.button_9_xy[0], self.button_9_xy[1], self.button_size, self.button_size) self.button_add_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) + 150, (self.screen.get_height() // 2) - 100) self.button_add = pygame.Rect(self.button_add_xy[0], self.button_add_xy[1], self.button_size, self.button_size) self.button_subtract_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) + 150, (self.screen.get_height() // 2)) self.button_subtract = pygame.Rect(self.button_subtract_xy[0], self.button_subtract_xy[1], self.button_size, self.button_size) self.button_multiply_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) + 150, (self.screen.get_height() // 2) + 100) self.button_multiply = pygame.Rect(self.button_multiply_xy[0], self.button_multiply_xy[1], self.button_size, self.button_size) self.button_divide_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) + 150, (self.screen.get_height() // 2) + 200) self.button_divide = pygame.Rect(self.button_divide_xy[0], self.button_divide_xy[1], self.button_size, self.button_size) self.button_calc_xy = ((self.screen.get_width() // 2) - (self.button_size // 2) + 50, (self.screen.get_height() // 2) + 200) self.button_calc = pygame.Rect(self.button_calc_xy[0], self.button_calc_xy[1], self.button_size, self.button_size) self.calc_screen_xy = (50, 10) self.calc_screen = pygame.Rect(self.calc_screen_xy[0], self.calc_screen_xy[1], self.screen.get_width() - 100, self.button_size) # --------------------------------------- Draws all Buttons -------------------------------------- # def draw(self): """ Displays all the buttons to screen, renders the button text by calling the sub-procedure draw_text(). Parameters ---------- None Returns ------- None """ pygame.draw.rect(self.screen, self.button_colours[0], self.button_1) pygame.draw.rect(self.screen, self.button_colours[1], self.button_2) pygame.draw.rect(self.screen, self.button_colours[2], self.button_3) pygame.draw.rect(self.screen, self.button_colours[3], self.button_4) pygame.draw.rect(self.screen, self.button_colours[4], self.button_5) pygame.draw.rect(self.screen, self.button_colours[5], self.button_6) pygame.draw.rect(self.screen, self.button_colours[6], self.button_7) pygame.draw.rect(self.screen, self.button_colours[7], self.button_8) pygame.draw.rect(self.screen, self.button_colours[8], self.button_9) pygame.draw.rect(self.screen, self.button_colours[9], self.button_add) pygame.draw.rect(self.screen, self.button_colours[10], self.button_subtract) pygame.draw.rect(self.screen, self.button_colours[11], self.button_multiply) pygame.draw.rect(self.screen, self.button_colours[12], self.button_divide) pygame.draw.rect(self.screen, self.button_colours[13], self.button_calc) pygame.draw.rect(self.screen, self.screen_colour, self.calc_screen) self.draw_text(f"{self.button_command[0]}", self.button_1_xy[0] + self.button_size // 2, self.button_1_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[1]}", self.button_2_xy[0] + self.button_size // 2, self.button_2_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[2]}", self.button_3_xy[0] + self.button_size // 2, self.button_3_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[3]}", self.button_4_xy[0] + self.button_size // 2, self.button_4_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[4]}", self.button_5_xy[0] + self.button_size // 2, self.button_5_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[5]}", self.button_6_xy[0] + self.button_size // 2, self.button_6_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[6]}", self.button_7_xy[0] + self.button_size // 2, self.button_7_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[7]}", self.button_8_xy[0] + self.button_size // 2, self.button_8_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[8]}", self.button_9_xy[0] + self.button_size // 2, self.button_9_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[9]}", self.button_add_xy[0] + self.button_size // 2, self.button_add_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[10]}", self.button_subtract_xy[0] + self.button_size // 2, self.button_subtract_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[11]}", self.button_multiply_xy[0] + self.button_size // 2, self.button_multiply_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[12]}", self.button_divide_xy[0] + self.button_size // 2, self.button_divide_xy[1] + self.button_size // 2) self.draw_text(f"{self.button_command[13]}", self.button_calc_xy[0] + self.button_size // 2, self.button_calc_xy[1] + self.button_size // 2) self.draw_text(f"{self.result}", self.screen.get_width() // 2, self.calc_screen_xy[1] + self.button_size // 2) pygame.display.update() # ---------------------------------------- Draws all Text ---------------------------------------- # def draw_text(self, text, x, y): """ Displays all the buttons to screen, renders the button text by calling the sub-procedure draw_text(). Parameters ---------- text: str The button's text. x: int The text's x position. y: int The text's y position. Returns ------- None """ textobj = self.font.render(text, 1, self.text_colour) textrect = textobj.get_rect() textrect.center = (x, y) self.screen.blit(textobj, textrect) # --------------------------------------- Checks User Input -------------------------------------- # def is_clicked(self): """ Determines whether a button is clicked, or if the esc or exit keys are clicked. Parameters ---------- None Returns ------- None """ #self.button_colours = [self.button_colour for i in self.button_command] mousex, mousey = pygame.mouse.get_pos() if self.button_1.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[0] self.button_colours[0] = self.clicked_button_colour elif self.button_2.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[1] self.button_colours[1] = self.clicked_button_colour elif self.button_3.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[2] self.button_colours[2] = self.clicked_button_colour elif self.button_4.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[3] self.button_colours[3] = self.clicked_button_colour elif self.button_5.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[4] self.button_colours[4] = self.clicked_button_colour elif self.button_6.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[5] self.button_colours[5] = self.clicked_button_colour elif self.button_7.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[6] self.button_colours[6] = self.clicked_button_colour elif self.button_8.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[7] self.button_colours[7] = self.clicked_button_colour elif self.button_9.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[8] self.button_colours[8] = self.clicked_button_colour elif self.button_add.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[9] self.button_colours[9] = self.clicked_button_colour elif self.button_subtract.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[10] self.button_colours[10] = self.clicked_button_colour elif self.button_multiply.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[11] self.button_colours[11] = self.clicked_button_colour elif self.button_divide.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[12] self.button_colours[12] = self.clicked_button_colour elif self.button_calc.collidepoint((mousex, mousey)): if self.click: self.option = self.button_command[13] self.button_colours[13] = self.clicked_button_colour self.click = False for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: self.click = True
be978ea10344389577386068b79cbf5c258916ae
BenDu89-zz/MoveWebsite
/media.py
938
3.8125
4
import webbrowser # To open urls in a webbrowser in the def show_movie class Movies(): ''' The class movie contains the basic data of the movie, as title, storyline, trailer url and poster image url''' VALID_RATINGS = ["G","PG","PG-13","R"] # diffrent posible rankings for the movies def __init__(self, title, storyline, trailer_youtube_url, poster_image_url): # init ist the creater and will reserve storage for the object self.title = title # title of the movie self.storyline = storyline # storyline of the movie self.trailer_youtube_url = trailer_youtube_url # the youtube url for the tailer of the movie self.poster_image_url = poster_image_url # url of the poster image of the movie def show_movie(self): ''' This def will take as an input the name of the movie and than play the trailer of the movie, by opening a webbrowser''' webbrowser.open(self.trailer_url)