blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
57501bc781022c39240df5cb23dcd8f67c74c53a
bruhmentomori/python
/lek3.py
726
3.9375
4
print("Välkommen till mitt räkneprogram") operator = input("Välj räknesätt +, -, *, /:") try: tal1 = int(input("Mata in ett heltal: ")) except: print("Du måste skriva in en siffra") tal1 = 0 try: tal2 = int(input("Mata in ett till heltal: ")) except: print("Du måste skriva in en siffra: ") tal2 = 0 if operator == "+": summa = tal1 + tal2 elif operator == "-": summa = tal1 - tal2 elif operator == "*": summa = tal1 * tal2 elif operator == "/": try: summa = tal1 / tal2 except(ZeroDivisionError): print("Det går ej att dividera med 0") summa = str(" say sike right now") else: print("FEL") print("Summan är:" + str(summa))
285a777fbb3fe740b2b16f2eb7696923f0c0ac08
luisdaRC/test_py
/main.py
3,199
3.71875
4
#Changes def practica(): goleadores_2014 = {"Muller": ("Alemania", 5), "Dempsey": ("USA", 2), "James": ("Colombia", 6), "Muller": ("Alemania", 5), "Schurrle": ("Alemania", 3), "Messi": ("Argentina", 4), "Suarez": ("Uruguay", 2), "van Persie": ("Holanda", 4), "Benzema": ("Francia", 3), "Klose": ("Alemania", 2), "Robben": ("Holanda", 3), "Valencia": ("Ecuador", 3), "Neymar": ("Brasil", 4), "Shaqiri": ("Suiza", 3), "Kroos": ("Alemania", 2), "Luiz": ("Brasil", 2) } #Ejercicio 1 """ mayor=0 for key, value in goleadores_2014.items(): if value[1]>mayor: mayor=value[1] nombre=key print(nombre) #Ejercicio 2 conjunto = set() for value in goleadores_2014.values(): conjunto.add(value[0]) print(type(conjunto)) print(conjunto) #Ejercicio 3 lista = [] goles_pais = {} for i in conjunto: acum = 0 for goles in goleadores_2014.values(): if i==goles[0]: acum=acum+goles[1] goles_pais[i]=acum lista.append(acum) mas_goles = max(goles_pais.values()) print(goles_pais) for key, value in goles_pais.items(): if mas_goles == value: print(key,value) tuplita =() print(type(tuplita)) """ #Ejercicio 4 Imprimir los nombres de los jugadores que marcaron entre 3 y 5 goles. # for key, value in goleadores_2014.items(): # if value[1] >= 3 and value[1]<=5: # print(key)""" #Ejercicio 5. Imprimir los nombres de los jugadores Alemanes. for key, value in goleadores_2014.items(): if value[0] == "Alemania": print(key, end="\n\n") #Ejercicio 6. Imprimir los nombres de los jugadores que marcaron menos goles. for key, value in goleadores_2014.items(): if value[1] < 3: print(key) total_goles = 0 total_jugadores = 0 #Ejercicio 7. Imprimir el número total de goles marcados por los jugadores que aparecen en la lista. for goles in goleadores_2014.values(): total_goles += goles[1] total_jugadores = total_jugadores+1 print("Total de goles anotados: ", total_goles) #Ejercicio 8. Imprimir el promedio de goles marcados por los jugadores que aparecen en la lista. promedio = total_goles/total_jugadores print("Promedio de goles anotados: ",promedio) print("Aguante el Diego, el más grande papá") """ Listas: Se puede hacer lo que quiera xD. Se define mi_lista = [] Tuplas: No se pueden eliminar valores. Se define tuplita = () >>> b = (5,) # Es una tupla <<< b = (5) es un int Conjuntos: No se pueden repetir valores. Se define: conjunto = set() Diccionarios: Key : Value. Se define diccionario = {} """ # Press the green button in the gutter to run the script. if __name__ == '__main__': practica()
d0434e4c42c139b85ec28c175749bb189d2a19bf
Francisco-LT/trybe-exercices
/bloco36/dia2/reverse.py
377
4.25
4
# def reverse(list): # reversed_list = [] # for item in list: # reversed_list.insert(0, item) # print(reversed_list) # return reversed_list def reverse(list): if len(list) < 2: return list else: print(f"list{list[1:]}, {list[0]}") return reverse(list[1:]) + [list[0]] teste = reverse([1, 2, 3, 4, 5]) print(teste)
5910d4439a26badf770e1aa6fdf08d46f4be93e6
danrludwig/CS-1400
/CS 1400/Ludwig-Daniel-Assn13/assn13-task2.py
527
4.03125
4
from password import Password def main(): password = Password() while True: passGuess = input('Enter password: ') password.setPassword(passGuess) if password.isValid() is True: print('Valid Password') else: print('Invalid Password\n', password.getErrorMessage()) again = input('Enter "y" to enter another password: ') again = again.lower() if again == 'y': continue else: break main()
aea6faec795ead1e46971ee3a3efa97f4dc08c9e
ALXTorresC/productosDesktop
/digito.py
807
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Tkinter Python 3.7 from tkinter import * def ventana(): window = Tk() window.title("Tkinter") window.geometry('350x200') lbl = Label(window, text="Introduce un número") lbl.grid(column=0, row=0) result = Label(window,text="") txt = Entry(window,width=10) txt.grid(column=1, row=0) result.grid(column=3,row=0) txt.focus() def mensaje(): res = txt.get() #aquí compruebas que es un número res = int(res) if res.isdigit() else 0 result.configure(text= res) txt.delete(0, END) btn = Button(window, text="Activa", bg="red",fg="white", command=mensaje) btn.grid(column=2, row=0) window.mainloop() def main(): ventana() if __name__ == '__main__': main()
c775866c264defa931101643723c011c93b2fa9f
mopeneye/CREDITRISK_PREDICTION_MACHINLEARNING_PYTHON
/CreditRiskPrediction.py
19,441
3.625
4
# # Problem # Establishing a machine learning model to classify credit risk. # # Data Set Story # # Data set source: https://archive.ics.uci.edu/ml/datasets/statlog+(german+credit+data) # # There are observations of 1000 individuals. # Variables # # Age: Age # # Sex: Gender # # Job: Job-Ability (0 - unskilled and non-resident, 1 - unskilled and resident, 2 - skilled, 3 - highly skilled) # # Housing: Housing Status (own, rent, or free) # # Saving accounts: Saving Status (little, moderate, quite rich, rich) # # Checking account: Current Account (DM - Deutsch Mark) # # Credit amount: Credit Amount (DM) # # Duration: Duration (month) # # Purpose: Purpose (car, furniture / equipment, radio / TV, domestic appliances, repairs, education, business, vacation / others) # # Risk: Risk (Good, Bad Risk) # imports import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from datetime import datetime from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.svm import SVC from lightgbm import LGBMClassifier from sklearn.model_selection import train_test_split from sklearn import preprocessing from sklearn.metrics import accuracy_score from xgboost import XGBClassifier from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score, GridSearchCV from sklearn.neighbors import LocalOutlierFactor import warnings warnings.filterwarnings("ignore") def load_CreditRisk_data(): df = pd.read_csv(r'E:\PROJECTS\dsmlbc\CreditRiskPredictiıon\datasets\credit_risk.csv', index_col=0) return df df = load_CreditRisk_data() # EDA # OVERVIEW print(df.head()) print(df.tail()) print(df.info()) print(df.columns) print(df.shape) print(df.index) print(df.describe().T) print(df.isnull().values.any()) print(df.isnull().sum().sort_values(ascending=False)) # INDEPENDENT VARIABLE OPERATIONS # convert JOB column to categorical category = pd.cut(df.Job, bins=[-1, 0.9, 1.9, 2.9, 3.9],labels=['unskilled_nonres', 'unskilled_res', 'skilled', 'highly_skilled']) df.insert(2, 'Job_category', category) df['Job_category'] = df['Job_category'].astype('O') df.drop('Job', axis=1, inplace=True) # Customers have saving, but don't have Checking account df[(df['Saving accounts'].isnull() == 0) & (df['Checking account'].isnull())] [['Saving accounts', 'Checking account']] # Convert Checking account nulls to None df.loc[(df['Checking account'].isnull()), 'Checking account'] = 'None' # Fill Saving accounmts Null values with Checking account df.loc[(df['Saving accounts'].isnull()), 'Saving accounts'] = df.loc[(df['Saving accounts'].isnull())]['Checking account'] # Convert Duration column to category # category2 = pd.cut(df.Duration, bins=[0, 11, 21, 31, 80],labels=['short', 'medium', 'high', 'veryhigh']) # df.insert(7, 'Duration_category', category2) # df['Duration_category'] = df['Duration_category'].astype('O') # df.drop('Duration', axis=1, inplace=True) # Convert Risk to 1 and 0 df['Risk'] = df['Risk'].replace('bad',1) df['Risk'] = df['Risk'].replace('good',0) # Create Has_Money column df.loc[(df['Saving accounts'] != 'None') | (df['Checking account'] != 'None'), 'Has_Money'] = 1 df['Has_Money'] = df['Has_Money'].replace(np.nan, 0).astype(('int')) # NEW FEATURES RELATED WITH AGE AND SEX df.loc[(df['Sex'] == 'male') & (df['Age'] <= 21), 'NEW_SEX_CAT'] = 'youngmale' df.loc[(df['Sex'] == 'female') & ((df['Age'] > 21) & (df['Age']) < 50), 'NEW_SEX_CAT'] = 'maturefemale' df.loc[(df['Sex'] == 'male') & ((df['Age'] > 21) & (df['Age']) < 50), 'NEW_SEX_CAT'] = 'maturemale' df.loc[(df['Sex'] == 'male') & (df['Age'] > 50), 'NEW_SEX_CAT'] = 'seniormale' df.loc[(df['Sex'] == 'female') & (df['Age'] <= 21), 'NEW_SEX_CAT'] = 'youngfemale' df.loc[(df['Sex'] == 'female') & (df['Age'] > 50), 'NEW_SEX_CAT'] = 'seniorfemale' cat_cols = [col for col in df.columns if df[col].dtypes == 'O'] print('Categorical Variable count: ', len(cat_cols)) print(cat_cols) # HOW MANY CLASSES DO CATEGORICAL VARIABLES HAVE? print(df[cat_cols].nunique()) def cats_summary(data, categorical_cols, number_of_classes=10): var_count = 0 # count of categorical variables will be reported vars_more_classes = [] # categorical variables that have more than a number specified. for var in data: if var in categorical_cols: if len(list(data[var].unique())) <= number_of_classes: # choose according to class count print(pd.DataFrame({var: data[var].value_counts(), "Ratio": 100 * data[var].value_counts() / len(data)}), end="\n\n\n") sns.countplot(x=var, data=data) plt.show() var_count += 1 else: vars_more_classes.append(data[var].name) print('%d categorical variables have been described' % var_count, end="\n\n") print('There are', len(vars_more_classes), "variables have more than", number_of_classes, "classes", end="\n\n") print('Variable names have more than %d classes:' % number_of_classes, end="\n\n") print(vars_more_classes) cats_summary(df, cat_cols) # NUMERICAL VARIABLE ANALYSIS print(df.describe().T) # NUMERICAL VARIABLES COUNT OF DATASET? num_cols = [col for col in df.columns if df[col].dtypes != 'O'] print('Numerical Variables Count: ', len(num_cols)) print('Numerical Variables: ', num_cols) # Histograms for numerical variables? def hist_for_nums(data, numeric_cols): col_counter = 0 data = data.copy() for col in numeric_cols: data[col].hist(bins=20) plt.xlabel(col) plt.title(col) plt.show() col_counter += 1 print(col_counter, "variables have been plotted") hist_for_nums(df, num_cols) # DISTRIBUTION OF "Risk" VARIABLE print(df["Risk"].value_counts()) #inbalancing problem! def plot_categories(df, cat, target, **kwargs): row = kwargs.get('row', None) col = kwargs.get('col', None) facet = sns.FacetGrid(df, row=row, col=col) facet.map(sns.barplot, cat, target); facet.add_legend() # TARGET ANALYSIS BASED ON CATEGORICAL VARIABLES def target_summary_with_cat(data, target): cats_names = [col for col in data.columns if len(data[col].unique()) < 10 and col not in target] for var in cats_names: print(pd.DataFrame({"TARGET_MEAN": data.groupby(var)[target].mean()}), end="\n\n\n") plot_categories(df, cat=var, target='Risk') plt.show() target_summary_with_cat(df, "Risk") # TARGET ANALYSIS BASED ON NUMERICAL VARIABLES def target_summary_with_nums(data, target): num_names = [col for col in data.columns if len(data[col].unique()) > 5 and df[col].dtypes != 'O' and col not in target] for var in num_names: print(df.groupby(target).agg({var: np.mean}), end="\n\n\n") target_summary_with_nums(df, "Risk") # INVESTIGATION OF NUMERICAL VARIABLES EACH OTHER def correlation_matrix(df): fig = plt.gcf() fig.set_size_inches(10, 8) plt.xticks(fontsize=10) plt.yticks(fontsize=10) fig = sns.heatmap(df[num_cols].corr(), annot=True, linewidths=0.5, annot_kws={'size': 12}, linecolor='w', cmap='RdBu') plt.show() correlation_matrix(df) # 6. WORK WITH OUTLIERS def outlier_thresholds(dataframe, variable): quartile1 = dataframe[variable].quantile(0.25) quartile3 = dataframe[variable].quantile(0.75) interquantile_range = quartile3 - quartile1 up_limit = quartile3 + 1.5 * interquantile_range low_limit = quartile1 - 0.5 * interquantile_range return low_limit, up_limit num_cols2 = [col for col in df.columns if df[col].dtypes != 'O' and len(df[col].unique()) > 10] def Has_outliers(data, number_col_names, plot=False): Outlier_variable_list = [] for col in number_col_names: low, high = outlier_thresholds(df, col) if (df[(data[col] < low) | (data[col] > high)].shape[0] > 0): Outlier_variable_list.append(col) if (plot == True): sns.boxplot(x=col, data=df) plt.show() print('Variables that has outliers: ', Outlier_variable_list) return Outlier_variable_list # def Replace_with_thresholds(data, col): # low, up = outlier_thresholds(data, col) # data.loc[(data[col] < low), col] = low # data.loc[(data[col] > up), col] = up # print("Outliers for ", col, "column have been replaced with thresholds ", # low, " and ", up) # # # var_names = Has_outliers(df, num_cols2, True) # # # print(var_names) # # for col in var_names: # Replace_with_thresholds(df, col) # MISSING VALUE ANALYSIS # Is there any missing values print(df.isnull().values.any()) #NO! # 8. LABEL ENCODING def label_encoder(dataframe): labelencoder = preprocessing.LabelEncoder() label_cols = [col for col in dataframe.columns if dataframe[col].dtypes == "O" and len(dataframe[col].value_counts()) == 2] for col in label_cols: dataframe[col] = labelencoder.fit_transform(dataframe[col]) return dataframe # df = label_encoder(df) # ONE-HOT ENCODING def one_hot_encoder(dataframe, category_freq=20, nan_as_category=False): categorical_cols = [col for col in dataframe.columns if len(dataframe[col].value_counts()) < category_freq and dataframe[col].dtypes == 'O'] dataframe = pd.get_dummies(dataframe, columns=categorical_cols, dummy_na=nan_as_category, drop_first=True) return dataframe df = one_hot_encoder(df) #LOF applied clf = LocalOutlierFactor(n_neighbors = 20, contamination=0.1) clf.fit_predict(df) df_scores = clf.negative_outlier_factor_ # np.sort(df_scores)[0:1000] threshold = np.sort(df_scores)[100] outlier_tbl = df_scores > threshold press_value = df[df_scores == threshold] outliers = df[~outlier_tbl] res = outliers.to_records(index = False) res[:] = press_value.to_records(index = False) df[~outlier_tbl] = pd.DataFrame(res, index = df[~outlier_tbl].index) Has_outliers(df, num_cols2, True) # Drop Unimportant columns # LGBM --> ['Job_category_unskilled_nonres', # 'Saving accounts_quite rich', # 'Purpose_domestic appliances' # 'Purpose_repairs', # 'Purpose_vacation/others', # 'NEW_SEX_CAT_seniorfemale', # 'NEW_SEX_CAT_youngfemale'], # dtype='object') # df.drop(['Job_category_unskilled_nonres', # 'Saving accounts_quite rich', # 'Purpose_domestic appliances', # 'Purpose_repairs', # 'Purpose_vacation/others', # 'NEW_SEX_CAT_seniorfemale', 'NEW_SEX_CAT_youngfemale'], axis=1, inplace=True) # RF --> # MODELLING y = df["Risk"] X = df.drop(["Risk"], axis=1) models = [#('RF', RandomForestClassifier())] # ('XGB', GradientBoostingClassifier())] # ("LightGBM", LGBMClassifier())] # ('KNN', KNeighborsClassifier())] ('SVC', SVC())] # evaluate each model in turn results = [] names = [] for name, model in models: kfold = KFold(n_splits=10, random_state=123) cv_results = cross_val_score(model, X, y, cv=10, scoring="accuracy") results.append(cv_results) names.append(name) msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print('Base: ', msg) # RF Tuned if name == 'RF': rf_params = {"n_estimators": [500, 1000, 1500], "max_features": [5, 10], "min_samples_split": [20, 50], "max_depth": [50, 100, None]} rf_model = RandomForestClassifier(random_state=123) print('RF Baslangic zamani: ', datetime.now()) gs_cv = GridSearchCV(rf_model, rf_params, cv=10, n_jobs=-1, verbose=2).fit(X, y) rf_cv_model = GridSearchCV(rf_model, rf_params, cv=10, verbose=2, n_jobs=-1).fit(X, y) # ??? print('RF Bitis zamani: ', datetime.now()) rf_tuned = RandomForestClassifier(**gs_cv.best_params_).fit(X, y) cv_results = cross_val_score(rf_tuned, X, y, cv=10, scoring="accuracy").mean() msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print('RF Tuned: ', msg) print('RF Best params: ', gs_cv.best_params_) # Feature Importance feature_imp = pd.Series(rf_tuned.feature_importances_, index=X.columns).sort_values(ascending=False) sns.barplot(x=feature_imp, y=feature_imp.index) plt.xlabel('Değişken Önem Skorları') plt.ylabel('Değişkenler') plt.title("Değişken Önem Düzeyleri") plt.show() plt.savefig('rf_importances.png') # LGBM Tuned elif name == 'LightGBM': lgbm_params = {"learning_rate": [0.01, 0.05, 0.1], "n_estimators": [500, 750, 1000], "max_depth": [8, 15, 20, 30], 'num_leaves': [31, 50, 100, 200]} lgbm_model = LGBMClassifier(random_state=123) print('LGBM Baslangic zamani: ', datetime.now()) gs_cv = GridSearchCV(lgbm_model, lgbm_params, cv=10, n_jobs=-1, verbose=2).fit(X, y) print('LGBM Bitis zamani: ', datetime.now()) lgbm_tuned = LGBMClassifier(**gs_cv.best_params_).fit(X, y) cv_results = cross_val_score(lgbm_tuned, X, y, cv=10, scoring="accuracy").mean() msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print('LGBM Tuned: ', msg) print('LGBM Best params: ', gs_cv.best_params_) # Feature Importance feature_imp = pd.Series(lgbm_tuned.feature_importances_, index=X.columns).sort_values(ascending=False) sns.barplot(x=feature_imp, y=feature_imp.index) plt.xlabel('Değişken Önem Skorları') plt.ylabel('Değişkenler') plt.title("Değişken Önem Düzeyleri") plt.show() plt.savefig('lgbm_importances.png') # XGB Tuned elif name == 'XGB': xgb_params = { # "colsample_bytree": [0.05, 0.1, 0.5, 1], 'max_depth': np.arange(1, 6), 'subsample': [0.5, 0.75, 1], 'learning_rate': [0.005, 0.01, 0.05], 'n_estimators': [500, 1000, 1500], 'loss': ['deviance', 'exponential']} xgb_model = GradientBoostingClassifier(random_state=123) print('XGB Baslangic zamani: ', datetime.now()) gs_cv = GridSearchCV(xgb_model, xgb_params, cv=10, n_jobs=-1, verbose=2).fit(X, y) print('XGB Bitis zamani: ', datetime.now()) xgb_tuned = GradientBoostingClassifier(**gs_cv.best_params_).fit(X, y) cv_results = cross_val_score(xgb_tuned, X, y, cv=10, scoring="accuracy").mean() msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print('XGB Tuned: ', msg) print('XGB Best params: ', gs_cv.best_params_) # KNN Tuned elif name == 'KNN': knn_params = {"n_neighbors": np.arange(1,50)} knn_model = KNeighborsClassifier() print('KNN Baslangic zamani: ', datetime.now()) gs_cv = GridSearchCV(knn_model, knn_params, cv=10, n_jobs=-1, verbose=2).fit(X, y) print('KNN Bitis zamani: ', datetime.now()) knn_tuned = KNeighborsClassifier(**gs_cv.best_params_).fit(X, y) cv_results = cross_val_score(knn_tuned, X, y, cv=10, scoring="accuracy").mean() msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print('KNN Tuned: ', msg) print('KNN Best params: ', gs_cv.best_params_) # SVC Tuned elif name == 'SVC': svc_params = {"C": np.arange(1,10), 'kernel': ['linear', 'poly', 'rbf', 'sigmoid']} svc_model = SVC() print('SVC Baslangic zamani: ', datetime.now()) gs_cv = GridSearchCV(svc_model, svc_params, cv=10, n_jobs=-1, verbose=2).fit(X, y) print('SVC Bitis zamani: ', datetime.now()) svc_tuned = SVC(**gs_cv.best_params_).fit(X, y) cv_results = cross_val_score(svc_tuned, X, y, cv=10, scoring="accuracy").mean() msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std()) print('SVC Tuned: ', msg) print('SVC Best params: ', gs_cv.best_params_) # LGBM # Base: LightGBM: 0.758000 (0.036000) # LGBM Baslangic zamani: 2020-11-09 22:55:59.023605 # Fitting 10 folds for each of 144 candidates, totalling 1440 fits # LGBM Bitis zamani: 2020-11-09 23:00:29.306755 # LGBM Tuned: LightGBM: 0.766000 (0.000000) # LGBM Best params: {'learning_rate': 0.01, 'max_depth': 8, 'n_estimators': 500, 'num_leaves': 50} # # RF # Base: RF: 0.740000 (0.020000) # RF Baslangic zamani: 2020-11-09 16:56:06.939579 # Fitting 10 folds for each of 60 candidates, totalling 600 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers. # RF Bitis zamani: 2020-11-09 17:08:02.005124 # RF Tuned: RF: 0.759000 (0.000000) # RF Best params: {'max_depth': 50, 'max_features': 5, 'min_samples_split': 20, 'n_estimators': 500} # # # KNN # Base: KNN: 0.671000 (0.036180) # XKNN Baslangic zamani: 2020-11-09 17:17:44.633991 # Fitting 10 folds for each of 49 candidates, totalling 490 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers. # KNN Bitis zamani: 2020-11-09 17:17:49.196383 # KNN Tuned: KNN: 0.731000 (0.000000) # KNN Best params: {'n_neighbors': 28} # # # SVC # Base: SVC: 0.731000 (0.017000) # SVC Baslangic zamani: 2020-11-09 17:42:24.504876 # Fitting 10 folds for each of 36 candidates, totalling 360 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers. # ?SVC Bitis zamani: 2020-11-09 19:38:40.977620 # SVC Tuned: SVC: 0.751000 (0.000000) # SVC Best params: {'C': 4, 'kernel': 'linear'} # # # XGB # Base: XGB: 0.770000 (0.034928) # XGB Baslangic zamani: 2020-11-09 23:09:12.546576 # Fitting 10 folds for each of 270 candidates, totalling 2700 fits # [Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers. # XGB Bitis zamani: 2020-11-09 23:30:16.700013 # XGB Tuned: XGB: 0.773000 (0.000000) # XGB Best params: {'learning_rate': 0.005, 'loss': 'exponential', 'max_depth': 5, 'n_estimators': 1000, 'subsample': 1}
a50af9f75080606073a752281f515057d3544564
AlexLecq/algotraining
/syracuse_algo.py
643
3.796875
4
#Entrainement à l'épreuve Algo BTS SIO number_enter = "" number_vol = 0 trig = False while(type(number_enter) is not int): try: number_enter = int(input("Veuillez saisir un nombre entier positif : ")) if(number_enter < 0): number_enter = "" except ValueError: print("Ceci n'est pas un entier positif") for i in range(1,20): if(number_enter % 2 == 0): number_enter /= 2 else: number_enter = (number_enter * 3) + 1 print(number_enter) if(number_enter != 1 and trig == False): number_vol += 1 else: trig = True continue print("Dernier nombre = " + str(number_enter)) print("Temps de vol = " + str(number_vol))
d2d8f309a900c4642f0e7c66b3d33e26cabaf4e9
synaplasticity/py_kata
/ProductOfFibNumbers/product_fib_num.py
597
4.34375
4
def fibonacci(number): if number == 0 or number == 1: return number*number else: return fibonacci(number - 1) + fibonacci(number - 2) def product_fib_num(product): """ Returns a list of the two consecutive fibonacci numbers that give the provided product and a boolean indcating if those two consecutive numbers where found. """ for n in range(1, product): f1 = fibonacci(n) f2 = fibonacci(n + 1) if f1 * f2 == product or f1 * f2 > product: break return [f1, f2, f1 * f2 == product] # return list[0]
4feaa6f54c0f3936461284ca0f3ef691bec7a559
rockneurotiko/ViolentPython
/Chapter-2/AnonymousFTPScanner.py
3,522
3.703125
4
import ftplib import optparse import re from threading import * maxConnections = 20 # The number of max connections at time connection_lock = BoundedSemaphore(value=maxConnections) #The Semaphore to control the max connections def anonLogin(* hostname): """ anonLogin tries to do the anonymous connection against the hostname or IP given as argument Have to remake the IP because sometimes the argument is a tuple instead of a string [A tuple like ("1","9","2",".","0",".","0",".","1")] """ IP = "" for i in hostname: IP = IP + i hostname = IP try: ftp = ftplib.FTP(hostname) ftp.login("anonymous", "[email protected]") print "\n[+]" + str(hostname) + " FTP Anonymous Logon Succeded" ftp.quit() return True except Exception, e: print "\n[-] %s FTP Logon Failed." % str(hostname) return False finally: connection_lock.release() def ipRange(start_ip, end_ip): """ ipRange is a function that takes a start IP and an end IP and return a list with all the range of the IPs >>> ipRange(192.168.1.1, 192.168.1.3) ["192.168.1.1","192.168.1.2","192.168.1.3"] """ start = list(map(int, start_ip.split("."))) end = list(map(int, end_ip.split("."))) temp = start ip_range = [] ip_range.append(start_ip) while temp != end: start[3] += 1 for i in (3, 2, 1): if temp[i] == 256: temp[i] = 0 temp[i-1] += 1 ip_range.append(".".join(map(str, temp))) return ip_range """ [TODO] If difference between a range of IPs or a hostname, so if a hostname is given try to do the Anon FTP Login against that hostname """ def main(): #Take the flags options. parser = optparse.OptionParser("usage %prog -s <IP from> -e <IP end>") parser.add_option("-s", dest="startIP", type="string", help="Specify the first IP") parser.add_option("-e", dest="endIP", type="string", help="Specify the last IP") (options, args) = parser.parse_args() startIP = options.startIP endIP = options.endIP #Control that both arguments have been passed if startIP == None or endIP == None: print parser.usage exit(1) #Check IPs with a regular expression. IPpattern = re.compile(r'\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b') isStartIP = IPpattern.search(startIP) isEndIP = IPpattern.search(endIP) if isStartIP == None or isEndIP == None: print parser.usage exit(1) #Split the IP's startIPRanges = startIP.split(".") endIPRanges = endIP.split(".") #Check if second one is grather or equal than the first one. That works beause of the lazy operators if endIPRanges[0] < startIPRanges[0] or endIPRanges[1] < startIPRanges[1] or endIPRanges[2] < startIPRanges[2] or endIPRanges[3] < startIPRanges[3]: print "[-] Error, the last IP must be greater" exit(1) IP_Range = ipRange(startIP, endIP) for i in IP_Range: connection_lock.acquire() #This semaphore is just to don't do more than 20 threads at time and don't overload the CPU print "[-] Testing %s" % i t = Thread(target=anonLogin, args=i) child = t.start() if __name__ == "__main__": main()
3abc9bc82008facaecb41970af680588e087612c
nedsanchezca/Juegode21
/Juego_21.py
3,378
4.09375
4
#Programa que sirve como juego de 21, cuya principal caracteristica es que no tiene asignaciones import random """"Funcion que permite dar carta apartir de un mazo""" def darMazo(): return [['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']] """"Funcion que permite asignar un valor a la carta si no tiene un valor numerico""""" def analizarCarta(card): if (card == 'K' or card == 'Q' or card == 'J'): return 10 elif (card == 'A'): return 1 or 11 else: return int(card) """""Funcion que anade a la baraja de juego las cartas en forma de una lista""""" def repartirCartas(mazo): mazo[0].insert(len(mazo[0]), analizarCarta(darMazo()[0][random.randint(0, 12)])) mazo[1].insert(len(mazo[1]), analizarCarta(darMazo()[0][random.randint(0, 12)])) return mazo """"Funcion que permite obtener el puntaje con respecto a los ases""" def obtenerMPuntaje(cartas, nu): if (nu == 0): return sum(cartas) elif (sum(cartas) + 10 * nu <= 21): return sum(cartas) + 10 * nu; else: return obtenerMPuntaje(cartas, nu - 1) def obtenerPuntaje(cartas): return obtenerMPuntaje(cartas, cartas.count(1)) """""Funcion que desarrolla el juego de la persona""""" def turnoJugador(cartas): print ("Su turno: ") print ("Su puntaje es: "), obtenerPuntaje(cartas[0]) if (obtenerPuntaje(cartas[0]) == 21): print("Ha ganado") elif (obtenerPuntaje(cartas[0]) < 21): print ("Sus cartas son:"), cartas[0] print ("si quiere coger otra carta oprima cualquier letra, si quiere plantarse oprima (0)") if (raw_input() != "0"): cartas[0].insert(len(cartas[0]), analizarCarta(darMazo()[0][random.randint(0, 12)])) return Juego(cartas, 'J') else: print("Maquina") return Juego(cartas, 'M') elif (obtenerPuntaje(cartas[0]) > 21): print("ha perdido el juego") print cartas """""Parte que desarrolla el juego de la maquina""" def turnoMaquina(cartas): if (obtenerPuntaje(cartas[1]) < 21 and (obtenerPuntaje(cartas[1]) <= obtenerPuntaje(cartas[0]))): if (obtenerPuntaje(cartas[1]) == obtenerPuntaje(cartas[0])): print ("empate, maquina gana") print cartas else: print ("maquina ha sacado una carta") cartas[1].insert(len(cartas[1]), analizarCarta(darMazo()[0][random.randint(0, 12)])) print(cartas) return Juego(cartas, 'M') if (obtenerPuntaje(cartas[1]) > 21): print ("Jugador ha ganado") print cartas if (obtenerPuntaje(cartas[1]) <= 21 and (obtenerPuntaje(cartas[1]) > obtenerPuntaje(cartas[0]))): print("Maquina gana") print cartas """""Parte del juego donde se asignan las cartas a jugar y cuando juega la maquina""" def Juego(mazo, jug): #print cartas if (mazo[0] == []): print ("Reparte cartas al jugador y al repartidor") return Juego(repartirCartas(mazo), 'J') elif (len(mazo[0]) == 1): print ("Reparte cartas jugador y al repartidor") return Juego(repartirCartas(mazo), 'J') if (jug == "M"): turnoMaquina(mazo) elif (len(mazo[0]) >= 2 and (jug == "J")): turnoJugador(mazo) Juego([[], []], 'J')
fda8998e0a52b89047d60b48acbc66138f07d1e3
billafy/Sample-Regression-Models-Python
/LinearRegression.py
1,429
4.0625
4
import numpy as np # Python Library used for efficient computation on arrays import scipy as sp # Science Python basically from scipy import stats # Importing stats module from scipy import matplotlib.pyplot as mpl # Matrices and Graph Plot Library called to plot our graph x = [5,7,8,7,2,17,2,9,4,11,12,9,6] # random sample dataset y = [99,86,87,88,111,86,103,87,94,78,77,85,86] slope,intercept,r,p,std_err = stats.linregress(x,y) # passing our dataset (x,y) to linear regression function in stats # module to get the slope, x and y intercepts, r(correlation), # p(P value of Regression), std_err(Standard Error of Regression) def predictSpeed(x) : # this function will predict the speed of our car i.e. predict y value on given x value return (slope*x) + intercept # this formula is basically y = a + bx (a : intercept, b : slope) mymodel = list(map(predictSpeed,x)) # this will map our function predictSpeed values to a Python List (we named it mymodel) mpl.scatter(x,y) # scatter the x and y points on the graph mpl.plot(x,mymodel) # plot mymodel mpl.show() # show it yrs = input("How old is your car : ") # take input of age of the car yrs = float(yrs) speed = predictSpeed(yrs) # pass it to the function print("The speed of your car is :",np.around(speed,3)) # output our prediction # Bawal Billa
caef72e12a5dfdee3d73c8b832077622c7ccaf08
smaeil/Des-101-m
/odd_even_sum(ismail_ahmadi).py
355
4.0625
4
number = int(input('Please enter a number that all odds and even numbers can be sumec upto: ')) odd_total = 0 even_total = 0 for n1 in range(1, (number + 1), 2): odd_total += n1 for n2 in range(2, (number + 1), 2): even_total += n2 print('The Sume of even Numbers upto {} is ={} and sum of even is ={}'.format(number, even_total, odd_total))
eb8eb12677310dcad5e6e67c8af08b7fa1b39000
kblicharski/big-data-hackathon-2017
/tutorial_scripts/pandas_video_tutorial.py
915
4.03125
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np from matplotlib import style style.use('ggplot') # How to create a DataFrame? web_stats = {'Day': [1, 2, 3, 4, 5, 6], 'Visitors': [43, 53, 34, 45, 64, 34], 'Bounce_Rate': [65, 72, 62, 64, 54, 66]} df = pd.DataFrame(web_stats) # How to visualize the data? ''' print(df) print(df.head()) print(df.tail()) print(df.tail(2)) ''' # How do we set the index? # new_df = df.set_index('Day') # print(new_df) df.set_index('Day', inplace=True) # How do we access a column? # print(df['Visitors']) # How do we access multiple columns? print(df[['Bounce_Rate', 'Visitors']]) # How do we turn a column of values into a list? print(df['Visitors'].tolist()) # What about multiple columns (a 2d array)? print(np.array(df[['Bounce_Rate', 'Visitors']])) df2 = pd.DataFrame(np.array(df[['Bounce_Rate', 'Visitors']])) print(df2)
861ce17144191ed60bdfe7938c4de8a3cb7d0fe5
LeonardoLDSZ/PythonNt
/app/variaveis.py
335
3.71875
4
#string = str --------- FUNÇÕES nome = 'Leonardo' #inteiro = int ---- FUNÇÕES idade = 10 #float ----- função # salario = float(input('Digite seu salario: ')) # print(f'Salario: {salario}') # Boaleana - TRUE OR FALSE - Variável LÓGICA verdadeiro = True falso = False bebe = bool(input('Voce bebe?')) print(f'Bebe: {bebe}')
b544a1b3eefab89ecb8fd6d93768ffbcbd99e16c
LeonardoLDSZ/PythonNt
/app/app/15-2-Classes.py
849
4.0625
4
# Classes # Variáveis de classe # Métodos de classe # self class Calculadora: n1 = 0 n2 = 0 def soma(self): resultado = self.n1 + self.n2 return resultado def subtracao(self): resultado = self.n1 - self.n2 return resultado def multiplicacao(self): resultado = self.n1 * self.n2 return resultado def divisao(self): resultado = self.n1 / self.n2 return resultado # Criação de uma variavél de tipo Classe Calculadora # Em POO = Instanciando um objeto da classe Calculadora calculadora = Calculadora() calculadora.n1 = 10 calculadora.n2 = 20 res = calculadora.soma() res2 = calculadora.subtracao() res3 = calculadora.multiplicacao() res4 = calculadora.divisao() print(res) print(res2) print(res3) print(res4)
ce9673a77c9479c98b2adbedfc49603a2ba60ece
LeonardoLDSZ/PythonNt
/app/inicio.py
555
4.09375
4
# #---- Imprimir info na tela (COMENTÁRIO) # #CTRL+K CTRL+C print('\n') # pular de linha print('*'*50) print('Olá', 'Joelma', 'do Calypso') print('Olá' + 'Chimbinha' + 'do Calypso') print('\n') # Pegar entrada do usuário nome = input('Digite seu nome: ') #ler sobrenome = input('Digite seu sobrenome: ') # usando a função format para concatenação de string print('Ola {} {}'.format( nome, sobrenome)) # interpolação de strings print( f'ola {nome} {sobrenome}') idade = (input('Digite a idade: ')) print (idade)
26060fca3e7b21456256310d8f73d0ae4bf92c4b
LeonardoLDSZ/PythonNt
/app/app/10-ex_dict.py
456
4.03125
4
#--- Cadastro de cerveja marca = input('Digite a marca da cerveja: ') tipo = input('Digite o tipo da cerveja: ') #---- Criando um dicionario vazio cervas = {} #--- Criando as chaves/valores apos a criacao do dicionario cervas['marca'] = marca cervas['tipo'] = tipo #---- Criando o dicionario com as chaves e valores cervas2 = {'marca':marca, 'tipo':tipo } print(cervas) print(cervas2) #cadastro de pessoa com nome, sobrenome e cpf
027769fe44d4c08972c3741924a7492247503142
stolaf-acm/vindinium-python
/example.py
718
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Example program using the vindinium package import vindinium client = vindinium.client() # Initialization / Configuration of the game goes here client.setKey('your_key') client.setParam('mode', 'training') # Begin the game client.startGame() # This is the main loop of the game, where you will decide how to move while not client.game.finished: # Code here to decide how to make a move # Make the chosen move - this function will update client's game and state # 'dir' can be one of 'Stay', 'North', 'South', 'East', or 'West' client.makeMove('dir') # See the results of the game print(client.game.results()) # Close the client client.close()
1687b77c4b2d3c44b6871e653a974153db7d3f96
ntuthukojr/holbertonschool-higher_level_programming-6
/0x07-python-test_driven_development/0-add_integer.py
578
4.125
4
#!/usr/bin/python3 """Add integer module.""" def add_integer(a, b=98): """ Add integer function. @a: integer or float to be added. @b: integer or float to be added (default set to 98). Returns the result of the sum. """ if not isinstance(a, int) and not isinstance(a, float): raise TypeError('a must be an integer') if not isinstance(b, int) and not isinstance(b, float): raise TypeError('b must be an integer') if isinstance(a, float): a = int(a) if isinstance(b, float): b = int(b) return (a + b)
121163d7ae0f64e8294a005550e6f052ce276477
ntuthukojr/holbertonschool-higher_level_programming-6
/0x0A-python-inheritance/4-inherits_from.py
259
3.75
4
#!/usr/bin/python3 """Only a sub class of module""" def inherits_from(obj, a_class): """Returns True if obj is an instance of a class that inherited from a_class; False otherwise""" return (type(obj) is not a_class and isinstance(obj, a_class))
53acf1631239ce2a0e369c83c395a8096394f7c6
ntuthukojr/holbertonschool-higher_level_programming-6
/0x0A-python-inheritance/100-my_int.py
311
3.703125
4
#!/usr/bin/python3 """MyInt class Module""" class MyInt(int): """Class MyInt that inherits from int""" def __eq__(self, other): """Inverts == and !=""" return not super().__eq__(other) def __ne__(self, other): """Inverts == and !=""" return not self.__eq__(other)
430943c3678d42e89da21a4906ff6ca160f60f37
evnewlund9/repo-evnewlund
/PythonCode/letterFrequency2.py
819
4.0625
4
def letterFrequency(phrase): string1 = ".,;:!? " for i in string1: phrase = phrase.replace(i,"") phrase = phrase.lower() phrase = [i for i in phrase] phrase.sort() dictionary = {} for letter in phrase: if letter not in dictionary: dictionary[letter] = 1 else: dictionary[letter] += 1 return dictionary def main(): frequencies = [] dictionary_final = {} phrase = input("Enter a string: ") dictionary = letterFrequency(phrase) for i in dictionary.values(): frequencies.append(i) frequencies.sort() for key, value in dictionary.items(): dictionary_final[key] = value for frequency in frequencies: print(dictionary_final[frequency], frequency) if __name__ == '__main__': main()
6d68b8627f25314a66c63a8597376046a834a4b2
evnewlund9/repo-evnewlund
/PythonCode/binary.py
668
4.0625
4
def binaryToInt(binary_string): binary = [character for character in binary_string] binary.reverse() x = 0 base_ten_number = 0 for i in binary: base_ten_number = base_ten_number + (2 * int(i)) ** x x = x + 1 return base_ten_number def main(): binary_string = str(input("Input a binary value: ")) print(binaryToInt(binary_string)) repeat = input("Continue? (y/n): ") if repeat == "y": while repeat == "y": binary_string = str(input("Input a binary value: ")) print(binaryToInt(binary_string)) repeat = input("Continue? (y/n): ") if __name__ == '__main__': main()
9acd9e00cfcfc930041f285225f5fb9c084dc94f
evnewlund9/repo-evnewlund
/PythonCode/rankandSuitCount.py
510
3.71875
4
def rankandSuitCount(hand): card_rank = {} card_suit = {} for card in hand: if card[0] not in card_rank: card_rank[card[0]] = 1 else: card_rank[card[0]] += 1 if card[1] not in card_suit: card_suit[card[1]] = 1 else: card_suit[card[1]] += 1 return card_rank, card_suit def main(): rank, suit = rankandSuitCount(['AS','AD','2C','TH','TS']) print(rank) print(suit) if __name__ == '__main__': main()
85c9d985cb91e3af51bd3358b0e66813df2d2f66
evnewlund9/repo-evnewlund
/PythonCode/test.py
581
3.6875
4
from turtle import * import tkinter.messagebox import tkinter window = tkinter.Tk() canvas = ScrolledCanvas(window,600,600,600,600) t = RawTurtle(canvas) screen = t.getscreen() screen.setworldcoordinates(-500,-500,500,500) frame = tkinter.Frame(window) frame.pack() window.title("What kind of farm do you have?") def NextQuestion(): print("placeholder") cattle = tkinter.Button(screen,text = "Cattle Farm",command = NextQuestion()) dairy = tkinter.Button(screen,text = "Dairy Farm",command = NextQuestion()) cattle.pack() dairy.pack() screen.listen() tkinter.mainloop()
df7369f0ae106b4cdbfe5f289d1556ac0021b1c3
evnewlund9/repo-evnewlund
/PythonCode/turtle_matrix.py
629
3.84375
4
import turtle import sparse import matrix import random def showMatrix(turtle_object,m,n): screen = turtle.getscreen() screen.tracer(0) value = 1 x = 0 m = matrix.matrix(n,0) while x <= n: x = x + 1 num1 = random.randint(0,n-1) num2 = random.randint(0,n-1) m[num1][num2] = 1 screen.setworldcoordinates(0.00,0.00,n-1,n-1) for n in m: if n != 0: turtle.goto(num1,num2) turtle.dot() turtle.update() def main(): turtle_object = turtle.Turtle() showMatrix(turtle_object,5,5) if __name__=="__main__": main()
87ee73accac83e33eb0bf032d403ca1fa16c3b63
evnewlund9/repo-evnewlund
/PythonCode/reverse_string.py
414
4.28125
4
def reverse(string): list = [character for character in string] x = 0 n = -1 while x <= ((len(list))/2)-1: a = list[x] b = list[n] list[x] = b list[n] = a x = x + 1 n = n - 1 stringFinal = "" for letter in list: stringFinal += letter return stringFinal def main(): reverse_string(string) if __name__=="__main__": main()
394bc8e14a370f22d39fc84f176275c58d1ac349
evnewlund9/repo-evnewlund
/PythonCode/alternating_sum.py
414
4.125
4
def altSum(values): sum = 0 for i in range(1,(len(values) + 1),2): sum = sum + (int(values[i]) - int(values[(i - 1)])) return sum def main(): values = [] num = "0" while num != "": values.append(num) num = input("Enter a floating point value: ") answer = str(altSum(values)) print("The alternating sum is: " + answer) if __name__ == "__main__": main()
308cce9f2d44d377db2566246fc29ef76f977432
abochkarev/simple-python-exercises
/test15.py
461
3.9375
4
from common import show @show def find_longest_word(list_): if not list_: raise RuntimeError("List shouldn't be none or empty") max_length = len(list_[0]) for i in xrange(1, len(list_)): if len(list_[i]) > max_length: max_length = len(list_[i]) return max_length assert find_longest_word(["abc", "cdf", "fgh", "a"]) == 3 assert find_longest_word(["a", "bb"]) == 2 assert not find_longest_word(["a", "bbb"]) == 2
11411d0b5837eb137b68c5a751c36568a213ad52
abochkarev/simple-python-exercises
/test27.py
415
3.703125
4
from common import show @show def for_loop(list_): res_list_ = [] for i in list_: res_list_.append(len(i)) return res_list_ @show def map_(list_): return map(len, list_) @show def list_comprehension(list_): return [len(i) for i in list_] list_ = ["a", "bb", "ccc"] assert for_loop(list_) == [1, 2, 3] assert map_(list_) == [1, 2, 3] assert list_comprehension(list_) == [1, 2, 3]
69cab52c841abc15caa898d0602a5ece350c2e76
abochkarev/simple-python-exercises
/test38.py
357
3.546875
4
def calc_words_average(file_name): word_lens = 0 word_counts = 0 with open(file_name) as f: while True: data = f.readline().strip() if not data: break word_lens += len(data) word_counts += 1 return word_lens / word_counts print calc_words_average('semordnilaps.txt')
8e00e1ad02a850917c6bc6d04b5c827d65ca5ca0
abochkarev/simple-python-exercises
/test1.py
145
3.53125
4
from common import show @show def max(a, b): return a if a >= b else b assert max(1, 3) == 3 assert max(3, 1) == 3 assert max(2, 2) == 2
dc4e919f72c815bbb536ee2a1533b2736ce2b7f3
abochkarev/simple-python-exercises
/test43.py
1,192
3.546875
4
from collections import defaultdict class FileReader(object): def __init__(self, file_name): super(FileReader, self).__init__() self.file_name = file_name def read_file(self): with open(self.file_name, mode='r') as f: while True: line = f.readline() if not line: break yield line.rstrip() class WordFinder(object): def __init__(self, text): super(WordFinder, self).__init__() self.words_map = defaultdict(list) for line in text: sorted_line = ''.join(sorted(line)) self.words_map[sorted_line].append(line) def find_words(self): return filter(lambda x: len(x) > 1, self.words_map.values()) class WordPrinter(object): def __init__(self, words): super(WordPrinter, self).__init__() self.words = words def print_words(self): for word in self.words: print word file_reader = FileReader('unixdict.txt') text_ = file_reader.read_file() word_finder = WordFinder(text_) words_ = word_finder.find_words() word_printer = WordPrinter(words_) word_printer.print_words()
440598418bc4e3f8e9062e81d369bc770bbde4bc
anujpuri72/LeetCodeSubmissions
/MayChallenge/Week1/CousinsinBinaryTree.py
1,408
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def lookup(self, root: TreeNode, x: int): if (root == None): return -999999 elif (root.val == x): return 0 else: leftheight = self.lookup(root.left, x)+1 rightheight = self.lookup(root.right, x)+1 return max(leftheight, rightheight) def findp(self, root: TreeNode, x: int): if (root == None): return None elif ((root.right != None and root.right.val == x) or (root.left != None and root.left.val == x)): return root else: found = self.findp(root.right, x) if (found == None): found = self.findp(root.left, x) return found def isCousins(self, root: TreeNode, x: int, y: int) -> bool: x_height = self.lookup(root, x) y_height = self.lookup(root, y) x_baap = self.findp(root, x) # print(x_height,y_height) if(x_height == y_height): if ((x_baap.right != None and x_baap.right.val == y) or (x_baap.left != None and x_baap.left.val == y)): return False else: return True else: return False
7d664b1fbf29656fc2244808a506cd3a83687a29
jggautier/tabulate
/src/tabulate
11,727
3.640625
4
#!/usr/bin/env python3 import pdb import argparse import textwrap import shutil import itertools from itertools import combinations_with_replacement import logging import sys def make_parser(): parser = argparse.ArgumentParser( description='Make fixed-width plaintext table with multi-line cell ' 'supports. Currently only support grid table, but it\'s ' 'trivial to adapt it to other layout once the table has ' 'been built. What plaintext table content is expected: ' '<TAB> will be regarded as field delimiter, <LF> ' '(or <CRLF> if on Windows) as row delimiter, and all the ' 'others as cell content.') parser.add_argument('-W', '--widths', metavar='WIDTH_LIST', type=comma_sep_list, help='a comma-separated list of WIDTH (int) or `-\'' ' specifying the width of each column; `-\' ' 'implies that the width of the underlying ' 'column can be decided by the program in ' 'objective of minimizing the total number of ' 'rows. Each WIDTH defines the maximum number of ' 'characters in the cell per row, except that ' 'when `-B\' is specified, (WIDTH - 2) will be ' 'the maximum number. Note, however, that the ' 'sum of WIDTHs does not necessarily equal to ' 'the width of table, since the table layout is ' 'not taken into account with WIDTHs.') parser.add_argument('-T', '--table-width', type=int, dest='total_width', help='the total table width; if specified, unless ' 'WIDTH_LIST contains at least one `-\', ' 'TABLE_WIDTH may not imply the actual table ' 'width rendered; default to terminal width') parser.add_argument('-B', '--bullets', metavar='CHARS', default='', type=bullet_set, help='a set of characters used as leading bullets ' 'with additional indentation; default none') parser.add_argument('-y', '--break-hyphen', action='store_true', dest='break_on_hyphens', help='to allow break on hyphen of long words') parser.add_argument('-L', '--layout', default='grid', help='table layout; default to %(default)s', choices=('grid',)) parser.add_argument('-S', '--strict', action='store_true', help='to enable strict mode, where wrapped lines ' 'exceeding the WIDTHs that will ruin the table ' 'layout are forbidden') parser.add_argument('-d', '--delimiter', default='\t', help='the column delimiter in input data, default ' 'to <TAB>') parser.add_argument('filename', nargs='?', metavar='FILE', help='table content from which to read; if FILE is ' 'not specified, the table content will be ' 'expected from stdin') return parser def comma_sep_list(string): try: l = [None if x == '-' else int(x) for x in string.rstrip('\n').split(',')] except ValueError as ex: raise argparse.ArgumentTypeError from ex return l def bullet_set(string): return list(map('{} '.format, string)) def read_content(args_filename, delimiter): if not args_filename: content = list(sys.stdin) else: try: with open(args_filename) as infile: content = list(infile) except IOError: logging.exception('Failed to read "%s"', args_filename) sys.exit(1) content = [l.rstrip('\n').split(delimiter) for l in content] return content def enum_partitions(l, k): if not l: return sl = sum(l) if sl > k: raise ValueError for x in combinations_with_replacement(range(k-sl+1), len(l)-1): x1 = x + (k-sl,) x2 = (0,) + x yield tuple(x1[i]-x2[i]+l[i] for i in range(len(l))) def ensure_ncols(content, user_widths, n_cols, strict): if user_widths is None: user_widths = [None for _ in range(n_cols)] elif len(user_widths) != n_cols: if strict: logging.error('Number of width specified (%d) does not ' 'match number of table columns (%d)', len(user_widths), n_cols) sys.exit(4) if len(user_widths) < n_cols: user_widths += [None for _ in range(n_cols - len(user_widths))] else: user_widths = user_widths[:n_cols] logging.warning('Number of width specified (%d) does not match ' 'number of table columns (%d); truncating/padding ' 'WIDTH_LIST to %s', len(user_widths), n_cols, user_widths) return user_widths def enum_possible_widths(content, user_widths, total_width, layout, break_on_hyphens, strict): n_cols = max(map(len, content)) user_widths = ensure_ncols(content, user_widths, n_cols, strict) assert len(user_widths) == n_cols layout_consumption = { 'grid': n_cols * 3 + 1, }[layout] total_width = total_width - layout_consumption logging.debug('Layout %s consumes %d from the total width %d', layout, layout_consumption, layout_consumption + total_width) llimits = find_width_llimits(content, break_on_hyphens) noneIndices = [i for i, x in enumerate(user_widths) if x is None] llimits = [llimits[i] for i in noneIndices] if llimits: partial_total = total_width - sum(filter(None, user_widths)) for partial_widths in enum_partitions(llimits, partial_total): w = user_widths[:] for j, i in enumerate(noneIndices): w[i] = partial_widths[j] yield w else: yield user_widths def find_width_llimits(rows, break_on_hyphens): if break_on_hyphens: def split_(string): return re.split(r'\s|-', string) else: def split_(string): return string.split() n_cols = max(map(len, rows)) ll = [0 for _ in range(n_cols)] for j in range(n_cols): for r in rows: try: cell = r[j] except IndexError: pass else: lwordlen = max(map(len, split_(cell))) if break_on_hyphens: lwordlen += 1 ll[j] = max(ll[j], lwordlen) return ll def wrap_lines(row, widths, bullets_space, break_on_hyphens): return [ textwrap.wrap(s, widths[j] - 2, subsequent_indent=' ' if s[:2] in bullets_space else '', break_long_words=False, break_on_hyphens=break_on_hyphens) for j, s in enumerate(row) ] class WrappedLineTooLongError(Exception): def __init__(self, rowid, colid, string): self.rowid = rowid self.colid = colid self.string = string def __repr__(self): return f'{self.__class__.__name__}(rowid=' \ f'{self.rowid}, colid={self.colid}, string={self.string})' def __str__(self): return f'Wrapped line "{self.string}" too long ' \ f'at row {self.rowid} col {self.colid}' def check_wrapped_lines(wrapped, widths): for j, col in enumerate(wrapped): for i, row in enumerate(col): if len(row) > widths[j]: raise WrappedLineTooLongError(i + 1, j + 1, row) def fill_wrapped_lines(wrapped, widths): return [([s + ' ' * (widths[j] - len(s)) for s in x] + [' ' * widths[j] for _ in range(max(map(len, wrapped)) - len(x))]) for j, x in enumerate(wrapped)] def attempt_wrap(content, widths, bullets_space, break_on_hyphens, strict): wrapped_rows = [wrap_lines(r, widths, bullets_space, break_on_hyphens) for r in content] err = None try: for wrapped in wrapped_rows: check_wrapped_lines(wrapped, widths) except WrappedLineTooLongError as err: if strict: raise nrows_total = sum(max(map(len, wr)) for wr in wrapped_rows) return nrows_total, err def find_best_widths(content, user_widths, bullets_space, break_on_hyphens, total_width, layout, strict): results = [] all_widths = [] for widths in enum_possible_widths(content, user_widths, total_width, layout, break_on_hyphens, strict): try: results.append(attempt_wrap(content, widths, bullets_space, break_on_hyphens, strict)) except WrappedLineTooLongError: pass else: all_widths.append(widths) if not results: logging.error('Not possible to form a table of current spec') sys.exit(8) noerr_results = [x[0] for x in results if x[1] is None] if noerr_results: results = noerr_results else: logging.warning('Not possible to form a table of current spec; the ' 'render result might be corrupted somewhat') results = [x[0] for x in results] return all_widths[results.index(min(results))] def do_wrap_and_fill(content, widths, bullets_space, break_on_hyphens): return [fill_wrapped_lines(wrap_lines( r, widths, bullets_space, break_on_hyphens), widths) for r in content] class TableRenderer: @classmethod def render_table(cls, wrapped_and_filled, widths, layout): try: f = getattr(cls, 'render_table_' + layout) except AttributeError as err: raise NotImplementedError from err else: return f(wrapped_and_filled, widths) @staticmethod def render_table_grid(wrapped_and_filled, widths): padded = [[[c.join(' ') for c in r] for r in col] for col in wrapped_and_filled] delimed = [list(map('|'.join, zip(*p))) for p in padded] delimed = [[r.join('||') for r in col] for col in delimed] hrule = '+'.join('-' * (w + 2) for w in widths).join('++') table = [[hrule]] for x in delimed: table.extend((x, [hrule])) return '\n'.join(itertools.chain.from_iterable(table)) def _main(): args = make_parser().parse_args() logging.basicConfig(format='%(filename)s: %(levelname)s: %(message)s') try: content = read_content(args.filename, args.delimiter) widths = find_best_widths(content, args.widths, args.bullets, args.break_on_hyphens, args.total_width or shutil.get_terminal_size().columns, args.layout, args.strict) wf = do_wrap_and_fill(content, widths, args.bullets, args.break_on_hyphens) table = TableRenderer.render_table(wf, widths, args.layout) print(table) except KeyboardInterrupt: pass except BrokenPipeError: sys.stderr.close() if __name__ == '__main__': _main()
a71c7b7eed40abbc353d208d3e214b448a57f807
somayejalilii/python_project3
/login.py
1,438
3.734375
4
import pandas as pd import hashlib import csv class User: def __init__(self, username, password): self.password = password self.username = username @staticmethod def log_in(): file_path = "account.csv" def_account = pd.read_csv(file_path) lst_username = list(def_account["username"]) username = input("enter your username") if username in lst_username: print("valid username") password = input("enter your password") hash_password = hashlib.sha256(password.encode("utf8")).hexdigest() if def_account.iloc[def_account.index[def_account['username'] == username].tolist()[0], 1] == hash_password: print("hello", username) def register(): file_path = "account.csv" def_account = pd.read_csv(file_path) lst_username = list(def_account["username"]) username = input("enter your username") if username in lst_username: print("valid username") password = input("enter your password") hash_password = hashlib.sha256(password.encode("utf8")).hexdigest() obj_user = User(username, hash_password) row_account = [[obj_user.username, obj_user.password]] with open(file_path, 'a', newline='') as csv_account: csv_writer = csv.writer(csv_account) # writing the data row csv_writer.writerows(row_account)
7294ac7e6fa9a8e9d9b17cc661f639f7a04c289f
vdubrovskiy/Python
/new.py
738
4.21875
4
# ------------------------------------------------------- # import library import math # ------------------------------------------------------- # calculate rect. square height = 10 width = 20 rectangle_square = height * width print("Площадь прямоугольника:", rectangle_square) # ------------------------------------------------------- # calculate circle square radius = 5 circle_square = math.pi * (radius**2) print("Площадь круга:", round(circle_square, 2)) print(type(circle_square)) # ------------------------------------------------------- # calculate hypotenuse catheter1 = 5 catheter2 = 6 hypotenuse = math.sqrt(catheter1**2 + catheter2**2) print("Гипотенуза:", round(hypotenuse, 2))
2c49b99944d44d68b6997edde1614acbc86bc301
marcosmcz/The-Impact-of-The-Minimum-Wage-On-Other-Wages
/dataCleaningRound3.py
2,293
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 20 01:38:04 2018 @author: User """ import pandas as pd import numpy as np df = pd.read_csv('minWageData.csv') #####convert education column to ordered numerics #create a dictionary clean = {'Typical education needed for entry': {"Doctoral or professional degree":13, "Master's degree":9.5, "Bachelor's degree":8, "Associate's degree":6, "Some college, no degree":7, "Postsecondary nondegree award":5, "High school diploma or equivalent":4, "No formal educational credential":0}} df.replace(clean,inplace=True) ####take logs of wage and minWage df['log_Hourly_Wages']=np.log(df['H_MEAN']) df['log_minWage']=np.log(df['minWage']) ###drop that weird column df=df.drop(['Unnamed: 0'], axis = 1) ##group the states by years, so alabama will show up 12 times d = {'State' : state, 'Year': year, 'minWage':minWage} grouped = df.groupby('STATE') df_main = pd.DataFrame(columns = ['State','Year','minWage']) for state, group in grouped: #state is the name, group is a df groupedYear = group.groupby('Year') for year, groupYear in groupedYear: minWage = groupYear['minWage'].iloc[0] df_new = pd.DataFrame( {'State' : state, 'Year': year, 'minWage':minWage}, index = [0]) df_main = df_main.append(df_new) year df = group[[' #label the dataframes column with the states name and occ code df = df.rename(columns={'OCC_CODE': state +' '+ 'OCC_CODE'}) #set the index to an index starting at 0 df = df.reset_index(drop=True) df_main = pd.concat([df_main, df], axis = 1) #data frame for all jobs among all YEARS grouped = df.groupby('STATE') df_main_year = pd.DataFrame() for state, group in grouped: print(group) df.to_csv('minWageDataUpdated.csv', encoding='utf-8', index=False) df_main.to_csv('minWageDistributionData.csv', encoding='utf-8', index=False)
56c29eb34d1603305f5233dbc9003f46663fc8b8
AmazedCape518/Python
/FuelEfficiency.py
540
3.921875
4
# Chap8ex9 # Luke De Guelle # A program that determines the fuel efficiency def main(): odometer = eval(input("Enter the starting odometer: ")) counter = 1 cont = 1 while(cont!= '\n') print("Leg number ", counter,".") odo = eval(input("Enter the odometer value: ")) gas = eval(input("Enter the amount of gas in gallons used: ")) totalLeg = (odometer - odo) / gas odometer = odo print("The miles per gallon for leg",counter,"is",totalLeg) counter = counter + 1 cont = eval(input("Is there another leg?")) main()
5d0fa3d6ddd3354a3865391afc456f234f733909
Deepak-Vengatesan/Skillrack-Daily-Challenge-Sloution
/21-7-2021.py
375
3.671875
4
class Fruit: count = 0 totalQuantity= 0 def __init__(self,name,quantity): self.name = name self.quantity = quantity Fruit.count += 1 Fruit.totalQuantity += quantity def __del__(self): Fruit.count -= 1 Fruit.totalQuantity -= self.quantity def __str__(self): return f"{self.name} : {self.quantity}"
716a6d37b848e9a87d458ad92c365f2292189ac5
alialwahish/strsAndLists
/stringAndLists.py
416
3.859375
4
words = "It's thanksgiving day. It's my birthday,too!" words=words.replace("day","month") print(words) x = [2,54,-2,7,12,98] min =x[0] max =x[0] for val in x: if val > max: max=val if val < min: min=val print "Max is:", max, "Min is:", min y = ["hello",2,54,-2,7,12,98,"world"] print "first word: ", y[0], "last word:", y[len(y)-1] li = [19,2,54,-2,7,12,98,32,10,-3,6] li.sort() print(li)
acf45ca7eb0ab0c92eaaf3bc52727ce8652f9f19
nptit/Check_iO
/Scientific Expedition/verify_anagrams.py
464
3.8125
4
from collections import Counter def verify_anagrams(x, y): return True if Counter(a.lower() for a in x if a.isalpha()) == \ Counter(b.lower() for b in y if b.isalpha()) else False if __name__ == '__main__': assert isinstance(verify_anagrams("a", 'z'), bool), "Boolean!" assert verify_anagrams("Programming", "Gram Ring Mop") is True assert verify_anagrams("Hello", "Ole Oh") is False assert verify_anagrams("Kyoto", "Tokyo") is True
99494eb07c62209d729ebcc05fdf59ed3b2fe126
nptit/Check_iO
/Mine/broken_clock.py
1,438
3.59375
4
def seconds_to_hms(seconds): h, mins = divmod(seconds, 3600) m, s = divmod(mins, 60) return '{:0>2}:{:0>2}:{:0>2}'.format(h, m, s) def to_seconds(time, t_value=None): if isinstance(time, str): return sum(int(a) * b for a, b in zip(time.split(':'), (3600, 60, 1))) if t_value.startswith('second'): return time elif t_value.startswith('minute'): return time * 60 return time * 3600 def broken_clock(starting_time, wrong_time, error_description): uno, uno_val, dos, dos_val = error_description.replace('at', '').split() uno = to_seconds(int(uno), uno_val) dos = to_seconds(int(dos), dos_val) start_seconds = to_seconds(starting_time) diff = abs(start_seconds - to_seconds(wrong_time)) return seconds_to_hms(start_seconds + int((dos / (uno + dos)) * diff)) if __name__ == "__main__": assert broken_clock('00:00:00', '00:00:15', '+5 seconds at 10 seconds') \ == '00:00:10', "First example" assert broken_clock('06:10:00', '06:10:15', '-5 seconds at 10 seconds') \ == '06:10:30', 'Second example' assert broken_clock('13:00:00', '14:01:00', '+1 second at 1 minute') \ == '14:00:00', 'Third example' assert broken_clock('01:05:05', '04:05:05', '-1 hour at 2 hours') \ == '07:05:05', 'Fourth example' assert broken_clock('00:00:00', '00:00:30', '+2 seconds at 6 seconds') \ == '00:00:22', 'Fifth example'
9842a1aa6dc27d12fba03027c00e0f2249455dc9
nptit/Check_iO
/Home/median.py
603
3.859375
4
def checkio(lst): length = len(lst) lst = sorted(lst) if length % 2 == 0: mid = int(length / 2) return (lst[mid] + lst[mid-1]) / 2 return lst[int(length / 2)] if __name__ == '__main__': assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list" assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list" assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average" assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length" print("Start the long test") assert checkio(list(range(1000000))) == 499999.5, "Long." print("The local tests are done.")
826a6ae785689b53d4d2bcc22310bd55ad124849
nptit/Check_iO
/Alice In Wonderland/the_hidden_word.py
1,219
3.8125
4
from itertools import zip_longest def checkio(text, word): def result(start, line_num, horizontal=True): if horizontal: return [line_num, start + 1, line_num, start + len(word)] return [start + 1, line_num, start + len(word), line_num] horizontal = list() for dex, line in enumerate(text.split('\n')): curr = ''.join(line.split()).lower() horizontal.append(curr) if word in curr: return result(curr.find(word), dex + 1) for dex, line in enumerate(zip_longest(*horizontal, fillvalue='*')): curr = ''.join(line).lower() if word in curr: return result(curr.find(word), dex + 1, horizontal=False) if __name__ == '__main__': assert checkio("""DREAMING of apples on a wall, And dreaming often, dear, I dreamed that, if I counted all, -How many would appear?""", "ten") == [2, 14, 2, 16] assert checkio("""He took his vorpal sword in hand: Long time the manxome foe he sought-- So rested he by the Tumtum tree, And stood awhile in thought. And as in uffish thought he stood, The Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came!""", "noir") == [4, 16, 7, 16]
169fac0c9c3ca48eeca323770a8f476277bb45bf
nptit/Check_iO
/Incomplete/network_loops.py
1,836
3.625
4
def find_cycle(connections): d = dict() for a, b in connections: try: d[a].add(b) except KeyError: d[a] = {b} print(d) find_cycle(((1, 2), (2, 3), (3, 4), (4, 5), (5, 7), (7, 6), (8, 5), (8, 4), (8, 1), (1, 5), (2, 4))) # [1, 2, 3, 4, 5, 8, 1] # if __name__ == '__main__': # def checker(function, connections, best_size): # user_result = function(connections) # if not isinstance(user_result, (tuple, list)) or not all(isinstance(n, int) for n in user_result): # print("You should return a list/tuple of integers.") # return False # if not best_size and user_result: # print("Where did you find a cycle here?") # return False # if not best_size and not user_result: # return True # if len(user_result) < best_size + 1: # print("You can find a better loop.") # return False # if user_result[0] != user_result[-1]: # print("A cycle starts and ends in the same node.") # return False # if len(set(user_result)) != len(user_result) - 1: # print("Repeat! Yellow card!") # return False # for n1, n2 in zip(user_result[:-1], user_result[1:]): # if (n1, n2) not in connections and (n2, n1) not in connections: # print("{}-{} is not exist".format(n1, n2)) # return False # return True, "Ok" # # assert checker(find_cycle, # ((1, 2), (2, 3), (3, 4), (4, 5), (5, 7), (7, 6), # (8, 5), (8, 4), (1, 5), (2, 4), (1, 8)), 6), "Example" # assert checker(find_cycle, # ((1, 2), (2, 3), (3, 4), (4, 5), (5, 7), (7, 6), (8, 4), (1, 5), (2, 4)), 5), "Second"
fe25a0f536bf2af5019f65aa6b24d47a75732947
littlewhiteJ/LeetcodeSolutions
/867.py
542
3.625
4
# maybe best Solution class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ return [list(line) for line in zip(*A)] ''' # my Solution class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ B = [[item] for item in A[0]] for i in range(1, len(A)): for j in range(len(A[i])): B[j].append(A[i][j]) return B '''
21f7c1a054fdf173f8ce0deeddc438600a277c49
Sandy4321/pytorch-resample
/pytorch_resample/utils.py
496
3.703125
4
import math import random __all__ = ['random_poisson'] def random_poisson(rate, rng=random): """Sample a random value from a Poisson distribution. This implementation is done in pure Python. Using PyTorch would be much slower. References: - https://www.wikiwand.com/en/Poisson_distribution#/Generating_Poisson-distributed_random_variables """ L = math.exp(-rate) k = 0 p = 1 while p > L: k += 1 p *= rng.random() return k - 1
37035e0594027f3bfc86c3c2a1b8cbe29d072df2
luoluo964/Website-link-crawling-template
/main.py
1,712
3.5
4
import requests import parsel #返回页面的全部代码 def get_http(myurl): #伪造的UA头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' } response=requests.get(myurl,headers=headers) data=response.text data.encode("UTF-8") return data #通过xpath得到需要的url def get_url(data): #存储数据的列表 dataList=[] urldata=parsel.Selector(data) #模糊匹配 #这里是你的Xpath匹配规则 XpathSelect='//*[contains(@id,"post")]/header/h2' parse_list=urldata.xpath(XpathSelect) for h in parse_list: #这里更进一步得到数据(最终数据) url=h.xpath("./a/@href").extract_first() dataList.append(url) return dataList def download(list): #写入文件 with open('urls.txt','w') as f: for url in list: f.write(str(url)+"\n") #当前文件为启动文件 if __name__=="__main__": #这个列表将会收集全部的网页链接 allUrl=[] #假设网页有11页,请根据情况修改 for page in range(1,12): # 用{}预留一个接口,通过.format将页数进行传递 #观察网站的翻页url变化,这里以page/1、page/2...为例 base_url = "https://这是你的网页.com/page/{}/".format(page) #得到这一网页的源代码 http=get_http(base_url) #得到源代码中的url urls=get_url(http) for url in urls: allUrl.append(str(url)) #加个提示给控制台 print("已经爬取完第"+str(page)+"页") #下载链接 download(allUrl)
b0cd7324e8b0835b40f9c1efbb48ff372ce54386
adyrmishi/100daysofcode
/rock_paper_scissors.py
843
4.15625
4
rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' import random choices = [rock, paper, scissors] player_choice = choices[int(input("Choose 0 for rock, 1 for paper and 2 for scissors.\n"))] computers_choice = choices[random.randint(0,2)] print(player_choice) print(computers_choice) if player_choice == computers_choice: print("You drew!") elif (player_choice == rock and computers_choice == scissors) or (player_choice == paper and computers_choice == rock) or (player_choice == scissors and computers_choice == paper): print("You won!") else: print("You lost!")
14d8730bb5d268b254b63dd6230007ca584d1958
Pokeluigi/Full_Moon_Escape
/for_and_while_loops.py
1,987
3.875
4
#favourite_drinks = ["coke", "fanta", "tonic"] #for drink in favourite_drinks: # print(drink) #favourite_drinks = ["coke", "fanta", "tonic"] #for i in favourite_drinks: # print(i) #for thing in iterable: # do stuff #for i in range(10): # print(i) #for i in range(0, 51, 5): #(start(the index value to start at), stop(the index value to stop at), step(the amount the index value goes up by each time)) # print(i) #fav_films=[ # "Ghost", # "Ghost in the shell", # #"Ghosty ghosts", # "Ghostbusters", # "Ghost Adventures" #] # #for films in fav_films: # print(films) # #def film_check(list): # if list.pop(2) == "Ghostbusters": # print("Wait which one the original or the remake?") # else: # print("But who you gonna call tho?") # #film_check(fav_films) #for i in range(9, -1, -1):# This allows you to count backwards # print(i) #done = False #while (not done): #value = random.randint(1, 100) #print(f"Value generated : {value}") #if (value > 90): # done = True #for i in range(13): # print("Hello Gorgeous") # #print(i) #i = 0 #while (i < 13): # print("Hello Gorgeous") # i += 1 # #print(i) import random #for i in range(6): # random_num=random.randint(1, 30) # print(random_num) # if random_num%7==0: # print("Divisible by 7") # else: # print("Not divisible by 7") #suits=[ # "Diamonds", # "Spades", # "Hearts", # "Clubs", #] #list_length=len(suits) #done = False #while not done: # suit = random.randint(0, list_length - 1) # card = suits[suit] # print(f"The suit is: {card}") # done = (card == "Diamonds") # if done == True: # print("Done there's my Diamonds you know these are my summer diamonds some are diamond and some are not") # else: # print("Not that suit I want Diamonds they're a girls best friend you know")
a8563b5a5cfb8fd42a1aa937a002a7c5bd49c1c7
WRHR/python-notes
/basics/functions.py
513
3.796875
4
# A function is a block of code that only runs when it is called, no braces uses indentation with tabs and spaces # create func def sayHello(name = 'Human Person'): print(f'Hello {name}') sayHello('Bob') sayHello() # Return val def getSum(num1, num2): total = num1 + num2 return total getSum(25, 5) # A lambda function is a small anonymous func # lambda func can take any number of args, but can only have one expression getNone = lambda num1, num2 : num1 - num2 none = getNone(10, 3) print(none)
8f3bb29526d1e093ebee5a5fa33c07cbfa56d2b5
gustavo-depaula/stalin-sort
/python/benchmark.py
611
3.546875
4
import timeit # tests a sort function on list of lengths 10 to ten million. def benchmark(sort_fun): length_exponents = [1, 2, 3, 4, 5, 6, 7] repetitions = 10 for exponent in length_exponents: length = 10 ** exponent res = benchmark_length(sort_fun, length, repetitions) print(f'Sorting {repetitions} lists of length 10^{exponent} took {res} seconds.') def benchmark_length(sort_fun, length, repetitions): res = timeit.timeit(stmt='sort_fun(xs)', setup=f'from random import choices; xs = choices(range(10000), k={length})', globals={'sort_fun': sort_fun}, number=repetitions) return res
c9d9129901ca087a89f82d58c68a45bf3b35cf0a
neuwangmq/gitskill
/iterator.py
132
3.921875
4
d = {'a': 1, 'b': 2, 'c': 3} for key in d: print key for value in d.itervalues(): print value for k,v in d.iteritems(): print k,v
bc34228e297b625d332ca96e085857eae76beb9f
neuwangmq/gitskill
/multi.py
43
3.5625
4
a = input("input a number:\n") print(a*a)
53bf0300d334909355777fa043e37beb823bd7d2
NixonRosario/Encryption-and-Decryption
/main.py
2,772
4.1875
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. # The Encryption Function def cipher_encrypt(plain_text, key): # key is used has an swifting value encrypted = "" for c in plain_text: if c.isupper(): # check if it's an uppercase character c_index = ord(c) - ord('A') # ord('A') used because A is the first value in the alphabet # shift the current character by key positions c_shifted = (c_index + key) % 26 + ord('A') c_new = chr(c_shifted) encrypted += c_new elif c.islower(): # check if its a lowercase character # subtract the unicode of 'a' to get index in [0-25] range c_index = ord(c) - ord('a') c_shifted = (c_index + key) % 26 + ord('a') c_new = chr(c_shifted) encrypted += c_new elif c.isdigit(): # if it's a number,shift its actual value c_new = (int(c) + key) % 10 encrypted += str(c_new) else: # if its neither alphabetical nor a number, just leave it like that encrypted += c return encrypted # The Decryption Function def cipher_decrypt(ciphertext, key): decrypted = "" for c in ciphertext: if c.isupper(): c_index = ord(c) - ord('A') # shift the current character to left by key positions to get its original position c_og_pos = (c_index - key) % 26 + ord('A') c_og = chr(c_og_pos) decrypted += c_og elif c.islower(): c_index = ord(c) - ord('a') c_og_pos = (c_index - key) % 26 + ord('a') c_og = chr(c_og_pos) decrypted += c_og elif c.isdigit(): # if it's a number,shift its actual value c_og = (int(c) - key) % 10 decrypted += str(c_og) else: # if its neither alphabetical nor a number, just leave it like that decrypted += c return decrypted plain_text = input("Enter the message:- ") ciphertext1 = cipher_encrypt(plain_text, 4) # function calling is made print("Your text message:\n", plain_text) print("Encrypted ciphertext:\n", ciphertext1) n = input("If you want to decrypt any text press y else n: ") if n == "y": ciphertext = input("Enter the Encrypted text:- ") decrypted_msg = cipher_decrypt(ciphertext, 4) print("The decrypted message is:\n", decrypted_msg) else: print("Thank You!!")
93e90078409a13ca5d54b0aa6a19af1d8df6bb76
jake-stewart/pygrid
/draw_grid.py
3,348
3.53125
4
from pygrid import PyGrid import math # adds drawing functionality # when using a mouse, mouse events are sent periodically # that means mouse events will not register for every cell # this class figures out which cells the mouse traversed over # and sends them to an on_mouse_event method class DrawGrid(PyGrid): def __init__(self, draw_buttons=None, *args, **kwargs): PyGrid.__init__(self, *args, **kwargs) if draw_buttons is None: self._draw_buttons = [1] else: self._draw_buttons = draw_buttons self._origin = None self._fill_x = True self._button_down = None # when inheriting this class, use this method for all mouse events def on_mouse_event(self, cell_x, cell_y, button, pressed): pass def on_mouse_down(self, cell_x, cell_y, button): if button in self._draw_buttons: self._fill_x = True self._origin = (cell_x, cell_y) self._button_down = button self.on_mouse_event(cell_x, cell_y, button, False) def on_mouse_up(self, cell_x, cell_y, button): if button == self._button_down: self._button_down = None def on_mouse_motion(self, target_x, target_y): if not self._button_down: return # origin is the previous mouse event position origin_x, origin_y = self._origin angle = math.atan2(target_x - origin_x, target_y - origin_y) x_vel = math.sin(angle) y_vel = math.cos(angle) # if there is no x movement or no y movement, we do not need their respective vel if origin_x == target_x: x_vel = 0 elif origin_y == target_y: y_vel = 0 # initialize variables x = last_x = cell_x = origin_x y = last_y = cell_y = origin_y while True: if cell_x == target_x: if cell_y == target_y: # both cells have reached their targets # loop can end break y += y_vel else: if cell_y != target_y: y += y_vel x += x_vel # you can use int() instead of round(), but round() is smoother cell_x = round(x) cell_y = round(y) # avoid multiple mouse events over the same cell if cell_x == last_x and cell_y == last_y: continue # trigger a mouse event for a traversed cell self.on_mouse_event(cell_x, cell_y, self._button_down, True) # if the cell jumped diagonally, we want to fill it in # whether we fill the cell on the x axis or y axis is important # if we always fill one axis, it will look choppy # filling follows the rule: always fill y, unless y has had > 2 cells for the current x if last_x != cell_x and last_y != cell_y: if self._fill_x: self.on_mouse_event(last_x, cell_y, self._button_down, True) else: self.on_mouse_event(cell_x, last_y, self._button_down, True) else: self._fill_x = last_y == cell_y last_x = cell_x last_y = cell_y self._origin = (cell_x, cell_y)
2c08ad7796c277e07d58e22085a4eaeba6f380fb
zhaoyongjun0911/-
/个人项目/0-1背包问题.py
5,381
3.984375
4
# 三维列表,存放整个文件各组数据价值的列表,该列表分为若干子列表,每个子列表用于存储一组价值数据,每个子列表的数据又按照三个一组分为若干个列表 global profit profit = [] # 三维列表,存放整个文件各组数据重量的列表,同profit global weight weight = [] # 三维列表,存放整个文件各组数据价值-重量-价值重量比的列表,该列表分为若干子列表,每个子列表用于存储一组价值-重量-价值重量比数据,每个子列表 # 的数据为一个九元组,包含三条价值数据-三条重量数据-三条价值重量比信息 global prowei prowei = [] # 存放价值初始数据,即刚读入并且仅对结尾做了处理的字符串 global profitData profitData = [] # 存放重量初始数据,即刚读入并且仅对结尾做了处理的字符串 global weightData weightData = [] # =======================文件读取和处理函数========================= def getData(): # -------打开指定文件,读入数据------- fileName = str(input('请输入文件名')) file = open(fileName, 'r') line = file.readline() while (line): # 读入一行数据 line = file.readline() # 如果匹配到profit关键字,则读入下一行的价值信息 if line.__contains__("profit"): # 去除结尾的换行符,逗号,原点,便于分割 line = file.readline().strip('\n').strip('.').strip(',') # 将该行数据存入列表 profitData.append(line) # 如果匹配到weight关键字,则读入下一行的重量信息 elif line.__contains__("weight"): # 去除结尾的换行符,逗号,原点,便于分割 line = file.readline().strip('\n').strip('.').strip(',') # 将该行数据存入列表 weightData.append(line) # ------------数据读取完成--------------- # ------------profitData存放初始价值信息--------------- # ------------weightData存放初始重量信息--------------- # 处理数据,外层遍历profitData和weightData的每一组数据,将profitData和weightData的数据进一步划分为三元组和九元组 for group in range(len(profitData)): # 临时数据,价值三元组 three_P_List = [] # 临时数据,重量三元组 three_W_List = [] # 临时数据,价值重量比三元组 three_PW_List = [] # 存放一组价值数据 group_P_List = [] # 存放一组重量数据 group_W_List = [] # 存放一组价值+重量构成的数据 group_PW_List = [] # 临时变量,计数器 n = 0 # 将每一组价值/重量数据按照逗号分组,两个列表分别用于存放每一组价值/重量数据分组后的结果 proList = str(profitData[group]).split(',') weiList = str(weightData[group]).split(',') # 内层循环遍历上述分组后的每一组数据,将每组数据按照三元组/九元组进行存储 for p in range(len(proList)): # 将该组价值/重量/价值重量比数据的一个放入三元组列表 three_P_List.append(int(proList[p])) three_W_List.append(int(weiList[p])) three_PW_List.append(int(proList[p]) / int(weiList[p])) # 三元组中数量+1 n = n + 1 # 如果三元组已有三条数据 if n == 3: # 将价值/重量三元组放入该组列表 group_P_List.append(three_P_List) group_W_List.append(three_W_List) # 构造九元组,并将价值-重量-价值重量比九元组放入该组列表 group_PW_List.append(three_P_List + three_W_List + three_PW_List) # 将三个临时三元组/九元组变量置空,为下一次做准备 three_P_List = [] three_W_List = [] three_PW_List = [] # 计数器置0 n = 0 # 将内层循环处理完成的一组数据(列表)放入最终结果列表 profit.append(group_P_List) weight.append(group_W_List) prowei.append(group_PW_List) return 'ok' def pack(w, v, n, c): dp = [0 for _ in range(c+1)] for i in range(1, len(w)+1): for j in reversed(range(1, c+1)): for k in range(3): if j-w[i-1][k] >= 0: # print(dp[j]) dp[j] = max(dp[j], dp[j-w[i-1][k]] + v[i-1][k]) # print(dp) print(dp[c]) def menu(): print("1.绘制散点图") print("2.排序") print("3.算法实现") print("4.退出") task = input("请输入选项进行对应操作") if task == '1': user_dict = creating_dictionary() elif task == '2': updating_dictionary(user_dict) elif task == '3': sorting_dictionary(user_dict) elif task == '4': break if __name__ == '__main__': fw = open("result.txt", 'w') # 将要输出保存的文件地址 for line in open("result.txt"): # 读取的文件 fw.write(result) fw.write("\n") # 换行
69b6abc0b48b7aeba70e606d7a7e17542cd09924
judsonwebb/SportsAnalytics
/Regression.py
6,840
3.703125
4
""" Sports Analytics """ import numeric import codeskulptor import urllib2 import comp140_module6 as sports def read_matrix(filename): """ Parse data at the input filename into a matrix. """ ordered_data=[] url = codeskulptor.file2url(filename) netfile = urllib2.urlopen(url) for line in netfile.readlines(): row=line.split(',') #Converts strings to usable floats. for each in range(len(row)): row[each] = row[each].strip() row[each] = float(row[each]) ordered_data.append(row) return numeric.Matrix(ordered_data) class LinearModel: """ A class used to represent a Linear statistical model of multiple variables. This model takes a vector of input variables and predicts that the measured variable will be their weighted sum. """ def __init__(self, weights): """ Create a new LinearModel. """ self._weights = weights def __str__(self): """ Return weights as a human readable string. """ return str(self._weights) def get_weights(self): """ Return the weights associated with the model. """ return self._weights def generate_predictions(self, inputs): """ Use this model to predict a matrix of measured variables given a matrix of input data. """ return inputs*self._weights def prediction_error(self, inputs, actual_result): """ Calculate the MSE between the actual measured data and the predictions generated by this model based on the input data. """ predictions = self.generate_predictions(inputs) shape = predictions.shape() expected=[] the_real=[] for each in range(shape[0]): expected.append(predictions[(each,0)]) the_real.append(actual_result[(each,0)]) return mse(the_real,expected) def mse(result, expected): """ Calculates the mean squared error between the sequences result and expected. """ #Assumes result and expected are the same length. comp_sum=0 for each in range(len(expected)): comp_sum+=((expected[each]-result[each])**2)/(1.0*len(expected)) return comp_sum def fit_least_squares(input_data, output_data): """ Create a Linear Model which predicts the output vector given the input matrix with minimal Mean-Squared Error. """ return LinearModel((((output_data.transpose()*input_data))*(((input_data.transpose()*input_data).inverse()))).transpose()) def fit_lasso(param, iterations, input_data, output_data): """ Create a Linear Model which predicts the output vector given the input matrix such that: 1) Mean-Squared error in predictions is small 2) The weights vector is simple This is done using the LASSO method with lambda parameter param, calculated for the specified number of iterations. """ weights = fit_least_squares(input_data,output_data).get_weights() cursor = 0 while cursor<iterations: old_weights=weights.copy() for each in range(input_data.shape()[1]): distance= bajj(param,each,input_data) change= ajj(weights,input_data,output_data,each) weights[(each,0)]=soft_threshold(weights[(each,0)]+change,distance) if (((weights - old_weights)).abs()).summation()<.00001: break cursor+=1 return LinearModel(weights) def soft_threshold(value,distance): """ Moves x closer to zero by the distance t """ if value>distance: return value-distance if abs(value)<=distance: return 0 if value<(0-distance): return value+distance def ajj(weights, input_data, output_data,iter_value): """ Computes a change value to update the weights Matrix """ numerator= (input_data.transpose()*output_data)[(iter_value,0)]-(((input_data.transpose()*input_data).getrow(iter_value)*weights)[(0,0)]) denominator = (input_data.transpose()*input_data)[(iter_value,iter_value)] return numerator/denominator def bajj(param, iter_value, input_data): """ Computes a distance value to update the weights Matrix """ return param/(2.0*(input_data.transpose()*input_data)[(iter_value,iter_value)]) def run_experiment(iterations): """ Using some historical data from 1954-2000, as training data, generate weights for a Linear Model using both the Least-Squares method and the LASSO method (with several different lambda values). Test each of these models using the historical data from 2001-2012 as test data. """ #Sets up data being used early_stats=read_matrix("comp140_analytics_baseball.txt") early_wins=read_matrix("comp140_analytics_wins.txt") modern_stats=read_matrix("comp140_analytics_baseball_test.txt") modern_wins=read_matrix("comp140_analytics_wins_test.txt") lse_model=fit_least_squares(early_stats,early_wins) lasso_model_a=fit_lasso(2000, iterations,early_stats,early_wins) lasso_model_b=fit_lasso(7000, iterations,early_stats,early_wins) lasso_model_c=fit_lasso(50000, iterations,early_stats,early_wins) sports.print_weights(lasso_model_a) print "1954-2000 Data Prediction Error" #Prints out 1954-2000 prediction error based on these models print "LSE Model" print lse_model.prediction_error(early_stats,early_wins) print "LASSO Model, Lambda = 2000" print lasso_model_a.prediction_error(early_stats,early_wins) print "LASSO Model, Lambda = 7000" print lasso_model_b.prediction_error(early_stats,early_wins) print "LASSO Model, Lambda = 50000" print lasso_model_c.prediction_error(early_stats,early_wins) print "2001-2012 Data Prediction Error" #Prints out 2001-2012 prediction error based on these models print "LSE Model" print lse_model.prediction_error(modern_stats,modern_wins) print "LASSO Model, Lambda = 2000" print lasso_model_a.prediction_error(modern_stats,modern_wins) print "LASSO Model, Lambda = 7000" print lasso_model_b.prediction_error(modern_stats,modern_wins) print "LASSO Model, Lambda = 50000" print lasso_model_c.prediction_error(modern_stats,modern_wins) #run_experiment(500) #Received Output: #1954-2000 Data Prediction Error #LSE Model #93.7399686198 #LASSO Model, Lambda = 2000 #124.478829393 #LASSO Model, Lambda = 7000 #131.138684403 #LASSO Model, Lambda = 50000 #139.93154029 #2001-2012 Data Prediction Error #LSE Model #105.085529071 #LASSO Model, Lambda = 2000 #99.805693628 #LASSO Model, Lambda = 7000 #95.4418952917 #LASSO Model, Lambda = 50000 #92.8456084221
5bf3ff360b4e18e36467b50b865514e3f8eaef89
peterdocter/small-spider-project
/synchronous/sample/thread_test1.py
836
3.796875
4
import _thread import threading import time def _thread_handle(thread_name, delay): for num in range(10): time.sleep(delay) print("{}的num:{}".format(thread_name, num)) def threading_handle(delay=1): for num in range(10): time.sleep(delay) print("{}-num-{}".format(threading.current_thread().name, num)) def main(): # for item in range(10): # _thread.start_new_thread(_thread_handle, ("Thread - {}".format(item), 1)) # # 和进程不同,如果进程死亡,则线程也会死亡 # time.sleep(200) for item in range(10): # thread = threading.Thread(target=threading_handle, args=(1,), name="执行线程-{}".format(item)) thread = threading.Thread(target=threading_handle, args=(1,)) thread.start() if __name__ == '__main__': main()
249e0802f3665f16a695b84faef88692ba7dfa25
taruchit/CodeChef_Beginner
/Flow010.py
395
3.78125
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 13 16:43:13 2021 @author: pc """ #Number of testcases T=int(input()) #Input, computation and output for i in range(T): id=input() if(id=='B' or id=='b'): print("BattleShip") elif(id=='C' or id=='c'): print("Cruiser") elif(id=='D' or id=='d'): print("Destroyer") else: print("Frigate")
a9ccfc50a33f44b713443d50c365faf62abb495e
taruchit/CodeChef_Beginner
/Flow013.py
314
3.59375
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 13 11:23:00 2021 @author: pc """ #Number of testcases T=int(input()) #Input, computation and output for i in range(T): N=input().split(" ") A=int(N[0]) B=int(N[1]) C=int(N[2]) if((A+B+C)==180): print("YES") else: print("NO")
8a14238ded132a4ce8ff644f3cf5ac6b99c619d8
taruchit/CodeChef_Beginner
/SecondLargest.py
328
3.625
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 9 23:29:54 2021 @author: pc """ #Number of testcases T=int(input()) #Input, Computation and Output for i in range(T): temp=input().split(" ") N=list() N.append(int(temp[0])) N.append(int(temp[1])) N.append(int(temp[2])) N.sort() print(N[1])
29d0f0a5b83dbbcee5f053a2455f9c8722b6cb51
MrYsLab/pseudo-microbit
/neopixel.py
2,943
4.21875
4
""" The neopixel module lets you use Neopixel (WS2812) individually addressable RGB LED strips with the Microbit. Note to use the neopixel module, you need to import it separately with: import neopixel Note From our tests, the Microbit Neopixel module can drive up to around 256 Neopixels. Anything above that and you may experience weird bugs and issues. NeoPixels are fun strips of multi-coloured programmable LEDs. This module contains everything to plug them into a micro:bit and create funky displays, art and games Warning Do not use the 3v connector on the Microbit to power any more than 8 Neopixels at a time. If you wish to use more than 8 Neopixels, you must use a separate 3v-5v power supply for the Neopixel power pin. Operations Writing the colour doesn’t update the display (use show() for that). np[0] = (255, 0, 128) # first element np[-1] = (0, 255, 0) # last element np.show() # only now will the updated value be shown To read the colour of a specific pixel just reference it. print(np[0]) Using Neopixels Interact with Neopixels as if they were a list of tuples. Each tuple represents the RGB (red, green and blue) mix of colours for a specific pixel. The RGB values can range between 0 to 255. For example, initialise a strip of 8 neopixels on a strip connected to pin0 like this: import neopixel np = neopixel.NeoPixel(pin0, 8) Set pixels by indexing them (like with a Python list). For instance, to set the first pixel to full brightness red, you would use: np[0] = (255, 0, 0) Or the final pixel to purple: np[-1] = (255, 0, 255) Get the current colour value of a pixel by indexing it. For example, to print the first pixel’s RGB value use: print(np[0]) Finally, to push the new colour data to your Neopixel strip, use the .show() function: np.show() If nothing is happening, it’s probably because you’ve forgotten this final step..! Note If you’re not seeing anything change on your Neopixel strip, make sure you have show() at least somewhere otherwise your updates won’t be shown. """ from typing import Tuple, List, Union from microbit import MicroBitDigitalPin class NeoPixel: def __init__(self, pin: MicroBitDigitalPin, n: int): """ Initialise a new strip of n number of neopixel LEDs controlled via pin pin. Each pixel is addressed by a position (starting from 0). Neopixels are given RGB (red, green, blue) values between 0-255 as a tuple. For example, (255,255,255) is white. """ def clear(self) -> None: """ Clear all the pixels. """ def show(self) -> None: """ Show the pixels. Must be called for any updates to become visible. """ def __len__(self) -> int: pass def __getitem__(self, key) -> Tuple[int, int, int]: pass def __setitem__(self, key: int, value: Union[Tuple[int, int, int], List[int]]): pass
630ce08828c6dbb4c9121499ea76b21374e97efa
sminix/skill-challenges
/word_funnel1.py
2,293
3.796875
4
''' Sam Minix 5/28/2020 https://www.reddit.com/r/dailyprogrammer/comments/98ufvz/20180820_challenge_366_easy_word_funnel_1/ Given two strings of letters, determine whether the second can be made from the first by removing one letter. The remaining letters must stay in the same order. ''' def word_funnel1 (str1, str2): if len(str2) > len(str1): #failure check, if str2 is longer is will always fail return False for i in range(len(str1)): #for every letter in str1 new_str1 = str1[0:i] + str1[i+1:] #make a new string removing one letter at a time if new_str1 == str2: #if they are equal it is true return True return False #if after going though all the letter it isn't true, return false ''' #Test Case print(word_funnel1("leave", "eave")) #True print(word_funnel1("reset", "rest")) #True print(word_funnel1("dragoon", "dragon"))#True print(word_funnel1("eave", "leave")) #False print(word_funnel1("sleet", "lets")) #False print(word_funnel1("skiff", "ski")) #False ''' ''' Given a string, find all words from the enable1 word list that can be made by removing one letter from the string. If there are two possible letters you can remove to make the same word, only count it once. Ordering of the output words doesn't matter. ''' def bonus(word): reader = open("enable1.txt", "r") #open the enable1 list, this part is different depending on where it is stored funnel = [] #initiate list of funnel words for line in reader: if word_funnel1(word, line.strip()): #for each line compare the given word with the line funnel.append(line.strip()) #if it works, add it to the funnel list return funnel ''' Test Cases print(bonus("dragoon")) #['dragon'] print(bonus("boats")) #['bats', 'boas', 'boat', 'bots', 'oats'] print(bonus("affidavit")) #[] ''' ''' Given an input word from enable1, the largest number of words that can be returned from bonus(word) is 5 One such input is "boats". There are 28 such inputs in total. Find them all. In theory this code works but I can't figure out how to make it quicker ''' def bonus2(): reader = open("enable1.txt" ,"r") words = [] for line in reader: if len(bonus(line.strip())) == 5: words.append(line.strip()) print(bonus2())
9d7df65d3a7a46a8c762c189d76bdebc04db78a9
Baude04/Translation-tool-for-Pirates-Gold
/fonctions.py
299
4.1875
4
def without_accent(string): result = "" for i in range(0,len(string)): if string[i] in ["é","è","ê"]: letter = "e" elif string[i] in ["à", "â"]: letter = "a" else: letter = string[i] result += letter return result
638715d691110084c104bba50daefd5675aea398
baif666/ROSALIND_problem
/find_all_substring.py
501
4.25
4
def find_all(string, substr): '''Find all the indexs of substring in string.''' #Initialize start index i = -1 #Creat a empty list to store result result = [] while True: i = string.find(substr, i+1) if i < 0: break result.append(i) return result if __name__ == '__main__': string = input('Please input your string : ') substr = input("Please input your substring : ") print('Result : ', find_all(string, substr))
752ab686e61aef181c8301fbc5a0b7b5f3c4f6a5
eldq5d/UMKC-490-Python
/Lab2/Task 2.2.py
326
3.9375
4
# With any given number n, Write a program to generate a dictionary that contains (k, k*k). # Print the dictionary generated and the series should include both 1 and k. n = int(input("Enter an integer to create a dictionary: ")) dictionary1 = {} for i in range(1, n+1): dictionary1[i] = i*i i += 1 print(dictionary1)
f17fa85bade1d23b68e4ef8516eb587d3a0f63f3
maliksh7/Data-Structure-and-Algorithms-in-Python
/Assignments/a08/a08.py
2,087
3.703125
4
class HashMap: def __init__(self): self.size = 10 self.map = [None] * self.size def _get_hash(self, key): if type(key) == int: return key % 10 if type(key) == str: return len(key) % 10 if type(key) == tuple: return len(key) % 10 def add(self, key, value): hashed_key = self._get_hash(key) hashed_val = [key, value] if self.map[hashed_key] is None: self.map[hashed_key] = [hashed_val] return True else: for pair in self.map[hashed_key]: if pair[0] == key: pair[1] = value return self.map[hashed_key].append(hashed_val) return True def get(self, key): hashed_key = self._get_hash(key) if self.map[hashed_key] is not None: for pair in self.map[hashed_key]: #print("[Note]", type(pair) , pair) if pair[0] == key: return pair[1] raise KeyError(str(key)) def __str__(self): ret = " " for i, item in enumerate(self.map): if item is not None: ret += str(i) + ":" + str(item) + "\n" return ret def delete(self,key): hashed_key = self._get_hash(key) if self.map[hashed_key] is None: raise KeyError(str(key)) for i in range(0,len(self.map[hashed_key])): if self.map[hashed_key][i][0] == key: self.map[hashed_key].pop(i) return True raise KeyError(str(key)) if __name__ == '__main__': h = HashMap() h.add(17, "seventeen") h.add(26, "twenty six") h.add(35, "thirty five") h.add(25, "twenty five") h.add(26, "twenty six updated") h.add(887, "large number") print(h) print("[NOTE] Running Test on String type keys ...") h.add("Saad", "Hassan") h.add("Saad", "Mubeen") h.add("MAK", "Mubariz") print(h) print("[NOTE] Running Test on Tuple type keys ...") h.add(("saad","mak","been"), "bawa") print(h) print(h.get(17)) print(h.get("Saad")) print(h.get("MAK")) print(h.get(("saad", "mak", "been"))) print("[NOTE] Running Test on Deletion of Keys ...") print(h.delete(17)) print(h.delete("MAK")) print(h.delete(("saad", "mak", "been"))) print(h)
8da0284269b489e21ea98fedc85936c64618c917
maliksh7/Data-Structure-and-Algorithms-in-Python
/a06/a06.py
4,070
3.5625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def dfs(self): print(self.val) if self.left: self.left.dfs() if self.right: self.right.dfs() def dfs_inoder(self): if self.left: self.left.dfs_inoder() print(self.val) if self.right: self.right.dfs_inoder() def dfs_postorder(self): if self.left: self.left.dfs_postorder() if self.right: self.right.dfs_postorder() print(self.val) def bfs(self): to_visit = [ self ] while to_visit: current = to_visit(0) #get the first one out .... so, queue print(current.val) if current.left: to_visit.append(current.left) if current.right: to_visit.append(current.right) def dfs_apply(self , fn): fn(self) if self.left: self.left.dfs_apply(fn) if self.right: self.right.dfs_apply(fn) class Person: def __init__(self, name): self.name = name def __str__(self): return str(self.name) #TreeNode.Person = Person class Collector: def __init__(self): self.lst = [] def process(self,node): self.lst.append(node.val.name) def get_list(self): return self.lst def reset_list(self): self.lst = None # Add the find_val function here ########## def find_val(self, value): if self.val.name == value: return self if self.left: if self.left.find_val(value): return self.left.find_val(value) if self.right: if self.right.find_val(value): return self.right.find_val(value) if self.val.name != value: return None # End of find_val function ################ TreeNode.find_val = find_val # Add the find_people_in_hierarchy function here ########## def find_people_in_hierarchy(self, name): col = Collector() if self.val.name == name: self.dfs_apply(col.process) return col.get_list() if self.left: if self.left.find_val(name): return self.left.find_people_in_hierarchy(name) if self.right: if self.right.find_val(name): return self.right.find_people_in_hierarchy(name) if self.val.name != name: raise ValueError("No node found .... invalid string or name") TreeNode.find_people_in_hierarchy = find_people_in_hierarchy # End of find_people_in_hierarchy function ################ if __name__ == "__main__": pass # # Section 1: creating people print("Section 1: ") director = Person("Director") hod_1 = Person("HoD 1") hod_2 = Person("HoD 2") faculty_cs_1 = Person("CS 1") faculty_cs_2 = Person("CS 2") faculty_ee_1 = Person("EE 1") faculty_ee_2 = Person("EE 2") print(director) # should print: Director # Section 2: inserting people in the tree print("\nSection 2: ") t_d = TreeNode(director) t_d.left = TreeNode(hod_1) t_d.right = TreeNode(hod_2) t_d.left.left = TreeNode(faculty_cs_1) t_d.left.right = TreeNode(faculty_cs_2) t_d.right.left = TreeNode(faculty_ee_1) t_d.right.right = TreeNode(faculty_ee_2) t_d.dfs() # Section 3: try find_val individually print("\nSection 3: ") node = t_d.find_val("Director") print(node.val) # should print the string: Director node = t_d.find_val("HoD 1") print(node.val) # should print the string: HoD 1 node = t_d.find_val("HoD 2") print(node.val) # should print the string: HoD 2 node = t_d.find_val("HoD 3") print(node) # should print the string: None # Section 4: try the collector print("\nSection 4: ") c = Collector() t_d.dfs_apply(c.process) print(c.get_list()) # should print the list: ['Director', 'HoD 1', 'CS 1', 'CS 2', 'HoD 2', 'EE 1', 'EE 2'] # Section 5: find hierarchy print("\nSection 5: ") people = t_d.find_people_in_hierarchy("HoD 1") print(people) # Should print the list: ['HoD 1', 'CS 1', 'CS 2']
32ef8db9fd30ff2bfb08c19dfde5c0733bb80767
vinobc/UGE1176
/nmbrs.py
402
4.03125
4
#!/usr/local/bin/python3 from decimal import Decimal def main(): x = Decimal(".20") y = Decimal(".60") a = x + x + x - y print(f"a is {a}") print(type(a)) # b = 10/3 # print(f"b is {b}") # print(type(b)) # c = 10//3 # print(f"c is {c}") # print(type(c)) # d = 10**3 # print(f"d is {d}") # print(type(d)) if __name__ == "__main__": main()
26057466c749ab510bd9b99790af6b0eb93b5cf0
vinobc/UGE1176
/while.py
290
3.8125
4
pwd = "octopus" res = "" user_auth = False attempt = 0 max_attempts = 3 while res != pwd: attempt += 1 if attempt > max_attempts: break res = input("Enter the password:") else: user_auth = True print("Successfully logged in" if user_auth else "try again in one hour..")
3cc4e9f05c3e59dea68ad6604b87117b859d377a
LouisKamp/unipython
/Exercise project 1/data_load.py
1,359
4.09375
4
# %% import numpy as np import pandas as pd from pandas.core.frame import DataFrame from constants import dataColumn, bacteriaValues # %% def dataLoad(filename: str) -> DataFrame: """Loads data from a space separated values file Keyword arguments: filename: str -- The name of the file to be loaded Returns: data: DataFrame """ # Loads data into a dataframe data = pd.read_csv(filename, names=dataColumn, delimiter=" ") # Gets the number of rows in the dataframe xSize = len(data) # Creates a boolean array of the selected rows in the dataframe selectedRows = np.ones(xSize, dtype=bool) # Loops through the dataframe and selects the rows that compiles with the rules for i, row in data.iterrows(): if (row['Temperature'] >= 10 and row['Temperature'] <= 60) == False: selectedRows[i] = False print( f"The row: {i+1} does not have the required tempeture range!") if row['Growth rate'] < 0: selectedRows[i] = False print(f"The row: {i+1} does not have a positive growth rate!") if row['Bacteria'] not in bacteriaValues: selectedRows[i] = False print(f"The row: {i+1} contains a not allowed bacteria!") # Returns the only the selected rows of the data return data[selectedRows]
82bad5160889c903a78a44a5a470627302bd73ec
oregzoltan/trial-exam-python-2016-06-06
/2.py
444
3.84375
4
# Create a function that takes a filename as string parameter, # and counts the occurances of the letter "a", and returns it as a number. # It should not break if the file not exists just return 0 def count_a(name): try: f = open(name) text = f.read() except: return 0 f.close() counter = 0 for i in text: if i == 'a': counter += 1 return counter print(count_a('test.txt'))
805d6f805b9f558ac4a2d19e706b211173938a19
pritesprite/prite
/game.py
2,508
3.5
4
#all immport import random import time #Set up command class Player(): def __init__(self): self.player_hungry = 2 self.player_health = 10 self.inventory = {} def has_item(self,item): item_count = self.inventory.get(item, 0) if item_count > 0: return True else: return False def item_count(self): pass def add_item(self, item, count=1): item_count = self.inventory.get(item, 0) self.inventory[item] = item_count + count def remove_item(self, item): if self.has_item(item): item_count = self.inventory.get(item, 0) self.inventory[item] = item_count - 1 def show_inv(self): print("Your item is-----") class Event(): def main_event(player): rand_num = random.randint(7) #Not finish def explore(player): rand_num = random.randint(0,100) if rand_num < 10: "rare_event" elif rand_num < 30: "common_event" else: "normal__event" #Not finish def intro_user_choice(): print("you hve to pick 3 item out of 7") print("which is food, video game, cat, gun, first aid kit, radio , bird") def get_user_choice () : #input1 start_item1 = input("What 1 item you want to choose?") if start_item1 in ['food','video game','cat','gun','first aid kit','radio','bird']: valid_choice = True else: print("That is not an option...Plz try again") get_user_choice() #input2 start_item2 = input("What 2 item you want to choose?") if start_item2 in ['food','video game','cat','gun','first aid kit','radio','bird']: valid_choice = True else: print("That is not an option...Plz try again") get_user_choice() #input3 start_item3 = input("What 3 item you want to choose?") if start_item3 in ['food','video game','cat','gun','first aid kit','radio','bird']: valid_choice = True else: print("That is not an option...Plz try again") get_user_choice() #out put123 print(start_item1,start_item2,start_item3) def test_change() pass intro_user_choice() get_user_choice()
3e562ee261acc916e0c25a44f5b4084c5489eb68
setsumei1974/AlienArmageddon
/alien_invasion.py
1,238
3.5625
4
#Module for Functionality of the Game import pygame from pygame.sprite import Group #Module to Import Settings from settings import Settings #Module to Import the Ship from ship import Ship #Module to Import the Alien from alien import Alien #Module to Import the Functions of the Game import game_functions as gf def run_game(): #Initialize a Game and Create a Screen Object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Armageddon!") #Set the Background Color bg_color = (0, 25, 51) #Make a Ship, a Group of Aliens, and a Group of Bullets ship = Ship(ai_settings, screen) #Make a Group to Store Aliens aliens = Group() #Make a Group to Store Bullets bullets = Group() #Create the Fleet of Aliens gf.create_fleet(ai_settings, screen, ship, aliens) #Start the Main Loop for the Game while True: gf.check_events(ai_settings, screen, ship, bullets) ship.update() gf.update_bullets(aliens, bullets) gf.update_aliens(ai_settings, aliens) gf.update_screen(ai_settings, screen, ship, aliens, bullets) run_game()
08c0b696d0bc9a5a584881af22d71378dcc06515
crazynoodle/Noodle-s-git
/python-code/fib.py
226
3.96875
4
def fib2(n): #return Fibonacci series up to n """Return a list containing the Fibonacci series up to n.""" result = [] a,b = 0,1 while a < n: result.append(a) # see below a,b = b,a+b return result
b126f74d86f783cafb4639aeb4aeb01587496a27
dennisurtubia/Automato-Finito
/src/estado.py
580
3.796875
4
class Estado: def __init__(self, nome): """ Description Método construtor de estado, define os atributos que um estado deve ter :type nome: str :param nome: Nome ou descrição do estado """ self.nome = nome self.inicial = False self.final = False def getNome(self): return self.nome def setNome(self, nome): self.nome = nome def isInicial(self): return self.inicial def setInicial(self): self.inicial = True def isFinal(self): return self.final def setFinal(self): self.final = True
b0cad0b1e60d45bc598647fa74cb1c584f23eeaa
JGMEYER/py-traffic-sim
/src/physics/pathing.py
1,939
4.1875
4
from abc import ABC, abstractmethod from typing import Tuple import numpy as np class Trajectory(ABC): @abstractmethod def move(self, max_move_dist) -> (Tuple[float, float], float): """Move the point along the trajectory towards its target by the specified distance. If the point would reach the target in less than the provided move distance, move the point only to the target destination. max_move_dist - maximum distance point can move towards target returns: (new_x, new_y), distance_moved """ pass class LinearTrajectory(Trajectory): """Trajectory that moves a point linearly towards a target point.""" def __init__(self, start_x, start_y, end_x, end_y): self._cur_x, self._cur_y = start_x, start_y self._end_x, self._end_y = end_x, end_y def move(self, max_move_dist) -> (Tuple[float, float], float): """See parent method for desc.""" dx = self._end_x - self._cur_x dy = self._end_y - self._cur_y # Optimization if dx == 0 or dy == 0: norm = max(abs(dx), abs(dy)) # Target reached if max_move_dist >= norm: return (self._end_x, self._end_y), max_move_dist - norm self._cur_x += np.sign(dx) * max_move_dist self._cur_y += np.sign(dy) * max_move_dist return (self._cur_x, self._cur_y), max_move_dist else: vector = np.array([dx, dy]) norm = np.linalg.norm(vector) # Target reached if max_move_dist >= norm: return (self._end_x, self._end_y), max_move_dist - norm unit = vector / norm self._cur_x, self._cur_y = tuple( np.array([self._cur_x, self._cur_y]) + max_move_dist * np.array(unit) ) return (self._cur_x, self._cur_y), max_move_dist
4716a82fc74372b92fb9cf7e0d068cf3bbc662ac
carlosvcerqueira/Projetos-Python
/ex036.py
437
3.859375
4
casa = float(input('Valor da casa: R$')) salario = float(input('Salário do comprador: R$')) prazo = int(input('Quantos anos de financiamento? ')) prestação = casa / (prazo * 12) mínimo = salario * 30 / 100 print('Para pagar uma casa de R${:.2f} em {} anos a prestação será de R${:.2f}.'.format(casa, prazo, prestação)) if prestação <= mínimo: print("Empréstimo APROVADO!") else: print('Empréstimo NEGADO!')
9f49c6b3aebb19090fffff52065ef0b1230d4549
carlosvcerqueira/Projetos-Python
/ex038.py
363
4.09375
4
from time import sleep print('-=-'* 10) print('ANALISADOR DE NÚMEROS') print('-=-' * 10) n1 = int(input('Digite um número: ')) n2 = int(input('Digite outro número: ')) print('ANALISANDO...') sleep(3) if n1 > n2: print('O primeiro valor é maior.') elif n1 < n2: print('O segundo valor é maior.') else: print('Os valores são iguais.')
8a9af8bdf68db8fda144b35601ca9dab76408632
carlosvcerqueira/Projetos-Python
/ex031.py
201
3.75
4
km = float(input('Quantos km você irá viajar? ')) if km <= 200: print('O valor da passagem é R${:.2f}'.format(km * 0.50)) else: print('O valor da passagem é R${:.2f}'.format(km * 0.45))
e373a41f098dcdafad1fe9c6d97ec298aac91cad
carlosvcerqueira/Projetos-Python
/ex045.py
1,281
3.765625
4
from time import sleep from random import randint itens = ('Pedra', 'Papel', 'Tesoura') computador = randint(0, 2) print('''Suas opções: [0] PEDRA [1] PAPEL [2] TESOURA''') jogador = int(input('Qual sua jogada? ')) print('PEDRA...') sleep(0.7) print('PAPEL...') sleep(0.7) print('TESOURA!!!') sleep(1) print('-=-'*7) print('Computador jogou {}.'.format(itens[computador])) print('Jogador jogou {}.'.format(itens[jogador])) print('-=-'*7) if computador == 0: #computador jogou PEDRA if jogador == 0: print('EMPATE!') elif jogador == 1: print('Jogador vence!') elif jogador == 2: print('Computador vence!') else: print('Jogada inválida, tente novamente!') elif computador == 1: #computador jogou PAPEL if jogador == 0: print('Computador vence!') elif jogador == 1: print('EMPATE!') elif jogador == 2: print('Jogador vence!') else: print('Jogada inválida, tente novamente!') elif computador == 2: #computador jogou TESOURA if jogador == 0: print('Jogador vence!') elif jogador == 1: print('Computador vence!') elif jogador == 2: print('EMPATE!') else: print('Jogada inválida, tente novamente!')
778390bb9e7055402c0d55bd63d14c4e2086a827
soldierloko/Curso-em-Video
/Ex_44.py
1,267
3.765625
4
#Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: #A vista Dinheiro ou Cheque: 10% de Desconto #A vista no cartão: 5% de Desconto #2x No cartão: preço normal #3x ou mais no cartão: 20% de juros vProduto = float(input('Digite o valor do Produto: ')) vCondicao = int(input('Digite a condiçaõ de Pagamento:' '\n1 à vista (Dinheiro/Cheque)' '\n2 à vista no cartão' '\n3 2 x no cartão' '\n4 3 x ou mais no cartão ')) if vCondicao == 4: print('Valor total do produto {}' '\nValor do Acrescimo {} ' '\nNo parcelamento acima de 2x Acrescenta-se 20%!'.format(vProduto+(vProduto*0.2),(vProduto*0.2))) elif vCondicao == 3: print('Valor total do produto {}!'.format(vProduto)) elif vCondicao == 2: print('Valor total do produto {}' '\nValor do Desconto {}' '\nÀ Vista no Cartão 5% de Desconto!'.format(vProduto-(vProduto*0.05),(vProduto*0.05))) else: print('Valor total do produto {}' '\nValor do Desconto {}' '\nÀ Vista no Cartão 10% de Desconto!'.format(vProduto-(vProduto*0.1),(vProduto*0.1)))
b652abe6ca74239b17389be5f7a947fab50069d3
soldierloko/Curso-em-Video
/Ex_41.py
588
4.0625
4
#A confederação nacional de natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade #Até 9 anos: MIRIM #Até 14 anos: INFANTIL #Até 19 anos: JUNIOR #Até 20 anos: SÊNIOR #Acima: MASTER from datetime import date vAno = int(input('Digite o ano de Nascimento: ')) vAnoAtual = date.today().year vQtdeAnos = vAnoAtual - vAno if vQtdeAnos >= 20: print('Categoria SÊNIOR!') elif vQtdeAnos >=19: print('Categoria JUNIOR!') elif vQtdeAnos >=14: print('Categoria INFANTIL!') else: print('Categoria MIRIM!')
2c437396a0a3fd9686bbf94fdec8445c42c1f649
soldierloko/Curso-em-Video
/Ex_58.py
735
4.0625
4
#Melhore o Jogo Desafio 028 onde o computador vai pensar em um n´úmro entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. from random import randint vPc = randint(0,10) print('Acabei de pensar em um númerp entre 0 e 10.') print('Será que você consegue adivinhar qual foi?') acertou = False palpite = 0 while not acertou: jogador = int(input('Qual o seu palpite? ')) palpite += 1 if jogador == vPc: acertou = True else: if jogador < vPc: print('Mais...tente mais uma vez!') else: print('Menos...tente mais uma vez!') print('Acertou com {} Tentativas!'.format(palpite))
220f08fca0713fc8ed3c2ce02e23fbc24eb45165
soldierloko/Curso-em-Video
/Ex_82.py
642
4.0625
4
#Crie um programa que vai ler vários números e colocar em uma lista #Depois disso, crie duas listas extras que vão conter apenas os valores pares e impares digitados, respectivamentes #Ao final, mostre o conteúdo das 3 listas geradas lista = [] par = [] impar = [] while True: n = int(input("Digite um número: ")) lista.append(n) if n % 2 ==0: par.append(n) else: impar.append(n) if input("Deseja continuar? [S/N]").upper() == "N": break print(f"Os números digitados foram {lista}") print(f"Os números pares digitados foram {par}") print(f"Os números impares digitados foram {impar}")
a5209df360f77046a2fdbd832238265a0461e478
soldierloko/Curso-em-Video
/Ex_38.py
503
3.859375
4
#Escreva umn programa que leia 2 números inteiros e compare-os, mostrando na tela uma mensagem: #O Primeiro valor é maior #O Segundo valor é menor #Ambos os valores são iguais vn1 = int(input("Digite o Primeiro Valor: ")) vn2 = int(input("Digite o Segundo Valor: ")) if vn1>vn2: print('O primeiro Valor {} é maior que o segundo {}'.format(vn1,vn2)) elif vn1<vn2: print('O segundo Valor {} é maior que o primeiro {}'.format(vn2,vn1) ) else: print('Ambos os valores são iguais!')
6dd66f64267394e60fe06601a74f39f9b15ac48f
Aaryan-kapur/hactktoberfesttimebois2021
/AvastYe.py
5,609
3.953125
4
#You are a part of a pirate ship that survives by looting islands. Your crew has the #responsibility of devising a plan to efficiently rob the islands where each island is divided #into smaller land parts due to the river flowing through it. Each land part is joined to another #land part by a bridge. (i.e. one land part can be directly connected to another land part by #using almost 1 bridge). After thorough discussion, the crew came to a conclusion that the #only way to carry out the loot successfully is to loot only those islands in which all the #bridges are covered only once. Given the topology of the island, your job is to analyze the #island and tell whether the pirates should loot the given island or not. #INPUT: #The first line of the input asks for the ‘Number of Islands’ #Second line asks for the number of land parts (nodes) #And based on the number of land parts (nodes) each subsequent line gives the details #about the number of degrees of those land parts #OUTPUT: #"island can be looted" or "island cannot be looted" #SAMPLE INPUT : ##1 - 2 ##2 - 3 ##3 - 2 2 3 ##4 - 2 1 3 ##5 - 2 1 2 ##6 - 1 ##7 - 0 ##1 denotes the ‘number of islands’ ##2 denotes the ‘ number of land parts/nodes' ##3 first digit, in this case ‘2’ denotes the degrees of the ‘first’ land part and following digits, #‘2’ & ‘3’ denote the land parts, first land part is connected to ##4 first digit, in this case ‘2’ denotes the degrees of the ‘second’ land part and following #digits, ‘1’ & ‘3’ denote the land parts, second land part is connected to ##5 first digit, in this case ‘2’ denotes the degrees of the ‘second’ land part and following #digits, ‘1’ & ‘2’ denote the land parts, third land part is connected to ##6 is the number of land parts for the second island because we chose ‘2’ as an input in #1 ##7 in this case, second island has only one land part/node therefore it’s degree can’t be #more than (degree-1) i.e. ‘0’. #SAMPLE OUTPUT: #"island can be looted" # Python program to check if a given island can be looted or not # Complexity: O(V+E) from collections import defaultdict # This class represents a undirected graph using adjacency list representation class island: def __init__(self, vertices): self.V = vertices # No. of vertices self.island = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self, u, v): self.island[u].append(v) self.island[v].append(u) # A function used by isConnected def DFSUtil(self, v, visited): # Mark the current node as visited visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.island[v]: if visited[i] == False: self.DFSUtil(i, visited) '''Method to check if all non-zero degree vertices are connected. It mainly does DFS traversal starting from node with non-zero degree''' def isConnected(self): # Mark all the vertices as not visited visited = [False] * (self.V) # Find a vertex with non-zero degree for i in range(self.V): if len(self.island[i]) > 1: break # If there are no edges in the graph, return true if i == self.V - 1: return True # Start DFS traversal from a vertex with non-zero degree self.DFSUtil(i, visited) # Check if all non-zero degree vertices are visited for i in range(self.V): if visited[i] == False and len(self.island[i]) > 0: return False return True '''The function returns one of the following values 0 --> If grpah is not Eulerian 1 --> If graph has an Euler path (Semi-Eulerian) 2 --> If graph has an Euler Circuit (Eulerian) ''' def canLoot(self): # Check if all non-zero degree vertices are connected if self.isConnected() == False: return 0 else: # Count vertices with odd degree odd = 0 for i in range(self.V): if len(self.island[i]) % 2 != 0: odd += 1 '''If odd count is 2, then semi-eulerian. If odd count is 0, then eulerian If count is more than 2, then graph is not Eulerian Note that odd count can never be 1 for undirected graph''' if odd == 0: return 2 elif odd == 2: return 1 elif odd > 2: return 0 # Function to run test cases def test(self): res = self.canLoot() if res == 0: print("island cannot be looted") elif res == 1: print("island can be looted") else: print("island can be looted") # # Let us create and test graphs shown in above figures # THESE COMMENTS ARE FOR REFERRAL, SO THAT EITHER ME ANYONE ELSE CAN GET A PROPER UNCDERSTANDING OF WHAT THIS CODE ACTUALLY DOES # g1 = Graph(5) # g1.addEdge(1, 0) # g1.addEdge(0, 2) # g1.addEdge(2, 1) # g1.addEdge(0, 3) # g1.addEdge(3, 4) # g1.test() # # g2 = Graph(5) # g2.addEdge(1, 0) # g2.addEdge(0, 2) # g2.addEdge(2, 1) # g2.addEdge(0, 3) # g2.addEdge(3, 4) # g2.addEdge(4, 0) # g2.test() # # g3 = Graph(5) # g3.addEdge(1, 0) # g3.addEdge(0, 2) # g3.addEdge(2, 1) # g3.addEdge(0, 3) # g3.addEdge(3, 4) # g3.addEdge(1, 3) # g3.test() # # # Let us create a graph with 3 vertices # # connected in the form of cycle # g4 = Graph(3) # g4.addEdge(0, 1) # g4.addEdge(1, 2) # g4.addEdge(2, 0) # g4.test() # # Let us create a graph with all veritces # # with zero degree # g5 = Graph(3) # g5.test() # Automation of the input process print("start") num_island = int(input()) island_lst = [None]*num_island for num in range(num_island): num_nodes = int(input()) island_lst[num] = island(num_nodes) for node_i in range(num_nodes): land_part_lst = input().split(" ") degree = int(land_part_lst[0]) for j in range(1,degree): land_part_num = int(land_part_lst[j]) island_lst[num].addEdge(node_i,land_part_num) island_lst[num].test()
3be669c9b967be7ac8e0d3601b7793842e34d2c5
xia0nan/Project-Euler
/problem015.py
554
3.5
4
""" Author: Nan <[email protected]> https://projecteuler.net/problem=15 [Lattice paths] Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? """ def count_path(x): numlist = [1] * (x + 1) n = 1 while n < x: for i in xrange(x + 1): for j in xrange(i + 1, x + 1): numlist[i] += numlist[j] n += 1 return sum(numlist) def main(): count_path(20) if __name__ == '__main__': main()
b651ff2da4c5f138ee573fa738e96326476e8bd0
xia0nan/Project-Euler
/problem003.py
663
3.796875
4
__author__ = "xiaonan" """ Largest prime factor Problem 3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def isprime(number): if number < 2: return False elif number == 2 or number == 3: return True elif number % 2 == 0 or number % 3 == 0: return False i = 5 while i * i <= number: if number % i == 0 or number % (i + 2) == 0: return False i += 6 return True def check_prime(number): sqroot = int(number**0.5) for i in reversed(xrange(sqroot)): if number % i == 0 and isprime(i): print "found", i return -1 if __name__ == '__main__': check_prime(600851475143)
5854831f486c7fc9fa8ff44083186ba604419c3b
xia0nan/Project-Euler
/problem006.py
450
3.703125
4
__author__ = "xiaonan" """ Solution for: https://projecteuler.net/problem=6 """ def sum_of_square(number): result = 0 for i in xrange(number): result += (i+1)**2 print "sum_of_square", result return result def square_of_sum(number): result = 0 for i in xrange(number): result += i + 1 print "square_of_sum", result ** 2 return result ** 2 def main(): print square_of_sum(100) - sum_of_square(100) if __name__ == '__main__': main()
affa5bd44bd4bd55231e33e2cae6abf86a3b2a82
usupsuparma/Object-Oriented-Programming-Python
/Getter and Setter.py
784
3.796875
4
class Hero: def __init__(self, name, armor, health): self.name = name self.__armor = armor self.__health = health @property def info(self): return "name {} : \n\thealth {} \n\tarmor {}".format(self.name, self.__health, self.__armor) @property def armor(self): pass @armor.getter def armor(self): return self.__armor @armor.setter def armor(self, input): self.__armor = input @armor.deleter def armor(self): print("armor didelete") self.__armor = None sniper = Hero('sniper',100,10) print("merubah info") print(sniper.info) sniper.name = 'dadang' print(sniper.info) print("percobaan setter dan getter") print(sniper.armor) sniper.armor = 10 print(sniper.armor)
cbbe2621cdcb691ad6046ed26e1b70038ed8d8bd
stepheneasleywalsh/computerProgrammingIWeek5Lesson2
/main.py
484
3.859375
4
# THE BIO FUNCTION def bio(name,born,pronoun): age = 2021-born future = born+67 print("----------------------------------------") print(name.capitalize(), "was born in", born) print(pronoun.capitalize(), "will turn", age, "years old this year") print(pronoun.capitalize(), "will be 67 in the year", future) print("----------------------------------------") # PRINT BIOS bio("stephen",1984,"he") bio("mary",1990,"she") bio("jane",2000,"she") # EXIT quit()
e28dc8156acba525f2fdf65ea3cc9fc990770114
AdorableNewYs/learn_sicp
/practice_1_19.py
328
3.703125
4
def even(n): return n % 2 == 0 def fib(n): def fib_iter(a,b,p,q,count): if count == 0: return b elif even(count): return fib_iter(a,b,p*p + q*q,2*p*q + q*q,count / 2) else: return fib_iter(b*q + a*q + a*p,b*p + a*q,p,q,count-1) return fib_iter(1,0,0,1,n)
ad9c8bed2c23d82a0df3a4e65ce05df16c9032ea
Utkarshmalik99/Python
/Python_Program_for_n-th_Fibonacci_number.py
198
4.21875
4
n=int(input("enter the n'th number:")) def fibonacci(n): if n <= 1: return n else: return(fibonacci(n-1) + fibonacci(n-2)) print("N'th fibonacci number is ",fibonacci(n))
c7660f95432c083ccc5af38f284d340ea33db9d9
Utkarshmalik99/Python
/Python Program for simple interest.py
313
3.890625
4
def simple_interest(p,r,t): if p==0 or r==0 or t==0: return 0 else: simple_interest=(p*r*t)/100 return simple_interest p=int(input("enter the value of p: ")) r=int(input("enter the value of r: ")) t=int(input("enter the value of t: ")) print("simple_interest is ",simple_interest(p,r,t))
b32db989e7f68bf9b1bc7b93739dc8e353db82cb
Utkarshmalik99/Python
/Sum_of_squares_of_first_n_natural_numbers.py
205
4.09375
4
n=int(input("enter the n'th natural number:")) def squareSum(n): sum=0 for n in range(1,n+1): sum+=(n*n) return sum print("Sum of squares of first n entered natural numbers is",squaresum(n))
fd340d5fef141c91bbcb13c89cfe22cbcea0ccce
MarcosParengo/Unsam-2do-cuatri-2021
/mate III/clase 4 pruebas/graficos/6. zip y leyendas/main.py
512
3.6875
4
import matplotlib.pyplot as plt zip_generator=zip([1,2,3,4,5],[60,70,80,90,100]) x,y=zip(*zip_generator) print(x) print(y) plt.figure() plt.scatter(x[:3],y[:3],s=100,c='red',label='Ingresos más bajos') plt.scatter(x[2:],y[2:],s=50,c='green',label='Ingresos más altos') #x[:2],y[:2] -> ((1, 2), (60, 70)) #x[2:],y[2:] -> ((3, 4, 5), (80, 90, 100)) plt.xlabel('Experiencia en años') plt.ylabel('Ingresos obtenidos') plt.title('Relación entre experiencia e ingresos') plt.legend(loc=4,frameon=False) plt.show()
332b8139b6d2b2e56a93720a436b40a1b8827807
bingecodingJC/NLPTA-Group-Flying-Circus
/data_merge.py
5,522
3.5
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 4 10:14:22 2018 @author: ZHANG Xin(Serene) """ import pandas as pd from datetime import datetime from datetime import timedelta def month_transfer(month): # this function is to convert the type of month if month == 'January': month_number = 1 if month == 'February': month_number = 2 if month == 'March': month_number = 3 if month == 'April': month_number = 4 if month == 'May': month_number = 5 if month == 'June': month_number = 6 if month == 'July': month_number = 7 if month == 'August': month_number = 8 if month == 'September': month_number = 9 if month == 'October': month_number = 10 if month == 'November': month_number = 11 if month == 'December': month_number = 12 return month_number def preprocess_seeking_alpha(): # this function is to preprocess seekingalpha.csv seeking_alpha = pd.read_excel(r'C:\Users\76355\Desktop\NPLTA\seekingalpha.xlsx') seeking_alpha.columns = ['title','time','company','label','text'] seeking_alpha['date of call'] = '' seeking_alpha['Ticker'] = '' seeking_alpha['day0'] = '' seeking_alpha['day1'] = '' seeking_alpha['day2'] = '' seeking_alpha['day3'] = '' seeking_alpha['day4'] = '' seeking_alpha['day5'] = '' call_transcript_list_text = list(seeking_alpha['text']) for text_id, everytext in enumerate(call_transcript_list_text): # for every text, dig out the date of the earning call based on the observation that the date is listed after the first 'call' in the text text_split = everytext.split() try: for index, value in enumerate(text_split): if value == 'Call': date_info = str(month_transfer(text_split[index + 1])) + ' ' + text_split[index + 2][:-1] + ' ' + text_split[index + 3] break seeking_alpha.iloc[text_id, 5] = datetime.strptime(date_info, '%m %d %Y') # convert string date information to datetime type except: print("Cannot find date information based on the position of the word'call'", text_id) company_list = list(seeking_alpha['company']) for company_id, everycompany in enumerate(company_list): # for every text, dig out the ticker information based on the 'company' column data try: ticker = everycompany.split("(")[-1].split(")")[0] seeking_alpha.iloc[company_id,6] = ticker except: print('Cannot find ticker information from company column', everycompany) # delete null value of 'Ticker' or 'date of call' seeking_alpha = seeking_alpha[seeking_alpha['date of call'] != ''] seeking_alpha = seeking_alpha[seeking_alpha['Ticker'] != ''] #create index for each call, the index form is tuple(ticker, date of call) seeking_alpha['index_label'] = seeking_alpha[['Ticker', 'date of call']].apply(tuple, axis = 1) return seeking_alpha def preprocess_stock_price(): stock_price = pd.read_csv(r'C:\Users\76355\Desktop\NPLTA\stock_price.csv') stock_price = stock_price.drop(['gvkey','iid','conm'],axis = 1) #62492275 rows stock_price = stock_price.dropna(how = 'any') #62474239 rows stock_price['datadate'] = pd.to_datetime(stock_price['datadate'].astype(str)) return stock_price def data_merge(): stock_price = preprocess_stock_price() seeking_alpha = preprocess_seeking_alpha() seeking_alpha = seeking_alpha.sort_values(by = ['Ticker']) seeking_alpha_ticker_list = list(set(seeking_alpha['Ticker'])) seeking_alpha = seeking_alpha.set_index('index_label') for everytic in seeking_alpha_ticker_list: # for every ticker, extract the related stock price information stock_price_everydic = stock_price[stock_price['tic'] == everytic] stock_price_everydic = stock_price_everydic.set_index('datadate') single_tic_dataframe = seeking_alpha[seeking_alpha['Ticker'] == everytic] date_of_call_list = list(single_tic_dataframe['date of call']) for eachdate in date_of_call_list: try: day0 = eachdate seeking_alpha.loc[(everytic,eachdate),'day0'] = stock_price_everydic.loc[day0, 'prccd'] day1 = eachdate + timedelta(days = 1) seeking_alpha.loc[(everytic,eachdate),'day1'] = stock_price_everydic.loc[day1, 'prccd'] day2 = eachdate + timedelta(days = 2) seeking_alpha.loc[(everytic,eachdate),'day2'] = stock_price_everydic.loc[day2, 'prccd'] day3 = eachdate + timedelta(days = 3) seeking_alpha.loc[(everytic,eachdate),'day3'] = stock_price_everydic.loc[day3, 'prccd'] day4 = eachdate + timedelta(days = 4) seeking_alpha.loc[(everytic,eachdate),'day4'] = stock_price_everydic.loc[day4, 'prccd'] day5 = eachdate + timedelta(days = 5) seeking_alpha.loc[(everytic,eachdate),'day5'] = stock_price_everydic.loc[day5, 'prccd'] except: print('the date is out of the observation') seeking_alpha.to_csv(r'C:\Users\76355\Desktop\NPLTA\seeking_alpha_processed.csv') return seeking_alpha if __name__ == '__main__': mmm = data_merge()