blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
959c2cbc231db6724ad9bb29ca5be19dea021cbc
gjtjdtn201/practice
/수업/stack2/미로.py
808
3.515625
4
import sys sys.stdin = open("미로.txt", "r") def safe(y, x): return N > y >= 0 and N > x >= 0 and(Maze[y][x] == 0 or Maze[y][x] == 3) def DFS(sty, stx): global ans if Maze[sty][stx] == 3: ans = 1 return visit.append((sty, stx)) for i in range(4): Py = sty + dy[i] Px = stx + dx[i] if (Py, Px) not in visit and safe(Py, Px): DFS(Py, Px) T = int(input()) for test_case in range(1,T+1): N = int(input()) Maze =[] for i in range(N): Maze.append(list(map(int,input()))) for y in range(N): for x in range(N): if Maze[y][x] == 2: sty, stx = y, x dy = [-1,1,0,0] dx = [0,0,-1,1] ans = 0 visit =[] DFS(sty,stx) print('#{} {}'.format(test_case, ans))
4d3d6d0bbbf92446cf1a69dd5f7e2c42f043853f
syurskyi/Python_Topics
/021_module_collection/counter/_exercises/templates/counter_003_Finding the n most Common Elements_template.py
1,873
3.859375
4
# # Finding the n most Common Elements # # Let's find the n most common words (by frequency) in a paragraph of text. # # Words are considered delimited by white space or punctuation marks such as ., ,, !, etc - basically anything except # # a character or a digit. This is actually quite difficult to do, so we'll use a close enough approximation # # that will cover most cases just fine, using a regular expression: # # import d..d.. # f.. c... _______ d..d.. C.. # # sentence _ # his module implements pseudo-random number generators for various distributions. # For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, # a function to generate a random permutation of a list in-place, and a function for random sampling without replacement. # On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, # and beta distributions. For generating distributions of angles, the von Mises distribution is available. # Almost all module functions depend on the basic function random(), which generates a random float uniformly # in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces # 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. # The Mersenne Twister is one of the most extensively tested random number generators in existence. However, # being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic # purposes. # # words _ r_.sp.. %W s.. # print w.. # # # But what are the frequencies of each word, and what are the 5 most frequent words? # # word_count _ C.. w.. # print w.._c.. # # print w.._c__.m.._c.. 5 # # [('', 38), ('a', 8), ('random', 7), ('is', 7), ('the', 7)]
e57cdc1ccc2f3a8a211c5bafec2cb96abaf8af1e
redpanda-ai/ctci
/solutions/animal_shelter.py
2,104
3.828125
4
""" Title: Animal Shelter Question: An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis. People must adopt either the "oldest" (based on arrival time) of all animals in the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement options such as enqueue, dequeAny, dequeueDog, and dequeueCat. You may use the built-in LinkedList data structure. """ from collections import deque class Shelter: def __init__(self): self.dogs = deque([]) self.cats = deque([]) self.id = 0 def __repr__(self): return f"dogs: {self.dogs}\ncats: {self.cats}" def enqueue(self, animal): if animal == "cat": self.cats.append(Cat(self.id)) else: self.dogs.append(Dog(self.id)) self.id += 1 def dequeueDog(self): return self.dogs.popleft() def dequeueCat(self): return self.cats.popleft() def dequeueAny(self): c, d = None, None if self.dogs: d = self.dogs[0] if self.cats: c = self.cats[0] if not c and not d: raise Exception("No dogs or cats, sorry!") if c and not d: return self.cats.popleft() elif d and not c: return self.dogs.popleft() elif d.id_num < c.id_num: return self.dogs.popleft() else: return self.cats.popleft() class Dog: def __init__(self, id_num): self.id_num = id_num def __repr__(self): return f"dog({self.id_num})" class Cat: def __init__(self, id_num): self.id_num = id_num def __repr__(self): return f"cat({self.id_num})" s = Shelter() print(s) s.enqueue("cat") s.enqueue("dog") s.enqueue("cat") print(s) print(s.dequeueCat()) # print(s.dequeueDog()) print(s) print(s.dequeueAny()) print(s.dequeueAny()) print(s.dequeueAny())
3682e80cb780a03106473a4e8aba19de083d778c
Nguyen101/League-of-Legends-Data-Analysis
/mysklearn/myevaluation.py
6,249
3.6875
4
import mysklearn.myutils as myutils import random import math def train_test_split(X, y, test_size=0.33, random_state=None, shuffle=True): """Split dataset into train and test sets (sublists) based on a test set size. Args: X(list of list of obj): The list of samples The shape of X is (n_samples, n_features) y(list of obj): The target y values (parallel to X) The shape of y is n_samples test_size(float or int): float for proportion of dataset to be in test set (e.g. 0.33 for a 2:1 split) or int for absolute number of instances to be in test set (e.g. 5 for 5 instances in test set) random_state(int): integer used for seeding a random number generator for reproducible results shuffle(bool): whether or not to randomize the order of the instances before splitting Returns: X_train(list of list of obj): The list of training samples X_test(list of list of obj): The list of testing samples y_train(list of obj): The list of target y values for training (parallel to X_train) y_test(list of obj): The list of target y values for testing (parallel to X_test) Note: Loosely based on sklearn's train_test_split(): https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html """ if random_state is not None: random.seed(random_state) if shuffle: myutils.randomize_in_place(X, parallel_list=y) num_instances = len(X) if isinstance(test_size, float): test_size = math.ceil(num_instances * test_size) split_index = num_instances - test_size return X[:split_index], X[split_index:], y[:split_index], y[split_index:] def kfold_cross_validation(X, n_splits=5): """Split dataset into cross validation folds. Args: X(list of list of obj): The list of samples The shape of X is (n_samples, n_features) n_splits(int): Number of folds. Returns: X_train_folds(list of list of int): The list of training set indices for each fold X_test_folds(list of list of int): The list of testing set indices for each fold Notes: The first n_samples % n_splits folds have size n_samples // n_splits + 1, other folds have size n_samples // n_splits, where n_samples is the number of samples (e.g. 11 samples and 4 splits, the sizes of the 4 folds are 3, 3, 3, 2 samples) Loosely based on sklearn's KFold split(): https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html """ X_train_folds = [] X_test_folds = [] x_len = len(X) fold_modulus = x_len % n_splits start_idx = 0 for fold in range(n_splits): if fold < fold_modulus: fold_size = x_len // n_splits + 1 else: fold_size = x_len // n_splits fold_end = (start_idx + fold_size) - 1 tmp = [] for i in range(start_idx, fold_end + 1): tmp.append(i) X_test_folds.append(tmp) tmp = [] for i in range(0, x_len): if i not in X_test_folds[fold]: tmp.append(i) X_train_folds.append(tmp) start_idx = fold_size + start_idx return X_train_folds, X_test_folds def stratified_kfold_cross_validation(X, y, n_splits=5): """Split dataset into stratified cross validation folds. Args: X(list of list of obj): The list of instances (samples). The shape of X is (n_samples, n_features) y(list of obj): The target y values (parallel to X). The shape of y is n_samples n_splits(int): Number of folds. Returns: X_train_folds(list of list of int): The list of training set indices for each fold. X_test_folds(list of list of int): The list of testing set indices for each fold. Notes: Loosely based on sklearn's StratifiedKFold split(): https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html#sklearn.model_selection.StratifiedKFold """ indices = [x for x in range(0, len(X))] labels = [] uniq_feat = [] for idx,clss in enumerate(y): if clss in uniq_feat: labels[uniq_feat.index(clss)].append(indices[idx]) else: labels.append([indices[idx]]) uniq_feat.append(clss) index = 0 X_test_folds = [[] for _ in range(0, n_splits)] for label in labels: for val in label: fold_idx = index%n_splits X_test_folds[fold_idx].append(val) index += 1 X_train_folds = [[] for _ in range(0, n_splits)] for i in range(0, len(X)): for j in range(0, n_splits): if i not in X_test_folds[j]: X_train_folds[j].append(i) return X_train_folds, X_test_folds def confusion_matrix(y_true, y_pred, labels): """Compute confusion matrix to evaluate the accuracy of a classification. Args: y_true(list of obj): The ground_truth target y values The shape of y is n_samples y_pred(list of obj): The predicted target y values (parallel to y_true) The shape of y is n_samples labels(list of str): The list of all possible target y labels used to index the matrix Returns: matrix(list of list of int): Confusion matrix whose i-th row and j-th column entry indicates the number of samples with true label being i-th class and predicted label being j-th class Notes: Loosely based on sklearn's confusion_matrix(): https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html """ matrix = [] for i, yt in enumerate(labels): matrix.append([]) for _, yp in enumerate(labels): matrix[i].append(0) for t, p in zip(y_true, y_pred): t_num = labels.index(t) p_num = labels.index(p) matrix[t_num][p_num] += 1 return matrix
c2d8f3e7df9932067c67425ccc10bdc9e259628b
ljia2/leetcode.py
/solutions/math/233.Number.of.Digit.One.py
397
3.890625
4
class Solution(object): def countDigitOne(self, n): """ Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. Example: Input: 13 Output: 6 Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. :type n: int :rtype: int """
68a9d33f8c4f0f71e887467f258c1f17fa343471
jihoonog/Tim-The-Enchanter
/spellbook.py
8,609
3.78125
4
import pickle, os from spell import * class Spellbook: def __init__(self, name): self.name = name self.spells = list() def addSpell(self, spell): self.spells.append(spell) self.spells.sort(key=lambda k: k.name) def removeSpell(self, spell): try: self.spells.remove(spell) except: pass def spellbookFinder(spellbooks, spellbookName): savedSpellbook = None text = [] for spellbook in spellbooks.keys(): if spellbook.lower().replace("'", "").replace(" ", "") == spellbookName.lower().replace("'", "").replace(" ", ""): return True, spellbook elif spellbookName.lower().replace("'", "").replace(" ", "") in spellbook.lower().replace("'", "").replace(" ", ""): if not savedSpellbook: savedSpellbook = spellbook else: text.append(spellbook) if not savedSpellbook: return False, "Spellbook not found" elif text == []: return True, savedSpellbook else: text.append(savedSpellbook) return False, "? ".join(sorted(text)) + "?" def spellbookParser(spells, spellbooks, command): try: if command[0] == "list": if len(command) > 1: sbfound, sbresult = spellbookFinder(spellbooks, command[1]) if sbfound: spellList = spellbooks[sbresult].spells return ", ".join([spell.name for spell in spellList]) if len(spellList) > 0 else "Spellbook is empty" else: return sbresult text = ", ".join(spellbooks.keys()) return text if text else "No spellbooks found" elif command[0] == "new": if command[1].isalpha(): if command[1] not in spellbooks.keys(): spellbooks[command[1]] = Spellbook(command[1]) return "Created spellbook " + command[1] else: return "Spellbook already exists" else: return "Please use letters exclusively for the spellbook name" elif command[0] == "delete": try: del spellbooks[command[1]] return "Deleted spellbook " + command[1] except: return "Spellbook doesn't exist" elif command[0] == "save": sbfound, sbresult = spellbookFinder(spellbooks, command[1]) if sbfound: pickle.dump(spellbooks[sbresult], open("spellbooks/" + sbresult + '.pickle', 'wb')) return "Sucessfully saved " + sbresult else: return sbresult elif command[0] in ["fullsave", "saveall"]: for spellbook in spellbooks.keys(): pickle.dump(spellbooks[spellbook], open("spellbooks/" + spellbook + '.pickle', 'wb')) return "Saved all spellbooks" elif command[0] == "load": try: spellbooks[command[1]] = pickle.load(open("spellbooks/" + command[1] + '.pickle', 'rb')) return "Sucessfully loaded " + command[1] except: return "Spellbook not found" elif command[0] in ["fullload", "loadall"]: for file in [file for file in os.listdir("spellbooks/") if os.path.isfile("spellbooks/" + file) and file[-7:] == ".pickle"]: spellbooks[file[:-7]] = pickle.load(open("spellbooks/" + file, 'rb')) return "Loaded all spellbooks" elif command[1] == "add": sbfound, sbresult = spellbookFinder(spellbooks, command[0]) if sbfound: found, result = spellFinder(spells, "".join(command[2:])) if found: spellbooks[sbresult].addSpell(result) return "Added " + result.name + " to " + sbresult else: return result else: return sbresult elif command[1] == "remove": sbfound, sbresult = spellbookFinder(spellbooks, command[0]) if sbfound: found, result = spellFinder(spellbooks[sbresult].spells, "".join(command[2:])) if found: spellbooks[sbresult].removeSpell(result) return "Removed " + result.name + " from " + sbresult else: return result else: return sbresult elif command[1] == "multiadd": sbfound, sbresult = spellbookFinder(spellbooks, command[0]) if sbfound: reply = "" for spell in "".join(command[2:]).split("|"): found, result = spellFinder(spells, spell.lower().replace(" ", "").replace("'", "")) if found: spellbooks[sbresult].addSpell(result) reply += "Added " + result.name + " to " + sbresult + "\n" else: reply += result + "\n" return reply else: return sbresult elif command[1] == "multiremove": sbfound, sbresult = spellbookFinder(spellbooks, command[0]) if sbfound: reply = "" for spell in "".join(command[2:]).split("|"): found, result = spellFinder(spells, spell.lower().replace(" ", "").replace("'", "")) if found: spellbooks[sbresult].removeSpell(result) reply += "Removed " + result.name + " from " + sbresult + "\n" else: reply += result + "\n" return reply else: return sbresult elif command[1] == "list": sbfound, sbresult = spellbookFinder(spellbooks, command[0]) if sbfound: spellList = spellbooks[sbresult].spells return ", ".join([spell.name for spell in spellList]) if len(spellList) > 0 else "Spellbook is empty" else: return sbresult elif command[1] == "search": sbfound, sbresult = spellbookFinder(spellbooks, command[0]) if sbfound: if len(command) > 2: spellList = spellbooks[sbresult].spells returnList = spellSearch(spellList, command[2:]) if len(returnList) == 0: return "No valid spells found" elif len(returnList) == 1: found, result = spellFinder(spells, returnList[0]) return Spell.spellText(result) else: return ", ".join(returnList) else: return "No filter supplied" else: return sbresult elif command[1] == "bulkadd": sbfound, sbresult = spellbookFinder(spellbooks, command[0]) if sbfound: if len(command) > 2: returnList = spellSearch(spells, command[2:]) count = 0 for spell in returnList: found, result = spellFinder(spells, spell) if found: spellbooks[sbresult].addSpell(result) count = count + 1 return "Added " + str(count) + " spell(s) to " + sbresult else: return "No filter supplied" else: return sbresult elif command[1] == "bulkremove": sbfound, sbresult = spellbookFinder(spellbooks, command[0]) if sbfound: if len(command) > 2: returnList = spellSearch(spellbooks[sbresult].spells, command[2:]) count = 0 for spell in returnList: found, result = spellFinder(spellbooks[sbresult].spells, spell) if found: spellbooks[sbresult].removeSpell(result) count = count + 1 return "Removed " + str(count) + " spell(s) from " + sbresult else: return "No filter supplied" else: return sbresult else: return "Invalid spellbook command" except Exception as e: print(e) return "Spellbook command exception"
8869e2e8b324fdcd308b9d003f0aa0c34398ee35
S-Tim/saene
/saene/utils/copy_dict.py
1,040
4.03125
4
""" Utility to copy dictionaries that also have lists as values Author: Tim Silhan """ import numpy as np def copy_dict(original): """ Copies the *original* dictionary This function makes sure that lists and numpy arrays are copied as well instead of only referencing the original list in the copy. Args: original: Dictionary that should be copied Returns: A copy of the *original* dictionary """ copied = original.copy() for key in copied.keys(): if isinstance(copied[key], list): copied[key] = copied[key][:] elif isinstance(copied[key], np.ndarray): copied[key] = np.copy(copied[key]) return copied if __name__ == "__main__": TEST = {"a" : 1, "b" : "hello", "c" : [1, 2, 3], "d" : ["he", "lo"]} COPIED = copy_dict(TEST) TEST["d"][0] = "world" TEST["c"][2] = 4 assert TEST["d"][0] != COPIED["b"][0] assert TEST["c"][2] != COPIED["c"][2] assert TEST["c"][1] == COPIED["c"][1] assert TEST["b"] == COPIED["b"]
cb23bbc23c62bddc3749522a5f79b4487b7bc59f
manhcuogntin4/Code_Gym
/cube_pile.py
1,672
4
4
'''There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if is on top of then . When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time. Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks. Input Format The first line contains a single integer , the number of test cases. For each test case, there are lines. The first line of each test case contains , the number of cubes. The second line contains space separated integers, denoting the sideLengths of each cube in that order. Constraints Output Format For each test case, output a single line containing either "Yes" or "No" without the quotes. Sample Input 2 6 4 3 2 1 3 4 3 1 3 2 Sample Output Yes No ''' # Enter your code here. Read input from STDIN. Print output to STDOUT def stack_able(l): i=0 j=len(l)-1 max_temp=max(l[i],l[j]) while i<=j and i<len(l) and j>0: if i==j: if l[i]<=max_temp: return True if l[i]>=l[j]: if l[i]<=max_temp: max_temp=l[i] i+=1 else: return False else: if l[j]<=max_temp: max_temp=l[j] j-=1 else: return False return True import sys data = sys.stdin.readlines() m=int(data[0].strip()) for i in range(0,m): l=list(map(int,data[(i+1)*2].strip().split(" "))) #print(l) if stack_able(l): print("Yes") else: print("No")
c8e761c436ef53bd64163d0b515127d92d2fc72f
AdamsEatin/Data_Sci
/breakdown_per_country.py
3,024
3.671875
4
# -*- coding: utf-8 -*- """ Author: Adam Eaton - C00179859 This file generates a graph showing a breakdown of the different types of renewable energies used by each member of the EU. """ import pandas as pd import numpy as np import plotly import plotly.plotly as py import plotly.graph_objs as go plotly.tools.set_credentials_file(username='VMunt', api_key='w2tEETwgAuCdgRwVDqiK') def split_vals(data, opt): if(opt == 1): y_vals = [] for k, v in data.items(): y_vals.append(v) return y_vals else: x_vals = [] y_vals = [] for k, v in data.items(): x_vals.append(k) y_vals.append(v) return x_vals, y_vals # Function to clean up a given dataset, it does this by; # -Pulling only data to do with individual EU member states # -Setting the index column to the country names as opposed to numbers # -Filling any missing values with Nan values # -Backfilling these values def clean_data(dataset): dataset = dataset[1:29] dataset = dataset.set_index(["Unnamed: 0"]) dataset = dataset.replace(':', np.nan) dataset = dataset.fillna(method='backfill') return dataset def each_type(data): val_dict = {} col_len = len(list(data.columns)) for index, row in data.iterrows(): val_dict[index] = float(row[col_len-1]) return val_dict def sources_per_country(): hydro_data = pd.read_csv('Datasets/Hydro_Consumption-By_Country.csv') solar_data = pd.read_csv('Datasets/Solar_Consumption-By_Country.csv') thermal_data = pd.read_csv('Datasets/Thermal_Consumption-By_Country.csv') wind_data = pd.read_csv('Datasets/Wind_Consumption-By_Country.csv') # Selecting the data we want to use from the datasets hydro_data = clean_data(hydro_data) solar_data = clean_data(solar_data) thermal_data = clean_data(thermal_data) wind_data = clean_data(wind_data) hydro_dict = each_type(hydro_data) solar_dict = each_type(solar_data) thermal_dict = each_type(thermal_data) wind_dict = each_type(wind_data) x_vals, hy_y_vals = split_vals(hydro_dict, 0) so_y_vals = split_vals(solar_dict, 1) th_y_vals = split_vals(thermal_dict, 1) wi_y_vals = split_vals(wind_dict, 1) trace1 = go.Bar(x = x_vals, y = hy_y_vals, name = 'Hydro') trace2 = go.Bar(x = x_vals, y = so_y_vals, name = 'Solar') trace3 = go.Bar(x = x_vals, y = th_y_vals, name = 'Thermal') trace4 = go.Bar(x = x_vals, y = wi_y_vals, name = 'Wind') data = [trace1, trace2, trace3, trace4] layout = go.Layout(title = 'Renewable Energy Breakdown per Country in 2016', yaxis=dict(title="Thousand' Tonnes of Oil Equivelent"), barmode='stack') fig = go.Figure(data=data, layout=layout) py.plot(fig, filename='Renewable Energy Breakdown per Country')
57c6ac48d70d5382e3a96e168f9d69d82debc15e
tenrenjun/python_experimental-task
/Experimental task/CH2_Task5.py
840
3.984375
4
# 新建list并输出其长度 classmates = ['Michael', 'Bob', 'Tracy'] print(len(classmates)) # 查看列表中第一个和第二个元素 print(classmates[0]) print(classmates[1]) # 添加元素 classmates.append('Adam') print(classmates) # 指定位置插入元素 classmates.insert(1, 'Jack') print(classmates) # 删除末尾元素 classmates.pop() print(classmates) # 删除指定位置元素 classmates.pop(1) print(classmates) # 替换 classmates[1] = 'Sarah' print(classmates) # list中存放不同元素类型 L = ['Apple', 123, True] print(L) # 二维数组 s = ['python', 'java', ['asp', 'php'], 'scheme'] print(s) print(len(s)) # 二维数组,内层数组可以用数组变量代替 p = ['asp', 'php'] s = ['python', 'java', p, 'scheme'] print(s) # 空列表的长度为0 L = [] print(len(L))
ebfa5ed29b3df005b6f8533751ad3bebe88c0f43
n-alegria/ProyectosPython
/Juegos_Python/Adivina el numero - facil/main.py
2,011
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from random import randint from exception_number import NumberException def juego(): print(""" Bienvenido Se le solicitará que ingrese un numero de tres digitos entre el 100 y 999 el cual será cotejado con un numero secreto generado automaticamente. Si el numero ingresado es incorrecto se le vovlerá a pedir que ingrese un numero nuevamente y se le indicará si el numero secreto es mayor o menor al numero que usted ingreso. En caso de llegar a cinco intentos fallidos se le proporcionara una ayuda, al finalizar el juego se le indicará la cantidad de intentos que tuvo hasta obtener el numero ganador. Buena Suerte!""") numero_secreto = randint(100, 999) cantidad_intentos = 0 continuar = 's' while(True): try: numero_string = input("\nIngrese un numero: ") if not numero_string.isnumeric(): raise NumberException() numero_int = int(numero_string) cantidad_intentos += 1 if(numero_int == numero_secreto): print(f"\n->> Ganaste al {cantidad_intentos} intento <<-\n") break elif(numero_int > numero_secreto): print("\n--> El numero que ingresaste es mayor al numero secreto <--") elif(numero_int < numero_secreto): print("\n--> El numero que ingresaste es menor al numero secreto <--") if(cantidad_intentos == 4): continuar = input('\nContinuar? (s/n): ') print(f"\nEl primer numero secreto es: {numero_string[:1]}") elif(cantidad_intentos == 8): print(f"\nLos primeros dos numeros secretos son: {numero_string[:2]}") continuar = input('\nContinuar? (s/n): ') if continuar.lower() != 's': break except NumberException as e: print(f'\n-> {e} <-') if __name__ == '__main__': juego()
d47f6548cbbec022548169d2556ad9e390056f8b
Kang-Hoon/Python_reviews
/190614_fin exam/1906_3.py
376
3.734375
4
# 스크립트 창입니다 import turtle t = turtle.Turtle() t.penup() t.goto(100,100) t.write("It's positive integer") t.goto(100,0) t.write("It's Zero") t.goto(100,-100) t.write("It's negative integer") t.goto(0,0) t.pendown() i = turtle.textinput("","Enter integer : ") j = int(i) if j>0: t.goto(100,100) if (j==0): t.goto(100,0) if j<0: t.goto(100,-100)
1286a43a47ea69dc31f61408dcc8d0e1030b9abc
winonachen/2020-Jayden-AE401
/成績.py
227
3.75
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 21 11:28:58 2020 @author: user """ a=input("請輸入你的考試成績:") a=float(a) if a>59: print("恭喜你~!有及格!") else: print("嗚~!沒及格!")
d764b2b0ff06e08116824a16b54b23d6aa3f94b9
zhaoxy92/leetcode
/918_maximum_sum_subarray.py
782
3.59375
4
def max_sum_noncircular_subarray(array): ans = cur = array[0] for n in array[1:]: cur = n + max(cur, 0) ans = max(ans, cur) return ans def maxSubarraySumCircular(A): """ :type A: List[int] :rtype: int """ ans1 = max_sum_noncircular_subarray(A) ans2 = sum(A) + max_sum_noncircular_subarray([-A[i] for i in range(1, len(A))]) ans3 = sum(A) + max_sum_noncircular_subarray([-A[i] for i in range(len(A)-1)]) # print(ans1, ans2, ans3) return max(ans1, ans2, ans3) print(maxSubarraySumCircular([1,-2,3,-2])) print(maxSubarraySumCircular([5,-3,5])) print(maxSubarraySumCircular([3,-1,2,-1])) print(maxSubarraySumCircular([3,-2,2,-3])) print(maxSubarraySumCircular([-2,-3,-1])) print(maxSubarraySumCircular([3,1,3,2,6]))
83a640198eb4ebfab509ae6fc14b2ca9bf9c3936
HarshaVardhan-Kaki/Hashing-2
/longest_palindrome.py
422
3.5625
4
# O(N) TIME AND O(N) SPACE WHERE N IS LEN(S) class Solution: def longestPalindrome(self, s: str) -> int: palindrome_len = 0 counts = set() for char in s: if char not in counts: counts.add(char) else: palindrome_len += 2 counts.remove(char) return palindrome_len if len(counts) == 0 else palindrome_len + 1
d6a8a7e1597ded9d8433d2757e17ed64159c5279
jannuprathyusha/jannuprathyusha
/cspp1practicem3/m6/p3/digit_product.py
134
3.578125
4
N = int(input()) PRODUCT = 1 TEMP = 0 while N != 0: TEMP = N%10 PRODUCT = PRODUCT*TEMP N = N//10 print(PRODUCT)
243f03bb0f3a21d8d008ed4c1bbb862341fd7a1d
pranayreddy604/gitam-2019
/28-06-2k19.py
1,718
3.75
4
#!/usr/bin/env python # coding: utf-8 # In[2]: def test(): print("test() for function") return test() # In[22]: class Demo: n=0 m=0 def test(self,n,m): self.n=n self.m=m print("test() for the class and method",n+m) return obj=Demo() obj.test(55,40) # In[35]: class demo1: def fact(self,n): fact=1 while(n!=0): fact=fact*n n=n-1 return fact p1=demo1() print(p1.fact(5)) # In[1]: import numpy as np np.arange(1,10) # In[2]: np.arange(1,20,5) # In[5]: print(np.arange(1,2048,564)) print(np.arange(1,20,5) # In[8]: a1=np.array([(1,2,3),(4,5,6)]) print("slicing column :",a1[:,1]) # In[9]: a1=np.array([(1,2,3),(4,5,6)]) print("slicing column :",a1[:,2]) # In[10]: a1=np.array([(1,2,3),(4,5,6)]) print("first row :",a1[0]) # In[11]: a1=np.array([(1,2,3),(4,5,6)]) print("second row :",a1[1]) # In[16]: a1=np.array([(1,2,3),(4,5,6)]) print(a1) # In[18]: a1=np.random.normal(5,1,10) print(a1) print("min value",np.min(a1)) print("max value",np.max(a1)) print("mean value",np.min(a1)) print("median value",np.median(a1)) # In[19]: c1=np.array([1,2]) c2=np.array([4,5]) np.dot(c1,c2) # In[22]: c1=np.array([(1,2),(4,5)]) c2=np.array([(3,4),(3,2)]) np.dot(c1,c2) # In[32]: import pandas as pd dict={"name":["anil","akhil","dinesh","harsha","ajay","kranth"], "email.Id":["anil@gmail.com","akhil@gmail.com","dinesh@gmail.com","harsha@gmail.com","ajay@gmail.com","kranth@gmail.com"], "p.no":[686535498,25775418,71745,5419814,1472285,58255], "address":["gfhscj","nfgths","ftgggfj","wnjhr","dgjtydt","bgffhhfgc"]} b=pd.DataFrame(dict) print(b) # In[ ]:
d1cb3700ddecb7b563e04496b5372dde766e447b
saraht0607/phyton-
/evenloops.py
48
3.609375
4
#using while i=2 while(i<=26): print(i) i=i+2
e64aa24b8697cc026b1079b06b09308bf55192d3
kkemppi/TIE-courses
/Ohjelmointi 1/Ohjelmointi 1/alle 7. krs/teiskon_bussi.py
579
3.796875
4
def main(): lahtoajat = [630, 1015, 1415, 1620, 1720, 2000] lahtoaika = int(input("Enter the time (as an integer): ")) ensimmainen = mika_eka(lahtoajat, lahtoaika) print("The next buses leave:") i = 1 monesko = ensimmainen while i <= 3: if monesko >= 6: monesko = 0 print(lahtoajat[monesko]) monesko = monesko + 1 i += 1 def mika_eka(lahtoajat, lahtoaika): hakulista = [] + lahtoajat hakulista.append(lahtoaika) hakulista.sort() paikka = hakulista.index(lahtoaika) return paikka main()
f3e30374970762c265f3a4b762b4a0bf76417f22
eric496/leetcode.py
/tree/666.path_sum_IV.py
1,615
4.03125
4
""" If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers. For each integer in this list: The hundreds digit represents the depth D of this node, 1 <= D <= 4. The tens digit represents the position P of this node in the level it belongs to, 1 <= P <= 8. The position is the same as that in a full binary tree. The units digit represents the value V of this node, 0 <= V <= 9. Given a list of ascending three-digits integers representing a binary tree with the depth smaller than 5, you need to return the sum of all paths from the root towards the leaves. Example 1: Input: [113, 215, 221] Output: 12 Explanation: The tree that the list represents is: 3 / \ 5 1 The path sum is (3 + 5) + (3 + 1) = 12. Example 2: Input: [113, 221] Output: 4 Explanation: The tree that the list represents is: 3 \ 1 The path sum is (3 + 1) = 4. """ class Solution: def pathSum(self, nums: List[int]) -> int: lookup = {n // 10: n % 10 for n in nums} res = [0] self.dfs(nums[0] // 10, 0, lookup, res) return res[0] def dfs(self, val: int, presum: int, lookup: dict, res: List[int]) -> None: depth, pos = divmod(val, 10) cur = presum + lookup[val] left = (depth + 1) * 10 + (2 * pos - 1) right = (depth + 1) * 10 + 2 * pos if left not in lookup and right not in lookup: res[0] += cur return if left in lookup: self.dfs(left, cur, lookup, res) if right in lookup: self.dfs(right, cur, lookup, res)
2e34b0bb6dfc6f0db072ef96163d1079c679c4df
RoopakParashar/turtle-race-with-python
/TURTLEPROJECT.py
1,077
3.78125
4
from turtle import * from random import randint speed(20) penup() goto(-140,140) for step in range(15): write(step, align='center') right(90) forward(10) pendown() forward(150) penup() backward(160) left(90) forward(20) kirti= Turtle() kirti.color('red') kirti.shape('turtle') kirti.penup() kirti.goto(-160, 100) kirti.pendown() for turn in range(100): # kirti.forward(randint(1,5)) kirti.right(3.6) roopak= Turtle() roopak.color('blue') roopak.shape('turtle') roopak.penup() roopak.goto(-160,70) roopak.pendown() for turn in range(72): roopak.left(5) amit = Turtle() amit.shape('turtle') amit.color('green') amit.penup() amit.goto(-160, 40) amit.pendown() for turn in range(60): amit.right(6) sirisa = Turtle() sirisa.shape('turtle') sirisa.color('orange') sirisa.penup() sirisa.goto(-160, 10) sirisa.pendown() for turn in range(30): sirisa.left(12) for turn in range(100): kirti.forward(randint(1,5)) roopak.forward(randint(1,5)) amit.forward(randint(1,5)) sirisa.forward(randint(1,5))
5962f3f6aebeb00ab024833bcacb29fee86af064
jimmy623/LeetCode
/Solutions/Simplify Path.py
832
3.671875
4
class Solution: # @param path, a string # @return a string def simplifyPath(self, path): folders = path.split("/") result = [] for p in folders: #print result,p if p == "." or p == "": continue if p == "..": if len(result) > 0: result.pop() continue result.append(p) str = "" if len(result): for d in result: str += "/" str += d return str else: return "/" a = "/Z/Iyy/HSyT/ItVqc/.././//Z/.././.././../a/gK/../ZurH///x/../////././../.." s = Solution() print s.simplifyPath(a) #Simplify Path #https://oj.leetcode.com/problems/simplify-path/
29a904cb6c9b0c37b24dbd960bfef3cd712136ce
svelezp/ST0245-008
/Parcial_2/punto3_parcial2.py
1,473
3.53125
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def buildtree(inorder, preorder, instrt, inend): if instrt > inend: return None Nodo = Node(preorder[buildtree.preIndex]) buildtree.preIndex += 1 if instrt == inend: return Nodo inindex = search(inorder, instrt, inend, Nodo.data) Nodo.left = buildtree(inorder, preorder, instrt, inindex - 1) Nodo.right = buildtree(inorder, preorder, inindex + 1, inend) return Nodo def search(arr, start, end, value): for i in range(start, end + 1): if arr[i] == value: return i def postorder(a): if a is None: return None else: postorder(a.left) postorder(a.right) print(a.data, end=' ') def inorden(a): if a is None: return None else: inorden(a.left) print(a.data, end=' ') inorden(a.right) def preorden(a): if a is None: return None else: print(a.data, end=' ') preorden(a.left) preorden(a.right) preord = ['G', 'E', 'A', 'I', 'B', 'M', 'C', 'L', 'D', 'F', 'K', 'J', 'H'] inord = ['I', 'A', 'B', 'E', 'G', 'L', 'D', 'C', 'F', 'M', 'K', 'H', 'J'] buildtree.preIndex = 0 arbol = buildtree(inord, preord, 0, len(inord) - 1) inorden(arbol) print(" ") preorden(arbol) print(" ") postorder(arbol) print(" ")
5781b03ab66ba69289f83bddd9748a7f8ad4a688
makchamp/puzzle-search-algorithms
/src/node.py
2,963
4.125
4
from puzzle import Puzzle class Node: # this is a node in the tree on which we will apply a search algorithm # this will be a static variable to store all the previously visited setups # visited_setups = [] def __init__(self, puzzle: Puzzle, parent, arriving_move, move_cost, moved_tile, cost_to_reach, heuristic_function=None): self.puzzle = puzzle self.parent = parent self.arriving_move = arriving_move self.move_cost = move_cost self.moved_tile = moved_tile self.cost_to_reach = cost_to_reach # record the depth of the node self.depth = 0 if parent is not None: self.depth = 1 + self.parent.depth # the total cost needed to reach this node self.total_cost = 0 if parent is not None: self.total_cost = move_cost + self.parent.total_cost self.child_nodes = [] self.heuristic_function = heuristic_function # h(n) or the heuristic value of the node self.h_n = self.puzzle.get_heuristic(heuristic_function) or 0 # the cost of the immediate step that made us arrive at this node self.g_n = cost_to_reach self.f_n = self.h_n + self.g_n def expand(self): # This method will expand the current node by applying all the possible moves to the puzzle and it # will create child nodes using the new setups successor_puzzle_tuples = self.puzzle.get_successors() for puzzle_tuple in successor_puzzle_tuples: puzzle = puzzle_tuple[0] # check if puzzle has been visited before # TODO: check for the visited setups (or nodes) in the algorithm # if puzzle.current_setup in self.visited_setups: # continue arriving_move = puzzle_tuple[1] move_cost = puzzle_tuple[2] moved_tile = puzzle_tuple[3] cost_to_reach = self.cost_to_reach + move_cost child_node = Node(puzzle, self, arriving_move, move_cost, moved_tile, cost_to_reach, self.heuristic_function) self.child_nodes.append(child_node) return self.child_nodes def __eq__(self, other): # check if two nodes are equal if self.puzzle.current_setup == self.puzzle.current_setup \ and self.puzzle.rows == self.puzzle.rows: return True return False def __str__(self): # "to_String" method # the token to move, a space, the cost of the move, a space, # the new configurationof the board (each tile separated by a space) debug = f"moved tile:{self.moved_tile} | move cost:{self.move_cost} | cost_to_reach:{self.cost_to_reach} --> {self.puzzle}" s = f"{self.moved_tile} {self.move_cost} {self.puzzle}" return debug def is_goal(self): # return true if the puzzle is goal else false return self.puzzle.is_goal()
84d80c6c25ace281f635952375cc971ab27a5072
longhao54/leetcode
/easy/263.py
793
4.03125
4
''' 编写一个程序判断给定的数是否为丑数。 丑数就是只包含质因数 2, 3, 5 的正整数。 示例 1: 输入: 6 输出: true 解释: 6 = 2 × 3 ''' class Solution: def isUgly(self, num): """ :type num: int :rtype: bool """ # 下面这个方法测试用例42 就过不去 # if num < 0: # num = -num # return num % 6 ==0 or num %10 == 0 or num % 15 ==0 or num %4 == 0 or num %9 ==0 or num %25 ==0 if n == 0 : return False while num % 2 == 0: num /= 2 while num % 3 ==0: num /= 3 while num % 5 == 0: num /= 5 if num == 1: return True return False a = Solution() print(a.isUgly(42)) #
6f1090fbdbcf1992dc0e9ceed8b5449374de43b3
stevenbrand99/holbertonschool-higher_level_programming
/0x06-python-classes/2-square.py
525
4.1875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ 0. My first square: Write an empty class Square that defines a square: You are not allowed to import any module """ class Square: """Square class - receive the size of an square""" def __init__(self, size=0): """Init methos recive size attr ans pass it to the class""" if not isinstance(size, int): raise TypeError('size must be an integer') if size < 0: raise ValueError('size must be >= 0') self.__size = size
0a75816b4e91d17a766fb4ed7d76eeba501a56fc
JessicaJang/cracking
/Coursera/guess_the_number.py
2,485
4.09375
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import random import math import simplegui secret_number = 0 limit = 0 count = 0 #indicate the range is up to 100 or 1000 flag = 0 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global secret_number global flag secret_number = 0 if(flag == 0): range100() else: range1000() # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global secret_number global limit global count global flag flag = 0 count = 0 limit = int(math.ceil(math.log(101,2))) secret_number = random.randrange(0,100) print 'New game. Range is [0,100)' print 'Number of remaining guesses is ' + str(limit) + '\n' def range1000(): # button that changes the range to [0,1000) and starts a new game global secret_number global limit global count global flag flag = 1 count = 0 limit = int(math.ceil(math.log(1001,2))) secret_number = random.randrange(0,1000) print 'New game. Range is [0,1000)' print 'Number of remaining guesses is ' + str(limit) + '\n' def input_guess(guess): # main game logic goes here global secret_number global count global limit player_number = int(guess) print 'Guess was '+ str(player_number) #compare the number of tryout count = count+1 if(count >= limit): print 'You ran out of guesses. The number was ' + str(secret_number) + '\n' new_game() return else: left = limit - count print 'Number of remaining guesses is ' + str(left) if(player_number < secret_number): print 'Higher!\n' elif(player_number > secret_number): print 'Lower!\n' else: print 'Correct!\n' new_game() return # create frame frame = simplegui.create_frame("Guess the number",300,300) # register event handlers for control elements and start frame frame.add_button("Rnage is [0,100)",range100,200) frame.add_button("Range is [0,1000)",range1000,200) frame.add_input("Enter",input_guess,200) frame.start() # call new_game new_game() # always remember to check your completed program against the grading rubric
377bbfd815ff51578db8bfbc11c5b47473035b44
bontu-fufa/competitive_programming-2019-20
/day24/contains-duplicate-ii.py
607
3.515625
4
#https://leetcode.com/problems/contains-duplicate-ii class Solution(object): def containsNearbyDuplicate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ d = {} for i in range(len(nums)): if nums[i] in d and i - d[nums[i]] <= k: return True else: d[nums[i]] = i return False print(Solution().containsNearbyDuplicate([1,2,3,1,2,3],2)) print(Solution().containsNearbyDuplicate( [1,0,1,1],1))
48d9aec213003c6301fb112f3d792deff66129f9
doraemon1293/Leetcode
/archive/2249. Count Lattice Points Inside a Circle.py
504
3.625
4
from typing import List class Solution: def countLatticePoints(self, circles: List[List[int]]) -> int: ans=set() for x,y,r in circles: for x0 in range(x-r,x+r+1): for y0 in range(y-r,y+r+1): if (x0-x)**2+(y0-y)**2<=r**2: ans.add((x0,y0)) return len(ans) circles=[[8,9,6],[9,8,4],[4,1,1],[8,5,1],[7,1,1],[6,7,5],[7,1,1],[7,1,1],[5,5,3]] # circles=[[8,9,6]] print(Solution().countLatticePoints(circles))
d1a5856b1e2d5a90b7de5ea007a277ef940d6c0b
ww8007/Python
/Study/GUI/Text.py
276
3.59375
4
from tkinter import * window = Tk() t = Text(window, height = 5, width = 60) t.pack() t.insert(END, "텍ㅌ스트 위젯은 여러줄의 \n 텍스트를 표시할 수 있습니다.") window.mainloop() #텍스트는 html이나 css 스타일도 사용이 가능하다.
ff2c98389e13ce2061601068c93999ff9f20a7a5
OleksandrNikitenko/CodeSignal-Arcade
/ListForestEdge/IsSmooth.py
1,229
4.21875
4
""" We define the middle of the array arr as follows: if arr contains an odd number of elements, its middle is the element whose index number is the same when counting from the beginning of the array and from its end; if arr contains an even number of elements, its middle is the sum of the two elements whose index numbers when counting from the beginning and from the end of the array differ by one. An array is called smooth if its first and its last elements are equal to one another and to the middle. Given an array arr, determine if it is smooth or not. Example For arr = [7, 2, 2, 5, 10, 7], the output should be isSmooth(arr) = true. The first and the last elements of arr are equal to 7, and its middle also equals 2 + 5 = 7. Thus, the array is smooth and the output is true. For arr = [-5, -5, 10], the output should be isSmooth(arr) = false. The first and middle elements are equal to -5, but the last element equals 10. Thus, arr is not smooth and the output is false """ def isSmooth(arr): middle = arr[len(arr) // 2] if len(arr)%2 == 1 else (arr[(len(arr) // 2)-1] + arr[(len(arr) // 2)]) return True if arr[0] == middle == arr[-1] else False
11ae6090b834b1cabe02614fd290720330195dea
thehealer15/Freelance-work
/pdf/rotating_pdf.py
655
3.625
4
import PyPDF2 as p # rotating pdf location="file.pdf" with open(location,'rb') as f: pdf=p.PdfFileReader(location) writer=p.PdfFileWriter() # why writer? # After rotating we need to save as pdf page=pdf.getPage(0) page.rotateClockwise(90) # counterClockwise also there angle must be standard angle i.e. multiple of 90 degree # if not passed no rotation writer.addPage(page) # we added page in writer, still this is RAM if we don't write it won't reflect in ROM - File heandling of Python # to export with open("newFile.pdf",'wb') as f2: writer.write(f2) print("Rotated SuccessFully")
a4730135dc0515a8f46847780b4c8fd056664f39
Matchinski/ImageQuizzer
/MongolianBirdTeacher.py
9,336
3.5625
4
import os import random as rd import tkinter as tk from tkinter import font from PIL import ImageTk, Image # Clear the terminal at the start of each run os.system('cls' if os.name == 'nt' else 'clear') # Set the background image and the path to the picture folder backgroundImageName = 'Background.png' birdFolder = 'BirdPics/' # Open the list of names nameFile = open('Names.txt', 'r') lines = nameFile.readlines() birdArray = [] # Add all of the picture paths to an array for name in lines: name = name.strip() pictureLocation = birdFolder + name + '.png' birdArray.append(pictureLocation) rd.shuffle(birdArray) # Initialize the tracking variables counter = 0 right = 0 total = 0 repeat = False repeatShow = False moveOn = 0 # Default path and label birdPath = birdArray[counter] birdImageLabel = 0 # Update the picture to the next bird def nextBird(dir): global counter global birdPath global birdImageLabel global repeat # Reset the answer label to be white and blank labelTextAnswer.set(' ') labelAnswer.config(bg = 'white') repeat = False entryBox.delete(0, 'end') entryBox.insert(0, '') if dir == 1: counter += 1 elif dir == 0: counter -= 1 else: counter += 0 if counter >= len(birdArray): counter = 0 # Create a label that displays the bird image and then scales it birdPath = birdArray[counter] birdPhotoImage = scaleImage() birdImageLabel.configure(image = birdPhotoImage) birdImageLabel.image = birdPhotoImage # Generate the dashes that give a hint of the name and update the label dashLength = generateDash() labelTextLetters.set(dashLength) labelTextGuess.set('Waiting for a guess...') # Update the guess label with the guess def displayGuess(entry): global right global total global repeat global moveOn entry = entry.lower() labelTextGuess.set(entry) answer = (birdPath[9:(len(birdPath) - 4)]).lower() repeat, total, right, moveOn = fractionUpdate(repeat, entry, answer, total, right, moveOn) moveOn = setColor(entry, answer, moveOn, counter) # Sets the color based on the answer def setColor(entryVar, answerVar, moveOnVar, counterVar): if entryVar == answerVar: labelTextAnswer.set('Correct') labelAnswer.config(bg = 'green') if moveOnVar < 2: moveOnVar = 2 birdArray.remove(birdArray[counterVar]) elif moveOnVar == 2: nextBird(1) else: labelTextAnswer.set('Wrong') labelAnswer.config(bg = 'red') return moveOnVar # Update the correct fraction def fractionUpdate(repeatVar, entryVar, answerVar, totalVar, rightVar, moveOnVar): if repeatVar is False: repeatVar = True totalVar += 1 if entryVar == answerVar: rightVar += 1 fraction = str(rightVar) + ' / ' + str(totalVar) labelPercentValue.set(fraction) moveOnVar = 1 else: fraction = str(rightVar) + ' / ' + str(totalVar) labelPercentValue.set(fraction) moveOnVar = 0 return repeatVar, totalVar, rightVar, moveOnVar # Add functionality to the reset button def resetButton(): global repeat global right global total labelTextAnswer.set('This will display if you are correct or not') labelTextGuess.set('Waiting for a guess...') labelGuess.config(bg = 'white') labelAnswer.config(bg = 'white') repeat = False right = 0 total = 0 labelPercentValue.set('0 / 0') entryBox.delete(0, 'end') entryBox.insert(0, '') # Add functionality to the show button def showButton(): global total global repeatShow if repeatShow is False: repeatShow = True total += 1 fraction = str(right) + ' / ' + str(total) labelPercentValue.set(fraction) bird = birdPath[9:(len(birdPath) - 4)] labelTextGuess.set(bird) # Generate the dashes that give a hint of the name def generateDash(): dashLength = '' bird = birdPath[9:(len(birdPath) - 4)] for char in bird: if char == ' ': dashLength += ' ' elif char == '-': dashLength += '- ' else: dashLength += '_ ' return dashLength # Scale the next image to fit the screen def scaleImage(): # Open an image and convert it to a photoimage birdImage = Image.open(birdPath) birdPhotoImage = ImageTk.PhotoImage(birdImage) # Get the height and width of the image imageHeight = birdPhotoImage.height() imageWidth = birdPhotoImage.width() ratio = 1 # If the image is too wide, scale it down if imageWidth > imageHeight and imageWidth > 400: ratio = imageHeight/imageWidth imageWidth = 400 imageHeight = int(imageWidth * ratio) resizedBirdImage = birdImage.resize((imageWidth, imageHeight), Image.ANTIALIAS) return ImageTk.PhotoImage(resizedBirdImage) # If the image is too tall, scale it down elif imageHeight > imageWidth and imageWidth > 400: ratio = imageWidth/imageHeight imageHeight = 400 imageWidth = int(imageHeight * ratio) resizedBirdImage = birdImage.resize((imageWidth, imageHeight), Image.ANTIALIAS) return ImageTk.PhotoImage(resizedBirdImage) # This creates the main window of an application window = tk.Tk() # Get the screen height and width WIDTH = window.winfo_screenwidth() * 0.9 HEIGHT = window.winfo_screenheight() * 0.9 # This makes the window open at a given size canvas = tk.Canvas(window, height = HEIGHT, width = WIDTH) canvas.pack() # Add the background image over the whole canvas backgroundImage = tk.PhotoImage(file = backgroundImageName) backgroundLabel = tk.Label(window, image = backgroundImage) backgroundLabel.place(relx = 0, rely = 0, relheight = 1, relwidth = 1) # The name displayed above the canvas window.title('Mongolian Bird Species Teacher') # Creates a canvas where widgets can be placed, size is controled by height and width constants frame = tk.Frame(window, bg = '#81a2d6') frame.place(relx = 0.1, rely = 0.1, relheight = 0.8, relwidth = 0.8) # Creates the text entry box at the bottom middle of the screen entryBox = tk.Entry(frame, font = ('Calibre', 16)) entryBox.place(relx = 0.35, rely = 0.25, relheight = 0.075, relwidth = 0.6) entryBox.bind('<Return>', (lambda event: displayGuess(entryBox.get()))) # Creates a button that calls a function to show the next bird button = tk.Button(frame, command = lambda: nextBird(0), text = 'Prev', font = ('Calibre', 16)) button.place(relx = 0.05, rely = 0.05, relwidth = 0.12, relheight = 0.075) # Creates a button that calls a function to show the previous bird button = tk.Button(frame, command = lambda: nextBird(1), text = 'Next', font = ('Calibre', 16)) button.place(relx = 0.18, rely = 0.05, relwidth = 0.12, relheight = 0.075) # Creates a button to reset the fraction tracker reset = tk.Button(frame, command = lambda: resetButton(), text = 'Reset', font = ('Calibre', 16)) reset.place(relx = 0.05, rely = 0.25, relwidth = 0.25, relheight = 0.075) # Creates a button to show the answer when you are stuck show = tk.Button(frame, command = lambda: showButton(), text = 'Show Answer', font = ('Calibre', 16)) show.place(relx = 0.05, rely = 0.35, relwidth = 0.25, relheight = 0.075) # Create a string var used to change the label through a function labelTextGuess = tk.StringVar(window, 'Waiting for a guess...') labelTextAnswer = tk.StringVar(window, 'This will display if you are correct or not') # Generate the dashes that give a hint of the name and update the label dashLength = generateDash() labelTextLetters = tk.StringVar(window, dashLength) # The initial value of the amount correct labelPercentValue = tk.StringVar(window, '0 / 0') # Create a label to display the last typed guess labelGuess = tk.Label(frame, textvariable = labelTextGuess, font = ('Calibre', 16)) labelGuess.place(relx = 0.35, rely = 0.05, relwidth = 0.6, relheight = 0.075) # Create a label to display the correct answer labelAnswer = tk.Label(frame, textvariable = labelTextAnswer, font = ('Calibre', 16)) labelAnswer.place(relx = 0.35, rely = 0.15, relwidth = 0.6, relheight = 0.075) # Create a label to display the number of letters in the bird's name labelLetters = tk.Label(frame, bg = '#81a2d6', textvariable = labelTextLetters, font = ('Calibre', 20)) labelLetters.place(relx = 0.35, rely = 0.35, relwidth = 0.6, relheight = 0.075) # Create a label to display the amount right and wrong labelPercent = tk.Label(frame, bg = '#81a2d6', textvariable = labelPercentValue, font = ('Calibre', 20)) labelPercent.place(relx = 0.05, rely = 0.15, relwidth = 0.25, relheight = 0.075) # Create a label that displays the bird image and then center it birdPhotoImage = scaleImage() birdImageLabel = tk.Label(frame, image = birdPhotoImage) birdImageLabel.place(relx = 0.05, rely = 0.95, anchor = 'sw') # Start the GUI window.mainloop()
803cd4156f07966baf3c15d955a73cc8b714b8b9
aristeidismoustakas/Advanced-ML-techniques
/datasets/WineQualityDataset.py
1,065
3.5
4
import pandas as pd from datasets.Dataset import Dataset class WineQualityDataset(Dataset): def __init__(self, data_file): super(WineQualityDataset, self).__init__() # Loading the 2 files with the red and the white wines. red_wines = pd.read_csv((data_file + '-red.csv'), delimiter=';', header=0) white_wines = pd.read_csv(data_file + '-white.csv', delimiter=';', header=0) # Concat the two arrays in one. frames = [red_wines, white_wines] dataset = pd.concat(frames) self._x = dataset.iloc[:, 0:-1] self._y = dataset.iloc[:, -1] def preprocessing(self): """ Preproccesing of the explanatory variables. At first we remove the NA values, next we apply one-hot encoding to the columns that is necessary and finally we normalize our data in the interval 0-1. """ self.removeNA() expl_vars = self.get_x() norm_expl_vars = self.normalize(expl_vars) self._x = pd.DataFrame(data=norm_expl_vars)
43e755556cf3e08412a33f539e7905cb0f35e507
nehakumari7/pythontutorial_
/strings/palindrome_strings func.py
426
3.953125
4
if __name__=="__main__": name="madam" ''' x=name[::-1] if x==name : print("yes it is palindrome") else : print("no it is not palindrome") ''' length=len(name) print(length) rev="" i=length-1 while(i>=0): rev=rev+name[i] i=i-1 print(rev) if (name==rev): print("yes it is palindrome") else: print("no it is not palindrome")
f83ee57628f1d9e23fa193da42863d9cc3430f5c
ctOS-2019/Answer-to-exercises
/Zhejiang_University_Edition_Python Programming/Programming questions/T3.11.py
812
4.03125
4
''' 本题要求编写程序,读入5个字符串,按由小到大的顺序输出。 输入格式: 输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。 输出格式: 按照以下格式输出排序后的结果: After sorted: 每行一个字符串 输入样例: red yellow blue green white 输出样例: After sorted: blue green red white yellow ''' def com(a, b): if a < b: return True else: return False list = [] for i in input().split(): list.append(i) list2 = [] while list: max = 0 for i in range(len(list)): if com(list[i], list[max]): max = i list2.append(list[max]) list.pop(max) print('After sorted:') for i in list2: print(i)
f969b8b9863ae299037d92c933f7824b465d5ca3
TonyNewbie/TicTacToe
/Tic-Tac-Toe/task/tictactoe/tictactoe.py
2,812
3.703125
4
# write your code here def table_printer(table): print('---------') print(f'| {table[0][0]} {table[0][1]} {table[0][2]} |') print(f'| {table[1][0]} {table[1][1]} {table[1][2]} |') print(f'| {table[2][0]} {table[2][1]} {table[2][2]} |') print('---------') def check_table(table): x_wins = ((table[0].count('X') == 3) or (table[1].count('X') == 3) or (table[2].count('X') == 3) or (table[0][0] == table[1][0] == table[2][0] == 'X') or (table[0][1] == table[1][1] == table[2][1] == 'X') or (table[0][2] == table[1][2] == table[2][2] == 'X') or (table[0][0] == table[1][1] == table[2][2] == 'X') or (table[0][2] == table[1][1] == table[2][0] == 'X')) y_wins = ((table[0].count('O') == 3) or (table[1].count('O') == 3) or (table[2].count('O') == 3) or (table[0][0] == table[1][0] == table[2][0] == 'O') or (table[0][1] == table[1][1] == table[2][1] == 'O') or (table[0][2] == table[1][2] == table[2][2] == 'O') or (table[0][0] == table[1][1] == table[2][2] == 'O') or (table[0][2] == table[1][1] == table[2][0] == 'O')) table_printer(table) if x_wins: return 'X wins' elif y_wins: return 'O wins' elif table[0].count(' ') == 0 and table[1].count(' ') == 0 and table[2].count(' ') == 0: return 'Draw' else: return 'Game not finished' game_table = [[' ' for j in range(3)] for i in range(3)] symbol = 'X' game_status = check_table(game_table) coordinates = input('Enter the coordinates: ').split() while game_status == 'Game not finished': if len(coordinates) < 2: print('You should enter numbers') coordinates = input('Enter the coordinates: ').split() elif (not coordinates[0].isdigit()) or (not coordinates[1].isdigit()): print('You should enter numbers') coordinates = input('Enter the coordinates: ').split() elif (not (0 < int(coordinates[0]) < 4)) or (not (0 < int(coordinates[1]) < 4)): print('Coordinates should be from 1 to 3!') coordinates = input('Enter the coordinates: ').split() elif game_table[3 - int(coordinates[1])][int(coordinates[0]) - 1] != ' ': print('This cell is occupied! Choose another one!') coordinates = input('Enter the coordinates: ').split() else: game_table[3 - int(coordinates[1])][int(coordinates[0]) - 1] = symbol game_status = check_table(game_table) if game_status == 'X wins' or game_status == 'O wins' or game_status == 'Draw': print(game_status) else: if symbol == 'X': symbol = 'O' else: symbol = 'X' coordinates = input('Enter the coordinates: ').split()
e39b5337eb70061a7688fbd8c742d13f33d0ac24
P4NK4J/Competitive_Coding
/practice problems/beginner/Easy_math.py
580
3.59375
4
def sumOfDigits(n): sum = 0 while(n > 0): sum += n % 10 # n%10 gives the digit at units place n //= 10 # Integer division leads to loss of digit at unit's place, and shifts all digits by 1 place right. return sum t = int(input()) for k in range(t): n = int(input()) arr = [int(x) for x in input().split()] ans = 0 for i in range(n): for j in range(i+1,n): product = arr[i] * arr[j] sum = sumOfDigits(product) ans = max(ans, sum) print(ans)
0e1e460933a5ae4d20fc089a7f47c42bf055e152
KYBee/DataStructure
/practice/dfs.py
440
3.609375
4
def dfs(graph, start, visited = set()): if start not in visited: visited.add(start) print(start, end=" ") nbr = graph[start] - visited for v in nbr: dfs(graph, v, visited) mygraph = { "A" : {"B", "C"}, "B" : {"A", "D"}, "C" : {"A", "D", "E"}, "D" : {"B", "C", "F"}, "E" : {"C", "G", "H"}, "F" : {"D"}, "G" : {"E", "H"}, "H" : {"E", "G"}, } dfs(mygraph, "A")
c0c13d05aeedf02235bdb2dd8cdf8723745efe7e
cfee89/QualifyingOffer
/src/data/PlayerRecord.py
585
3.5
4
class PlayerRecord: def __init__(self,inPlayerName,inSalary,inYear,inLeague): self.playerName = inPlayerName self.salary = inSalary self.year = inYear self.league = inLeague def __str__(self): return "Name: " + self.playerName + " Salary: " + str(self.salary) def isValid(self): if self.playerName is None: return False if self.salary is None: return False if self.year is None: return False if self.league is None: return False return True
240b3c972aced7ae9bbbf2d77ddbc3bb4a58c02b
tugrazbac/web_science
/a1/scatter.py
1,371
3.5
4
#!/usr/bin/env python # encoding: utf-8 import os import sys import json import numpy import networkx import matplotlib.pylab as plt def perform(graph): ''' Takes a networkx.Graph, calculates the degrees and clustering coefficients for the given graph, calls 'plot' to generate a scatterplot (degree vs. clustering coefficients) and returns a 2-tuple containing two lists with the degrees and clustering coefficients. ''' degree, clustering = [], [] # TODO Student: Calculate list of degrees. degree = networkx.degree(graph).values() degree = [v for v in degree] # TODO Student: Calculate list of clustering coefficients. coefficient = networkx.clustering(graph).values() clustering = [ v for v in coefficient] if(len(degree) > 0 and len(clustering) > 0): plot(degree, clustering) return (degree, clustering) def plot(degree, clustering): ''' Takes the 'degree' and 'clustering' lists and produces a scatter plot. ''' # TODO Student: Visualize the results using a scatter plot. # TODO Student: Store the plot in 'submission/scatter.png'. plt.scatter(degree, clustering) # plt.show() plt.savefig("submission/scatter.png") return True if __name__ == u'__main__': graph = networkx.read_gml(u'graph-b.gml.gz') results = perform(graph) with open(u'submission/scatter.json', 'w') as fh: json.dump(results, fh)
09b08c50183e43278387ca93385d78fb5d261aef
981377660LMT/algorithm-study
/11_动态规划/dp分类/有限状态dp/1824. 最少侧跳次数.py
2,082
3.53125
4
from functools import lru_cache from typing import List INF = int(1e20) # 这只青蛙从点 0 处跑道 2 出发,并想到达点 n 处的 任一跑道 ,请你返回 最少侧跳次数 。 # 注意:点 0 处和点 n 处的任一跑道都不会有障碍。 # 1 <= n <= 1e5 # dp[i][j]表示第i点第j道最少的侧跳次数(一次侧跳可以跳多个格子) class Solution: def minSideJumps2(self, obstacles: List[int]) -> int: """AC 用 dp 和 ndp 数组 来枚举行间状态转移,逻辑会清晰一些 """ n = len(obstacles) dp = [0, 0, 0] dp[0] = 1 if obstacles[1] != 1 else INF dp[1] = 0 if obstacles[1] != 2 else INF dp[2] = 1 if obstacles[1] != 3 else INF for i in range(2, n): ndp = [INF] * 3 for cur in range(3): if obstacles[i] == cur + 1 or obstacles[i - 1] == cur + 1: continue for pre in range(3): ndp[cur] = min(ndp[cur], dp[pre] + (cur != pre)) dp = ndp res = min(dp) return res if res != INF else -1 def minSideJumps(self, obstacles: List[int]) -> int: """TLE""" @lru_cache(None) def dfs(col: int, row: int) -> int: if col == n - 1: return 0 res = INF for nextRow in range(1, 4): if obstacles[col + 1] == nextRow or obstacles[col] == nextRow: continue res = min(res, dfs(col + 1, nextRow) + (nextRow != row)) return res n = len(obstacles) - 1 res = dfs(0, 2) dfs.cache_clear() return res print(Solution().minSideJumps(obstacles=[0, 1, 2, 3, 0])) print(Solution().minSideJumps2(obstacles=[0, 1, 2, 3, 0])) # 输出:2 # 解释:最优方案如上图箭头所示。总共有 2 次侧跳(红色箭头)。 # 注意,这只青蛙只有当侧跳时才可以跳过障碍(如上图点 2 处所示)。
ca13c468574004e1f68c80f6e14168bc38092157
jinudaniel/Python-Projects
/Book_Store/book_store_frontend.py
3,012
3.703125
4
from tkinter import * import book_store_backend def get_selected_row(event): global selected_tuple if list1.curselection(): index = list1.curselection()[0] #returns index of selected element in tuple format so selecting the first element selected_tuple = list1.get(index) e1.delete(0, END) e1.insert(END, selected_tuple[1]) e2.delete(0, END) e2.insert(END, selected_tuple[2]) e3.delete(0, END) e3.insert(END, selected_tuple[3]) e4.delete(0, END) e4.insert(END, selected_tuple[4]) #return selected_tuple def view_command(): list1.delete(0, END) for row in book_store_backend.view(): list1.insert(END, row) def search_command(): list1.delete(0, END) for row in book_store_backend.search(title_value.get(), author_value.get(), year_value.get(), isbn_value.get()): list1.insert(END, row) def add_command(): book_store_backend.insert(title_value.get(), author_value.get(), year_value.get(), isbn_value.get()) list1.delete(0, END) list1.insert(END, (title_value.get(), author_value.get(), year_value.get(), isbn_value.get())) def delete_command(): book_store_backend.delete(selected_tuple[0]) def update_command(): book_store_backend.update(selected_tuple[0], title_value.get(), author_value.get(), year_value.get(), isbn_value.get()) window = Tk() window.wm_title("Book Store") # Labels l1 = Label(window, text = 'Title') l1.grid(row = 0, column = 0) l2 = Label(window, text = 'Author') l2.grid(row = 0, column = 2) l3 = Label(window, text = 'Year') l3.grid(row = 1, column = 0) l4 = Label(window, text = 'ISBN') l4.grid(row = 1, column = 2) #Entry title_value = StringVar() e1 = Entry(window, textvariable = title_value) e1.grid(row =0, column = 1) author_value = StringVar() e2 = Entry(window, textvariable = author_value) e2.grid(row =0, column = 3) year_value = StringVar() e3 = Entry(window, textvariable = year_value) e3.grid(row =1, column = 1) isbn_value = StringVar() e4 = Entry(window, textvariable = isbn_value) e4.grid(row =1, column = 3) #List box and Scroll bar list1 = Listbox(window, height = 6, width = 35) list1.grid(row = 2, column = 0, rowspan = 6, columnspan = 2) sb1 = Scrollbar(window) sb1.grid(row = 2, column = 2, rowspan = 6) list1.configure(yscrollcommand = sb1.set) sb1.configure(command = list1.yview) list1.bind("<<ListboxSelect>>", get_selected_row) #Buttons b1 = Button(window, text = 'View All', width = 12, command = view_command) b1.grid(row = 2, column = 3) b2 = Button(window, text = 'Search Entry', width = 12, command = search_command) b2.grid(row = 3, column = 3) b3 = Button(window, text = 'Add Entry', width = 12, command = add_command) b3.grid(row = 4, column = 3) b4 = Button(window, text = 'Update Selected', width = 12, command = update_command) b4.grid(row = 5, column = 3) b5 = Button(window, text = 'Delete Selected', width = 12, command = delete_command) b5.grid(row = 6, column = 3) b6 = Button(window, text = 'Close', width = 12, command = window.destroy) b6.grid(row = 7, column = 3) window.mainloop()
57d31ca3efe29523c304e958f744b1ab34afd5cf
taylorfuter/Tetris
/tetris.py
8,714
3.5625
4
# 15-112, Summer 2, Homework 4.2 ###################################### # Full name: Taylor Futernick # Andrew ID: tfuterni # Section: C ###################################### #################################### # use the run function as-is #################################### from tkinter import * import random def init(data): # set board dimensions and margin data.rows,data.cols,data.margin =15,10, 20# make board data.emptyColor = "blue" data.board = [([data.emptyColor]*data.cols) for row in range(data.rows)] iPiece = [[True, True, True, True]] jPiece = [[True, False, False],[True, True, True]] lPiece = [[False, False, True],[True, True, True]] oPiece = [[True, True],[True, True]] sPiece = [[False, True, True], [True, True, False]] tPiece = [[False, True, False], [True, True, True]] zPiece = [[True, True, False], [False, True, True]] data.tetrisPieces = [iPiece, jPiece, lPiece, oPiece, sPiece, tPiece, zPiece] data.tetrisPieceColors = ["red", "yellow", "magenta", "pink", "cyan", "green", "orange"] data.fallingColor,data.score="",0 data.fallingPieceCol,data.fallingPieceRow=data.cols//2,0 data.isGameOver,data.isPaused=False,False data.gallingPiece=newFallingPiece(data) def newFallingPiece(data): piece=random.randint(0,len(data.tetrisPieces)-1) data.fallingPiece=data.tetrisPieces[piece] data.fallingColor=data.tetrisPieceColors[piece] #set col to width/2 - width of piece/2 data.fallingPieceCol=data.cols//2-(len(data.fallingPiece[0])//2) def isLegalMove(data): row,col=data.fallingPieceRow,data.fallingPieceCol for i in range(len(data.fallingPiece)): for j in range(len(data.fallingPiece[0])): if data.fallingPiece[i][j]: #If not a legal move return false if not(0<=i+data.fallingPieceRow<len(data.board) and \ 0<=j+data.fallingPieceCol<len(data.board[0]) and \ data.board[i+row][j+col]==data.emptyColor): return False return True def rotatefallingPiece(data): fallingPiece,row=data.fallingPiece,data.fallingPieceRow col,newBoard=data.fallingPieceCol,[] oldCenterRow=row+len(fallingPiece)//2 oldCenterCol = col + len(fallingPiece[0])//2 #equation from site for i in range(len(data.fallingPiece[0])-1,-1,-1): #first row backwards newRow=[] for j in range(0,len(data.fallingPiece)): #loop through cols newRow.append(data.fallingPiece[j][i]) newBoard.append(newRow) data.fallingPiece=newBoard data.fallingPieceRow=oldCenterRow-len(newBoard)//2 #equation from site data.fallingPieceCol = oldCenterCol-len(newBoard[0])//2 #same as ^ if isLegalMove(data)==False: #reset the piece if illegal data.fallingPiece=fallingPiece data.fallingPieceCol=col data.fallingPieceRow=row def moveFallingPiece(data,drow,dcol): data.fallingPieceRow+=drow data.fallingPieceCol+=dcol if not isLegalMove(data): #reset the piece data.fallingPieceCol-=dcol data.fallingPieceRow-=drow return False return True def placeFallingPiece(data): for i in range(len(data.fallingPiece)): for j in range(len(data.fallingPiece[0])): if data.fallingPiece[i][j]: #set color on board data.board[i+data.fallingPieceRow]\ [j+data.fallingPieceCol]=data.fallingColor # getCellBounds from grid-demo.py def getCellBounds(row, col, data): # aka "modelToView" # returns (x0, y0, x1, y1) corners/bounding box of given cell in grid gridWidth = data.width - 2*data.margin gridHeight = data.height - 2*data.margin x0 = data.margin + gridWidth * col / data.cols x1 = data.margin + gridWidth * (col+1) / data.cols y0 = data.margin + gridHeight * row / data.rows y1 = data.margin + gridHeight * (row+1) / data.rows return (x0, y0, x1, y1) def mousePressed(event, data): pass def keyPressed(event, data): if event.keysym=="r": init(data) #reset if event.keysym=="p":data.isPaused=not data.isPaused if data.isPaused:return #stop movement if event.keysym=="Left": moveFallingPiece(data,0,-1) elif event.keysym=="Right": moveFallingPiece(data,0,1) elif event.keysym=="Down": moveFallingPiece(data,1,0) elif event.keysym=="Up": rotatefallingPiece(data) def isFullRow(data,r): for i in range(len(data.board[r])): if data.board[r][i]==data.emptyColor: return False return True def removeFullRows(data): numRem=0 newBoard=[[data.emptyColor]*len(data.board[0]) for i in range(len(data.board))] #set empty board newRow=len(data.board)-1 #last row for oldRow in range(len(data.board)-1,-1,-1): #rows from bottom if isFullRow(data,oldRow)==False: newBoard[newRow]=data.board[oldRow] #copy if not full newRow-=1 else:numRem+=1 #remove the row data.score+=(numRem**2) #add square of num removed data.board=newBoard def timerFired(data): if data.isPaused:return #do nothing if moveFallingPiece(data,1,0)==False: #can't go down placeFallingPiece(data) data.fallingPieceRow=0 #next piece starts to fall from top newFallingPiece(data) #get new piece removeFullRows(data) #see if row is full if isLegalMove(data)==False: #next piece fails immediately data.isGameOver=True def drawGame(canvas, data): if data.isGameOver: #display game over message canvas.create_text(data.width/2,data.height/2, font=("Times", "24", "bold"),text="GAME OVER") canvas.create_text(data.width/2,data.height/1.5, font=("Times", "14", "bold"),text="Score: "+str(data.score)) return canvas.create_rectangle(0, 0, data.width, data.height, fill="orange") drawBoard(canvas, data) drawFallingPiece(canvas,data) def drawFallingPiece(canvas,data): for i in range(len(data.fallingPiece)): for j in range(len(data.fallingPiece[0])): if data.fallingPiece[i][j]: drawCell(canvas,data,i+data.fallingPieceRow, j+data.fallingPieceCol,data.fallingColor) def drawBoard(canvas, data): # draw grid of cells scoreY=10 #display score canvas.create_text(data.width/2,scoreY,text=str(data.score)) for row in range(data.rows): for col in range(data.cols): drawCell(canvas, data, row, col,data.board[row][col]) def drawCell(canvas, data, row, col,color): (x0, y0, x1, y1) = getCellBounds(row, col, data) m = 1 # cell outline margin canvas.create_rectangle(x0, y0, x1, y1, fill="black") canvas.create_rectangle(x0+m, y0+m, x1-m, y1-m, fill=color) def redrawAll(canvas, data): drawGame(canvas, data) #################################### # use the run function as-is #################################### def run1(width=300, height=300): def redrawAllWrapper(canvas, data): canvas.delete(ALL) redrawAll(canvas, data) canvas.update() def mousePressedWrapper(event, canvas, data): mousePressed(event, data) redrawAllWrapper(canvas, data) def keyPressedWrapper(event, canvas, data): keyPressed(event, data) redrawAllWrapper(canvas, data) def timerFiredWrapper(canvas, data): timerFired(data) redrawAllWrapper(canvas, data) # pause, then call timerFired again canvas.after(data.timerDelay, timerFiredWrapper, canvas, data) # Set up data and call init class Struct(object): pass data = Struct() data.width = width data.height = height data.timerDelay = 300 # milliseconds init(data) # create the root and the canvas root = Tk() canvas = Canvas(root, width=data.width, height=data.height) canvas.pack() # set up events root.bind("<Button-1>", lambda event: mousePressedWrapper(event, canvas, data)) root.bind("<Key>", lambda event: keyPressedWrapper(event, canvas, data)) timerFiredWrapper(canvas, data) # and launch the app root.mainloop() # blocks until window is closed print("bye!") # run(300, 300) #################################### # playTetris() [calls run()] #################################### def run(): rows = 19 cols = 10 margin = 20 # margin around grid cellSize = 20 # width and height of each cell width = 2*margin + cols*cellSize height = 2*margin + rows*cellSize run1(width, height) run()
a50774bc2aea65fa994a93252b3c50f9e4cf60eb
RBabaev/Annoying-Fence
/RobertsSolution.py
735
4.0625
4
n = int(input()) maxLength = n // 2 #This portion sorts the boards by height. boards = [int(s) for s in input().split()] heights = set(boards) lHeights = list(heights) lHeights.sort() #This portion assesses the possible heights. possHeights = [] for height in lHeights: for i in range(len(lHeights)): if lHeights[i] != height: possHeights.append(lHeights[i] + height) setPossHeights = set(possHeights) print(setPossHeights) #This portion adds boards of a particular type #to a 2d list corresponding to their height. boardTypes = [] for i in range(len(heights)): boardTypes.append([]) for i in range(len(boards)): for j in range(len(lHeights)): if boards[i] == lHeights[j]: boardTypes[j].append(boards[i])
cde62f98c13afd6ad02a93f7e13e40980d9a54c7
sacrrie/reviewPractices
/CC150/Python solutions/5-0.py
1,272
4.0625
4
#bit manipulation practice file #a simple bit manipulation function ''' import bitstring print(int('111001', 2)) def repeated_arithmetic_right_shift(base,time): answer=base for i in range(time): answer=base>>1 return(answer) a=repeated_arithmetic_right_shift(-75,1) print(a) def repeated_logical_right_shift(base,time): answer=bitstring.BitArray(int=base,length=32) print(answer.int) for i in range(time): answer=answer >> 1 return(answer) b=repeated_logical_right_shift(5,1) print(b.int) def get_bit(num, index): left=num right=1 << index #code below won't work , the right most 1 would disappear #right=1 >> index return((left & right) != 0) print(get_bit(4,2)) def set_bit(num,index): left=num right=1 << index return(left | right) print(set_bit(4,1)) def clear_bit(num,index): left=num right=~(1 << index) return(left & right) print(clear_bit(7,1)) ''' #clear bit from most significant to i index inclusively def left_clear_bit(num,index): left=num right=(1 << index)-1 return(left & right) print(left_clear_bit(7,1)) #the other way def right_clear_bit(num,index): left=num right=(-1 << index+1) return(left & right) print(right_clear_bit(7,1))
dc373038e9ba86473fd190f6ce1bc7122dd27db7
Vampirskiy/Algoritms_python
/unit2/Task 7.py
810
4.03125
4
# Task 7 # Напишите программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2, где n - любое натуральное число. # Ссылка на блоксхемму: https://drive.google.com/file/d/14vZjr7HoUfCmdr0BNCNs41PCJdkclAL2/view?usp=sharing def m(n): if n == 1: return 1 return m(n - 1) + n def f(n): return int(n*(n+1)/2) b = '(1+2+...+n = n(n+1)/2)' s = int(input('Введите придел вычисления: ' )) if m(s) == f(s): print(f'Равенство {b} выполняется ( {m(s)} = {f(s)} )') else: print(f'Равенство {b} не выполняется ( {m(s)} = {f(s)} )')
7250b0d22f23a19cc05ecdca3abb5590211a4291
apecr/astwp-section-2
/lists_tuples_sets.py
491
3.703125
4
my_variable = 'hello' grades = [77, 80, 90, 95, 100] grades_tuple = (77, 80, 90, 95, 100, 105, 107, 90) set_grades = {77, 80, 90, 100, 100} def average(grades): return sum(grades) / len(grades) set_grades.add(60) set_grades.add(60) # print(set_grades) your_lottery_numbers = {1, 2, 3, 4, 5} winning_number = {1, 3, 5, 6, 9, 11} # print(your_lottery_numbers.union(winning_number)) # print(your_lottery_numbers.intersection(winning_number)) # print({1, 2, 3, 4}.difference({1, 2}))
61b65618eb74fb06030834d2e812043acc40c5d5
HenryCheng923/Henry_Cheng_PythonCode
/password-retry.py
555
4
4
#練習密碼判斷程式 #password = 'a123456' #讓使用者重複輸入密碼 #最多輸入3次 #如果正確 就印出"登入成功!" #如果不正確 就印出 "密碼錯誤! 還有__次機會!" password = 'a123456' count_pwds = 3 #三次機會 while count_pwds > 0: count_pwds = count_pwds - 1 pwd = input('請輸入密碼: ') if pwd == password: print('登入成功!') break elif pwd != password and count_pwds > 0: print("密碼錯誤! 還有",count_pwds,"次機會") else: print('已錯誤三次無法登入!') break
20440fe476895e42c0459d5ceef6a12d7996a1e8
penguin0416/my_repos
/2021136051_박선호_과제-06-2.py
838
3.546875
4
#실습과제06 import math #수학함수 불러오기 def fun_glb_distance(x1,x2,y1,y2): #함수 fun_distance 생성 print("첫번째 좌표는 (",round(x1,1), round(y1,1),") 이다.") print("두번째 좌표는 (",round(x2,1), round(y2,1),") 이다.") result = math.sqrt(((x1-x2)**2) + ((y1-y2)**2)) #좌표 사이 거리 구하기 print("두 좌표 사이의 거리는", round(result,1), "이다.") #학번이 1로 끝나므로 소숫점 자리수 1 x1, y1 = map(float,input("첫번째 좌표를 입력하시오.").split(',')) #전역변수 x1,y1 x2, y2 = map(float,input("두번째 좌표를 입력하시오.").split(',')) #전역변수 x2,y2 fun_glb_distance(x1,x2,y1,y2)
9fb0891693abffe94168010768110465f8cb1f40
PengZiqiao/report_factory_3
/utils.py
676
3.859375
4
from datetime import date class Month: def __init__(self): self.month = date.today().month self.year = date.today().year def before(self, i): """i个月之前""" if self.month - i > 0: return self.year, self.month - i elif self.month - (i - 12) > 0: return self.year - 1, self.month - (i - 12) else: return self.year - 2, self.month - (i - 24) def date(self): past = True if 1 <= date.today().day < 25 else False return date(*self.before(1), 1) if past else date(self.year, self.month, 1) def date_before(self, i): return date(*self.before(i), 1)
8d41a9714ebb48ac1f641cd86f42876cc82b6469
himanshu2922t/FSDP_2019
/DAY-02/centered.py
537
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 4 15:06:43 2019 @author: Himanshu Rathore """ number_list = input("Enter array of numbers space separated: ").split() # sorting of numbers in another list sorted_number_list = sorted(number_list) # removing smallest and largest from sorted list del sorted_number_list[0] sorted_number_list.pop() # average without including smallest and largest #sum = 0 #for number in sorted_number_list: # sum += int(number) average = sum(sorted_number_list) / len(sorted_number_list) print("Result:",average)
7ed3f5eddeb8f49f3cc8bffc9444e343165e60b4
gladieschanggoodluck/CS5010_SemesterProject
/1_1116_FIFA_Normal_Plot.py
12,128
3.5
4
#!/usr/bin/env python # coding: utf-8 # # FIFA visulization and statistical analysis # In[54]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import datetime import pandas as pd import matplotlib.pyplot as plt import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') from math import pi # In[55]: df = pd.read_csv('FIFA_1112.csv', index_col=0) df.head() # # Participants - England is the top one followed by Germany then Argentina # In[56]: plt.figure(figsize=(15,32)) sns.countplot(y = df.Country,palette="Set2") #Plot all the nations on Y Axis # # Top three national participating- England, Germany and Spain # In[57]: # To show Different nations participating in the FIFA 2019 df['Country'].value_counts().plot.bar(color = 'orange', figsize = (35, 15 )) plt.title('Different Nations Participating in FIFA') plt.xlabel('Name of The Country') plt.ylabel('count') plt.show() # # Different position acquired by the players # In[58]: plt.figure(figsize = (12, 8)) sns.set(style = 'dark', palette = 'colorblind', color_codes = True) ax = sns.countplot('Position', data = df, color = 'orange') ax.set_xlabel(xlabel = 'Different Positions in Football', fontsize = 16) ax.set_ylabel(ylabel = 'Count of Players', fontsize = 16) ax.set_title(label = 'Comparison of Positions and Players', fontsize = 20) plt.show() # # Different position group acquired by the players # In[59]: plt.figure(figsize = (12, 8)) sns.set(style = 'dark', palette = 'colorblind', color_codes = True) ax = sns.countplot('Position Group', data = df, color = 'orange') ax.set_xlabel(xlabel = 'Different Positions in Football', fontsize = 16) ax.set_ylabel(ylabel = 'Count of Players', fontsize = 16) ax.set_title(label = 'Comparison of Positions and Players', fontsize = 20) plt.show() # # Players Height distribution -180cm # In[87]: # Height of Players plt.figure(figsize = (20, 8)) ax = sns.countplot(x = 'Height', data = df, palette = 'dark') ax.set_title(label = 'Count of players on Basis of Height', fontsize = 20) ax.set_xlabel(xlabel = 'Height in Foot per inch', fontsize = 16) ax.set_ylabel(ylabel = 'Count', fontsize = 16) plt.show() # # Make correlation plot to see overall rating related to the features # In[61]: # plotting a correlation heatmap plt.rcParams['figure.figsize'] = (15,10) sns.heatmap(df[['Overall Rating', 'Pace', 'Shooting', 'Dribbling', 'Defending', 'Physicality', 'Height', 'Base Stats', 'In Game Stats']].corr(), annot = True) plt.title('Histogram of the Dataset', fontsize = 30) plt.show() # # Best players per each position with their country, club based on the overall score - Here are players names # In[62]: df.iloc[df.groupby(df['Position'])['Overall Rating'].idxmax()][['Position', 'Name', 'Club', 'Country']] # # Best players per each position group with their country, club based on the overall score - Here are player's names # In[63]: df.iloc[df.groupby(df['Position Group'])['Overall Rating'].idxmax()][['Position Group', 'Name', 'Club', 'Country']] # # Top 10 Countries based on participants and compare their overal scores - which country has the highest overall rating? --- Spain # In[64]: # Top 10 countries with highest number of players to compare their overall scores df['Country'].value_counts().head(10) # # Lets check Overall Rating of TOP 10 participant countries # In[86]: # Every Nations' Player and their Weights some_countries = ('England', 'Germany', 'Spain', 'France', 'Argentina', 'Italy', 'Colombia', 'Japan') df_countries = df.loc[df['Country'].isin(some_countries) & df['Overall Rating']] plt.rcParams['figure.figsize'] = (12, 7) ax = sns.violinplot(x = df_countries['Country'], y = df_countries['Overall Rating'], palette = 'colorblind') ax.set_xlabel(xlabel = 'Countries', fontsize = 9) ax.set_ylabel(ylabel = 'Overall Rating', fontsize = 9) ax.set_title(label = 'Distribution of Overall rating of players from different countries', fontsize = 20) plt.show() # In[66]: #Data sanity check- Need to do continent conversion df.isnull().sum() # # This is statistical summary of correlation matrix # In[67]: #Compute pairwise correlation of Dataframe's attributes corr = df.corr() corr # # Use heatmap to check correlation strength # In[68]: #Compute pairwise correlation of Dataframe's attributes based on position group fig, (ax) = plt.subplots(1, 1, figsize=(10,6)) hm = sns.heatmap(corr, ax=ax, # Axes in which to draw the plot, otherwise use the currently-active Axes. cmap="coolwarm", # Color Map. #square=True, # If True, set the Axes aspect to “equal” so each cell will be square-shaped. annot=True, fmt='.2f', # String formatting code to use when adding annotations. #annot_kws={"size": 14}, linewidths=.05) fig.subplots_adjust(top=0.93) fig.suptitle('Overall Rating Correlation Heatmap', fontsize=14, fontweight='bold') # # Correlation based on position group = goal keeper # In[69]: ColumnNames = list(df.columns.values) df_goa= df[df['Position Group'] == 'Goal Keeper'] C_Data_goa = pd.concat([df_goa[['Position Group','Overall Rating']],df_goa[ColumnNames[11:17]]],axis=1) #Compute pairwise correlation of Dataframe's attributes corr_goa = C_Data_goa.corr() corr_goa # In[70]: #Compute pairwise correlation of Dataframe's attributes based on position group fig, (ax) = plt.subplots(1, 1, figsize=(10,6)) hm = sns.heatmap(corr_goa, ax=ax, # Axes in which to draw the plot, otherwise use the currently-active Axes. cmap="coolwarm", # Color Map. #square=True, # If True, set the Axes aspect to “equal” so each cell will be square-shaped. annot=True, fmt='.2f', # String formatting code to use when adding annotations. #annot_kws={"size": 14}, linewidths=.05) fig.subplots_adjust(top=0.93) fig.suptitle('Overall Rating Correlation Heatmap for Goal Keeper', fontsize=14, fontweight='bold') # # Correlation based on position group = Midfieder # In[71]: df_mid= df[df['Position Group'] == 'Midfieder'] C_Data_mid = pd.concat([df_mid[['Position Group','Overall Rating']],df_mid[ColumnNames[11:17]]],axis=1) #Compute pairwise correlation of Dataframe's attributes corr_mid = C_Data_mid.corr() corr_mid # In[72]: #Compute pairwise correlation of Dataframe's attributes based on position group fig, (ax) = plt.subplots(1, 1, figsize=(10,6)) hm = sns.heatmap(corr_mid, ax=ax, # Axes in which to draw the plot, otherwise use the currently-active Axes. cmap="coolwarm", # Color Map. #square=True, # If True, set the Axes aspect to “equal” so each cell will be square-shaped. annot=True, fmt='.2f', # String formatting code to use when adding annotations. #annot_kws={"size": 14}, linewidths=.05) fig.subplots_adjust(top=0.93) fig.suptitle('Overall Rating Correlation Heatmap for Midfieder', fontsize=14, fontweight='bold') # # Correlation based on position group = Defender # In[73]: df_def= df[df['Position Group'] == 'Defender'] C_Data_def = pd.concat([df_def[['Position Group','Overall Rating']],df_def[ColumnNames[11:17]]],axis=1) #Compute pairwise correlation of Dataframe's attributes corr_def = C_Data_def.corr() corr_def # In[74]: #Compute pairwise correlation of Dataframe's attributes based on position group fig, (ax) = plt.subplots(1, 1, figsize=(10,6)) hm = sns.heatmap(corr_def, ax=ax, # Axes in which to draw the plot, otherwise use the currently-active Axes. cmap="coolwarm", # Color Map. #square=True, # If True, set the Axes aspect to “equal” so each cell will be square-shaped. annot=True, fmt='.2f', # String formatting code to use when adding annotations. #annot_kws={"size": 14}, linewidths=.05) fig.subplots_adjust(top=0.93) fig.suptitle('Overall Rating Correlation Heatmap for Goal Keeper', fontsize=14, fontweight='bold') # # Correlation based on position group = Midfieder, Goal Keeper, Defender, Attacker # In[75]: ColumnNames = list(df.columns.values) C_Data = pd.concat([df[['Position Group','Overall Rating']],df[ColumnNames[11:17]]],axis=1) HeatmapData = C_Data.groupby('Position Group').mean() sns.heatmap(HeatmapData,cmap='Oranges',xticklabels = True,yticklabels = True) # In[78]: labels = np.array(HeatmapData.columns.values) N = len(labels) Position = 'Attacker' stats=HeatmapData.loc[Position,labels] angles = [n / float(N) * 2 * pi for n in range(N)] stats=np.concatenate((stats,[stats[0]])) angles=np.concatenate((angles,[angles[0]])) fig=plt.figure(figsize=(12,10)) ax = fig.add_subplot(111, polar=True) ax.plot(angles, stats, 'p-', linewidth=1) ax.fill(angles, stats, alpha=0.5) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title(Position) ax.grid(True) # # Midfieder correlation strength to each feature # In[79]: labels = np.array(HeatmapData.columns.values) N = len(labels) Position = 'Midfieder' stats=HeatmapData.loc[Position,labels] angles = [n / float(N) * 2 * pi for n in range(N)] stats=np.concatenate((stats,[stats[0]])) angles=np.concatenate((angles,[angles[0]])) fig=plt.figure(figsize=(12,10)) ax = fig.add_subplot(111, polar=True) ax.plot(angles, stats, 'o-', linewidth=1) ax.fill(angles, stats, alpha=0.5) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title(Position) ax.grid(True) # # Goal Keeper correlation strength to each feature # In[80]: labels = np.array(HeatmapData.columns.values) N = len(labels) Position = 'Goal Keeper' stats=HeatmapData.loc[Position,labels] angles = [n / float(N) * 2 * pi for n in range(N)] stats=np.concatenate((stats,[stats[0]])) angles=np.concatenate((angles,[angles[0]])) fig=plt.figure(figsize=(12,10)) ax = fig.add_subplot(111, polar=True) ax.plot(angles, stats, 'o-', linewidth=1) ax.fill(angles, stats, alpha=0.5) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title(Position) ax.grid(True) # # Defender correlation strength to each feature # In[81]: labels = np.array(HeatmapData.columns.values) N = len(labels) Position = 'Defender' stats=HeatmapData.loc[Position,labels] angles = [n / float(N) * 2 * pi for n in range(N)] stats=np.concatenate((stats,[stats[0]])) angles=np.concatenate((angles,[angles[0]])) fig=plt.figure(figsize=(12,10)) ax = fig.add_subplot(111, polar=True) ax.plot(angles, stats, 'o-', linewidth=1) ax.fill(angles, stats, alpha=0.5) ax.set_thetagrids(angles * 180/np.pi, labels) ax.set_title(Position) ax.grid(True) # # pair plot to see all correlations # In[82]: g = sns.pairplot(C_Data, hue="Position Group") # # Players top 4 features based on position # For example CAM: pace, dribbling, passing, Shooting # In[85]: # defining the features of players player_features = ('Pace', 'Shooting', 'Passing', 'Dribbling', 'Defending', 'Physicality', ) # Top five features for every position in football for i, val in df.groupby(df['Position'])[player_features].mean().iterrows(): print('Position {}: {}, {}, {}, {}'.format(i, *tuple(val.nlargest(4).index))) # # Position group top 4 features # Attacker - pace, dribbling, shooting, nad physicality # In[84]: # defining the features of players player_features = ('Pace', 'Shooting', 'Passing', 'Dribbling', 'Defending', 'Physicality', ) # Top five features for every position in football for i, val in df.groupby(df['Position Group'])[player_features].mean().iterrows(): print('Position {}: {}, {}, {}, {}'.format(i, *tuple(val.nlargest(4).index))) # In[ ]:
ce9b9f59aa0b90757b8f60e35becc4f4cd01c761
clovery410/mycode
/python/chapter-1/discuss4-1.1.py
428
4.0625
4
#1.1 Print out a countdown using recursion. def countdown(n): """ >>> countdown(3) 3 2 1 """ if n <= 0: return print(n) countdown(n - 1) #1.2 Change countdown to countup instead. def countup(n): """ >>> countup(3) 1 2 3 """ if n <= 0: return countup(n - 1) print(n) if __name__ == "__main__": import doctest doctest.testmod()
7d1fa29b488499995a74c8f0a50ba7e493761a7a
anjana996/luminarpython
/mockexam/wordcount.py
199
3.578125
4
file="hai hello hai hello" words=file.split() dict={} for word in words: if (word not in dict): dict[word]=1 else: dict[word]+=1 for k,v in dict.items(): print(k,",",v)
48489e987ae2730270aba07cc8b943282f65bb2f
nikolasvargas/python-adventures
/mini_games/playground.py
1,251
3.65625
4
""" main of main """ import riddle import hangman def main(): """ start select """ print("***************************************************", end="\n") print("*********** Bem vindo ao salão de jogos! **********", end="\n") print("***************************************************", end="\n") print("***** (1) hangman game <---> (2) riddle game *****") game_choise = int(input("escolha o game: ")) if game_choise == 1: hangman.run() elif game_choise == 2: riddle.run() def play_again(): """play again""" main() def welcome(): """ zzZZZzzzzZZZzzzzzz """ print("*****************************************") print("*********** Bem vindo ao jogo! **********") print("*****************************************") def win_print(): print("Winner!") print(" ___________ ") print(" '._==_==_=_.' ") print(" .-\\: /-. ") print(" | (|:. |) | ") print(" '-|:. |-' ") print(" \\::. / ") print(" '::. .' ") print(" ) ( ") print(" _.' '._ ") print(" '-------' ") if __name__ == '__main__': main()
a74e5e89715c1f9d650a2e30051f638291b939cc
BIAOXYZ/variousCodes
/_CodeTopics/LeetCode/401-600/000437/000437.py
2,128
3.609375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def pathSum(self, root, targetSum): """ :type root: TreeNode :type targetSum: int :rtype: int """ # 这道题还挺新颖的感觉。想法是用一个列表表示当前状态,其含义是以该点为末尾的所有可能路径和。 # 构造方法就是:每次新往下走一层,前面的元素都加上新元素的值,然后数组末尾还要append一下新元素的值。 ## 每次往上一层走,数组除了最后一个元素,前面每一个都减去最后一个元素,然后最后一个元素还要pop出去。 # 比如对于输入 [10,5,-3,3,2,null,11,3,-2,null,1],在root时,这个状态数组是 [10], ## 紧接着到了一下层左边,就会变成 [15, 5],再左下一次,变成 [18, 8, 3],依次类推。 ## 返回的时候就反过来: [18, 8, 3] -- [18-3, 8-3, 3(pop掉)] = [15, 5],依次类推。 res = [0] def dfs_with_state(node, arr): for i in range(len(arr)): arr[i] += node.val if arr[i] == targetSum: res[0] += 1 arr.append(node.val) if node.val == targetSum: res[0] += 1 if node.left: dfs_with_state(node.left, arr) if node.right: dfs_with_state(node.right, arr) for i in range(len(arr) - 1): arr[i] -= node.val arr.pop() if not root: return 0 dfs_with_state(root, []) return res[0] """ https://leetcode-cn.com/submissions/detail/223930451/ 126 / 126 个通过测试用例 状态:通过 执行用时: 320 ms 内存消耗: 14.5 MB 执行用时:320 ms, 在所有 Python 提交中击败了49.65%的用户 内存消耗:14.5 MB, 在所有 Python 提交中击败了37.42%的用户 """
3f64bed0bc77f15de807b3694b294240e6b3a93b
bmcclannahan/sort-testing
/sorts.py
611
3.90625
4
def is_sorted(arr): for i in range(len(arr)-1): if arr[i] > arr[i+1]: return False return True def swap(a, b, arr): temp = arr[a] arr[a] = arr[b] arr[b] = temp def insertion_sort(start, end, arr): for i in range(start, end): curr = i while curr >= 1 and arr[curr] < arr[curr-1]: swap(curr, curr-1, arr) curr -= 1 def selection_sort(start, end, arr): for i in range(start, end-1): curr = i for j in range(i+1, end): if arr[curr] > arr[j]: curr = j swap(i, curr, arr)
c43b784c766fd9156c9a894282e4fcf509511a47
W7297911/test
/python/firstPython/类属性_统计.py
427
3.828125
4
class Tool(object): # 使用赋值语句定义类属性,记录所有工具对象 count = 0 def __init__(self, name): self.name = name # 让类属性的值+1 Tool.count += 1 # 1.创建工具对象 tool1 = Tool("斧头") tool2 = Tool("砍刀") tool3 = Tool("钳子") tool4 = Tool("榔头") # print(Tool.count) # print("工具对象总数:{}".format(tool1.count)) print("工具对象总数:{}".format(tool1.count))
244bb4f68578359a91df336efbeb253ae2ffebe0
will-i-amv-books/Functional-Python-Programming
/CH3/ch03_ex3.py
2,675
4.5
4
#!/usr/bin/env python3 """Functional Python Programming Chapter 3, Example Set 4 """ ########################################### # Imports ########################################### import math import itertools from typing import Iterable, Iterator, Any ########################################### # Generator expressions ########################################### # Locate the prime factors of a number using generators and for loops def calc_factors_iterative(x): """Loop/Recursion factors. Limited to numbers with 1,000 factors. >>> list(calc_factors_iterative(1560)) [2, 2, 2, 3, 5, 13] >>> list(calc_factors_iterative(2)) [2] >>> list(calc_factors_iterative(3)) [3] """ # Find even factors if x % 2 == 0: yield 2 if x // 2 > 1: yield from calc_factors_iterative(x//2) return # Find odd factors for i in range(3, int(math.sqrt(x) + 0.5) + 1, 2): if x % i == 0: yield i if x // i > 1: yield from calc_factors_iterative(x//i) return yield x # Locate the prime factors of a number using pure recursion def calc_factors_recursive(x): """Pure Recursion factors. Limited to numbers below about 4,000,000 >>> list(calc_factors_recursive(1560)) [2, 2, 2, 3, 5, 13] >>> list(calc_factors_recursive(2)) [2] >>> list(calc_factors_recursive(3)) [3] """ def factor_n(x, n): if n*n > x: yield x return if x % n == 0: yield n if x//n > 1: yield from factor_n(x // n, n) else: yield from factor_n(x, n + 2) # Find even factors if x % 2 == 0: yield 2 if x//2 > 1: yield from calc_factors_recursive(x//2) return # Find odd factors yield from factor_n(x, 3) ########################################### # Generator limitations ########################################### # Generators don't have a proper value until we consume the generator functions calc_factors_iterative(1560) factors = list(calc_factors_iterative(1560)) # Some list methods don't work with generators len(calc_factors_iterative(1560)) # Will throw error len(factors) # Will succeed # Generators can be used only once result= calc_factors_iterative(1560) sum(result) # Will show sum sum(result) # Will show 0 # Using itertools.tee() to clone a generator 2 or more times def calc_extreme_values(iterable): """ >>> calc_extreme_values([1, 2, 3, 4, 5]) (5, 1) """ max_tee, min_tee = itertools.tee(iterable, 2) return max(max_tee), min(min_tee)
3c4fe8360ff25b984d1af3131aca1797ea18cf7f
josephcalver/CompleteDataStructuresAndAlgorithmsInPython
/ArraysAndLists/arrays.py
1,599
4.375
4
from array import array # 1. Create an array and traverse print("#1:") my_array = array('i', [1, 2, 3, 4, 5]) print(my_array) for i in my_array: print(i) # 2. Access individual element via index print("#2:") print(my_array[0]) # 3. Append a value to the array print("#3:") my_array.append(6) print(my_array) # 4. Insert value at specified index print("#4:") my_array.insert(0, 0) print(my_array) # 5. Extend array print("#5:") array_extension = array('i', [7, 8, 9]) my_array.extend(array_extension) print(my_array) # 6. Append items from list print("#6:") my_list = [10, 11, 12] my_array.fromlist(my_list) print(my_array) # 7. Remove item print("#7:") my_array.remove(12) print(my_array) # 8. Remove last item with pop() print("#8:") my_array.pop() print(my_array) # 9. Find any item by index print("#9:") print(my_array[7]) # 10. Reverse array print("#10:") my_array.reverse() print(my_array) my_array.reverse() # 11. Access array buffer info print("#11:") print(my_array.buffer_info()) # 12. Count occurrences of item print("#12:") my_array.append(9) print(my_array) print(my_array.count(9)) # 13. Convert array to string print("#13:") str_temp = my_array.tostring() print(str_temp) ints = array('i') ints.fromstring(str_temp) print(ints) # 14. Convert array to list print("#14:") list_temp = my_array.tolist() print(type(my_array)) print(type(list_temp)) # 15. Slice elements of array (end index not inclusive) array_slice = my_array[3:7] print(array_slice) print(my_array[6:10]) print(my_array[7:]) print(my_array[:4]) print(my_array)
9ae57aabb32f6075c852791e12edcdc2f2ded907
thrika/Gradient-Descent-from-Scratch
/Problem_2.py
1,387
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import math # In[ ]: function = lambda x: np.sin(10*(math.pi)*x) + ((x-1)**4) # In[ ]: x = np.linspace(-0.5,2.5,500) # In[ ]: plt.plot(x, function(x)) # In[ ]: def deriv(x): return (((5*math.pi)*(np.cos(10*math.pi*x)))/x) - ((math.sin(10*math.pi*x))/(2*(x**2))) + (4*((x-1)**3)) # In[ ]: def step_function(x_new, x_prev, precision, learning_rate): x_list, y_list = [x_new], [function(x_new)] while abs(x_new - x_prev) > precision: x_prev = x_new deriv_x = - deriv(x_prev) x_new = x_prev + (learning_rate * deriv_x) x_list.append(x_new) y_list.append(function(x_new)) print ("Minimum occurs at: "+ str(x_new)) print ("Number of steps: " + str(len(x_list))) plt.subplot(1,2,2) plt.scatter(x_list,y_list,c="g") plt.plot(x_list,y_list,c="g") plt.plot(x,function(x), c="r") plt.title("Gradient descent") plt.show() # In[ ]: step_function(2.4, 0, 0.001, 0.001) # In[ ]: step_function(2.4, 0, 0.000000001, 0.000000001) # In[ ]: step_function(1.8, 0, 0.000000001, 0.000000001) # In[ ]: step_function(1.5, 0, 0.000000001, 0.000000001) # In[ ]: step_function(0.5, 0, 0.000000001, 0.000000001) # In[ ]:
030eba724fff9b8752c2c2bcf35bbcfee3d7bab4
Dash275/herochest
/die_cast.py
736
3.546875
4
import random import re import itertools def roll(n, x): result = 0 for i in range(1, n + 1): result += random.randrange(1, x + 1) return result def roll_expression(expression): result = 0 expression = expression.replace(" ", "") pieces = re.findall('\+?-?\d*d?\d+', expression) for piece in itertools.chain(pieces): die = False if re.match('.*d', piece): die = True n, x = re.findall('\d+', piece) n, x = int(n), int(x) if re.match('-', piece): if die: result -= roll(n, x) else: result += int(piece) else: if die: result += roll(n, x) else: result += int(piece) return result
edd13fb17ba91e07ada865333baa4b77b24cc3cc
IlshatVEVO/Data-Analys-Labs
/lab3/Task2_1.py
203
3.671875
4
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 50, 0.01) y = [i * 2.9 + 10 for i in x] plt.plot(x, y, 'b') plt.xlabel('x axis') plt.ylabel('y axis') plt.title('Draw line') plt.show()
3d48062483273a58ccc26b9041dd4a6af677cfe5
dkoh12/gamma
/Python/sort.py
2,733
3.90625
4
def binarySearch(lst, value, low, high): if low > high: return -1 mid = (low + high) // 2 if lst[mid] == value: return mid elif lst[mid] < value: return binarySearch(lst, value, mid+1, high) else: return binarySearch(lst, value, low, mid) def selectionSort(lst): for i in range(len(lst)): small = i for j in range(i+1, len(lst)): if lst[j] < lst[small]: small = j lst[i], lst[small] = lst[small], lst[i] return lst def insertionSort(lst): for i in range(1, len(lst)): j = i-1 while(j >= 0 and lst[j] > lst[i]): lst[i], lst[j] = lst[j], lst[i] j-=1 return lst def bubbleSort(lst): for i in range(len(lst)): for j in range(1, len(lst)): if lst[j-1] > lst[j]: lst[j-1], lst[j] = lst[j], lst[j-1] return lst ''' merge() works for merging 2 list but a heap data structure is able to merge k lists in O(k log n) ''' def mergeSort(lst): if len(lst) <= 1: return lst mid = len(lst)//2 left = lst[:mid] right = lst[mid:] mergeSort(left) mergeSort(right) i, j, k = 0, 0, 0 while i < len(left) and j < len(right): if left[i] < right[j]: lst[k] = left[i] i+=1 else: lst[k] = right[j] j+=1 k+=1 while i < len(left): lst[k] = left[i] i+=1 k+=1 while j < len(right): lst[k] = right[j] j+=1 k+=1 return lst def quickSort(lst): if len(lst) <= 1: return lst left = [] equal = [] right = [] pivot = lst[0] for val in lst: if val < pivot: left.append(val) elif val == pivot: equal.append(val) else: right.append(val) return quickSort(left) + equal + quickSort(right) def quicksort2(lst): if not lst: return [] pivots = [x for x in lst if x == lst[0]] left = quicksort2([x for x in lst if x < lst[0]]) right = quicksort2([x for x in lst if x > lst[0]]) return left+pivots+right ''' Given a nearly sorted list find k largest integers http://www.geeksforgeeks.org/nearly-sorted-algorithm/ Put k elements in min heap. Then for rest of elements you traverse heap O(k) + O((n-k)log k) ''' import heapq def k_largest(lst, k): print(lst) # One line # print(heapq.nlargest(k, lst)) # Same thing but multiple lines # heap = [] # for i in lst: # if len(heap) < k: # heapq.heappush(heap, i) # else: # if i > heap[0]: # heapq.heappop(heap) # heapq.heappush(heap, i) # arr = [] # while len(heap) > 0: # arr.append(heapq.heappop(heap)) # print(arr) # done using insertion sort arr = insertionSort(lst) print(arr[len(arr)-k:]) if __name__=="__main__": # lst = [5, 7, 3, 8, 4, 2] # print(insertionSort(lst)) # print(bubbleSort(lst)) # print(mergeSort(lst)) # print(quickSort(lst)) # print(quicksort2(lst)) lst = [1, 3, 5, 8, 2, 10, 4, 12, 16] k_largest(lst, 3)
cc574d42a17f2ae51d5691ee1aea78197dc1580a
Felipe-Ferreira-Lopes/programacao-orientada-a-objetos
/listas/lista-de-exercicio-03/questao3.py
414
4.03125
4
letra = str (input("Digite a letra desejada: ")) if letra == ("F"): print("Feminino") elif letra == ("M"): print("Masculino") '''A partir daqui eu fiz o restante das possibilidades apenas por diversão :), e para testar a linguagem identificando letras maisculas e minusculas ''' elif letra ==("f"): print("Feminino") elif letra == ("m"): print("Masculino") else: print("Sexo invalido")
073bad8632066d50d21a80b3ee599727e7d60d98
hanroy/Guess-the-Number
/guess-the-number.py
398
3.8125
4
from random import * answer = raw_input("Do you wanna play [Y/N] : ") guessnumber = randint(1, 15) while (answer == "Y" or "y" or "yes"): userguess = int(raw_input("Guess a number: ")) if userguess < guessnumber: print ("Little Higher") elif userguess > guessnumber: print ("Little Lower") else: print "Well done" break else : print("Bye!.")
509f1def0a896bc83ebf6bfa6b95ce05e94adfd4
ho600-ltd/ho600-ltd-python-libraries
/ho600_ltd_libraries/utils/formats.py
2,044
3.984375
4
def customize_hex_from_integer(number, base='0123456789abcdef'): """ convert integer to string in any base, example: convert int(31) with binary-string(01) will be '11111' convert int(31) with digit-string(0-9) will be '31' convert int(31) with hex-string(0-9a-f) will be '1f' convert int(31) with base-string(a-fg-v0-5) will be '5' convert int(63) with base-string(abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,) will be ',' convert int(16777215) with base-string(abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,) will be ',,,,' convert int(16777216) with base-string(abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,) will be 'baaaa' """ base_len = len(base) if number < base_len: return base[number] else: return customize_hex_from_integer(number//base_len, base) + base[number%base_len] def integer_from_customize_hex(string, base='0123456789abcdef'): """ convert string to integer in any base, example: convert '11111' with binary-string(01) will be int(31) convert int(31) with digit-string(0-9) will be '31' convert int(31) with hex-string(0-9a-f) will be '1f' convert int(31) with base-string(a-fg-v0-5) will be 'bd' convert int(27) with base-string(a-fg-v0-5) will be '5' convert int(63) with base-string(abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,) will be ',' convert int(16777215) with base-string(abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,) will be ',,,,' convert int(16777216) with base-string(abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,) will be 'baaaa' """ position_dict = {} base_len = len(base) for i, s in enumerate(base): position_dict[s] = i string_len = len(string) number = 0 for i, s in enumerate(string): _n = position_dict[s] * base_len ** (string_len - i - 1) number += _n return number
b4223446ccb2dc8d7e248ca50b84b44a60d802e7
knshkp/hacktoberfest2021
/Python/heapsort.py
485
3.71875
4
def heap(arr, n, i): a = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[i] < arr[l]: a = l if r < n and arr[a] < arr[r]: a = r if a != i: arr[i],arr[a] = arr[a],arr[i] heap(arr, n, a) def hS(arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): heap(arr, n, i) for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] heap(arr, i, 0) arr = [ 12, 1, 33, 25, 63, 17] hS(arr) n = len(arr) print ("Sorted array =") for i in range(n): print ("%d" %arr[i])
b1c8fbe1c5c4375caac646244d322403d2cb1688
MeXaHu3M/PythonTasks
/practice 1/task 04.py
355
3.90625
4
print("Обмен значениями с промежуточной переменной") a = int(input()) b = int(input()) c = a a = b b = c print("A =", a, "B =", b) print("Обмен значениями без промежуточной переменной") a = int(input()) b = int(input()) a = a + b b = a - b a = a - b print("A =", a, "B =", b)
08740496fb5aa5045df39fcca2873c1cef588de2
MarioDeCrist/Python-Programs
/MadLibs_Lab.py
2,412
3.890625
4
#Madlibs Lab #Mario DeCristofaro #md2224 #9-11-17 #Section 1 print("Mad Libs Story please enter words accordingly: ") print("=============================================\n") #these are the adj's, nouns, and names that asks us for the input first_name = input("Type a name ") first_noun = input("Type a noun ") first_adjective = input("Type an adjective ") second_noun = input("Type a noun ") second_adjective = input("Type an adjective ") third_noun = input("Type a noun ") fourth_noun = input("Type a noun ") third_adjective = input("Type an adjective ") fifth_noun = input("Type a noun ") second_name = input("Type a name ") sixth_noun = input("Type a noun ") seventh_noun = input("Type a noun ") third_name = input("Type another name ") fourth_name = input("Type another name ") #with these print functions we use strings mainly and then add the past inputs from the adj, nouns, and names print("Dear " + first_name + ",") print(" I’m writing you a letter to inform you about your " + first_noun + ", it has been acting up in the neighborhood lately") print( " doing some crazy things. One of the things that happened was a " + first_adjective + " " + second_noun + " eating contest. Which got out ") print( " of hand so fast. The second thing was a " + second_adjective + third_noun + "racing contest where one of the contestants died from ") print ( " a " + fourth_noun + ". These activities do not fly around this neighborhood and my company " + third_adjective + fifth_noun + " corporation will ") print ( " not handle this lightly if they continue. I will pursue this legally with my lawyer, " + second_name + " over at the " + sixth_noun) print ( " lawyer agency. These guys are pros with this kind of stuff and can ruin reputations with these types of ") print ( " trials if it comes to it. All of your neighbors have been complaining about this activity for the past few ") print ( " weeks. In fact, one named name even attended one of those contests and recently has his " + seventh_noun + " broken ") print ( " because of it. His family has been wanting to press charges against you and have asked me to step in and ") print ( " help them pursuit this. You need to stop these activities right now or my next letter will be not so much a ") print ( " letter but a legal notice that.") print ( " Sincerely,") print (third_name + " " + fourth_name)
a2eac8b9f6a884de20a41eb982a1c2096533e5d0
amen619/python-practise
/Week-2/Operators/11-else-not-required.py
151
3.9375
4
def is_even(number): if number % 2 == 0: return True return False # Only if the IF statement fails this will be executed. is_even(20)
ceff2e666e5ed34ec4e7a53341332e4598d80d71
JulCesWhat/Unscramble_Computer_Science_Problems
/Task4.py
1,616
3.953125
4
#!/usr/bin/env python3 """ Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv def getCSVData(): texts = [] calls = [] with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) return (texts, calls) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ if __name__ == '__main__': texts, calls = getCSVData() send_calls = {} for row_call in calls: if not send_calls.get(row_call[0]): send_calls[row_call[0]] = True for row_text in texts: if send_calls.get(row_text[0]): # send_calls[row_text[0]] = False del send_calls[row_text[0]] if send_calls.get(row_text[1]): # send_calls[row_text[1]] = False del send_calls[row_text[1]] for row_call in calls: if send_calls.get(row_call[1]): # send_calls[row_call[1]] = False del send_calls[row_call[1]] print("These numbers could be telemarketers: ") all_send_calls = sorted(list(send_calls)) for send in all_send_calls: print(send)
503ce68333579c7fb7f4d7ba86036da9ca8f940f
kbutler52/python_scripts
/williamHw/hw2.py
231
3.890625
4
#05-19-2020 #Williams HW#2 first = 5 second = 2 print(first > second)#checks if statement print(not(first > second))# chekcs ekse statement if first > second: print("5 is greater than 2") else: print("5 is less than 2")
68918f822db5babda0faeb501a0979447d27143d
misrapk/tkinter-Tutorials
/ClickEvents.py
242
3.578125
4
from tkinter import * root = Tk() def leftClick(event): print("Left Press") def RightClick(event): print("Right Press") frame = Frame(root, width = 300, height=300) frame.bind("<Button-1>", leftClick) frame.pack() root.mainloop()
a31bfe119af111ac9d549d78f9dfde0b3810daaa
Groookie/pythonBasicKnowledge
/015_01_func_demo.py
6,635
3.671875
4
#!/usr/bin/python3 # -*-coding:utf-8-*- # author: https://blog.csdn.net/zhongqi2513 # ==================================================== # 内容描述: 函数操作相关 # ==================================================== print(ord("A")) # 把一个字符转换成unicode编码 print(chr(65)) # 把数字转换成一个字符 print(abs(-1)) # 求绝对值 print(type(3 + 4j)) # 求参数变量的类型 print("---------------------------1-----------------------------") a = 1 b = str(a) print(a, b) print(type(a), type(b)) c = int(b) print(type(b), type(c)) d = float(c) print(type(c), type(d)) print("---------------------------2-----------------------------") e = "True" f = bool(e) print(type(e), type(f)) print(type(3 > 2)) print(bool(""), type(bool(""))) print(bool(" "), type(bool(" "))) print(bool(0), type(bool(0))) print(bool(3), type(bool(3))) print("---------------------------3-----------------------------") """ 自定义函数,基本有以下规则步骤: 1、函数代码块以 def 关键词开头,后接函数标识符名称和圆括号() 2、任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数 3、函数的第一行语句可以选择性地使用文档字符串(用于存放函数说明) 4、函数内容以冒号起始,并且缩进 5、return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的 return 相当于返回 None。 """ """ 定义一个函数: 1、def 定义一个函数,给定一个函数名 sum 2、声明两个参数 num1 和 num2 3、函数的第一行语句进行函数说明:两数之和 4、最终 return 语句结束函数,并返回两数之和 """ # 定义函数 def mysum(num1, num2): """两数之和""" return num1 + num2 # 调用函数 print(mysum(5, 6)) print("---------------------------4-----------------------------") """ 函数参数:传参分为两种: 1、可变类型, 传递的是引用 2、不可变类型, 传递的是值的拷贝 解释:b = 1,创建了一个整形对象 1 ,变量 b 指向了这个对象,然后通过函数 chagne_number 时, 按传值的方式复制了变量 b ,传递的只是 b 的值的一个copy,并没有影响到 b 的本身。 """ # 有意思的测试: def chagne_number(a): a = 1000 return a b = 1 c = chagne_number(b) print(b, c) print("---------------------------5-----------------------------") def change_array(array): array[0] = "huangbo" array = [1, 2, 3, 4, 5] change_array(array) print(array) def change_array1(arr): arr[0] = "huangbo" return arr array1 = [1, 2, 3, 4, 5] some = change_array1(array1) print(array1) print(some) print("---------------------------6-----------------------------") """ 函数默认参数 有时候,我们自定义的函数中,如果调用的时候没有设置参数,需要给个默认值, 这时候就需要用到默认值参数了。 """ def print_user_info(name, sex, age=18): print(name, sex, age) ## 位置参数 print_user_info("huangbo", "F", 20) print_user_info("huangbo", "F") ## 关键字参数 print_user_info(age=30, name="huangbo", sex="M") """ 需要注意的是: 1、只有在形参表末尾的那些参数可以有默认参数值 2、默认参数的值是不可变的对象,比如None、True、False、数字或字符串, 当默认参数是可变对象时,默认值在其他地方被修改后你将会遇到各种麻烦。 这些修改会影响到下次调用这个函数时的默认值。 """ print("---------------------------7-----------------------------") """ 变长参数 有时我们在设计函数接口的时候,可会需要可变长的参数。也就是说,我们事先无法确定传入的参数个数。 Python 提供了一种元组的方式来接受没有直接定义的参数。这种方式在参数前边加星号 * 。 如果在函数调用时没有指定参数,它就是一个空元组。我们也可以不向函数传递未命名的变量。 在如下函数定义中:hobby就是一个元组 """ def print_user_info2(name, age, sex='男', *hobby): print(name, age, sex) print(hobby) print_user_info2("huangbo", "F", 20, 20) print_user_info2("huangbo", "F", 20, "a", "b", "c", 1, 2, 33.33) print("---------------------------8-----------------------------") """ 匿名函数: python 使用 lambda 来创建匿名函数,也就是不再使用 def 语句这样标准的形式定义一个函数。 匿名函数主要有以下特点: 1、lambda 只是一个表达式,函数体比 def 简单很多。 2、lambda 的主体是一个表达式,而不是一个代码块。仅仅能在 lambda 表达式中封装有限的逻辑进去。 3、lambda 函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。 注意:尽管 lambda 表达式允许你定义简单函数,但是它的使用是有限制的。 你只能指定单个表达式,它的值就是最后的返回值。 也就是说不能包含其他的语言特性了, 包括多个语句、条件表达式、迭代以及异常处理等等。 """ # 例子: sum_f = lambda num1, num2: num1 + num2 s = sum_f(1, 2) print(s) # 有趣测试 lambda的参数是运行时绑定的 num2 = 100 sum1 = lambda num1: num1 + num2 num2 = 10000 sum2 = lambda num1: num1 + num2 print(sum1(1)) print(sum2(1)) print("---------------------------9-----------------------------") """ 在Python中定义函数,可以用必选参数、默认参数、可变长参数、关键字参数和命名关键字参数 这5种参数都可以组合使用。 但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变长参数、命名关键字参数和关键字参数。 """ def f1(a, b, c=0, *args, **kw): """ :param a: 必选参数 :param b: 必选参数 :param c: 默认参数 :param args: 可变长参数 :param kw: 关键字参数 """ print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) f1(1, 2) f1(1, 2, 3) f1(1, 2, aa="aa") f1(1, 2, 3, 4) f1(1, 2, 3, 4, 5, 6, 7, 8, aa="aa", bb="bb") print("----------------------------10-----------------------------") def fact(n): """ 递归函数:求阶乘 """ if n == 1: return 1 return n * fact(n - 1) result = fact(100) print(result) def febonacci(n): """ 递归函数:斐波那契数列 """ if n == 1: return 1 elif n == 2: return 1 else: return febonacci(n-1) + febonacci(n-2) result = febonacci(50) print(result)
9b92236383c5b2f9b48d3c8cff5f066683e996a5
L1nwatch/Mac-Python-3.X
/Others/装饰器学习/learn_wrapper.py
918
3.546875
4
#!/bin/env python3 # -*- coding: utf-8 -*- # version: Python3.X """ 2017.02.15 想学习一下装饰器的知识, 参考资料: http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html """ __author__ = '__L1n__w@tch' def wrapper(arg): def _for_wrapper(func): def _true_wrapper(*args, **kwargs): print("[*] 这里的装饰器能够接受参数了: {}".format(arg)) ret = func(*args, **kwargs) print("[*] 最初级的装饰器结束了") return ret return _true_wrapper return _for_wrapper @wrapper("装饰器4") def raw_function(a, b): print("我有两个参数: {}, {}".format(a, b)) return a + b if __name__ == "__main__": print("{sep} 原始函数调用开始 {sep}".format(sep="*" * 30)) result = raw_function(1, 2) assert result == 3 print("{sep} 原始函数调用结束 {sep}".format(sep="*" * 30))
54169f69caab30c6669b74aded329c6c38320de3
mrajalakshmim/python-programming
/amstrong no.py
225
4.03125
4
n=int(input("enter a number")) sum=0 temp=numberwhile temp>0: digit=temp%10 sum+=digit**3 temp//=10 if n==sum: print(n,"is an Armstrong number") else: print(n,"is not an Armstrong number")
1927317a0a77e845258eb9bf63f6c24c8dd7642e
pedromxavier/euler
/src/euler0034.py
447
3.53125
4
''' Project Euler 0034 ==================== ''' import eulerlib as lib import math M = math.factorial(9) def u(n: int): 'upper bound' return (n / math.log10(n)) <= M def find(): n = 10 s = set() while u(n): if n == sum(math.factorial(d) for d in lib.digits(n)): s.add(n) n += 1 else: return s @lib.answer def main(): return sum(find()) if __name__ == '__main__': main()
e7e3293f72a26440106c435171f3a01d23e2ee1c
taalaybolotbekov/ch1pt2task10
/task10.py
874
4.21875
4
f = 'In the first line, print the third character of this string' print(f[3]) s = 'In the second line, print the second to last character of this string.' print(s[1:-1]) t = 'In the third line, print the first five characters of this string.' print(t[0:5]) f = 'In the fourth line, print all but the last two characters of this string.' print(f[0:-2]) five = 'In the fifth line, print all the characters of this string with even indices.' print(five[1::2]) six = 'In the sixth line, print all the characters of this string with odd indices.' print(six[0::2]) sev = 'In the seventh line, print all the characters of the string in reverse order.' print(sev[::-1]) ei = 'In the eighth line, print every second character of the string in reverse order,starting from the last one.' print(ei [::-2]) nin = 'In the ninth line, print the length of the given string.' print(len(nin))
c1baa12b9c0a4b97c2ebc6636176d6fbdece9a35
rishabhsinghvi/CS383-Artificial_Intelligence
/Assignment_2/agent.py
318
3.90625
4
from abc import ABC, abstractmethod class Agent(ABC): """An abstract game-playing agent.""" @abstractmethod def select_action(self, game, state): """ Choose a move given some game state. The implementation of this method will be different for each agent! """ pass
af2171df4bd0fb98fba04d68bcb378b7ef258a0b
EpsilonHF/Leetcode
/Python/476.py
620
4.03125
4
""" Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The given integer is guaranteed to fit within the range of a 32-bit signed integer. You could assume no leading zero bit in the integer’s binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. """ class Solution: def findComplement(self, num: int) -> int: n = 1 while n <= num: n <<= 1 return n - 1 - num
4ec60842cb8646734fa0702d7e2ba5f3eea62531
kalasu-1999/MultipleErrors
/FindErrors.py
3,259
4.0625
4
# -*- coding: UTF-8 -*- # 文件多行不同判断 def clean(line, num): while num < line.__len__() and line[num].strip() == '': num = num + 1 return num def logic(c): # 最后一行 if c.trueNum + 1 == c.trueLine.__len__() or c.falseNum + 1 == c.falseLine.__len__(): return False # 中间行 else: temp1 = c.trueNum temp2 = c.falseNum clean(c.trueLine, temp1) clean(c.falseLine, temp2) if c.trueLine[temp1 + 1].replace(' ', '') == c.falseLine[temp2 + 1].replace(' ', ''): return True else: return False # 少了一些行 def lessTrue(c): temp1 = c.falseNum + 1 temp1 = clean(c.falseLine, temp1) temp2 = c.trueNum + 1 temp2 = clean(c.trueLine, temp2) temp3 = temp2 + 1 temp3 = clean(c.trueLine, temp3) while temp3 != c.trueLine: if c.trueLine[temp2].replace(' ', '') == c.falseLine[c.falseNum].replace(' ', '') and \ c.trueLine[temp3].replace(' ', '') == c.falseLine[temp1].replace(' ', ''): return temp2 else: temp2 = temp2 + 1 temp2 = clean(c.trueLine, temp2) temp3 = temp2 + 1 temp3 = clean(c.trueLine, temp3) return -3 def check(c): # 去空行 answerDict = {} clean(c.trueLine, c.trueNum) clean(c.falseLine, c.falseNum) while c.trueNum < c.trueLine.__len__() and c.falseNum < c.falseLine.__len__(): # 相同行继续 if c.trueLine[c.trueNum].replace(' ', '') == c.falseLine[c.falseNum].replace(' ', ''): c.trueNum = c.trueNum + 1 c.falseNum = c.falseNum + 1 # 不同行 else: # 判断是否为逻辑错误 if logic(c): answerDict[c.falseNum] = 0 c.trueNum = c.trueNum + 1 c.falseNum = c.falseNum + 1 else: lessReturn = lessTrue(c) if lessReturn != 0: answerDict[c.falseNum] = lessReturn - c.trueNum c.trueNum = lessReturn + 1 c.falseNum = c.falseNum + 1 c.trueNum = clean(c.trueLine, c.trueNum) c.falseNum = clean(c.falseLine, c.falseNum) # 运行到最后有剩余行 # 正确程序还有剩余行 if c.trueNum == c.trueLine.__len__() and c.falseNum != c.falseLine.__len__(): answerDict[c.falseNum] = -1 # 错误程序还有剩余行 elif c.falseNum == c.falseLine.__len__() and c.trueNum != c.trueLine.__len__(): answerDict[c.falseNum] = -2 return answerDict class CheckCode: def __init__(self): pass trueLine = [] falseLine = [] trueNum = 0 falseNum = 0 # path1:正确程序列 # path2:错误程序列 # checkDir:错误行数字典 # key: 错误行数 # value: 0 //单行逻辑错误 # -1 //正确程序有剩余行 # -2 //错误程序有剩余行 # -3 //多行缺失,可能存在问题 # 其他正数 //相较于正确程序的缺失行数 def checkMain(line1, line2): ck = CheckCode() ck.trueLine = line1 ck.falseLine = line2 checkDict = check(ck) return checkDict
471a83a86cb86406bc497ac198b09d2ac5d767a9
Connor1996/Core-Python-Promgramming-Exercise
/Chapter11/11-10.py
242
3.59375
4
import string def delspace(filename): func = lambda string: string.strip() with open(filename, 'r+') as f: Is = map(func, f) f.seek(0) f.write(''.join(Is)) if __name__ == '__main__': delspace('test.txt')
117c4e710ed710632be1558d89f5e5f2d7db0b97
Aminoragit/Mr.noobiest
/my1021_4_5.py
687
4
4
str1='python is' str2=' good programming' str3 = str1 + str2 #string 연산자 overloding 원래+는 사칙연산이라 숫자만 되는데 파이썬에서 내부에서.__add__가 써지는것임 str1.__add__(' ') #str 덧셈=__add__ 메서드 print(str3) print('='*40) #= print('len :', len(str1)) #문자열의 길이 length = len mylist = [3,6,8,0] print('list len : ' , len(mylist)) print(str1[0],str1[1],str1[-1]) ## -1대신 str1[len(str1)-1] 써도 됩니다. print(str1[:-1]) #분할연산(:) #결과값 : python i #-1전까지=마지막 단어 전까지 표시 print(str1[1:4:1]) #확장 분할 연산(start:end:jump) print(str1[::-1]) #거꾸로
7be1cecb563a8d6373e101b2e098d828bc3348c3
MarkoNerandzic/FoodRecommendations
/FileIO.py
3,465
3.578125
4
#------------------------------------------------------------------------------- # Name: FileIO - Class of FoodRecommendations # Purpose: To gather the survey results from the .csv file and write out the # user's inputs to the file. # # Author: Justin Moulton & Marko Nerandzic # # Created: April 9, 2013 # Copyright: (c) Justin Moulton & Marko Nerandzic 2013 # Licence: This work is licensed under the Creative Commons # Attribution-NonCommercial-ShareAlike 3.0 Unported License. # To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc-sa/3.0/. #------------------------------------------------------------------------------- class FileIO: genderArray = [] #Defines and declares all of the required variables nationalityArray = [] ageArray = [] spicyArray = [] favNationalityArray = [] secondFavNationalityArray = [] thirdFavNationalityArray = [] countryArray = [] def getInfoFromFile(self): fin = open("Favourite Food Survey (Responses).csv") for line in fin: #Repeats for each line in the file line = line.strip() genderEndComma = line.find(",") #Specifies the end point of each piece of data in the line nationalityEndComma = line.find(",", genderEndComma + 1) ageEndComma = line.find(",", nationalityEndComma + 1) spicyEndComma = line.find(",", ageEndComma + 1) favNationalityEndComma = line.find(",", spicyEndComma + 1) secondFavNationalityEndComma = line.find(",", favNationalityEndComma + 1) thirdFavNationalityEndComma = line.find(",", secondFavNationalityEndComma + 1) gender = line[:genderEndComma] #Retrieves each piece of data from the line nationality = line[genderEndComma + 1:nationalityEndComma] age = line[nationalityEndComma + 1:ageEndComma] spicy = line[ageEndComma + 1:spicyEndComma] favNationality = line[spicyEndComma + 1:favNationalityEndComma] secondFavNationality = line[favNationalityEndComma + 1:secondFavNationalityEndComma] thirdFavNationality = line[secondFavNationalityEndComma + 1:thirdFavNationalityEndComma] country = line[thirdFavNationalityEndComma + 1:] self.genderArray.append(gender.lower()) #Appends the data to relevant array self.nationalityArray.append(nationality.lower()) self.ageArray.append(age.lower()) self.spicyArray.append(spicy.lower()) self.favNationalityArray.append(favNationality.lower()) self.secondFavNationalityArray.append(secondFavNationality.lower()) self.thirdFavNationalityArray.append(thirdFavNationality.lower()) self.countryArray.append(country.lower()) def getGenderArray(self): #Returns the requested data return self.genderArray def getNationalityArray(self): return self.nationalityArray def getAgeArray(self): return self.ageArray def getSpicyArray(self): return self.spicyArray def getFavNationalityArray(self): return self.favNationalityArray def getSecondFavNationalityArray(self): return self.secondFavNationalityArray def getThirdFavNationalityArray(self): return self.thirdFavNationalityArray def getCountryArray(self): return self.countryArray
b79374cf976930eacc42cf1d87adde3f7f1c8681
tylerBrittain42/cse-111-project
/myComicList/my_comic_list.py
33,537
3.671875
4
import sqlite3 from sqlite3 import Error def openConnection(_dbFile): #print("++++++++++++++++++++++++++++++++++") #print("Open database: ", _dbFile) conn = None try: conn = sqlite3.connect(_dbFile) print("Connection Success") except Error as e: print(e) #print("++++++++++++++++++++++++++++++++++") return conn def closeConnection(_conn, _dbFile): #print("++++++++++++++++++++++++++++++++++") #print("Close database: ", _dbFile) try: _conn.close() print("Close success") except Error as e: print(e) #print("++++++++++++++++++++++++++++++++++") #Initial database setup ############################################################################################################### #Creates all the relevant tables def createTable(_conn): #print("++++++++++++++++++++++++++++++++++") #print("Create table") try: print('createTable') #Issues sql = """CREATE TABLE Issues ( i_id decimal(9,0) NOT NULL PRIMARY KEY, i_title char(50) NOT NULL, i_issue char(50), --considering removing this i_date date(4,0) NOT NULL, i_srp decimal(2,2) NOT NULL )""" _conn.execute(sql) #readerList #sql = """CREATE TABLE readerList( # r_id decimal(9,0) NOT NULL PRIMARY KEY, # r_name char(50) NOT NULL) """ #_conn.execute(sql) #readingList sql = """CREATE TABLE ReadingList( rl_readerID decimal(9,0) NOT NULL, rl_issueID char(4) NOT NULL, rl_ownStat char(10) NOT NULL ) """ _conn.execute(sql) #FollowList sql = """CREATE TABLE FollowList( fl_id decimal(9,0) NOT NULL, fl_issueID char(4) NOT NULL --Do i need to change this part? --fl_artistID decimal(9,0) NOT NULL, --fl_writerID decimal(9,0) NOT NULL ) """ _conn.execute(sql) #artist sql = """CREATE TABLE Artist( a_id decimal(9,0) NOT NULL PRIMARY KEY, a_name char(50) NOT NULL )""" _conn.execute(sql) #Writer sql = """CREATE TABLE Writer( w_id decimal(9,0) NOT NULL PRIMARY KEY, w_name char(50) NOT NULL ) """ _conn.execute(sql) #ReccList sql = """CREATE TABLE ReccList( --r_aId decimal(9,0) NOT NULL, --r_wId decimal(9,0) NOT NULL, rc_readerID decimal(9,0) NOT NULL, rc_issueID decimal(9,0) NOT NULL )""" _conn.execute(sql) #userCost sql = """CREATE TABLE userCost( u_id decimal(9,0) NOT NULL PRIMARY KEY, u_cost decimal(4,2) NOT NULL )""" _conn.execute(sql) print('create tablee done') except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Drops all tables in the database def dropTable(_conn, reader): #print("++++++++++++++++++++++++++++++++++") #print("Drop tables") try: print((reader)) print('dropping') sql = """DROP TABLE Issues""" _conn.execute(sql) #sql = "DROP TABLE readerList" #_conn.execute(sql) sql = """DELETE FROM readerList WHERE ? <> r_id""" args = [reader] _conn.execute(sql, args) sql = "DROP TABLE ReadingList" _conn.execute(sql) sql = "DROP TABLE FollowList" _conn.execute(sql) sql = "DROP TABLE Artist" _conn.execute(sql) sql = "DROP TABLE Writer" _conn.execute(sql) sql = "DROP TABLE ReccList" _conn.execute(sql) sql = "DROP TABLE UserCost" _conn.execute(sql) print('Drop table success') except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Inserts information from txt file into Issues def populateIssues(_conn): #print("++++++++++++++++++++++++++++++++++") #print("Populate issues") try: inF = open("data/pull_w_tabs.txt", "r") contents = inF.readlines() for x in contents: currentIssue = x.split('\t') sql = """ INSERT INTO Issues(i_id, i_title, i_issue, i_date, i_srp) VALUES(?, ?, ?, ?, ?) """ args = [currentIssue[0], currentIssue[1], currentIssue[2], currentIssue[3], currentIssue[4]] _conn.execute(sql, args) print('Populate Issues success') except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Inserts from text file into Writer and Artist tables def populateCreative(_conn): #print("++++++++++++++++++++++++++++++++++") #print("Populate creative") try: inF = open("data/revisedCreator.txt", "r") contents = inF.readlines() #Since the writer and artists are stored in the same line, we will insert into both lists at the same time for x in contents: currentLine= x.split('\t') currentID = currentLine[0] for y in range(len(currentLine)): currentLine[y] = currentLine[y].split(")") sql = """ INSERT INTO Artist(a_id, a_name) VALUES(?, ?) """ args = [currentID, (currentLine[2][1])] _conn.execute(sql, args) sql = """ INSERT INTO Writer(w_id, w_name) VALUES(?, ?) """ args = [currentID, (currentLine[1][1])] _conn.execute(sql, args) print('PopulateCreative success') except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Reader List operatoins ############################################################################################################ #Addes a new reader def addReader(_conn, reader): #print("++++++++++++++++++++++++++++++++++") #print("Add reader") try: sql = """ SELECT MAX(r_id) FROM readerList """ cur = _conn.cursor() cur.execute(sql) readerMaxId = cur.fetchone() nextID = 0 nextID = readerMaxId[0] print(nextID) print(type(0)) x = int(nextID) + 1 sql = """ INSERT INTO readerList(r_id, r_name) VALUES (?, ?) """ args = [(x), reader] _conn.execute(sql, args) print('Added reader ' + reader + " successfully") except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Views a list of all readers def viewReaderList(_conn): #print("++++++++++++++++++++++++++++++++++") print("\nReaderList\n") try: sql = """ SELECT * FROM readerList """ cur = _conn.cursor() cur.execute(sql) l = '{:<20}{:<30}'.format("ID", "Name") print(l) readerCount = cur.fetchall() # for x in readerCount: # print(x) for x in readerCount: l = '{:<20}{:<30}'.format(x[0], x[1]) print(l) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #when we are deleting a reader def deleteReader(_conn, reader): #print("++++++++++++++++++++++++++++++++++") #print("Delete reader" + reader) try: sql = """DELETE FROM readerList WHERE r_id = ?""" args = [reader] _conn.execute(sql, args) sql = """DELETE FROM FollowList WHERE fl_id = ?""" args = [reader] _conn.execute(sql, args) sql = """DELETE FROM ReadingList WHERE ? = rl_readerID""" args = [reader] _conn.execute(sql, args) sql = """DELETE FROM ReccList WHERE rc_issueID = ?""" args = [reader] _conn.execute(sql, args) sql = """DELETE FROM userCost WHERE u_id = ?""" args = [reader] _conn.execute(sql, args) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Recc List ############################################################################################################### #Updating is a three step process #Remove all entries from this readerID #Select all new recommendations #insert all new recommendations #Note: we only update for a single user at a time #We will call this function anytime a change is made to a user's followinglist def updateReccList(_conn, readerID): #print("++++++++++++++++++++++++++++++++++") try: #Deleting all entries sql = """DELETE FROM reccList WHERE rc_readerID = ?""" args = [readerID] _conn.execute(sql, args) #Selecting all new recommendations sql = """SELECT DISTINCT(i_id) FROM ( SELECT i_id--(i_title || i_issue) AS issueTitle, Writers, a_name --Writers, Writer.w_id FROM Writer,Issues,Artist, ( SELECT fl_id , w_name AS 'Writers'--, a_name AS 'Artists', fl_issueID AS sq1_id, * FROM FollowList, Writer,Artist WHERE a_id = fl_issueID AND w_id = fl_issueID AND fl_id = ? )sq1 WHERE Writer.w_name = Writers AND Writer.w_id = i_id AND Artist.a_id = i_id UNION --Selects issues with the same artists SELECT i_id--(i_title || i_issue) AS issueTitle, Writer.w_name AS Writers, a_name FROM Writer,Issues,Artist, ( SELECT fl_id , a_name AS 'Artists' FROM FollowList, Writer,Artist WHERE a_id = fl_issueID AND w_id = fl_issueID AND fl_id = ? )sq1 WHERE Artist.a_name = Artists AND Writer.w_id = i_id AND Artist.a_id = i_id )sq1 """ cur = _conn.cursor() args = [readerID, readerID] cur.execute(sql, args) toAdd = cur.fetchall() #inserting all new recomendations for x in toAdd: sql = """INSERT INTO ReccList(rc_readerID, rc_issueID) VALUES (?, ?)""" args = [readerID, x[0]] _conn.execute(sql, args) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Views a user's recommended list #Note: it is rare for a single artist to work on multiple books at a time so the majority of #recommendations shown will be based off of the writer def viewRecclist(_conn, readerID): #print("++++++++++++++++++++++++++++++++++") print('\n' + getName(_conn,readerID) + "'s recc list\n") try: sql = """SELECT i_id,(i_title || i_issue) AS issueTitle, i_date, i_srp FROM Issues, ReccList WHERE i_id = rc_issueID AND rc_readerID = ?""" cur = _conn.cursor() args = [readerID] cur.execute(sql, args) l = '{:<10}{:<65}{:<35}{:<35}'.format('ID','Issue Title', 'Date', 'SRP') print(l + '\n') readerCount = cur.fetchall() for x in readerCount: # print(x[0] + "\t" + x[1] + "\t" + x[2]) # print(x) l = '{:<10}{:<65}{:<35}{:<35}'.format(x[0], x[1], x[2], x[3]) print(l) except Error as e: print(e) _conn.rollback() #Issue, writer, artist operations ############################################################################################################### #Views a list of all of the issues def viewIssues(_conn): #print("++++++++++++++++++++++++++++++++++") print("IssueList") try: sql = """ SELECT * FROM Issues,Writer,Artist WHERE i_id = a_id AND i_id = w_id ORDER BY i_id ASC """ cur = _conn.cursor() cur.execute(sql) l = '{:<5}{:<45}{:<50}{:<15}{:<15}{:<35}{:<35}'.format('ID', 'Title', 'Issue Number', 'Date', 'Price', 'Writers', 'Artists') print(l) readerCount = cur.fetchall() #print(str(x[0]) + "\t" + x[1] + "\t" + x[2].split(' ')[0] + "\t" + x[3] + "\t" + x[4] + "\t" + x[6] + "\t" + x[8]) for x in readerCount: l = '{:<5}{:<45}{:<50}{:<15}{:<15}{:<35}{:<35}'.format(x[0], x[1], x[2], x[3], x[4], x[6], x[8]) print(l) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Views a list of all of the writers def viewWriters(_conn): #print("++++++++++++++++++++++++++++++++++") print("Writer List") try: sql = """ SELECT DISTINCT(w_name) FROM Writer ORDER BY w_name ASC """ cur = _conn.cursor() cur.execute(sql) l = '{:<25}'.format("Name") print(l) readerCount = cur.fetchall() for x in readerCount: # print(x[0]) l = '{:<25}'.format(x[0]) print(l) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Views a list of all of the artists def viewArtists(_conn): #print("++++++++++++++++++++++++++++++++++") print("Artist List") try: sql = """ SELECT DISTINCT(a_name) FROM Artist ORDER BY a_name ASC """ cur = _conn.cursor() cur.execute(sql) l = '{:<25}'.format("Name") print(l) readerCount = cur.fetchall() for x in readerCount: # print(x[0]) l = '{:<25}'.format(x[0]) print(l) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Reading list(of a reader) operations ############################################################################################################### #Adds an issue to a reading list def addToReadingList(_conn, userID, issueID,ownership): #print("++++++++++++++++++++++++++++++++++") #print("Add " + str(issueID) + " to " + str(userID) + "'s reading list") try: #rl_ownStat key #w = want #o = own #m = maybe sql = """ INSERT INTO ReadingList(rl_readerID, rl_issueID, rl_ownStat) VALUES (?, ?, ?) """ args = [userID, issueID, ownership] cur = _conn.cursor() cur.execute(sql, args) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Deletes deletes an issue from a reading list def deleteFromReadingList(_conn,reader, issue): #print("++++++++++++++++++++++++++++++++++") #print("Deleting " + str(issue) + " from " + str(reader) + "'s reading list") try: sql = """DELETE FROM ReadingList WHERE rl_readerID = ? AND rl_issueID = ?""" args = [reader, issue] _conn.execute(sql, args) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Changes the ownnership status of a single issue from a reading def changeOwnership(_conn, readerID, issueID, newStatus): #print("++++++++++++++++++++++++++++++++++") #print("Updating " + str(readerID) + "'s reading list") try: sql = """UPDATE readingList SET rl_ownStat = ? WHERE rl_readerID = ? AND rl_issueID = ?""" args = [newStatus, readerID, issueID] _conn.execute(sql, args) print("\n") except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #View everyone's reading list def viewAllReadingLists(_conn): #print("++++++++++++++++++++++++++++++++++") print('{:>65}'.format("View all reading lists")) try: sql = """ SELECT r_name,i_title,i_issue, rl_ownStat FROM ReadingList, readerList, Issues WHERE r_id = rl_readerID AND i_id = rl_issueID ORDER BY rl_readerID, rl_issueID asc """ cur = _conn.cursor() cur.execute(sql) l = '{:<25}{:<35}{:<45}{:<55}'.format('Name', 'Title', 'Issue', 'Own Status') print(l) readerCount = cur.fetchall() for x in readerCount: # print(x[0] + "\t" + x[1] + "\t" + x[2].split(' ')[0] + "\t" + x[3]) l = '{:<25}{:<35}{:<45}{:<55}'.format(x[0], x[1], x[2], x[3]) print(l) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #View a specific reading list def viewSpecReadingList(_conn, readerID): #print("++++++++++++++++++++++++++++++++++") print(getName(_conn,readerID) + "'s reading lists\n") try: sql = """SELECT rl_issueID,i_title,i_issue, rl_ownStat FROM ReadingList, readerList, Issues WHERE r_id = rl_readerID AND i_id = rl_issueID AND r_id = ? ORDER BY rl_issueID asc """ args = [readerID] cur = _conn.cursor() cur.execute(sql, args) l = '{:<20}{:<35}{:<45}{:<5}'.format('Key', 'Title', 'Issue', 'Own Status') print(l) readerCount = cur.fetchall() for x in readerCount: # print(x[1] + "\t" + x[2].split(' ')[0] + "\t" + x[3]) l = '{:<20}{:<35}{:<45}{:<5}'.format(x[0], x[1], x[2], x[3]) print(l) except Error as e: _conn.rollback() print(e) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Follow list ############################################################################################################### #Creators are added to a followlist based on an issue that they create #Adds a creative team to a follow list def addToFollowList(_conn, userID, issueID): #print("++++++++++++++++++++++++++++++++++") #print("Add " + str(issueID) + " to " + str(userID) + "'s followList") try: sql = """ INSERT INTO FollowList(fl_id, fl_issueID) VALUES (?, ?) """ args = [userID, issueID] cur = _conn.cursor() cur.execute(sql, args) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Deletes a creative team from a follow list def deleteFromFollowList(_conn,reader, issue): #print("++++++++++++++++++++++++++++++++++") #print("Deleting " + str(issue) + " from " + str(reader) + "'s following list") try: #Can find reader id given a name # sql = """ SELECT r_id # FROM readerList # WHERE r_name = ? # """ # args = [reader] # cur = _conn.cursor() # cur.execute(sql, args) # deletedReader = cur.fetchall()[0][0] sql = """DELETE FROM followList WHERE fl_id = ? AND fl_issueID = ?""" #args = [deletedReader, issue] args = [reader, issue] _conn.execute(sql, args) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #for now we will add in all creators from a specific issue to the following list def viewFollowList(_conn, userID): #print("++++++++++++++++++++++++++++++++++") print("\n " + getName(_conn,userID) + "'s followList\n") try: sql = """SELECT fl_issueID, w_name AS 'Writers', a_name AS 'Artists' FROM FollowList, Writer,Artist WHERE a_id = fl_issueID AND w_id = fl_issueID AND fl_id = ? """ args = [userID] cur = _conn.cursor() cur.execute(sql, args) l = '{0:<45}{1:<45}{2:<45}'.format('Key',' Writers', ' Artists') print(l) following = cur.fetchall() for x in following: # print(x) l = '{0:<45}{1:<45}{2:<45}'.format(x[0],x[1],x[2]) print(l) except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") #Calculates the cost of a user's list #same 3 steps as recc list def updateUserCost(_conn): #print("++++++++++++++++++++++++++++++++++") try: #Delete sql = """DELETE FROM userCost""" _conn.execute(sql) #Select sql = """SELECT r_id, SUM(SUBSTR(i_srp, 7)) AS 'pullList price' FROM Issues, ReadingList, readerList WHERE i_id = rl_issueID AND rl_readerID = r_ID AND rl_ownStat = 'w' GROUP BY r_name """ cur = _conn.cursor() cur.execute(sql) toAdd = cur.fetchall() for x in toAdd: sql = """INSERT INTO userCost(u_id, u_cost) VALUES(?, ?)""" args = [x[0], x[1]] _conn.execute(sql, args) print() except Error as e: _conn.rollback() print(e) #print("++++++++++++++++++++++++++++++++++") def viewSingleUserCost(_conn, userID): #print("++++++++++++++++++++++++++++++++++") try: sql = """SELECT r_name, u_cost FROM userCost,readerList WHERE u_id = r_id AND r_ID = ? """ args = [userID] cur = _conn.cursor() cur.execute(sql,args) print(getName(_conn,userID) + "'s cost list\n") l = '{:<20}{:<10}'.format("Name", "Cost") print(l) readerCount = cur.fetchall() for x in readerCount: # print(x) #print(x) l = '{:<20}{:<10}'.format(x[0], x[1]) print(l) except Error as e: print(e) _conn.rollback() def viewAllUserCost(_conn): #print("++++++++++++++++++++++++++++++++++") try: sql = """SELECT r_name, u_cost FROM userCost,readerList WHERE u_id = r_id """ cur = _conn.cursor() cur.execute(sql) print("Viewing all cost lists\n") l = '{:<20}{:<10}'.format("Name", "Cost") print(l) readerCount = cur.fetchall() for x in readerCount: # print(x) #print(x) l = '{:<20}{:<10}'.format(x[0], x[1]) print(l) except Error as e: print(e) _conn.rollback() #Rearrange THESE IN LATER ##############################################3333 def updateReadingList(_conn, id): viewSpecReadingList(_conn,id) print() print(' 1) {0:<10}'.format('Add')) print(' 2) {0:<10}'.format('Delete')) print(' 3) {0:<10}'.format('Edit Ownership status')) option = input("\nSelect an action: ") toDel = 1 toAdd = 1 toStat = 'w' print('\n') if option == '1': viewIssues(_conn) print('Enter the key and ownership status(w, o, m)') print('Enter 0 to stop adding issues') while(int(toAdd) != 0): print() toAdd = input('Key: ') if (int(toAdd) != 0): toStat = input('Ownership status: ') addToReadingList(_conn,id,int(toAdd),toStat) topBorder() elif option == '2': topBorder() viewSpecReadingList(_conn,id) print('\nEnter the key of the Issue you want deleted') print('Enter 0 to stop deleting') print() while(int(toDel) != 0): toDel = input('Key: ') if (int(toDel) != 0): deleteFromReadingList(_conn,id,toDel) topBorder() viewSpecReadingList(_conn,id) elif option == '3': topBorder() viewSpecReadingList(_conn,id) print('\nEnter the key and new ownership status(w, o, m)') print('Enter 0 to stop adding issues') while(int(toAdd) != 0): toAdd = input('\nKey: ') if (int(toAdd) != 0): toStat = input('New ownership status: ') changeOwnership(_conn,id,int(toAdd),toStat) topBorder() viewSpecReadingList(_conn,id) def updateFollowList(_conn, id): viewFollowList(_conn, id) print() print(' 1) {0:<10}'.format('Add')) print(' 2) {0:<10}'.format('Delete')) print(' 3) {0:<10}'.format('Exit\n')) option = input("Select an action: ") toDel = 1 toAdd = 1 print('\n') if option == '1': viewIssues(_conn) print('Enter the key of the creative team you wish to follow') print('Enter 0 to stop\n') while(int(toAdd) != 0): toAdd = input('Key: ') if (int(toAdd) != 0): addToFollowList(_conn,id,toAdd) topBorder() elif option == '2': topBorder() viewFollowList(_conn,id) print('\nEnter the key of the creative team you want deleted') print('Enter 0 to stop deleting') print() while(int(toDel) != 0): print() toDel = input('Key: ') if (int(toDel) != 0): deleteFromFollowList(_conn,id,toDel) topBorder() viewFollowList(_conn,id) updateReccList(_conn,id) def getName(_conn, id): #print("++++++++++++++++++++++++++++++++++") try: sql = """ SELECT r_name FROM readerList WHERE r_id = ? """ args = [id] cur = _conn.cursor() cur.execute(sql, args) reader = cur.fetchall() return(reader[0][0]) print('viewReaderlist success') except Error as e: _conn.rollback() print(e) def switchUser(_conn, id): print() viewReaderList(_conn) print('\nEnter the user id that you wish to select') newId = int(input('User id: ')) return(newId) def updateUser(_conn): print('update user list called\n') viewReaderList(_conn) print() newName = input('Please enter new name: ') addReader(_conn,newName) a = """ print(' 1) {0:>10}'.format('Add')) print(' 2) {0:>10}'.format('Delete')) option = input("Select an action: ") tempKey = 1 print('\n') id = str(id) if option == '1': newName = input('New name: ') addReader(_conn,newName) elif option == '2': viewReaderList(_conn) print('Enter the key of the user you want deleted') print('Enter 0 to stop deleting') print('\n') while((tempKey) != 0): tempKey = input('Key:') if(int(tempKey) == id): print('Cannot delete self') elif (int(tempKey) != 0): deleteReader(_conn, tempKey) viewReaderList(_conn)""" #Relating to formatting ############################################################################################################### def resetPTwo(_conn): try: sql = """UPDATE readerList SET r_name = 'John Smith' WHERE r_id""" _conn.execute(sql) except Error as e: _conn.rollback() print(e) #Resets the database def resetDB(conn, id): dropTable(conn, id) createTable(conn) populateIssues(conn) populateCreative(conn) addReader(conn,'temp') resetPTwo(conn) def topBorder(): top = "" for x in range(140): top = top + "_" print(top) def botBorder(): bot = "" for x in range(200): bot = bot + "_" print(bot) def populateUserLists(conn): addToFollowList(conn, 1, 20) #Bob addToFollowList(conn, 1, 193) #Bob addToFollowList(conn, 3, 196) #Jim #add another book jim addToReadingList(conn,2,20,'o')#Bob addToReadingList(conn,2,196 ,'o')#Bob addToReadingList(conn, 1, 193, 'w')#Jim addToReadingList(conn,3, 189, 'w')#Bob addToReadingList(conn,3, 534, 'w')#Bob def prompt(conn,id): #ref setnece #print('{0:>100}'.format('test')) topBorder() print('\n {0:^75}'.format('My Comic List')) print() try: print(' User: ' + getName(conn,id)) except IndexError: #try changing this TO just PROMPTING USER TO CREATE NAME #addReader(conn,'John Smith') ##print(' User: ' + getName(conn,id)) x = 0 print(' {0:^75}'.format('Reading List Actions')) print(' 1) {0:>10}'.format('View Issues')) print(' 2) {0:>10}'.format('View My Reading List')) print(' 3) {0:>10}'.format('Update Reading List')) print(' 4) {0:>10}'.format('View All Reading Lists')) print(' {0:^75}'.format('Follow List Actions')) print(' 5) {0:>10}'.format('View Following List')) print(' 6) {0:>10}'.format('Update Following List')) #Stopped here print(' 7) {0:>10}'.format('View Recc List')) print(' {0:^75}'.format('Cost List Actions')) print(' 8) {0:>10}'.format('View My Cost List')) print(' 9) {0:>10}'.format('View Everyones Cost List')) print(' {0:^75}'.format('Adminstrative Actions')) print(' 10) {0:>10}'.format('View Users')) print(' 11) {0:>10}'.format('Switch User')) print(' 12) {0:>5}'.format('Add User')) print(' 13) {0:>10}'.format('Reset Database')) print(' 14) {0:>5}'.format('EXIT\n')) #botBorder() def main(): database = r"data/comicDB.sqlite" option = 15 currUser = 1 # create a database connection conn = openConnection(database) with conn: #Testing intitial database setup #REMOVE THIS LINE POST TESTING #resetDB(conn) while option != '14': prompt(conn,currUser) option = input('Select an action: ') topBorder() try: if option == '1': viewIssues(conn) topBorder() elif option == '2': viewSpecReadingList(conn,currUser) topBorder() elif option == '3': updateReadingList(conn,currUser) elif option == '4': viewAllReadingLists(conn) elif option == '5': viewFollowList(conn,currUser) elif option == '6': updateFollowList(conn,currUser) elif option == '7': viewRecclist(conn,currUser) elif option == '8': updateUserCost(conn) viewSingleUserCost(conn,currUser) elif option == '9': updateUserCost(conn) viewAllUserCost(conn) elif option == '10': viewReaderList(conn) elif option == '11': currUser = switchUser(conn, id) elif option == '12': updateUser(conn) elif option == '13': currUser = 1 resetDB(conn, 1) elif option == '69': populateUserLists(conn) except ValueError: print("INVALID INPUT") spam = input("\nPress any key to continue") if option != '14' and option != '3' and option != '6' and option != '11' and option != '12' : spam = input("\nPress any key to continue") closeConnection(conn, database) if __name__ == '__main__': main()
3cc8ae521a848aa3ab7670262bc5abe6378c74ef
AdamZhouSE/pythonHomework
/Code/CodeRecords/2172/60604/267797.py
1,543
3.90625
4
def priority(z): if z in ['×', '*', '/']: return 2 elif z=='^': return 3 elif z in ['+', '-']: return 1 def in2post(expr): stack = [] # 存储栈 post = [] # 后缀表达式存储 for z in expr: if z not in ['×', '*', '/', '+', '-', '(', ')','^']: # 字符直接输出 post.append(z) #print(1, post) else: if z != ')' and (not stack or z == '(' or stack[-1] == '(' or priority(z) > priority(stack[-1])): # stack 不空;栈顶为(;优先级大于 stack.append(z) # 运算符入栈 elif z == ')': # 右括号出栈 while True: x = stack.pop() if x != '(': post.append(x) #print(2, post) else: break else: # 比较运算符优先级,看是否入栈出栈 while True: if stack and stack[-1] != '(' and priority(z) <= priority(stack[-1]): post.append(stack.pop()) #print(3, post) else: stack.append(z) break while stack: # 还未出栈的运算符,需要加到表达式末尾 post.append(stack.pop()) return ''.join(post) n=int(input()) for I in range(n): x=input() #print(x) print(in2post(x))
59d26e57c578e0f7ecd6919a33ae766d89203616
seonhan427/python-study-unictre-
/2021.03.29/while_1.py
225
3.96875
4
i = 0 while i < 10: print(i, end=" ") i = i + 1 # 출력값과 변수값의 순서는 중요 # 대부분의 증감문들은 문장 제일 아래에 둔다 """ for i range (10): print(i, end=" ") """
266199b9f3f663e58e9e207c6f0c5a0bee67b204
ducang/python
/session8/crud.py
724
4.03125
4
lis = ['1','2','3'] print(lis) while True: action = input('enter action (C;R;U;D) or Exit:') if action == 'C': add = input('enter ur number:') lis.append(add) print('ur list here:',lis) elif action == 'R': if lis == []: print('list has nothing inside') else: for i in lis: print(i) elif action == 'U': update = input('update ur number:') position = int(input('enter the position:')) - 1 lis[position] = update print('new list:',lis) elif action == 'exit': break else: delete = input('enter what you want to delete:') lis.remove(delete) print(lis)
86a32918c2d82a435042553c90529198f6dabc58
MARGARITADO/Mision_04
/Triangulos.py
1,388
4.25
4
#Autor: Martha Margarita Dorantes Cordero #Identificar tipo de triángulo def identificarTipo(l1, l2, l3) : #Función que realiza la operación requerida para identificar el tipo de triángulo con las medidas recibidas. #Si todos los lados son iguales es un equilátero. #Si dos de los lados son iguales es un isósceles. #Si todos los lados son diferentes es un escaleno. if((l1 == l2) and (l2 == l3)) : return "equilátero" elif((l1 == l2) or (l1 == l3) or (l2 == l3)) : return "isósceles" elif((l1 != l2) or (l1 != l3) or (l2 != l3)) : return "escaleno" else : return "otro" def main() : #Función principal que solicita la longitud de cada uno de los lados de un triángulo y llama a la función #previamente definida para identificar el tipo de triángulo. #Si alguno de los lados tiene una longitud de 0 o negativa, se imprime la leyenda de que el triángulo no existe. lado1 = float(input("\n Ingrese la longitud del primer lado del triángulo: ")) lado2 = float(input(" Ingrese la longitud del segundo lado del triángulo: ")) lado3 = float(input(" Ingrese la longitud del tercer lado del triángulo: ")) if((lado1 <= 0) or (lado2 <= 0) or (lado3 <= 0)) : print("\n El triángulo con las medidas ingresadas no existe.") else : print('\n Las medidas ingresadas corresponden a un triángulo %s.'%(identificarTipo(lado1, lado2, lado3))) main()
e3c364cac5b7ba35ef8592ee5ab72444f09d4e26
sandykramb/PythonBasicConcepts
/Second_counter.py
420
3.6875
4
segundos_str = input("Por favor, entre com o número de segundos que deseja converter:") total_segs = int(segundos_str) days = total_segs // 86400 segs_restantes = total_segs % 86400 horas = segs_restantes // 3600 segs_restantes2 = total_segs % 3600 minutos = segs_restantes2 // 60 segs_restantes_final = segs_restantes % 60 print(days,"dias,",horas,"horas,",minutos,"minutos e",segs_restantes_final,"segundos.")
48d8316e46e0bc58d52f30ef051833845ce8cea3
andresilmor/Python-Exercises
/Ficha N4/ex01.py
541
4.0625
4
#Desenvolver um programa que vá lendo do teclado números inteiros até que a #soma desses números atinja ou ultrapasse um limite máximo indicado previamente #pelo utilizador. O algoritmo deverá no final dizer quantos foram os valores #digitados. def soma2(): try: num=int(input('Indique um número: ')) except ValueError: print('Não foi inserido um número.') soma=cont=0 while soma<num: cont+=1 soma+=cont print('Foram inserido ao todo %d números.' %cont) soma2()
0df8c6d53c9011e0d4e90da899602acb148ec57b
RonanLeanardo11/Python-Lectures
/Lectures, Labs & Exams/Lecture Notes/Lect 5 - Classes and Definitions/lect5Classes.py
1,142
4.4375
4
# Define class and attributes class car: make = "Unknown" model = "Unknown" engineCC = 1.2 # "Objects" or "Instances" of a class Mercedes = car() # assign Mercedes object to car class BMW = car() # assign BMW object to car class Audi = car() # assign Audi object to car class print(car) # prints <class '__main__.Car’> print(Mercedes) # prints <__main__.Car object at 0x029636D0> print(BMW) # prints <__main__.Car object at 0x029636D0> print(Audi) # prints <__main__.Car object at 0x029636D0> print("\n-------------------\n") print(Mercedes.make) # prints make from class above i.e. Unknown print(Mercedes.model) # prints model from class above i.e. Unknown print(Mercedes.engineCC) # prints engine size from class above i.e 1.2 print("\n-------------------\n") Mercedes.make = "Mercedes" # assign new values to the object Mercedes.model = "C-Class" # assign new values to the object Mercedes.engineCC = 3.0 # assign new values to the object print(Mercedes.make) # prints newly assigned make value print(Mercedes.model) # prints newly assigned model value print(Mercedes.engineCC) # prints newly assigned engine CC value
db074e8eba6f955e20feba2b218e299f7351c7e2
011235813etc/QA_tests_stepik_course_homework
/chapter_2/lesson3_step6.py
2,232
3.53125
4
""" Задание: переход на новую вкладку В этом задании после нажатия кнопки страница откроется в новой вкладке, нужно переключить WebDriver на новую вкладку и решить в ней задачу. Сценарий для реализации выглядит так: - Открыть страницу http://suninjuly.github.io/redirect_accept.html - Нажать на кнопку - Переключиться на новую вкладку - Пройти капчу для робота и получить число-ответ Если все сделано правильно и достаточно быстро (в этой задаче тоже есть ограничение по времени), вы увидите окно с числом. Отправьте полученное число в качестве ответа на это задание. """ from selenium import webdriver import time import math def calc(x): return str(math.log(abs(12*math.sin(int(x))))) if __name__ == "__main__": try: link = "http://suninjuly.github.io/redirect_accept.html" browser = webdriver.Chrome() browser.get(link) # Нажимаем на кнопку для запуска задачи browser.find_element_by_css_selector("button.btn").click() # Переключаемся на следующее окно new_window = browser.window_handles[1] browser.switch_to.window(new_window) # Получаем значение x x = browser.find_element_by_id("input_value").text y = calc(x) # Заполняем форму browser.find_element_by_id("answer").send_keys(y) # Отправляем заполненную форму browser.find_element_by_css_selector("button.btn").click() finally: # ожидание чтобы визуально оценить результаты прохождения скрипта time.sleep(10) # закрываем браузер после всех манипуляций browser.quit()
fef5c8706e2e297a4bbda5d3d3288b0e8cdebb76
ppapuli/Portfolio
/Puzzles/ImportDecklist.py
969
3.515625
4
# This script will read a text file to clean up a decklist to import into Cockatrice # Type the name of your text file that will be manipulated #----------------------------------------------------------# textfile = 'Marwyn.txt' #----------------------------------------------------------# # open the file so we can write and alter file = open(textfile, 'r+') # define a function that will truncate the line argument past the first open parenthesis def TextSplit(line): sep = '(' txt = line return txt.split(sep, 1)[0] # create a dummy array that will hold our data cleanText = [] # import all of our cleaned up line data into an array for line in file: cleanText.append(TextSplit(line) + '\n') # first erase the previous data, then rewrite using the data saved in the array file.truncate(0) for line in cleanText: file.write(line) # Close the file once we are done so it doesn't use memory file.close()
991753395dc9e46d7e0e87080e125102a4bd1fda
chunchuvishnuvardhan/panagram
/p2.py
329
3.921875
4
import string str=input("enter your string") st=str.upper() a=string.ascii_uppercase answer=1 for i in a: for j in st: if i in st: break else: answer=answer+1 break if answer==2: print("its not a pangram") break else: print("its a pangram")
40ea42f58988f63ede281ef3655e556ae3e94270
logsdond4/Covid-Comorbidities
/Data Wrangle/data_filter_clean_analysis.py
1,207
3.640625
4
# -*- coding: utf-8 -*- """ Author: Dan Logsdon Date: 10/11/2020 Description: This code analyzes the CDC's data related to Covid deaths and comorbidities. Limitations: The CDC did not provide record level data, which means that it is impossible to do analysis by individual ICD10 code. """ #Package Imports import pandas as pd import os #%% File Import root = os.path.dirname(os.path.dirname(__file__)) #root folder src = root + '\\src' #source folder file = src + '\\Covid-19_comorbidities.csv' #input file df=pd.read_csv(file) #%% Functions def df_filter(df): df=df[df.State=='US'] #removed state data df=df[df['Age Group']== 'All Ages'] #remove ages return df def df_calc(df): #new row for COVID-19 deaths with no comorbidities, CDC specified this was 6% of total new_row = {'Condition Group':'Covid-19 Only', 'ICD10_codes':'U071', 'Number of COVID-19 Deaths':int(total_deaths*0.06)} df = df.append(new_row, ignore_index=True) df['percent_deaths']=df['Number of COVID-19 Deaths']/total_deaths*100 return df #%% Filter df=df_filter(df) #%% Globals total_deaths=int(df[df['Condition Group']=='COVID-19']['Number of COVID-19 Deaths']) #%% Analysis df=df_calc(df)
a67d7302faf3a1f4377c08a7f1ad5a0d32669408
williamboco21/pythonfundamentals
/FUNDPRO/temperature.py
838
4.3125
4
print(f'TEMPERATURE CONVERSION PROGRAM') print(f'------------------------------\n') print("Options:\n") print(f'1. Convert Celsius to Fahrenheit\n' f'2. Convert Fahrenheit to Celsius\n' f'3. Exit Program\n') choice = int(input("Enter your choice: ")) if choice == 1: celsius = int(input("\nEnter temperature in Celsius: ")) fahrenheit = (9 / 5) * celsius + 32 print(f'\nThe temperature in Celsius is {fahrenheit}.\n') elif choice == 2: fahrenheit = int(input("\nEnter temperature in Fahrenheit: ")) celsius = 5 / 9 * (fahrenheit - 32) print(f'\nThe temperature in Celsius is {celsius}.\n') elif choice == 3: print("\nProgram Exiting!\n") print("Thank you for using this program!") exit() else: print("\nInvalid entry! Please try again!\n") print("Thank you for using this program!")
af1644c2a3f2b282f13575de10643fe7c4803ada
rarose67/Python-practice-
/Exercises/Ch3. Ex.py
8,292
4.34375
4
""" 1. Below is a short program that prompts the user to input the number of miles they are to drive on a given trip and converts their answer to kilometers, printing the result. However, it doesn’t work properly. Find and fix the error in the program. miles = input("How many miles do you have to drive? ") kilometers = miles * 1.60934 print("That distance is equal to", kilometers, "kilometers") """ miles = input("How many miles do you have to drive? ") miles = float(miles) kilometers = miles * 1.60934 print("That distance is equal to", kilometers, "kilometers") """ 2. Picture a compass where 0 degrees represents North, 90 degrees represents East, and so on, all the way around to 360 degrees, which is again the same as 0 degrees: true north. The program below envisions the scenario in which a person is facing North (aka 0 degrees) and spins some number of rotations, either clockwise or counter-clockwise (-1 represents a full counter-clockwise spin and 1 represents a full clockwise spin). It calculates the direction they end up facing in degrees. However, it doesn’t work properly. Find and fix the error in the program. spins = input("How many times did you spin? (Enter a negative number for counter-clockwise spins) ") degrees = float(spins) * 360 print("You are facing", degrees, "degrees relative to north") """ spins = input("How many times did you spin? (Enter a negative number for counter-clockwise spins) ") degrees = float(spins) * 360 if degrees < 0: degrees = 360 + degrees quad = degrees // 90 if quad == 0: direction = "North" if quad == 1.0: direction = "East" if quad == 2.0: direction = "South" if quad == 3.0: direction = "West" if quad == 4.0: print("You are facing 0 degrees relative to north") else: print("You are facing", (degrees % 90), "degrees relative to", direction) """ 3. ou’ve written a program to convert degrees Celsius to degrees Fahrenheit. The program below makes the conversion in the opposite direction, from Fahrenheit to Celsius. However, it doesn’t work properly. Find and fix the error in the program. current_temp_string = input("Enter a temperature in degrees Fahrenheit: ") current_temp = int(current_temp_string) current_temp_celsius = (current_tmp - 32) * (5/9) print("The temperature in Celsius is:", current_temp_celsius) """ current_temp_string = input("Enter a temperature in degrees Fahrenheit: ") current_temp = int(current_temp_string) current_temp_celsius = (current_temp - 32) * (5/9) print("The temperature in Celsius is:", current_temp_celsius) """ 4. Football Scores Suppose you’ve written the program below. The given program asks the user to input the number of touchdowns and field goals scored by an American football team, and prints out the team’s score. (We generously assume that for each touchdown, the team always makes the extra point.) The European Union has decided that they want to start an American football league, and they want to use your killer program to calculate scores, but they like things that are multiples of 10 (e.g. the Metric System), and have decided that touchdowns will be worth 10 points (including the extra point they might score) and field goals are worth 5 points. Modify the program below to work on both continents, and beyond. It should ask the user how many points a touchdown is worth and how many points a field goal is worth. Then it should ask in turn for both the number of touchdowns and the number of field goals scored, and then print the team’s total score. num_touchdowns = input("How many touchdowns were scored? ") num_field_goals = input("How many field goals were scored? ") total_score = 7 * int(num_touchdowns) + 3 * int(num_field_goals) print("The team has", total_score, "points") """ num_touchdowns = input("How many touchdowns were scored? ") num_field_goals = input("How many field goals were scored? ") continent = input('''Is this game for the European Union? (If so, enter "Y")''') if continent == "Y": total_score = 10 * int(num_touchdowns) + 5 * int(num_field_goals) else: total_score = 7 * int(num_touchdowns) + 3 * int(num_field_goals) print("The team has", total_score, "points") """Weekly Graded Assignment This is a tricky one! You have a thermostat that allows you to set the room to any temperature between 40 and 89 degrees. The thermostat can be adjusted by turning a circular dial. For instance, if the temperature is set to 50 degrees and you turn the dial 10 clicks toward the left, you will set the temperature to 40 degrees. But if you keep turning 1 click to the left (represented as -1) it will circle back around to 89 degrees. If you are at 40 degrees and turn to the right by one click, you will get 41 degrees. As you continue to turn to the right, the temperature goes up, and the temperature gets closer and closer to 89 degrees. But as soon as you complete one full rotation (50 clicks), the temperature cycles back around to 40 degrees. Write a program that calculates the temperature based on how much the dial has been turned. The number of clicks (from the starting point of 40 degrees) is contained in a variable. You should print the current temperature for each given click variable so that your output is as follows: The temperature is 40 The temperature is 89 The temperature is 64 The temperature is 41 The temperature is 89 The temperature is 40 """ #For each click variable, calculate the temperature and print it as shown in the instructions temp = 40 reset = False click_1 = 0 # TODO calculate the temperature, and report it back to the user if click_1 == -1: temp = 89 reset = True if click_1 // 50 > 0: temp = 40 click_1 = click_1 % 50 new_temp = temp + click_1 if reset == False: if new_temp > 89: temp = 40 + (new_temp - 89) else: if new_temp < 40: temp = 89 - (40 - new_temp) else: temp = new_temp print("The temperature is", temp) reset = False click_2 = 49 # TODO calculate the temperature, and report it back to the user if click_2 == -1: temp = 89 reset = True if click_1 // 50 > 0: temp = 40 click_2 = click_2 % 50 new_temp = temp + click_2 if reset == False: if new_temp > 89: temp = 40 + (new_temp - 89) else: if new_temp < 40: temp = 89 - (40 - new_temp) else: temp = new_temp print("The temperature is", temp) reset = False click_3 = 74 # TODO calculate the temperature, and report it back to the user if click_3 == -1: temp = 89 reset = True if click_3 // 50 > 0: temp = 40 click_3 = click_3 % 50 new_temp = temp + click_3 if reset == False: if new_temp > 89: temp = 40 + (new_temp - 89) else: if new_temp < 40: temp = 89 - (40 - new_temp) else: temp = new_temp print("The temperature is", temp) reset = False click_4 = 51 # TODO calculate the temperature, and report it back to the user if click_4 == -1: temp = 89 reset = True if click_4 // 50 > 0: temp = 40 click_4 = click_4 % 50 new_temp = temp + click_4 if reset == False: if new_temp > 89: temp = 40 + (new_temp - 89) else: if new_temp < 40: temp = 89 - (40 - new_temp) else: temp = new_temp print("The temperature is", temp) reset = False click_5 = -1 # TODO calculate the temperature, and report it back to the user if click_5 == -1: temp = 89 reset = True if click_5 // 50 > 0: temp = 40 click_5 = click_5 % 50 new_temp = temp + click_5 if reset == False: if new_temp > 89: temp = 40 + (new_temp - 89) else: if new_temp < 40: temp = 89 - (40 - new_temp) else: temp = new_temp print("The temperature is", temp) reset = False click_6 = 200 # TODO calculate the temperature, and report it back to the user if click_6 == -1: temp = 89 reset = True if click_6 // 50 > 0: temp = 40 click_6 = click_6 % 50 new_temp = temp + click_6 if reset == False: if new_temp > 89: temp = 40 + (new_temp - 89) else: if new_temp < 40: temp = 89 - (40 - new_temp) else: temp = new_temp print("The temperature is", temp)