blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
cc7e59cd236bcd7099466fcd0c8ae81b08639a61
gratus907/Gratus_PS
/BOJ Originals/[BOJ Steps] BOJ 단계별로 풀어보기/[05] 실습 1/10817 세 수.py
120
3.578125
4
mem = input().split() a = 0 b = 1 for i in range (0,3) : mem[i] = int(mem[i]) smem = sorted(mem) print (smem[1])
5cb87538a3b33dd04ec2d3ded59f0524c04519c4
pkongjeen001118/awesome-python
/data-strucutre/dictionaries.py
480
4.375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # simple dictionary mybasket = {'apple':2.99,'orange':1.99,'milk':5.8} print(mybasket['apple']) # dictionary with list inside mynestedbasket = {'apple':2.99,'orange':1.99,'milk':['chocolate','stawbery']} print(mynestedbasket['milk'][1].upper()) # append more key mybasket['pizza'] = 4.5 print(mybasket) # get only keys print(mybasket.keys()) # get only values print(mybasket.values()) # get pair values print(mybasket.items())
23310258133eaae83937885a1edc2e5bd0e686ee
nischalshrestha/automatic_wat_discovery
/Notebooks/py/ariadneadler/xgboost-gridsearchcv-stratified-k-fold-top-5/xgboost-gridsearchcv-stratified-k-fold-top-5.py
6,366
3.703125
4
#!/usr/bin/env python # coding: utf-8 # ## Introduction ## # # This notebook is written in python. # The feature engineering is the work of Sina and the code below is inspired by ["Titanic best working classifier"][1]. # # # [1]: https://www.kaggle.com/sinakhorami/titanic-best-working-classifier # In[1]: import numpy as np import pandas as pd import re as re train1 = pd.read_csv('../input/train.csv', header = 0, dtype={'Age': np.float64}) test = pd.read_csv('../input/test.csv' , header = 0, dtype={'Age': np.float64}) train=train1.drop(columns=['Survived']) allfeat = pd.concat([train, test],axis=0) print (train.info()) print (train.shape) print (test.shape) # # Feature Engineering # # Firstly, we drop all the features we won't be using here. Cabin has a lot of missing values. Hence, it will not be used. Also, Ticket and PassengerId are not relevant to our predictions. # In[2]: allfeat=allfeat.drop(columns=['PassengerId','Cabin','Ticket']) # ## 1. Pclass ## # One hot encoding the values to represent different classes of the ship. # In[3]: allfeat=pd.concat([allfeat,pd.get_dummies(allfeat['Pclass'])], axis=1) #getting one hot encoding for PClass and concatenating as new columns allfeat=allfeat.drop(columns=['Pclass']) #column no longer needed # ## 2. Sex ## # In[4]: allfeat=pd.concat([allfeat,pd.get_dummies(allfeat['Sex'])], axis=1) #getting one hot encoding for Sex and concatenating as new columns allfeat=allfeat.drop(columns=['Sex']) #column no longer needed # ## 3. SibSp and Parch ## # With the number of siblings/spouse and the number of children/parents we can create new feature called Family Size. # In[5]: allfeat['FamilySize'] = allfeat['SibSp'] + allfeat['Parch'] + 1 allfeat=allfeat.drop(columns=['SibSp','Parch']) #column no longer needed # Another helpful feature would be to check whether they were travelling alone or not. # In[6]: allfeat['IsAlone'] = 0 allfeat.loc[allfeat['FamilySize'] == 1, 'IsAlone'] = 1 # ## 4. Embarked ## # The embarked feature has some missing values, so we try to fill those with the most frequent value ( 'S' ). # In[7]: allfeat['Embarked'] = allfeat['Embarked'].fillna('S') allfeat=pd.concat([allfeat,pd.get_dummies(allfeat['Embarked'])],axis=1) #one-hot encoding the embarked categories allfeat=allfeat.drop(columns='Embarked') #column no longer needed # ## 5. Fare ## # Fare also has some missing values which we will replace with the median. Then we categorize it into 4 ranges, to reduce noise. # In[8]: allfeat['Fare'] = allfeat['Fare'].fillna(train['Fare'].median()) allfeat['CategoricalFare'] = pd.qcut(allfeat['Fare'], 4) allfeat=pd.concat([allfeat,pd.get_dummies(allfeat['CategoricalFare'])],axis=1) #one-hot encoding the fare categories allfeat=allfeat.drop(columns=['Fare','CategoricalFare']) #column no longer needed # ## 6. Age ## # We have plenty of missing values in this feature. # generate random numbers between (mean - std) and (mean + std). # Again, to reduce noise, we categorize age into 5 range. # In[9]: avg=allfeat['Age'].mean() std=allfeat['Age'].std() allfeat['Age']=allfeat['Age'].fillna(value=np.random.randint(avg-std,avg+std)) allfeat['Age'] = allfeat['Age'].astype(int) allfeat['CategoricalAge'] = pd.cut(allfeat['Age'], 5) allfeat=pd.concat([allfeat,pd.get_dummies(allfeat['CategoricalAge'])],axis=1) #one-hot encoding the age categories allfeat=allfeat.drop(columns=['Age','CategoricalAge']) #column no longer needed # ## 7. Name ## # Here, we can find the titles of the passengers. # In[10]: def get_title(name): title_search = re.search(' ([A-Za-z]+)\.', name) # If the title exists, extract and return it. if title_search: return title_search.group(1) return "" allfeat['Title'] = allfeat['Name'].apply(get_title) allfeat=allfeat.drop(columns=['Name']) #column no longer needed # Now that we have titles... # In[11]: allfeat['Title'] = allfeat['Title'].replace(['Lady', 'Countess','Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare') allfeat['Title'] = allfeat['Title'].replace('Mlle', 'Miss') allfeat['Title'] = allfeat['Title'].replace('Ms', 'Miss') allfeat['Title'] = allfeat['Title'].replace('Mme', 'Mrs') allfeat=pd.concat([allfeat,pd.get_dummies(allfeat['Title'])],axis=1) #one-hot encoding the Title categories allfeat=allfeat.drop(columns='Title') #column no longer needed # Our dataset is almost ready. # In[12]: print (list(allfeat)) # In[13]: #for xgboost classifier to work, we must rename the columns, removing the header names containing '()' and '[]' allfeat.columns=['1', '2', '3', 'female', 'male', 'FamSize', 'IsAlone', 'C', 'Q', 'S', 'fare1', 'fare2', 'fare3', 'fare4', 'age1', 'age2', 'age3', 'age4', 'age5', 'Master', 'Miss', 'Mr', 'Mrs', 'Rare'] print (list(allfeat)) #now divide engineered dataset into train and test dataset X=allfeat[:][0:891] testdf=allfeat[:][891:1309] y=train1['Survived'] # # Applying Classifier using sklearn wrapper # # Trial and error showed that min_child_weight had the most contribution to increasing accuracy of the classifier, with or without best values of the other parameters. We use Stratified K-Fold cross validation to obtain best model. # In[14]: from xgboost import XGBClassifier from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedKFold from sklearn.metrics import accuracy_score param_grid = [{'min_child_weight': np.arange(0.1, 10.1, 0.1)}] #set of trial values for min_child_weight i=1 kf = StratifiedKFold(n_splits=10,random_state=1,shuffle=True) for train_index,test_index in kf.split(X,y): print('\n{} of kfold {}'.format(i,kf.n_splits)) xtr,xvl = X.loc[train_index],X.loc[test_index] ytr,yvl = y[train_index],y[test_index] model = GridSearchCV(XGBClassifier(), param_grid, cv=10, scoring= 'f1',iid=True) model.fit(xtr, ytr) print (model.best_params_) pred=model.predict(xvl) print('accuracy_score',accuracy_score(yvl,pred)) i+=1 # # Prediction # # We can use the same classifier we just trained. Finally, store the predicted array in a pandas DataFrame, and save in .csv file for submission. # In[15]: op=pd.DataFrame(data={'PassengerId':test['PassengerId'],'Survived':model.predict(testdf)}) op.to_csv('KFold_XGB_GridSearchCV_submission.csv',index=False)
1be6fb8430ecac7bd031eb6b9cff01bfd8745940
wandoufan/mycode
/study_note/python_learn/function/function_closure.py
925
4.3125
4
# 主要介绍python函数中的闭包closure概念 # 如果一个函数引用了其外层函数中的变量(不是全局变量),且外层函数的返回值是该函数的引用,则该函数就是闭包的 # 示例1:test2是一个闭包函数 # 注意:test1中的变量x也是局部变量,但是在test1的内部函数test2中也只能对x进行访问,不能修改 def test1(x): print('x:', x) def test2(y): print('y:', y) return x * y return test2 print(test1(5)) # x为5,y没有赋值 print('\n') print(test1(5)(8)) # x为5,y为8 # 示例2:装饰器中的wrapper函数是经典的闭包函数 import logging def get_run_log(func): """ 装饰器函数,记录包含函数名的日志信息 """ def wrapper(*args): logging.info('%s is running !' %func.__name__) func(*args) return wrapper @get_run_log def test1(): pass test1()
4578a59399c3511eea1ae768730db51762f1997e
karimeSalomon/API_Testing_Diplomado
/EduardoRocha/Primo.py
571
3.921875
4
def is_prime_number(x): if x >= 2: for y in range(2,x): if not ( x % y ): return False else: return False return True def calculate_prim(num1, num2): # list = [i for i in range(num1, num2)] result = [] for num in range(num1,num2): if is_prime_number(num): result.append(num) return result num1 = input('[+] Enter min value: ') num2 = input('[+] Enter max value: ') num1 = 0 if num1 == '' else int(num1) prime_numbers = calculate_prim(num1, int(num2)) print(prime_numbers)
1821ced4810fa58f69b6b7e4ec3415ad37e6f842
younik/gemballs
/gemballs/gemballsclassifier.py
7,799
4.125
4
import abc import numpy as np class Ball: """ Ball(center, radius, label) This class is aimed to model a ball of the GEM-balls classifier. Parameters ---------- center : array-like The center of the sphere. radius : float The radius of the sphere. label : int The associated class for this sphere. Attributes ---------- center : array-like The center of the sphere. radius : float The radius of the sphere. label : int The associated class for this sphere. """ def __init__(self, center, radius, label): self.center = center self.radius = radius self.label = label def __contains__(self, point): return np.linalg.norm(self.center - point) < self.radius class GEMBallsClassifier: """ GEMBallsClassifier(c0=1, c1=0, algorithm='kd_tree') This class implement the GEM-balls classifier. For further details about this classifier: http://www.algocare.it/L-CSL2018GEM.pdf Parameters ---------- c0 : int, default=1 During the construction of the model, the radius of spheres computed for points belonging to class 1 is the distance between the center and c0-nearest neighbor point belonging to class 0. c1 : int, default=1 During the construction of the model, the radius of spheres computed for points belonging to class 0 is the distance between the center and c1-nearest neighbor point belonging to class 1. algorithm : {'kd_tree', 'brute'}, default='kd_tree' The name of the algorithm to compute the classifier. Attributes ---------- c : list of length 2 The list [c0, c1] with the given c0 and c1. k : list of length 2 The list [k0, k1] with k0 and k1 respectively the support lengths for the classes 0 and 1. For the definition of support refer to the paper. n : list of length 2 The list [n0, n1] with n0 and n1 respectively the number of points in the training set belonging to classes 0 and 1. classifier : list of Ball List of Ball objects forming the classifier. """ algorithm_name = None def __new__(cls, algorithm='kd_tree', **kwargs): if cls != GEMBallsClassifier and issubclass(cls, GEMBallsClassifier): return super(GEMBallsClassifier, cls).__new__(cls) implementations = cls.get_algorithms() if algorithm not in implementations: raise ValueError("Unknown algorithm '%s'" % algorithm) subclass = implementations[algorithm] instance = super(GEMBallsClassifier, subclass).__new__(subclass) return instance @classmethod def get_algorithms(cls): return {subclass.algorithm_name: subclass for subclass in cls.__subclasses__()} def __init__(self, c0=1, c1=1, **kwargs): self.classifier = [] self.c = [c0, c1] self.k = [0, 0] self.n = [0, 0] @abc.abstractmethod def fit(self, x, y, first=0): """ fit(self, x, y, first=0) This method compute the model for the given data using the specified algorithm in the constructor. Parameters ---------- x : array-like of shape (n_queries, n_features) The data of the training set. y : array-like of shape (n_queries,) The classes associated to x. first : int, default=0 The index of the starting point for the construction of the model. """ raise NotImplementedError("There is no implementation of fit") def predict_proba(self, x): """ predict_proba(self, x) Estimate the probabilities of belonging to the classes for each target in x. Parameters ---------- x : array-like of shape (n_queries, n_features) Target samples. Returns ------- y : array of shape (n_queries, 2) Estimated probabilities of belonging to class 0 and class 1 respectively for each given target sample. Notes ----- This implementation of GEM-balls doesn't compute probabilities. This method assign probability of 1 to the predicted class and 0 the the other. Examples -------- >>> from gemballs import GEMBallsClassifier >>> from sklearn.model_selection import train_test_split >>> from sklearn.datasets import make_circles >>> features, labels = make_circles(n_samples=200, noise=0.2, factor=0.5, random_state=666) >>> X_train, X_test, y_train, y_test = \ train_test_split(features, labels, test_size=.3, random_state=7) >>> gemballs = GEMBallsClassifier() >>> gemballs.fit(X_train, y_train) >>> estimated_probabilities = gemballs.predict_proba(X_test) >>> estimated_probabilities.shape (60, 2) """ y = self.predict(x) y = y.reshape(-1, 1) return np.append(1 - y, y, axis=1) def predict(self, x): """ predict(self, x) Predict the class label for each target in x. Parameters ---------- x : array-like of shape (n_queries, n_features) Target samples. Returns ------- y : array of shape (n_queries,) Predicted class labels for each given target sample. Examples -------- >>> from gemballs import GEMBallsClassifier >>> from sklearn.model_selection import train_test_split >>> from sklearn.datasets import make_circles >>> features, labels = make_circles(n_samples=200, noise=0.2, factor=0.5, random_state=666) >>> X_train, X_test, y_train, y_test = \ train_test_split(features, labels, test_size=.3, random_state=7) >>> gemballs = GEMBallsClassifier() >>> gemballs.fit(X_train, y_train) >>> predicted_classes = gemballs.predict(X_test) """ if not self.classifier: raise Exception("You have to train the model before use it") if None in x: raise ValueError("Dataset contains None value") y = np.empty(len(x), dtype=np.int) for index, point in enumerate(x): for ball in self.classifier: if point in ball: y[index] = ball.label break return y def score(self, x, y): """ score(self, x, y) Return the accuracy score of the given test data and labels. Parameters ---------- x : array-like of shape (n_queries, n_features) Test samples. y : array-like of shape (n_queries,) True class of x. Returns ------- score : float The accuracy of the predicted labels of x with respect to y. Examples -------- >>> from gemballs import GEMBallsClassifier >>> from sklearn.model_selection import train_test_split >>> from sklearn.datasets import make_circles >>> features, labels = make_circles(n_samples=200, noise=0.2, factor=0.5, random_state=666) >>> X_train, X_test, y_train, y_test = \ train_test_split(features, labels, test_size=.3, random_state=7) >>> gemballs = GEMBallsClassifier() >>> gemballs.fit(X_train, y_train) >>> accuracy = gemballs.score(X_test, y_test) >>> accuracy 0.8 """ if len(x) != len(y): raise ValueError("Dataset and labels must have the same length") y_predicted = self.predict(x) score = np.count_nonzero(y_predicted == np.array(y)) / len(y) return score
b3b41e9c45e3fe285df1d16d9da3d28be5d98faa
kumarishalini6/chatbot
/bye.py
476
3.796875
4
from tkinter import * from PIL import ImageTk def Back(): root.destroy() import his root=Tk() root.title("thanks") root.geometry("441x380") root.resizable(0,0) photo=ImageTk.PhotoImage(file="cbot.jpg") photo_image=Label(image=photo).pack() Label(root,text="Thanks",font=("arial",26,'bold'),bg="white",fg="black").place(x=0,y=310,relwidth=1,height=70) Button(root,text="back",bg="darkorange",fg="white",font=("arial",15),command=Back).place(x=10,y=10) root.mainloop()
40cd88ba1f7a86e90a05522c75ccef1a12541982
superniaoren/fresh-fish
/effective_python_learn_v1/1_parallel_concurrent/test_subprocess_lock.py
1,342
3.546875
4
import os, sys, time, subprocess import threading from threading import Thread from threading import Lock class Counter(object): def __init__(self): self.count = 0 def increment(self, value): self.count += value class LockingCounter(object): def __init__(self): self.lock = Lock() self.count = 0 def increment(self, value): #with self.lock: # self.count += value if(self.lock.acquire()): self.count += value self.lock.release() def worker_cb(worker_idx, how_many, counter): for _ in range(how_many): # some read/load op # ... counter.increment(1) def run_threads(cb_func, how_many, counter): threads = [] for i in range(6): args = (i, how_many, counter) thread = Thread(target=cb_func, args=args) threads.append(thread) thread.start() for thread in threads: thread.join() if __name__ == '__main__': how_many = 10**5 counter = Counter() run_threads(worker_cb, how_many, counter) print('Counter should be %d, real value %d' % (6 * how_many, counter.count)) lock_counter = LockingCounter() run_threads(worker_cb, how_many, lock_counter) print('LockCounter should be %d, real value %d' % (6 * how_many, lock_counter.count))
ff889840b34f80572d820dc47ffbfbe57ca82892
iamasik/Python-For-All
/C7/in_Dictionary.py
364
4.03125
4
DIC={"Name":"Delwar","Age":23,"Movie":["coco","mowna"]} if "Name" in DIC: print("Ok") else: print("Not Ok") #Value Not Check if "Delwar" in DIC: #Not Ok Becouse "Delwar" in to "Name" print("Ok") else: print("Not Ok") #For Value Check #Values method if ("Delwar" or 23) in DIC.values(): print("OK") else: print("Not Ok")
e38727b177ff3419e36b4b60d46435d70466d4ce
dilippuri/PAN-Card-OCR
/src/crop_to_box.py
1,696
3.75
4
#!/usr/bin/env python """Crop an image to the area covered by a box file. The idea is that we're only interested in the portions of an image which contain text. The other parts can be removed to get better accuracy and smaller images. """ import sys from PIL import Image from box import BoxLine, load_box_file def find_box_extrema(boxes): """Returns a BoxLine with the extreme values of the boxes.""" left = min(b.left for b in boxes) right = max(b.right for b in boxes) bottom = min(b.bottom for b in boxes) top = max(b.top for b in boxes) page = max(b.page for b in boxes) return BoxLine('', left, top, right, bottom, page) def padded_box(box, pad_width, pad_height): """Adds some additional margin around the box.""" return BoxLine(box.letter, box.left - pad_width, box.top + pad_height, box.right + pad_width, box.bottom - pad_height, box.page) def crop_image_to_box(im, box): """ Returns a new image containing the pixels inside box. This accounts for BoxLine measuring pixels from the bottom up, whereas Image objects measure from the top down. """ w, h = im.size box = [int(round(v)) for v in (box.left, h - box.top, box.right, h - box.bottom)] return im.crop(box) if __name__ == '__main__': _, box_path, image_path, out_image_path = sys.argv boxes = load_box_file(box_path) big_box = find_box_extrema(boxes) pad_box = padded_box(big_box, 20, 20) im = Image.open(image_path) cropped_im = crop_image_to_box(im, pad_box) cropped_im.save(out_image_path)
7715958379ab0f643187b71060af5be2f4b7c44a
nbro/ands
/ands/algorithms/dp/fibonacci.py
4,229
4.5625
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 20/07/2015 Updated: 29/03/2022 # Description In this file, you can find some functions that return the nth fibonacci number, but they do it in different ways, which has also an impact on the performance and asymptotic complexity of the same algorithms. The Fibonacci numbers is an infinite sequence of numbers, where the next element of the sequence is constructed by summing the previous two elements of the same. The first two elements are (usually) 0 and 1, so the next element is 1, so the sequence is now {0, 1, 1}. We then add 1 + 1 = 2 to obtain the 4th element of the sequence, which is now {0, 1, 1, 2}, and so on. The nth Fibonacci number can thus be computed in a recursive way. First, the base cases are when n = 0 and n = 1, so fib(0) = 0 and fib(1) = 1. The inductive case is fib(n) = fib(n - 1) + fib(n - 2). It turns out that, if we compute the nth Fibonacci number in this way, we would repeat some computations. For example, to compute fib(5), you would need to compute fib(4) and fib(3). To compute fib(4), we would need to compute fib(3) and fib(2). So, we would compute fib(3) twice. To solve this problem, once we compute fib(3), we can solve the result. This is called memoization. The time complexity of memoized_fibonacci (below) is linear because we need to solve all fib(i), from i=0 to i=n, and each of these sub-problems takes constant time. ## References - "Lecture 19: Dynamic Programming I: Fibonacci, Shortest Paths" (https://www.youtube.com/watch?v=OQ5jsbhAv_M&ab_channel=MITOpenCourseWare) - https://www.youtube.com/watch?v=P8Xa2BitN3I&ab_channel=HackerRank ## TODO - Write a Fibonacci function for negative numbers. """ from typing import Union __all__ = ["recursive_fibonacci", "memoized_fibonacci", "bottom_up_fibonacci"] def _check_input(n: int): if not isinstance(n, int): raise TypeError("n should be an int") if n < 0: raise ValueError("n should be >= 0") def recursive_fibonacci(n: int) -> int: """Returns the nth fibonacci number using a recursive approach. Time complexity: O(2ⁿ).""" _check_input(n) if n == 0: return 0 elif n == 1: return 1 else: return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2) def _memoized_fibonacci_aux(n: int, memo: dict) -> int: """Auxiliary function of memoized_fibonacci.""" if n == 0 or n == 1: return n if n not in memo: memo[n] = _memoized_fibonacci_aux(n - 1, memo) + _memoized_fibonacci_aux( n - 2, memo ) return memo[n] def memoized_fibonacci(n: int) -> int: """Returns the nth fibonacci number using recursion and a technique called "memoization". Time complexity: O(n).""" _check_input(n) memo = {} return _memoized_fibonacci_aux(n, memo) def bottom_up_fibonacci(n: int, return_seq: bool = False) -> Union[int, list]: """Returns the nth fibonacci number if return_seq=False, else it returns a list containing the sequence of Fibonacci numbers from i=0 to i=n. For example, suppose return_seq == True and n == 5, then this function returns [0, 1, 1, 2, 3, 5]. If return_seq == False, it returns simply 5. Note: indices start from 0 (not from 1). This function uses a dynamic programing "bottom up" approach: we start by finding the optimal solution to smaller sub-problems, and from there, we build the optimal solution to the initial problem. Time complexity: O(n).""" _check_input(n) assert isinstance(return_seq, bool) if n == 0: return n if not return_seq else [n] if n == 1: return n if not return_seq else [0, n] # If we don't need to return the list of numbers, we only need to save the # last 2 values, so that would be constant space. fib = [0] * (n + 1) fib[0] = 0 fib[1] = 1 for i in range(2, n + 1): fib[i] = fib[i - 1] + fib[i - 2] return fib[-1] if not return_seq else fib if __name__ == "__main__": for f in range(10): print(recursive_fibonacci(f)) print(memoized_fibonacci(f)) print(bottom_up_fibonacci(f, True))
fed97d71e7f17068e8749c2e0a78b773ee31cb6b
sandeeps311094/Python-Programs
/P5_Student_Total_avg_Class.py
1,085
3.9375
4
#-- A simple student marks card report program import os import time def main(): os.system('clear') name = str(input("Enter name: ")) math = int(input("Enter math score: ")) science = int(input("Enter science score: ")) music = int(input("Enter music score: ")) total, avg = calc_avg(math, science, music) grade = calc_class(total) print ("Total --> ", total) print ("Average --> ", avg) print ("Class --> ", grade) #-- def calc_avg(math, science, music): total = (math + science + music) avg = (total / 3) time.sleep(1.0) return total, avg #-- def calc_class(total): grade = "" if (total >= 90): grade = "Excellent" elif (total >= 80 and total < 90): grade = "Very Good" elif (total >= 70 and total < 80): grade = "Good" elif (total >= 60 and total < 70): grade = "Satisifactory" elif (total >= 50 and total < 60): grade = "Bad" elif (total >= 40 and total < 50): grade = "Fail" elif (total == 0): grade = "Royally Fucked Up !!!" else: grade = "Go Fuck Yourself !!!" return grade #-- if __name__ == '__main__': main()
b174e40d3f0b89c9ba2ae0e454221f4b093988b6
tooreest/ppkrmn_gbu_pdf
/pyhton_basic/q01l02/task_05.py
2,181
3.734375
4
print('Geekbrains. Факультет python-разработки') print('Четверть 1. Основы языка Python') print('Урок 2. Встроенные типы и операции с ними') print('Домашнее задание 5.\nРеализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.\n\ У пользователя необходимо запрашивать новый элемент рейтинга.\n\ Если в рейтинге существуют элементы с одинаковыми значениями, то новый элемент с тем же значением должен разместиться после них.') for i in range(15,0): print(i) rait = [7, 5, 3, 3, 2] new = True while new: new = input('Введите новый элемент: ') # Проверка корректности ввода if not new.isdigit(): print('Не корректный ввод. Введите целое число больше нуля.') continue elif int(new) == 0: print('Не корректный ввод. Введите целое число больше нуля.') continue else: # Поиск места и вставка нового элемента n = len(rait) - 1 if int(new) in rait: # элемент есть в списке while n >= 0: if int(new) == rait[n]: rait.insert(n + 1, int(new)) break else: n -= 1 else: # Элемента нету в списке if int(new) > rait[0]: # Элемент больше первого (максимального) элемента rait.insert(0, int(new)) else: # while n >= 0: if int(new) < rait[n]: rait.insert(n + 1, int(new)) break else: n -= 1 print(f'{rait}') print(f'\nBye!!!')
bdfbebde8b7eefb859c3a3618a67bd5f0039536a
adosib/PyLearn
/Corey_Schafer_Beginner_Tutorial/Lists-tuples-sets.py
600
4.375
4
# ----------------------- Lists -------------------------- # Extend lists courses = ['Hisotry', 'Math', 'CompSci', 'Physics'] courses2 = ['Japanese', 'Statistics'] courses.extend(courses2) print(courses) # Remove values from a list courses.remove('Math') print(courses) # Remove last element of a list courses.pop() # returns the value removed print(courses) # Reverse list courses.reverse() print(courses) # Sort list courses.sort() print(courses) # Can sort without changing original list object stored to variable courses sorted_courses = sorted(courses) # courses variable doens't change
2acf1b66611e3690afea44815294807f6a2ae6e4
peppo-su/pcap-modules
/02module/number_systems.py
468
3.640625
4
octa = 0o123 hexa = 0x123 def show(octa,hexa): # octa = 0o123 # hexa = 0x123 print(octa) print(hexa) show(octa,hexa) f = .45 f2 = .97 print(f + f2) print("-----------------------------------") print(2e4) print(34e8) # e=base10 print(6.62607E-34) print(0.0000000000000000000001) print("-----------------------------------") print('I like "Monty Python"') print('Python can use "an apostrophe" instead of a quote')
db68d24f4ed3286a8b2b24bf113a23f3df74d8aa
Oiselenjakhian/Drawing-Adinkra-Symbols-using-Python
/damedame.py
3,671
3.859375
4
""" Project Name: Drawing Adinkra Symbols using Python Symbol Name: Dame Dame Developer Name: Truston Ailende Email Address: [email protected] """ import turtle import math # Square def drawSquare(length): turtle.penup() turtle.setposition(-length/2.0, length/2.0) turtle.pendown() for i in range(0, 4): turtle.forward(length) turtle.right(90) turtle.penup() turtle.home() # Horizontal lines def drawHorizontalLine(length, division): pixelSpace = int(length / division) half = int(length / 2) for j in range((-half + pixelSpace), half, pixelSpace): turtle.penup() turtle.setposition(-half, j) turtle.pendown() turtle.forward(length) turtle.penup() turtle.home() # Vertical lines def drawVerticalLine(length, division): pixelSpace = int(length / division) half = int(length / 2) turtle.right(90) for k in range((-half + pixelSpace), half, pixelSpace): turtle.penup() turtle.setposition(k, half) turtle.pendown() turtle.forward(length) turtle.penup() turtle.home() # Draw the grid turtle.speed(1000000) drawSquare(400) drawHorizontalLine(400, 40) drawVerticalLine(400, 40) # Change the colour mode turtle.colormode(255) # Change the pencolor to red turtle.pencolor(255, 0, 0) # Draw the horizontal centre line turtle.setposition(-200, 0) turtle.pendown() turtle.forward(400) turtle.penup() # Draw the vertical centre line turtle.setposition(0, 200) turtle.setheading(270) turtle.pendown() turtle.forward(400) # Reset all the properties turtle.home() turtle.pencolor(0, 0, 0) # Place code here # Set the pensize to 20 turtle.pensize(20) # Draw the filled center square turtle.setposition(-60, 60) turtle.pendown() turtle.begin_fill() turtle.forward(120) turtle.right(90) turtle.forward(120) turtle.right(90) turtle.forward(120) turtle.right(90) turtle.forward(120) turtle.right(90) turtle.end_fill() # Draw the outer circle turtle.penup() turtle.setposition(0, -170) turtle.pendown() turtle.circle(170) # Draw the right handle turtle.penup() turtle.setheading(0) turtle.setposition(60, 20) turtle.pendown() turtle.forward(50) turtle.right(90) turtle.forward(40) turtle.right(90) turtle.forward(50) # Draw the line joining the right handle to the circle turtle.penup() turtle.setheading(0) turtle.setposition(110, 0) turtle.pendown() turtle.forward(50) # Draw the top handle turtle.penup() turtle.setheading(90) turtle.setposition(-20, 60) turtle.pendown() turtle.forward(50) turtle.right(90) turtle.forward(40) turtle.right(90) turtle.forward(50) # Draw the line joining the top handle to the circle turtle.penup() turtle.setheading(90) turtle.setposition(0, 110) turtle.pendown() turtle.forward(50) # Draw the left handle turtle.penup() turtle.setheading(180) turtle.setposition(-60, -20) turtle.pendown() turtle.forward(50) turtle.right(90) turtle.forward(40) turtle.right(90) turtle.forward(50) # Draw the line joining the left handle to the circle turtle.penup() turtle.setheading(180) turtle.setposition(-110, 0) turtle.pendown() turtle.forward(50) # Draw the bottom handle turtle.penup() turtle.setheading(270) turtle.setposition(20, -60) turtle.pendown() turtle.forward(50) turtle.right(90) turtle.forward(40) turtle.right(90) turtle.forward(50) # Draw the line joining the bottom handle to the circle turtle.penup() turtle.setheading(270) turtle.setposition(0, -110) turtle.pendown() turtle.forward(50) # End the program turtle.done()
aadd85237c44dfc98f889504aa882bb1d2d885fa
garimadawar/LearnPython
/Average_02.py
127
3.5
4
print("This program calculates the average of two numbers.") print("numbers are 4 and 8") print("Average is:" , (4 + 8) /2)
b93ffd786ab3f4ff9e5ef020a86dd94a1c4eb239
Izardo/pands-problem-sheet
/sqrt_task5.py
1,933
4.5625
5
# This program defines a function which returns the # square root of a number using Newton's method # Author: Isabella Doyle # numList stores the result of the for loop iterations from the sqrt function numList = [0, 0] # the sqrt function takes in two values, the second is pre-defined def sqrt(number): a = float(number) # value that we want to get the square root of while number != numList[-2]: # the while loop is executed until the result of the code in the next line is the same twice number = 0.5 * (number + a / number) # uses newton's formula to estimate the square of a number numList.append(number) # number placed in list so it can be compared to the current number breaking the while loop broken when appropriate return round(number, 1) # rounds number to 1 decimal place # main program requests the user to input a positive number number = float(input("Please enter a positive number: ")) # requests input from the user, converts input to float and assigns to variable 'number' # If statment filters out negative numbers and the number 0 # If else statement executes, the square root is returned while number <= 0: # filters out negative number = float(input("Please enter a POSITIVE number: ")) # prompts the user to enter a positive number if number >= 0: print("The square root of {} is approximately {}".format(number, sqrt(number))) # prints the approx. square root of 'number' in a sentence ''' REFERENCES: [1] "Find root of a number using Newton's method" - GeeksforGeeks <br/> Available at: https://www.geeksforgeeks.org/find-root-of-a-number-using-newtons-method/#:~:text=Let%20N%20be%20any%20number,correct%20square%20root%20of%20N [2] "Newton Square Root Method in Python" - Siddik Acil <br/> Available at: https://medium.com/@sddkal/newton-square-root-method-in-python-270853e9185d '''
6fa35a1d52798546e8b09abab952a99019dc53e1
adbag19/booksearch
/routes.py
3,190
3.53125
4
#!/usr/bin/env python3 from flask import Flask, render_template, request, url_for, redirect, jsonify from Templates import BookTemplate, setAttributes, AuthorTemplate from getData import goodreads_get_book_data, goodreads_get_author_data # Init Flask app = Flask(__name__) @app.route('/') def form(): return render_template("form.html") @app.route('/index', methods=['GET','POST']) def index(): if request.method=='POST': #Example Book bookTitle = request.form['booktitle'] bookAuthor = request.form['bookauthor'] # this calls the API and related helper functions! goodreads_get_book_data(bookTitle, bookAuthor) # create object/instance of the Book class book = BookTemplate() # Assign the data dictionary as attributes of the object as shown setAttributes (book, goodreads_get_book_data(bookTitle, bookAuthor)) # Now, you can access the attributes of the book directly by referring to the object: print (book.title) # You can also access similar books by access that data dictionary. # Remember, it's an array of dictionaries though, so you have to refer to a specific item, or loop through all: if book.title==None: print('No similar books') return render_template('error.html', book=book) else: print (book.similar_books[0]['title']) # To get author info, you must collect author info. It's a slightly different API in Goodreads # This will call the API and hepler functions from getData.py. # Here, we are also passing along the same author and title variables from above (you will get these from your wtf input forms) # First, we will create a second object to store author data. # Why do we need this? Because the data being returned pertains directly to the author, not the book authorTemplate = AuthorTemplate() # We call setAttributes again to assign the dictionary items to the object # Like the book object, we can now call these by referencing the object setAttributes(authorTemplate, goodreads_get_author_data(bookAuthor, bookTitle)) # Now we associate the author object with the book object book.authorProfile = authorTemplate # Now, we can access author data directly. # Where are we getting this? From parse_response_author in the getData file! # Plese see the URL created in getData.py for all the attributes # Here is JSON data for author's published books: #print (book.authorProfile.books) # Here is the dictionary version: print (book.authorProfile.books_dict) # Now, to pass this information on to the webpage, we can simply pass the "book" object we created above along as a variable. Now we can call this object and its attributes using jinja (see index.html provided) return render_template('index.html', book=book) else: return render_template('form.html') if __name__ == "__main__": app.run(debug=True)
60257e249b423d7f7eb387768bc07e8977e9a627
Retkoj/AOC_2020
/src/5_2_find_seat_plus_binary_impl.py
1,376
3.8125
4
import fileinput def get_seat(lst): lst.sort() diffs = [] for i in range(0, len(lst) - 1): diffs.insert(i, lst[i + 1] - lst[i]) if lst[i + 1] - lst[i] == 2: print(f'index {i}, {lst[i:i+2]}') def binary_implementation(lst): """ Converts the seatdescription to the binary description and then to decimal. Finally the seat ID is calculated by the formula `(row number * 8) + seat number` Example: Seat on ticket: 'BFBFFBBLLR' Row number: '1010011' -> 83 Seat number: '001' - > 1 Seat ID: (83 * 8) + 1 = 665 :param lst: List of seat numbers as listed on the tickets :return: Dict with row number, seat number, seat ID per ticket """ seat_dict = {} for ticket in lst: row_no = int(ticket[0:7].replace('F', '0').replace('B', '1'), 2) seat_no = int(ticket[7:10].replace('L', '0').replace('R', '1'), 2) seat_dict[ticket] = { 'row_no': row_no, 'seat_no': seat_no, 'seat_ID': (row_no * 8) + seat_no } return seat_dict if __name__ == '__main__': lines = [i.strip('\n') for i in fileinput.input()] seats = binary_implementation(lines) print('Maximum seat ID in list: {}'.format(max([value['seat_ID'] for key, value in seats.items()]))) get_seat([value['seat_ID'] for key, value in seats.items()])
60e76dfcc6c77debd84b424628db4083fb812607
tvaisanen/AlgorithmsAndDatastructures2016
/list_main.py
626
3.921875
4
from linkedlist import * def main(): # Empty linked list coll = LinkedList() coll.head = None # Insert 0..9 into list for i in range(10): list_insert(coll, i) print('Original list:') print_list(coll) # Remove even keys L = [2 * x for x in range(5)] for i in L: list_remove(coll, i) print('List after removing even keys:') print_list(coll) # Remove odd keys L = [9 - 2 * x for x in range(5)] for i in L: list_remove(coll, i) print('List after removing odd keys:') print_list(coll) main()
2c104830051a53a77912fc1fabfb361410e9743c
michal-jewczuk/python-problems
/test_example.py
1,902
3.96875
4
import unittest import example as example class TestSortedWithoutMinMax(unittest.TestCase): def test_with_empty_list(self): initial = [] expected = [] result = example.getSortedWithoutMinMax(initial) self.assertEqual(result, expected) def test_with_one_element(self): initial = [-1] expected = [] result = example.getSortedWithoutMinMax(initial) self.assertEqual(result, expected) def test_with_two_elements(self): initial = [89,-1] expected = [] result = example.getSortedWithoutMinMax(initial) self.assertEqual(result, expected) def test_with_three_elements(self): initial = [5,89,-1] expected = [5] result = example.getSortedWithoutMinMax(initial) self.assertEqual(result, expected) def test_with_multiple_elements(self): testData = [ ([3,3,3,3], [3,3]), ([5,6,7,8], [6,7]), ([9,8,7,6,5], [6,7,8]), ([-100,55,12,4,121,-4], [-4,4,12,55]), (['ccc', 'aaa', 'ddd', 'eee', 'bbb'], ['bbb', 'ccc', 'ddd']) ] for data in testData: result = example.getSortedWithoutMinMax(data[0]) self.assertEqual(result, data[1]) def test_with_no_list(self): expected = "You need to supply an array with sortable elements" with self.assertRaises(ValueError) as error: example.getSortedWithoutMinMax(1) self.assertEqual(str(error.exception), expected) def test_with_string_as_argument(self): expected = "You need to supply an array with sortable elements" with self.assertRaises(ValueError) as error: example.getSortedWithoutMinMax('test') self.assertEqual(str(error.exception), expected) if __name__ == '__main__': unittest.main()
d8d6d2203c84a514259cb1061a8542da96f9d2ca
stone1949/study-1
/20170712/elif.py
127
4.15625
4
age=int(raw_input('input your age : ')) if age>= 18: print 'adult' elif age >=6: print 'teenager' else: print 'kid'
a4bcec136f2be7c05e2c8348e8281b4ba3b17806
eBLDR/MasterNotes_Python
/Concurrency_MultiThreading/thread_objects.py
2,099
3.953125
4
# Different types of thread objects. import threading import time # TIMER OBJECTS - certain function will be executed after certain time def salute(): print('Ave Caesar!') # timer.object(@seconds, @function) - function will be executed after @seconds # from start() call my_timer = threading.Timer(5, salute) my_timer.start() # here is where the timer starts if input('Cancel timer [y/n] ? ').lower() == 'y': # to cancel the count and the execution my_timer.cancel() # to wait executing main code until this thread is terminated my_timer.join() print('=' * 20) # PERIODIC TASK def periodic_task(): print('\t', time.ctime()) # Just before dying, the current thread invokes another thread with a call # to the same function once the timer is finished threading.Timer(2, periodic_task).start() periodic_task() print('=' * 20) # BARRIER OBJECTS - threads will wait for each other to be released # @parties (int type) - number of threads to be blocked before releasing them # @timeout (seconds) - time after which a BrokenBarrierError will be raised my_barrier = threading.Barrier(2, timeout=10) def server(): time.sleep(5) print('Server active.') # wait() call sends one thread to the barrier - parties += 1 # and wait for the barrier to have the number of specified parties before being released my_barrier.wait() def client(): print('Client active.') print('Waiting at the barrier for server...') my_barrier.wait() print('Connection established.') server_thread = threading.Thread(target=server) client_thread = threading.Thread(target=client) server_thread.start() client_thread.start() time.sleep(1) # return the number of threads currently waiting in the barrier print('Threads waiting in the barrier:', my_barrier.n_waiting) """ abort() method - puts the barrier into a broken state. This causes any active or future calls to wait() to fail with the BrokenBarrierError. reset() method - return the barrier to the default, empty state. Any threads waiting on it will receive the BrokenBarrierError exception. """
56f13f64677e95f9a0790e48e12eb402613de7c8
mtouhidchowdhury/CS1114-Intro-to-python
/Homework 2/hw2q1a.py
331
4.40625
4
#calculate the BMI of person by taking their weight and height weight = float(input("please enter weight in kilograms:")) #user weight input height = float(input("please enter height in meters:"))# user height input BMI = weight / (height**2) #using the BMI formula print ("BMI is", round(BMI,7))#printing the results
43e6c04d80b84ad93d8a3a346510b8fc3078b726
pragatij17/Algorithms
/bit_magic/power_of_two/efficient_method.py
136
4.03125
4
def isPower(n): if(n == 0): return True return ((n & (n - 1)) == 0) n=int(input("Enter the number:")) print(isPower(n))
a71cbb1cb9c5e2e44f1f66e1461099b60caf81cb
gitghought/python1
/myexcel/myexcel.py
3,739
3.515625
4
import xlrd from datetime import date,datetime single_num = 20 mul_num = 10 pan_num = 10 def read_student_excel(): #指定学生答案在第几列 student_answer_pos = 1 single_answer = [] single_start_pos = 4 mul_answer = [] mul_start_pos = 26 pan_answer = [] pan_start_pos = 38 #存储学生答案的数据结构 student_answer = {"single_answer":[], "mul_answer":[], "pan_answer":[]} #文件位置 ExcelFile=xlrd.open_workbook(r'F:\PycharmProjects\python1\myexcel\answer.xls') #获取第一个表格的对象 sheet=ExcelFile.sheet_by_name('Sheet1') #单选回答 single_answer=sheet.col_values(student_answer_pos, single_start_pos, single_start_pos+single_num)#第二列内容 # print(single_answer) # print(len(single_answer)) student_answer["single_answer"] = single_answer #多选回答 mul_answer=sheet.col_values(student_answer_pos, mul_start_pos, mul_start_pos+mul_num)#第二列内容 # print(mul_answer) # print(len(mul_answer)) student_answer["mul_answer"] = mul_answer #判断回答 pan_answer=sheet.col_values(student_answer_pos, pan_start_pos, pan_start_pos+pan_num)#第二列内容 # print(pan_answer) # print(len(pan_answer)) student_answer["pan_answer"] = pan_answer return student_answer def read_teacher_excel () : #指定学生答案在第几列 student_answer_pos = 1 single_answer = [] single_start_pos = 4 single_num = 20 mul_answer = [] mul_start_pos = 26 mul_num = 10 pan_answer = [] pan_start_pos = 38 pan_num = 10 #存储学生答案的数据结构 student_answer = {"single_answer":[], "mul_answer":[], "pan_answer":[]} #文件位置 ExcelFile=xlrd.open_workbook(r'F:\PycharmProjects\python1\myexcel\a.xls') #获取目标EXCEL文件sheet名 print(ExcelFile.sheet_names()) #获取第一个表格的对象 sheet=ExcelFile.sheet_by_name('Sheet1') #单选回答 single_answer=sheet.col_values(student_answer_pos, single_start_pos, single_start_pos+single_num)#第二列内容 # print(single_answer) # print(len(single_answer)) student_answer["single_answer"] = single_answer #多选回答 mul_answer=sheet.col_values(student_answer_pos, mul_start_pos, mul_start_pos+mul_num)#第二列内容 # print(mul_answer) # print(len(mul_answer)) student_answer["mul_answer"] = mul_answer #判断回答 pan_answer=sheet.col_values(student_answer_pos, pan_start_pos, pan_start_pos+pan_num)#第二列内容 # print(pan_answer) # print(len(pan_answer)) student_answer["pan_answer"] = pan_answer return student_answer def check_single(teacher , student) : # print(teacher) # print(student) #获取单选选项答案 # print(type(teacher)) teacher_single_answer = teacher["single_answer"] # print(teacher_single_answer) student_single_answer = student["single_answer"] # print(student_single_answer) # question_serialized = [for t in teacher_single_answer for s in student_single_answer] question_serialized = list() print(len(question_serialized)) mpos = 0 while True: if teacher_single_answer[mpos] == student_single_answer[mpos] : # question_serialized[mpos] = True question_serialized.append(True) else : question_serialized.append(False) mpos += 1 if mpos >= single_num : break print(question_serialized) print(len(question_serialized)) if __name__ == '__main__': stu = read_student_excel() # print(stuanw) te = read_teacher_excel() # print(te) check_single(te, stu)
05764e0266c28a2792f0223ec7607c0f25983a32
dkurchigin/gb_algorythm
/task2.py
702
4.21875
4
# Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6. # Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака # 5 = 101 # 6 = 110 a = 5 b = 6 print(f"Дано: {a} и {b}") print(f"Побитовое \"И\" = {a & b}") print(f"Побитовое \"ИЛИ\" = {a | b}") print(f"Побитовое \"Исключительное ИЛИ\" = {a ^ b}") print(f"Побитовый сдвиг влево числа {a} на два знака = {a << 2}") print(f"Побитовый сдвиг вправо числа {a} на два знака = {a >> 2}")
3157bf712b55ed5b931ecb94bd7e387cbdcd3d4e
EddylianOrigin/Chapter2_Python
/Dictionnaries.py
608
4.03125
4
names = ["Ben","Jan"] grades=[1,2] #dict {(key, value)} names_and_grades={"Ben":1,"Jan":2} print(names_and_grades) names_and_grades.update({"Pia":3}) print(names_and_grades) names_and_grades["Jan"] = 1 print(names_and_grades) names_and_grades.pop("Jan") print(names_and_grades) #keys for k in names_and_grades.keys(): print(k) #Values for v in names_and_grades.values(): print(v) #key,Values for v in names_and_grades.items(): print(v) for k,v in names_and_grades.items(): print(k,v) if "Jan" in names_and_grades: print("Jan is present!") else: print("Jan is not present")
5bf26b8b42e8cec869b5fe299e1f42b5e6a3f58a
ariadnecs/python_3_mundo_2
/exercicio047.py
220
3.953125
4
# Exercício Python 47: Crie um programa que mostre na tela # todos os números pares que estão no intervalo entre 1 e 50. for pares in range(2, 52, 2): print(pares, end=' ') print('\nNúmeros pares entre 1 e 50!')
0ef5fe4e1ba7ca92fdd225859a76cb024af30a12
AGoodDataScientist/ProjectEuler-Python-Solutions
/Prob0002.py
678
3.8125
4
# -*- coding: utf-8 -*- """ Project Euler Problem 2: Even Fibonacci numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ def FibEvenSum(): sumval = 0 TotVal = 0 i=2 PrevNum = 1 while i < 4000000: sumval = PrevNum + i if i%2 == 0: TotVal += i PrevNum = i i = sumval return(TotVal) if __name__ == "__main__": print(FibEvenSum())
d6628d6f000a25e4769cee812f1631f64cc43a26
damodardikonda/Python-Basics
/core2web/Week6/Day35/prime_sum.py
543
3.9375
4
''' Write a Program to check whether a number can be express as sum of two prime numbers. Input: 20 Output: 20 = 7 + 13 ''' def primeOrNot(num): for itr in range(2,(num/2)+1): if num%itr ==0: return 0; return 1; num = input("Enter the number : ") flag = 0 for itr in range(2,(num/2)+1): if primeOrNot(itr)==1: if primeOrNot(num-itr)==1: print(str(num)+" = "+str(num-itr)+" + "+str(itr)) flag =1 if flag ==0: print(str(num)+" cannot express as the sum of two prime ")
1dd6ee10167f2aa8a9c9a197daaf99a5248d66fc
jgross21/Programming
/Notes/Chapter6.py
6,547
4.5625
5
# Chapter 6 notes, More Loops # Learn to master the FOR loop. # more printing print('Francis', 'Parker') # Python automatically puts a space in between print('Francis' + 'Parker') # Smushes them together print('Python' * 10) # Printing miltiple times # Python automatically adds '\n' to the end of every print() print() print('First', end=' ') print('Second', end='whatever') print('Third', end='.') #1.) ''' * * * * * * * * * * ''' # Have this code print using a for loop, and print each # asterisk individually, rather than just printing ten asterisks with one print statement. # This can be done in two lines of code, a for loop and a print statement. for i in range(10): print('*', end=' ') print() #2.)Write code that will print the following: ''' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' # This is just like the prior problem, but also printing five and twenty stars. # Copy and paste from the prior problem, adjusting the for loop as needed. for i in range(10): print('*', end=' ') print() for i in range(5): print('*', end=' ') print() for i in range(20): print('*', end=' ') print() #3.) Use two for loops, one of them nested inside the other, to print the following 10x10 rectangle: ''' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' # To start, take a look at Problem 1. The code in Problem 1 generates one line of asterisks. # It needs to be repeated ten times. Work on this problem for at # least ten minutes before looking at the answer. for i in range(10): for j in range(10): print('*', end='') print() #4.) Use two for loops, one of them nested, to print the following 5x10 rectangle: ''' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' # is is a lot like the prior problem. # Experiment with the ranges on the loops to find exactly what the numbers passed # to the range function control. print('4.') for i in range(10): for j in range(5): print('*', end=' ') print() # 5.) Use two for loops, one of them nested, to print the following 20x5 rectangle: # * * * * * * * * * * * * * * * * * * * * # * * * * * * * * * * * * * * * * * * * * # * * * * * * * * * * * * * * * * * * * * # * * * * * * * * * * * * * * * * * * * * # * * * * * * * * * * * * * * * * * * * * # Again, like Problem 3 and Problem 4, but with different range values. print('5.') for i in range(5): for j in range(20): print('*', end=' ') print() #6.) Write code that will print the following: ''' 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 ''' #Use two nested loops. Print the first line with a loop, and not with: # print("0 1 2 3 4 5 6 7 8 9") #Tip: First, create a loop that prints the first line. # Then enclose it in another loop that repeats the line 10 times. # Use either i or j variables for what the program prints. # This example and the next one helps reinforce what those index variables are doing. #Work on this problem for at least ten minutes before looking at the answer. # The process of spending ten minutes working on the answer is far more important than the answer itself. print('6.') for i in range(10): for j in range(10): print(i, end=' ') print() # 7.) Adjust the prior program to print: # 0 0 0 0 0 0 0 0 0 0 # 1 1 1 1 1 1 1 1 1 1 # 2 2 2 2 2 2 2 2 2 2 # 3 3 3 3 3 3 3 3 3 3 # 4 4 4 4 4 4 4 4 4 4 # 5 5 5 5 5 5 5 5 5 5 # 6 6 6 6 6 6 6 6 6 6 # 7 7 7 7 7 7 7 7 7 7 # 8 8 8 8 8 8 8 8 8 8 # 9 9 9 9 9 9 9 9 9 9 print('7.') for i in range(10): for j in range(10): print(j, end=' ') print() # 8.) Write code that will print the following: # 0 # 0 1 # 0 1 2 # 0 1 2 3 # 0 1 2 3 4 # 0 1 2 3 4 5 # 0 1 2 3 4 5 6 # 0 1 2 3 4 5 6 7 # 0 1 2 3 4 5 6 7 8 # 0 1 2 3 4 5 6 7 8 9 # Tip: This is just problem 6, but the inside loop no longer loops a fixed number of times. # Don't use range(10), but adjust that range amount. # After working at least ten minutes on the problem. print('8.') for i in range(10): for j in range(i+1): print(j, end=' ') print() # 9.)Write code that will print the following: # 0 1 2 3 4 5 6 7 8 9 # 0 1 2 3 4 5 6 7 8 # 0 1 2 3 4 5 6 7 # 0 1 2 3 4 5 6 # 0 1 2 3 4 5 # 0 1 2 3 4 # 0 1 2 3 # 0 1 2 # 0 1 # 0 # This one is difficult. Tip: Two loops are needed inside the outer loop that controls each row. # First, a loop prints spaces, then a loop prints the numbers. Loop both these for each row. # To start with, try writing just one inside loop that prints: # # 0 1 2 3 4 5 6 7 8 9 # 0 1 2 3 4 5 6 7 8 # 0 1 2 3 4 5 6 7 # 0 1 2 3 4 5 6 # 0 1 2 3 4 5 # 0 1 2 3 4 # 0 1 2 3 # 0 1 2 # 0 1 # 0 # Then once that is working, add a loop after the outside loop starts and before the already # existing inside loop. Use this new loop to print enough spaces to right justify the other loops. print('9.') for i in range(10): for j in range(i): print(' ', end=' ') for j in range(10-i): print(j, end=' ') print() # Print a multiplication table print('10.') for i in range(1, 10): for j in range(1, 10): if i * j >= 10: print(i*j, end=' ') if i * j < 10: print(i*j, end=' ') print() # 11.)Write code that will print the following: # 1 # 1 2 1 # 1 2 3 2 1 # 1 2 3 4 3 2 1 # 1 2 3 4 5 4 3 2 1 # 1 2 3 4 5 6 5 4 3 2 1 # 1 2 3 4 5 6 7 6 5 4 3 2 1 # 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 # 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 # Tip: first write code to print: # # 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5 # 1 2 3 4 5 6 # 1 2 3 4 5 6 7 # 1 2 3 4 5 6 7 8 # 1 2 3 4 5 6 7 8 9 # Then write code to print: # # 1 # 1 2 1 # 1 2 3 2 1 # 1 2 3 4 3 2 1 # 1 2 3 4 5 4 3 2 1 # 1 2 3 4 5 6 5 4 3 2 1 # 1 2 3 4 5 6 7 6 5 4 3 2 1 # 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 # 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 # # Then finish by adding spaces to print the final answer. print('11.') for i in range (9): for j in range(9-i): print(' ', end=' ') # Left Half (count up) for j in range(1, i+2): print(j, end=' ') # Right Half (count down) for j in range (i, 0, -1): print(j, end=' ') print()
59bd0f24aa0a7b43fd129e500dee841f74ca7442
CoenvdStigchel/nogmaals
/coins.py
1,747
3.796875
4
# name of student: # number of student: # purpose of program: # function of program: # structure of program: toPay = int(float(input('Amount to pay: '))* 100) # vraagt hoeveel je moet betalen en zet het om in centen paid = int(float(input('Paid amount: ')) * 100) # vraagt hoeveel je betaalt hebt en maakt dat naar centen change = paid - toPay # berekent wat je moet terug geven if change > 0: # als er wisselgeld moet zijn is 500 het beginaantal coinValue = 500 # begin aantal while change > 0 and coinValue > 0: # zorgt ervoor dat als het niet in 1 keer word terug betaalt dat het dan naar de volgende gaat nrCoins = change // coinValue # de deelsom om het resultaat te berekenen if nrCoins > 0: # als je wisselgeld terug moet krijgen print('return maximal '+ str(nrCoins) + " coins of " + str(coinValue) + ' cents!' ) # laat het aantal zien dat je maximaal moet terug gevenß nrCoinsReturned = int(input('How many coins of ' + str(coinValue) + ' cents did you return? ')) # change -= nrCoinsReturned * coinValue # de rekensom om het teruggegeven geld te berekenen # comment on code below: if coinValue == 500: coinValue = 300 elif coinValue == 300: coinValue = 200 elif coinValue == 200: coinValue = 100 elif coinValue == 100: coinValue = 50 elif coinValue == 50: coinValue = 20 elif coinValue == 20: coinValue = 10 else: coinValue = 0 if change > 0: #als het groter is dan 0 en niet genoeg terug gegeven word er pinrt(Change not returned) print('Change not returned: ', str(change) + ' cents') else: print('je hebt in totaal ' + str(nrCoinsReturned) + " coins terug gegeven")
1e4be77c6c6e7471fcd7df5c5aec22d3f03993fc
randy36/intro-y-taller
/Examenes/Parcial #1- Introduccion a la programacion.py
2,038
3.8125
4
def formarLista(num): if num > 0 and isinstance (num,int): return formarLista_aux(num) else: return: "El numero ingresado no es positivo y entero" def formarLista_aux(num): if num == 0: return: [] elif num % 10 %2 == 0: return: num % 10 formarLista_aux(num) else: return: num // 10 fromarLista_aux(num) #------------------------------------------------------------------------------------------- def palidromo(num): Valor == X if num > 0 and isinstance (num,int): return: longitud_aux(num) and polindromo_aux(num) else: return: "El numero ingresado no es entero y mayor que cero" def longitud_aux(num): if num = 0: return polindromo_aux(n) else: return: num // 10 longitud_aux(num)+1 def polindromo_aux(num,n): if num == 0: return: 0 else: return: num % 10 ** (n-1) and num // (10*(10*n-1))polindromo_aux(num,n) if X = 0: return: True else return: False #------------------------------------------------------------------------------------------------------ def contarConsonantes(palabra): if isinstance (palabra,String): return: contarConsonantes_aux(palabra) else: return: "Error, no es un String" def contarConsonantes_aux(palabra): x = a y = e z = i w = o L = u if palabra = []: return: 0 elif [0] == x or [0] == y or [0] == z or [0] == w or [0] == L: return: +1 contarConsonantes_aux(palabra[1:]) else: return: contarConsonantes_aux(palabra[1:]) #-------------------------------------------------------------------------------------------------------- def intercambiar(lista): if isinstance (lista,list): return: intercambiar_aux(lista) else: return: "Error, no es una lista" def intercambiar_aux(lista): if lista == []: return: [] else: return: [1] + [0] + intercambiar_aux(lista[1:])
8b7c7d81b56e8e24a6de03771eb169ade9e5227b
klimmerst/py111-efimovDA
/Tasks/e0_breadth_first_search.py
622
3.6875
4
from typing import Hashable, List import networkx as nx def bfs(g: nx.Graph, start_node: Hashable) -> List[Hashable]: """ Do an breadth-first search and returns list of nodes in the visited order :param g: input graph :param start_node: starting node for search :return: list of nodes in the visited order """ buf_list = [start_node] final_list = [start_node] while len(buf_list) > 0: for i in g.neighbors(buf_list[0]): if i not in final_list: final_list.append(i) buf_list.append(i) buf_list.pop(0) return final_list
4b7623d1615d45b9919e7bcee71166e888642aad
Johannes-Walter/tml-reader
/tml-reader.py
6,658
4
4
""" TML-Reader-Module (Turtle-Markup-File). https://github.com/Johannes-Walter/tml-reader """ import shapes class Tag(): """ A Class which reads tag-pairs. This class saves the position of the tags in a given text with their starting/endig position and the name of the tag. """ def __init__(self): """ Create a new tag. Returns ------- None. """ self.opening_tag_start = None self.opening_tag_end = None self.tag_name = None self.closing_tag_start = None self.closing_tag_end = None def find_tag(text: str, start: int, end: int): """ Find the first tag-pair in the given text. Parameters ---------- text : str Text which will be searched in. start : int Start index of the search. end : int Ending index of the search. Returns ------- tag : Tag A tag-object containing all information or None, if no tag is found. """ # check if the end is after the beginnig assert start <= end tag = Tag() # if there is no opening tag, there will be an error # we will pass an "none" for no tag try: tag.__find_opening_tag(text, start, end) except ValueError: return None tag.__find_closing_tag(text, tag.opening_tag_end, end) if (tag.closing_tag_start is not None and tag.closing_tag_end is not None): return tag else: return None def __find_opening_tag(self, text: str, start: int, end: int): """ Find the first Tag in the Text. Parameters ---------- text : str Text which will be searched in. start : int Start index of the search. end : int Ending index of the search. Returns ------- Tag The tag which was worked on. """ # find the index of the starting and closing tag and save them self.opening_tag_start = text.index("<", start, end) self.opening_tag_end = text.index(">", self.opening_tag_start, end) # tag_name is saved without the tags ('<', '>') self.tag_name = text[self.opening_tag_start + 1: self.opening_tag_end] return self def __find_closing_tag(self, text: str, start: int, end: int): """ Find the closing tag in the given text. Parameters ---------- text : str Text which will be searched in. start : int Start index of the search. end : int Ending index of the search. Returns ------- Tag Returns the tag which was worked on. """ assert self.tag_name != "" opening_tag = f"<{self.tag_name}>" closing_tag = f"</{self.tag_name}>" level = 0 # scrutinize the text, looking for opening and closing tags # if an opening tag is found, the level will increase to 1 # if it is a closing tag, the level will decrease for index in range(start, end): if text.startswith(opening_tag, index): level += 1 if text.startswith(closing_tag, index): # we found our tag if the level is 0, thus leaving the loop if level == 0: self.closing_tag_start = index self.closing_tag_end = index + len(closing_tag) break else: level -= 1 return self def __read_tml(file_path: str): """ Read the given TML. Parameters ---------- file_path : str Path to the File. Returns ------- None. """ # open file with file reader with open(file_path) as file: text = file.read() tag = Tag.find_tag(text, start=0, end=len(text)) shape = shapes.get_shape(tag.tag_name) # delegate everything else in the file to the find_elements-function # to find all children in the code __find_elements(text, shape, tag.opening_tag_end, tag.closing_tag_start) return shape def __find_elements(text: str, shape, start: int, end: int): """ Find all tags in the given text and append everything to the tag. Parameters ---------- text : str Text to search through. shape : TYPE Shape which will have all subshapes appended to. start : int Start index of the search. end : int Ending index of the search. Returns ------- None. """ tag = Tag.find_tag(text, start, end) while tag: # get the shape from the possible shapes sub_shape = shapes.get_shape(tag.tag_name) if sub_shape is not None: shape.append_shape(sub_shape) # if there is no shape, try to check the tag as attribute which belongs to shape # this may appear an error, if the found tag is not valid else: shape.set_attribute(tag.tag_name, text[tag.opening_tag_end + 1: tag.closing_tag_start]) # find the next tag, start to search at the end of the current tag __find_elements(text, sub_shape, tag.opening_tag_end, tag.closing_tag_start) tag = Tag.find_tag(text, tag.closing_tag_end, end) def draw_tml(file_path: str): """ Draw the image contained in the given file. Parameters ---------- file_path : str Path of the .tml file. Returns ------- None. """ image = __read_tml(file_path) image.draw() def is_file_valid(file_path: str) -> bool: """ Check if the given file should be readable by this parser and valid. Parameters ---------- file_path : str Path of the .tml file. Returns ------- bool True if the file is valid, false if not. """ if not file_path.endswith(".tml"): return False try: __read_tml(file_path) except: return False return True if __name__ == "__main__": #draw_tml("samples//lotus.tml") #draw_tml("samples//sample.tml") #draw_tml("samples//heart.tml") #draw_tml("samples//house.tml") draw_tml("samples//triangle.tml")
11b691cd28eaa88f7174768c366b51e82295db47
marcfs31/joandaustria
/M3-Programacion/UF1/Practica5.py
2,747
4.46875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #Practica 5:Instrucions d'entrada i sortida """ #1 A=int(input("Pon un numero: ")) B=int(input("Pon otro numero: ")) #A,B= B,A metodo mejor pero solo para python A=A+B B=A-B A=A-B print(A,B) #2 A=int(input("Numero 1: ")) B=int(input("Numero 2: ")) print A+B #3 edad=int(input("Pon tu edad: ")) print edad+25 #4 num=int(input("Pon un numero: ")) print num**4 #5 euros=int(input("Pon la cantidad en euros")) pesetas= 166.386 print euros*pesetas #6 base=int(input("Pon la base del rectangulo: ")) altura=int(input("Pon la altura del rectangulo: ")) print base*altura #7 nombre=raw_input("Pon tu nombre: ") edad=int(input("Pon tu edad: ")) print ("Hola"+nombre+"la teva edat és "+str(edad)) #8 A=int(input("Pon un numero: ")) B=int(input("Pon otro numero: ")) print ("Suma "+str(A+B)+"\nResta "+str(A-B)+"\nMultiplicación "+str(A*B)+"\nDisión "+str(A/B)+"\nModulo "+str(A%B)) #9 import math math.pi radio = raw_input("Introduïu el radi:") radio2 = float(radio) area = math.pi * radio2**2 print "El area es:",area #10 print "Programa para calcula equaciones de tercer grado: " a=int(input("Valor de a: ")) b=int(input("Valor de b: ")) c=int(input("Valor de c: ")) d=int(input("Valor de d: ")) x=int(input("Valor de x: ")) result= a*x**3+b*x**2+c*x**1+d print "La equación de tercer grado da: ",result #11 cantidad=int(input("Pon la cantidad del producto: ")) precio=int(input("Pon el precio del producto: ")) total = cantidad*precio iva = total*21/100 total = iva+total print "El precio con IVA es: ",total,"€" #12 cantidad=int(input("Pon la cantidad del producto: ")) precio=int(input("Pon el precio del producto: ")) valoriva=int(input("Pon el IVA: ")) total = cantidad*precio iva = total*valoriva/100 total = iva+total print "El precio con IVA es: ",total,"€" #13 vendido1=int(input("Pon la cantidad vendida de cola: ")) precio1=float(input("Pon el precio de cola: ")) vendido2=int(input("Pon la cantidad vendida de taronja: ")) precio2=float(input("Pon el precio de taronja: ")) vendido3=int(input("Pon la cantidad vendida de llimona: ")) precio3=float(input("Pon el precio de llimona: ")) total1=vendido1*precio1 total2=vendido2*precio2 total3=vendido3*precio3 print "---------------------------------------" print "Producte Vendes Preu Total" print "Cola ",vendido1," ",precio1," ", total1 print "Taronja ",vendido2," ",precio2," ", total2 print "Llimona ",vendido3," ",precio3," ", total3 print "---------------------------------------" print "TOTAL ",total1+total2+total3 #\t #14 num=int(input("Pon un numero entero: ")) num2= num % 10 print num2 """ #15 segundos=int(input("Pon los segundos: ")) horas= segundos/60/60 horas= float(horas)
0d3df6a3c68aa1748d7568f070a75baea15cbd31
aav789/study-notes
/notes/reference/moocs/udacity/cs50-introduction-to-computer-science/source/bubble_sort.py
384
3.515625
4
arr = [5, 100, 3, 2, 101, 100] swap_count = 1 while swap_count: swap_coun = 0 for n in range(len(arr)): next = n + 1 try: if arr[n] > arr[next]: arr[n], arr[next] = arr[next], arr[n] swap_count = 1 except IndexError: # If it's the last value, there's nothing to swap pass print arr
bed0b39252ac9d8b75c94e825797177871fbf587
Nichollsean/Selection
/Selection SAC EX3.py
1,212
4.09375
4
#Sean Nicholls #30/09/14 #SAC EX3 day=int(input("Please enter the day in number format e.g '14' : ")) month=int(input("Please enter the month in number format e.g 'july = 7' : ")) year=int(input("Please enter the year in 2 digit format e.g '05' :")) if day >=4 and day <=20: day1 = ("{0}th".format(day)) elif day ==1 and day ==21 and day == 31: day1 = ("{0}st".format(day)) elif day ==3 and day == 23: day1 = ("{0}rd".format(day)) if month == 1: month1= ("January") elif month ==2: month1= ("Febuary") elif month ==3: month1 = ("March") elif month ==4: month1 = ("April") elif month ==5: month1 = ("May") elif month ==6: month1 = ("June") elif month ==7: month1 = ("July") elif month ==8: month1 = ("August") elif month ==9: month1 = ("September") elif month ==10: month1 = ("October") elif month ==11: month1 = ("November") elif month ==12: month1 = ("December") if year >=31 and year <=99: year1= ("19{0}".format(year)) elif year >=0 and year <=30: year1= ("20{0}".format(year)) else: year1 = ("Year is not in range") print (" The date is the {0} of {1} {2}".format(day1, month1, year1))
c5371b7c9555859a5f0d016365b33fc37cd4dbfe
Godmode-bishal/Python
/final_exam.py
362
3.765625
4
#Final Exam print "Hello" try: print "Fred" st=int("fred") print "World" except: print "Error !!" print "Yo" print "" tot = 0 for i in range(5): tot = tot + i print tot print "" def hello(): print "Hello" print "Fun" hello() hello() print "" x = -1 for value in [3, 41, 12, 9, 74, 15] : if value < x : x = value print x
229e77ac3d0b6ba3dd7eb119eb5a5c85ec205751
rsauhta/ProjectEuler
/p014.py
1,628
3.875
4
# https://projecteuler.net/problem=14 # # # Longest Collatz sequence # The following iterative sequence is defined for the set of positive integers: # # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # # Which starting number, under one million, produces the longest chain? # # NOTE: Once the chain starts the terms are allowed to go above one million. import util import math SequenceListMax = 1000000 # Keep the sequence length for the first million number SequenceLengthList = [0]*SequenceListMax SequenceLengthList[1] = 1 def findCollatzSequenceLength(number): if (number < SequenceListMax and SequenceLengthList[number] > 0): return SequenceLengthList[number] if (number % 2): newNumber = 3*number + 1 else : newNumber = number / 2 length = 1 + findCollatzSequenceLength(newNumber) if (number < SequenceListMax): SequenceLengthList[number] = length return length def testFindCollatzSequenceLength(): assert(findCollatzSequenceLength(13) == 10) assert(findCollatzSequenceLength(2) == 2) assert(findCollatzSequenceLength(4) == 3) testFindCollatzSequenceLength() maxLength = 1 for i in range(2,SequenceListMax): length = findCollatzSequenceLength(i) if length > maxLength: print " found a new max: ", i, " => " , length maxLength = length
6d3f882a0ebe74f18cce2aa2371f125032143066
dharunsri/Python_Journey
/Bubble_Sort.py
503
4.15625
4
# Bubble sort # Bubble sort takes 1st two values and compare if its big it swaps and then values get iterated and check for next 2 values and it continued def sort(lst): for i in range(len(lst)-1,0,-1): # outter loop - focus on total iteration for j in range(i): # inner loop - focus on number of values compare if lst[j]>lst[j+1]: lst[j],lst[j+1] = lst[j+1], lst[j] print(lst) lst = [2,1,5,3,8,6] sort(lst)
0e44b0d4de2846035cc30ae1a7b4da8668a7be53
JagadeeshmohanD/PythonTutorials
/ArrayProgramPractice/arrayMonotonic.py
405
4.09375
4
#An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. def isMonotonic(A): return (all(A[i]<=A[i+1]for i in range(len(A)-1)) or all(A[i]>=A[i+1]for i in range(len(A)-1))) #driving program # A = [6,5,4,4] A=[5,4,7,9,3] if bool(True):{ print(isMonotonic(A),"monotonic") } else:{ print("not monotonic") }
5d48b02ae607f6f754a1523f224958b06350bd33
BIDMAL/codewarsish
/LeetCode/Python/200-NumberOfIslands.py
3,575
3.59375
4
from typing import List from collections import deque """ Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. """ class Solution: # DFS def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 m, n = len(grid), len(grid[0]) ans = 0 def dfs(i, j): grid[i][j] = '2' for di, dj in (0, 1), (0, -1), (1, 0), (-1, 0): ii, jj = i+di, j+dj if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] == '1': dfs(ii, jj) for i in range(m): for j in range(n): if grid[i][j] == '1': dfs(i, j) ans += 1 return ans class SolutionBFS: # BFS def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 m, n = len(grid), len(grid[0]) ans = 0 for i in range(m): for j in range(n): if grid[i][j] == '1': q = deque([(i, j)]) grid[i][j] = '2' while q: x, y = q.popleft() for dx, dy in (0, 1), (0, -1), (1, 0), (-1, 0): xx, yy = x+dx, y+dy if 0 <= xx < m and 0 <= yy < n and grid[xx][yy] == '1': q.append((xx, yy)) grid[xx][yy] = '2' ans += 1 return ans class UF: def __init__(self, n): self.p = [i for i in range(n)] self.n = n self.size = n def union(self, i, j): pi, pj = self.find(i), self.find(j) if pi != pj: self.size -= 1 self.p[pj] = pi def find(self, i): if i != self.p[i]: self.p[i] = self.find(self.p[i]) return self.p[i] class SolutionUF: # Union-Find def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 m, n = len(grid), len(grid[0]) d = dict() idx = 0 for i in range(m): for j in range(n): if grid[i][j] == '1': d[i, j] = idx idx += 1 uf = UF(idx) for i in range(m): for j in range(n): if grid[i][j] == '1': if i > 0 and grid[i-1][j] == '1': uf.union(d[i-1, j], d[i, j]) if j > 0 and grid[i][j-1] == '1': uf.union(d[i, j-1], d[i, j]) return uf.size def test(input, output): solution = Solution() out = solution.numIslands(input) assert out == output if __name__ == '__main__': test( input=[ ["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"] ], output=1 ) test( input=[ ["1", "1", "0", "0", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "1", "0", "0"], ["0", "0", "0", "1", "1"] ], output=3 ) test( input=[ ["1", "1", "1"], ["0", "1", "0"], ["1", "1", "1"] ], output=1 )
9702b373677360f58f4a0cea397df47f339b45e5
dayananda30/Crack_Interviews
/Comprehensive Python Cheatsheet/Syntax/lamda_functions.py
923
4.4375
4
""" Python Lambda Functions are anonymous function means that the function is without a name. Syntax: lambda arguments: expression This function can have any number of arguments but only one expression, which is evaluated and returned. """ lamdbda_print = lambda input_string: print(input_string) lamdbda_print("Learning Lamda function") lamdbsa_cube = lambda number: number * number * number print(lamdbsa_cube(5)) # We can supply argument in lambda function itself (lambda x: print(x + 1))(2) tables = [lambda x=x: 10 * x for x in range(1, 11)] print("The Length of the list : {}".format(len(tables))) for table in tables: print(table()) # Lambda function with if else statement (lambda x: print("{} is Positive Number".format(x)) if (x >= 0) else print("{} is Negative Number".format(x)))(-1) (lambda x: print("{} is Positive Number".format(x)) if (x >= 0) else print("{} is Negative Number".format(x)))(1)
53874022e9ca00d8e3b286fcf27c6bb0d9e20f08
zelmaru/python_algorithms
/binary_search.py
447
3.921875
4
def binary_search(list, item): low = 0 high = len(list) - 1 while low <= high: # while we did not eliminate it to 1 element mid = (low + high) // 2 #get answer w/o the remainder guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid + 1 return None #if no item found my_list = [1, 2, 3, 4, 5, 6] print(binary_search(my_list, 6)) print(binary_search(my_list, 0))
fbf15b64c9b9050c954401cb0e0a923879b10f4b
kutipense/py-works
/mazegen.py
1,425
3.578125
4
import random import sys class Node(): def __init__(self, *args, **kwargs): self.isVisited = False self.type = 0 # 0: wall, 1: free space def __str__(self): return str(self.type) class MazeGen(): directions = ( (2,0,1,0), (0,2,0,1), (-2,0,-1,0), (0,-2,0,-1) ) def __init__(self, size): self.maze = [[Node() for _ in range(size)] for _ in range(size)] def __str__(self): return ''.join([''.join(map(str,i)) for i in self.maze]) def control(self,x,y): return 0<x<size and 0<y<size and not self.maze[x][y].isVisited def generate(self,x,y): self.maze[x][y].isVisited = True self.maze[x][y].type = 1 adjancents = [] for x_n, y_n, x_, y_ in self.directions: dx, dy = x+x_n, y+y_n if self.control(dx,dy): adjancents.append((dx,dy,x_, y_)) if adjancents: random.shuffle(adjancents) for x_next, y_next, x_, y_ in adjancents: if not self.maze[x_next][y_next].isVisited: self.maze[x+x_][y+y_].type = 1 self.generate(x_next, y_next) if __name__=='__main__': size = int(sys.argv[1]) size += not size%2 generator = MazeGen(size) generator.generate(1,1) with open('random.maze','w') as f: print(size,generator,sep='\n',file=f)
32a124b55238e3d8fa6bcc8f85ebb4d13909c658
ahmed-kaif/python-for-everybody
/course_2/ex_09_01.py
563
3.796875
4
# dictonary type in python name = input("Enter file:") if len(name) < 1: name = "mbox-short.txt" fh = open(name) counts = dict() for line in fh: if not line.startswith('From '): continue else: line = line.rstrip() pieces = line.split() words = pieces[1] counts[words] = counts.get(words, 0) + 1 bigCount = None bigWord = None for word, count in counts.items(): if bigCount is None or count > bigCount: bigWord = word bigCount = count print(bigWord, bigCount) print(max(counts.values()))
309f7f242a35637c8967cfe49f668e91041e30ea
cagatayonder/Cs50x-2019
/pset6/credit/credit.py
2,068
3.625
4
from cs50 import get_int import math card_number = get_int("Credit card number: ") n = 0 integars = [] while card_number >= 1: integar = card_number % 10 card_number = math.floor(card_number / 10) n += 1 integars.append(integar) def luhn(integars): i = 1 tf = [] while i < len(integars): # sondan ikinci rakamların ikiyle çarpımlarının rakamlarının toplamı için t1 = integars[i] * 2 if t1 >= 10: t1 = (t1 % 10) + 1 tf.append(t1) i += 2 tfinal = sum(tf) j = 0 tl = [] while j < len(integars): tl.append(integars[j]) j += 2 tfinal2 = sum(tl) tfinal3 = tfinal + tfinal2 return tfinal3 check = [13, 15, 16] if n not in check: print("INVALID") if n == 13 or n == 16: if n == 16: if (integars[15] == 5) and (integars[14] == 1 or 2 or 3 or 4 or 5): if luhn(integars) % 10 == 0: print("MASTERCARD") else: print("INVALID") elif integars[15] == 4: if luhn(integars) % 10 == 0: print("VISA") else: print("INVALID") else: print("INVALID") if n == 13: { if integars[12] == 4: if luhn(integars) % 10 == 0: print("VISA") else: print("INVALID") else: print("INVALID") } if n == 15: if integars[14] == 3 and integars[13] == 4 or 7: if luhn(integars) % 10 == 0: print("AMEX") else: print("INVALID") else: print("INVALID")
e8ed76db7df63bb28ab3d6f62c74f5070f69c4a9
beyondzhou/algorithms
/newarray2d.py
2,287
3.640625
4
from newarray import Array class Array2D: # init def __init__(self, nrows, ncols): self._theRows = Array(nrows) for i in range(len(self._theRows)): self._theRows[i] = Array(ncols) # the number of rows def numRows(self): return len(self._theRows) # the number of cols def numCols(self): return len(self._theRows[0]) # clear the array def clear(self, value): for i in range(self.numRows()): self._theRows[i].clear(value) # get the item def __getitem__(self, nTuple): assert len(nTuple) == 2, "The size of tuple should be 2." row = nTuple[0] col = nTuple[1] assert row >= 0 and row < self.numRows() and \ col >= 0 and col < self.numCols(), "out of subscript" the1dArray = self._theRows[row] return the1dArray[col] # set the itme def __setitem__(self, nTuple, value): assert len(nTuple) == 2, "The size of tuple should be 2." row = nTuple[0] col = nTuple[1] assert row >= 0 and row < self.numRows() and \ col >= 0 and col < self.numCols(), "out of subscript" the1dArray = self._theRows[row] the1dArray[col] = value # Compute the average grade of exam def avgGradeCompute(): ''' cat grade.txt 7 3 90 96 92 85 91 89 82 73 84 69 82 86 95 88 91 78 64 84 92 85 89 ''' # open the file gradeFile = open("grade.txt") # read the second line numStudents = int(gradeFile.readline()) # read the first line numExams = int(gradeFile.readline()) # init the array2d gradesArray = Array2D(numStudents, numExams) # read the grade i = 0 for line in gradeFile: grades = line.split() for j in range(len(grades)): gradesArray[i,j] = grades[j] i += 1 # close the file gradeFile.close() # compute the average grade for student in range(numStudents): total = 0.0 for col in range(numExams): total += float(gradesArray[student,col]) examAvg = total / numExams print "%2d: %6.2f" % (student+1, examAvg) if __name__ == '__main__': avgGradeCompute()
5761fa86e10617cb63a5d3e70689a83660b4b9d1
amahes7/Python-Basics
/Section 1-4/practiceCode1.py
98
3.546875
4
character="Jon snow" print(character) price=10 print(price) x = 1 y = 2 z = 3 print(((x*y)**z)/8)
b9e2fa8e2b71434188b844afe805a583e0c63ff8
seanhugh/Project_Euler_Problems
/Problem_5.py
1,078
3.8125
4
#!/usr/bin/env python #Problem_5 Soulution '''multiplication = [] palindromes = [] temp = 0 def check_palindrome(num): #abcde if num > 10000: num = str(num) if (num[0]==num[-1] and num[1]==num[-2] and num[2] == num [-3]): return 'true' else: pass def multiply(): for i in range (100, 1000): for j in range (100, 1000): temp = i * j if check_palindrome(temp) == 'true': palindromes.append(temp) def sort(list): palindromes.sort() multiply() sort(palindromes) print palindromes''' #problem 5 import timeit start = timeit.default_timer() i = 20 while (i % 2 != 0 or i % 3 != 0 or i % 4 != 0 or i % 5 != 0 or i % 6 != 0 or i % 7 != 0 or i % 8 != 0 or i % 9 != 0 or i % 10 != 0 or i % 11 != 0 or i % 12 != 0 or i % 13 != 0 or i % 14 != 0 or i % 15 != 0 or i % 16 != 0 or i % 17 != 0 or i % 18 != 0 or i % 19 != 0 or i % 20 != 0 ): i+=20 print i stop = timeit.default_timer() a = stop - start print "it took", a, "seconds"
62b15d04491574ceb78161dc271c4aa6ef734fa0
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/187/howold.py
826
3.890625
4
from dataclasses import dataclass from dateutil import parser from dateutil.relativedelta import relativedelta @dataclass class Actor: name: str born: str @dataclass class Movie: title: str release_date: str def get_age(actor: Actor, movie: Movie) -> str: """Calculates age of actor / actress when movie was released, return a string like this: {name} was {age} years old when {movie} came out. e.g. Wesley Snipes was 28 years old when New Jack City came out. """ date_delta = relativedelta(parser.parse(movie.release_date), parser.parse(actor.born)) return f"{actor.name} was {date_delta.years} years old when {movie.title} came out." # if __name__ == "__main__": # print(get_age(Actor('Wesley Snipes', 'July 31, 1962'), Movie('New Jack City', 'January 17, 1991')))
99c4237a54103df0dfa9a6a3e6c54115b19c0904
Villtord/python-course
/src/16 Scientific Libraries/03 Pandas/02_selection.py
2,237
4
4
import pandas as pd import pylab as pl pd.set_option('display.precision', 1) pd.set_option('display.width', None) # None means all data displayed pd.set_option('display.max_rows', None) def inspect(item): print() print(item) print(type(item)) print("------------------") def main(): df = pd.read_csv("data/sample.csv", skipinitialspace=True, index_col=0) print(df) # some standard dataframe methods # the index inspect(df.index) # the column headings inspect(df.columns) print(type(df.columns)) # the values of the dataset inspect(df.values) inspect(df.values[0]) inspect(df.values[0, 0]) print(list(df.index)) # convert index to a list print(list(df.columns)) # convert columns to a list # extracting a single column can create a new dataframe or a series a = df[['County']] # list parameter => returns a dataset print(f"{df[['County']]} returns: \n\t{type(a)}") b = df['County'] # scalar parameter => returns a series print(f"df['County'] returns: \n\t{type(b)}") # using .loc # loc uses the index of the dataset. A lot of datasets have an index of # integers, but the index can be any data type, often str # print 1 row inspect(df.loc['Peter']) # loc uses index # print several rows inspect(df.loc['Peter':'Bill']) # selecting rows and columns inspect(df.loc[['Peter', 'Bill'], ['County', 'Height', 'Weight']]) inspect(df.loc[:, ['County', 'Gender']]) # all rows, some columns inspect(df.loc[['Bill'], ['County']]) # 1 row, 1 column, two sets of [] inspect(df.loc['Bill', 'County']) # only 1 set of [] # remind ourselves of the complete dataframe print(df) # using iloc # iloc uses the numerical index of the dataset, starting with item 0 inspect(df.iloc[3]) # select row 3 as series inspect(df.iloc[[3, 6, 2, 4]]) # select multiple rows inspect(df.iloc[3, 2]) # select row and column # convert the index to a regular column # the new index will be numerical df.reset_index(inplace=True) print(df) main()
c5719ef09d0912a23820dc9da7643d16ae95fab3
sidaker/dq
/python_interview/code_interviews/Iterator_1.py
902
4.25
4
from itertools import count, chain, cycle def iter1(): c = count() print(next(c)) print(next(c)) print(next(c)) # you can go on def iter2(): d = cycle([1,2,3]) print(next(d)) print(next(d)) print(next(d)) print(next(d)) def iter3(): e = chain([1,2],{'adv:1'},[4,5,6],{'sid:1'}) print(next(e)) print(next(e)) print(next(e)) print(next(e)) def gen1(n): ''' Generator functions are distinguished from plain old functions by the fact that they have one or more yield statements. The easiest ways to make our own iterators in Python is to create a generator. ''' for i in range(n): yield i if __name__ == '__main__': iter1() print("*"*50) iter2() print("*"*50) iter3() print("*"*50) genobj = gen1(5) print(type(genobj)) print(genobj) for j in genobj: print(j)
991f6e079212986349f96145ce8e0fe1d6c52088
thomas-rohde/Classes-Python
/exercises/exe81 - 90/exe081.py
376
3.609375
4
n = [] n0 = [] n1 = [] #Insira um valor while True: n.append(int(input('Digite um valor: '))) r = str(input('Quer continuar? [s/n] ')) if r in 'Nn': break #Separação PAR / ÍMPAR for c in n: if c % 2 == 0: n0.append(c) else: n1.append(c) print(f'''A lista completa é {n} A lista dos pares é {n0} A lista dos ímpares é {n1}''')
3b40792a7692227eddb152f01f664fc5c7eae17a
martinamalberti/BicoccaUserCode
/FakeRate/EffAnalysis/batch/test.py
1,176
3.765625
4
#! /usr/bin/python import sys import os import stat args=sys.argv # check the command line and if wrong raise an error if len(args)!=2: print 'Usage:\n'+\ '%s CMSSW_dir rootfilelistfile basedir castor_dir queue\n' %args[0] +\ 'Example:\n'+\ '%s ./CMSSW_1_2_3 mylist.txt /tmp 8nm\n' %args[0] raise "Wrong number of arguments" # relevant parameters listofrootfiles_file_name=args[1] listofrootfiles_file=open(listofrootfiles_file_name,"r") listofrootfiles=listofrootfiles_file.readlines() listofrootfiles_file.close() import re #-------------------------------------------------------------- def removechars(string): """ removes 1st last but one and last character """ return string[1:-3] #-------------------------------------------------------------- # Loop on the content of the list of rootfiles. # map applies element by element the function removechars to the list # listofrootfiles and returns the resulting list for rootfile in map(removechars,listofrootfiles): basename = "_".join (re.match (".*/(.*)/(.*)[.]root",rootfile).group(1,2)) print basename
fe0a10db93ead8b760557a024bcd6c52ad32a754
222010326010/gradingassignment-222010326010-main
/1_problem.py
1,014
4.125
4
""" sum of first n odd numbers Exmple 1: input=3 output=9 Example 2: input=7 output=49""" import unittest def sum_of_odd_numbers(n): def oddSum(n) : sum = 0 curr = 1 i = 0 while i < n: sum = sum + curr curr = curr + 2 i = i + 1 return sum # Driver Code n = 20 print (" Sum of first" , n, "Odd Numbers is: ", oddSum(n) ) """ pass # Add these test cases, and remove this placeholder # 1. Test Cases from the Examples of Problem Statement # 2. Other Simple Cases # 3. Corner/Edge Cases # 4. Large Inputs # DO NOT TOUCH THE BELOW CODE class Testsum_of_odd_numbers(unittest.TestCase): def test_01(self): input_num = 7 output_num = 49 self.assertEqual(sum_of_odd_numbers(input_num), output_num) def test_02(self): input_num = 3 output_num = 9 self.assertEqual(sum_of_odd_numbers(input_num), output_num) if __name__ == '__main__': unittest.main(verbosity=2)
c9023dbe50645422efffafcd06e1223a0a89b6c3
malienko/projecteuler_python
/problem50.py
1,574
3.828125
4
''' The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? ''' import numpy as np import math from datetime import datetime start = datetime.now() def is_prime(x): if x < 2: return False else: for n in range(2,x): if x % n == 0: return False return True list_of_primes = [] top_limit = 10000 total = 0 arr = np.zeros((top_limit,1), dtype=bool) for num in range(len(arr)): if num > 1: for i in range(2,int(math.sqrt(num)+1)): if (num % i) == 0: break else: arr[num,0] = 1 list_of_primes = np.where(arr[:,0]==1)[0] list_of_primes = list_of_primes.tolist() sequences = [] summations = [] most_consecutive_primes = [] for i in list_of_primes: for j in list_of_primes: ind1 = list_of_primes.index(i) ind2 = list_of_primes.index(j) k = list_of_primes[ind1:-ind2] if len(k) > 21: if len(k) > len(most_consecutive_primes): summation = np.sum(k) if summation > 900_000: if summation < 1_000_000: if is_prime(summation): most_consecutive_primes = k summations.append(summation) if summations: print(max(summations)) # Answer: 997651 end = datetime.now() delta_time = end-start print(delta_time) # 0:00:48.028184
13e67dc7f9af4caf03239050248557db16cc90f1
bbwong23/flask101
/service/calculator.py
777
3.828125
4
################################################################## # *** DO NOT EDIT THIS FILE *** # All the functions below take a list of numbers as an argument ################################################################## def mean(number_list): size = len(number_list) return 0 if size == 0 else sum(number_list)/size def median(number_list): number_list.sort() size = len(number_list) if size == 0: median_index = "No median found because list is empty" else: median_index = int(size / 2) + size % 2 return median_index def mode(number_list): if len(number_list) == 0: mode_value = "No mode found because list is empty" else: mode_value = max(set(number_list), key=number_list.count) return mode_value
2fa3eba5d32abe0eb4810a10b8aca354cf77d53c
Rahulgarg95/datastructures-python
/linked_list.py
2,128
4.0625
4
class Element(object): def __init__(self,value): self.value=value self.next=None def print_el(self): print("Element: ",self.value) class LinkedList(object): #Function for initialization def __init__(self, head=None): self.head=head #Add new el to end of list def append(self, new_el): current=self.head if(self.head): while(current.next): current=current.next current.next=new_el else: self.head=new_el def get_position(self, pos): i=1 current=self.head if(pos<1): return None while current and i<=pos: if(pos==i): return current current=current.next i=i+1 return None def insert(self, new_el, pos): i=1 current=self.head if(pos>1): while current and i<pos: if(i==pos-1): new_el.next=current.next current.next=new_el current=current.next i=i+1 elif pos==1: new_el.next=self.head self.head=new_el def delete(self, value): current=self.head previous=None while current.value !=value and current.next: previous=current current=current.next if current.value == value: if previous: previous.next=current.next else: self.head=current.next def printlist(self): current=self.head while current: print(current.value," --> ") current=current.next a=Element(11) b=Element(22) c=Element(33) d=Element(44) e=Element(55) a.print_el() b.print_el() c.print_el() d.print_el() e.print_el() l1=LinkedList(a) l1.append(b) l1.append(c) l1.insert(d, 3) print(l1.get_position(3).value) l1.insert(e,4) print(l1.get_position(4).value) print("Print el ",l1.head.next.next.next.next.value) val=2 print(l1.get_position(val).value) l1.printlist() l1.delete(44) l1.printlist()
0a44d7b648fcb19bfc40ce10f77cbd177cad4898
branislavblazek/notes
/Python/1.lesson/vstup.py
425
3.625
4
print('Zadajte celočíselné hodnoty a stlačte Enter, v prípade skončenie stlačte Enter') total = 0 count = 0 while True: try: line = input('čislo: ') if line: number = int(line) except ValueError: print('Zadajte celé číslo!') continue except EOFError: break total += number count += 1 if count: print(total, count)
f596322d2f4e0f561f725d2ef15fcaf71cfb922f
Soham2020/Python-basic
/lists/multiplyAllElemnts_Array.py
171
4
4
a = [] print("Enter the Array Elements::") for i in range(5): n = int(input()) a.append(n) p = 1 for i in a: p = p*i print("Product of all Elements are :: ", p)
a6f6efb3c9d04f4a026d63a26ce97f891ab76deb
nvansturgill/Guessing-Game
/myGuessingGame.py
797
4.125
4
# Import built-in module for generating (random) number import random # Prompt, store, and print user name as `user` user = input("Hello, there. Enter your name to begin... ") print("Alright, {}!".format(user)) print("I'm thinking of a number between 1 and 10") # Generate random integer and store as `num` number = random.randint(1, 10) # Initialize `number_of_guesses` for counting tries (guesses) number_of_guesses = 0 while number_of_guesses < 10: guess = int(input("Take a guess: ")) number_of_guesses += 1 if guess < number: print("Shucks, your number is too low.") if guess > number: print("Rats! Your number is too high.") if guess == number: print("You guessed the number") print("{} gets a gold star." .format(user)) break
df92204548760384933e84f3468e88d28ce625da
clonest1ck/advent_of_code_2020
/day3.py
934
3.828125
4
class Tile: def __init__(self, is_tree): self.is_tree = is_tree def Travel(tiles, dx, dy): mapwidth = len(tiles[0]) - 1 mapheight = len(tiles) x = dx % mapwidth y = dy trees = 0 while y < mapheight: is_tree = tiles[y][x].is_tree if tiles[y][x].is_tree: trees += 1 x = (x + dx) % mapwidth y += dy return trees f = open('day3.txt') tiles = [] for line in f: row = [] for tile in line: if tile == "#": row.append(Tile(True)) else: row.append(Tile(False)) tiles.append(row) trees = Travel(tiles, 3, 1) print("Part 1: We encountered %d trees" % trees) trees_1 = Travel(tiles, 1, 1) trees_2 = trees trees_3 = Travel(tiles, 5, 1) trees_4 = Travel(tiles, 7, 1) trees_5 = Travel(tiles, 1, 2) product = trees_1 * trees_2 * trees_3 * trees_4 * trees_5 print("Part 2: The product is %d" % product)
64325183606c8f39513076e9cc44baeda37598f5
qorjiwon/LevelUp-Algorithm
/Programmers/Programmers_여행경로.py
992
3.546875
4
''' Programmers 여행경로 Prob. https://programmers.co.kr/learn/courses/30/lessons/43164?language=java Ref. https://dailyheumsi.tistory.com/22 Start Day: 2019. 09. 15 End Day: 미완성 - 오름차순 경로 불가능 ''' def dfs(node, tickets, visit, temp, answer, cnt): answer.append(node) if cnt is len(tickets): return True for i in range(len(tickets)): if (tickets[i][0] is node) and (visit[i] is False): visit[i] = True success = dfs(tickets[i][1], tickets, visit, temp, answer, cnt+1) if success: return True visit[i] = False answer.pop() return False def solution(tickets): temp = [] answer = [] visit = [False] * len(tickets) tickets = sorted(tickets, key=lambda x: x[0]) dfs("ICN", tickets, visit, temp, answer, 0) return answer print(solution([["ICN", "SFO"], ["ICN", "ATL"], ["SFO", "ATL"], ["ATL", "ICN"], ["ATL", "SFO"]]))
31a9cb894d9791660b213c21fc44c5302a71e5e3
sarim26/my-caluclator
/goodbasiccaluclator.py
1,109
4.15625
4
def addition(): num1 = input("Enter a number") num2 = input("Enter a number to add") answer_add = float(num1) + float(num2) print(answer_add) def subtract(): num3 = input("enter a number") num4 = input("enter your second number") answer_substract = float(num3) - float(num4) print(answer_substract) def multiply(): num5 = input("enter a number") num6 = input("enter your second number") answer_multiply = float(num4) * float(num6) print(answer_multiply) def divide(): num7 = input ("enter a number") num8 = input ("enter your second number") answer_divide = float(num7) / float(num8) print(answer_divide) ask = input ("You want to add, subtract, multiply or divide numbers?") if ask == "add": add() elif ask == "subtract": subtract() if ask == "multiply": multiply() elif ask == "divide": divide()
69de20cdb70a735114caf7349daef8071cac6fd0
npkhanhh/codeforces
/python/round537/1111A.py
359
3.609375
4
v = {'a':1, 'e':1, 'i':1, 'o':1, 'u':1} s1 = input() s2 = input() if len(s1) != len(s2): print('No') else: res = True for i in range(len(s1)): if s1[i] in v and s2[i] not in v: res = False break elif s1[i] not in v and s2[i] in v: res = False break print('Yes' if res else 'No')
21c112b4ec3d0fa090e216706ea6f2803fa1a9be
krishna-j-rajan/movielist
/mymovielist.py
1,164
3.546875
4
import mysql.connector db_connection = mysql.connector.connect( host="localhost", user="krishna", passwd="k@[email protected]", database="NAME" ) db_cursor = db_connection.cursor() db_cursor.execute("CREATE TABLE mymovielist (Slno INT, movie_name VARCHAR(255),actor_name VARCHAR(255),actress_name VARCHAR(255),year_of_release INT,director_name VARCHAR(255))") insert_stmt= ("INSERT INTO customers(Slno, movie_name, actor_name, actress_name, year_of_release, director_name)" "VALUES (%d,%s,%s,%s,%d,%s)") data=[ (1,'Quills', 'Geoffrey Rush','Kate Winslet',2000,'Philip Kaufman'), (2,'Unlikely Hero', 'Jeff Daniels','Emma Stone',2009,'Kieran Mulroney'), (3,'Bernie', 'Jack Black','Jack Black',2011,'Richard Linklater'), (4,'The Experts', 'John Travolta','Arye Gross',1989,'Dave Thomas'), (5,'Mike Nichols', 'Jack Nicholson','Meryl Streep',1986,'Dave Thomas') ] try: db_cursor.executemany(insert_stmt,data) db_connection.commit() except: db_connection.rollback() cursor = db.cursor() query1 = "SELECT * FROM mymovielist" query = "SELECT movie_name, actor_name FROM mymovielist" cursor.execute(query1) cursor.execute(query) data = cursor.fetchall() for pair in data: print(pair) print("Data inserted") db_connection.close()
08d1d43b365e2aaff7cd46a668cd9326162b6b75
txwjj33/leetcode
/problems_100/023_mergeKLists.py
6,603
4
4
''' 题目:合并K个排序链表 描述: 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None ''' 把每个值对应的ListNode串起来,head,tai分别保存这个串的首位 然后把keys排序,从小到大把这些串再连到一起 这个方法最主要的是不需要创建多余的ListNode,所以很快 其实这个题目费时的不是排序,而是创建那些ListNode 能达到56ms,是所有提交里最快的 如果把那些keys按照原来的lists顺序存在一个list里面,然后使用更快的排序方式,应该能比56更小 ''' class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None if len(lists) == 1: return lists[0] head = {} tail = {} for t in lists: while(t): v = t.val if v in head: tail[v].next = t tail[v] = t else: head[v] = t tail[v] = t t = t.next keys = head.keys() keys.sort() r = ListNode(0) temp = r for k in keys: temp.next = head[k] temp = tail[k] return r.next ''' 每两个列表排序合并成新的列表,所有新的列表放在一起,作为新的lists,如果len(lists) > 1,则继续 相比以下的方法优化点在于,中间的计算结果都是list,不用ListNode,最后返回的时候再把list转成ListNode 112 ms ''' class Solution(object): def mergeTwoListNode(self, l1, l2): r = [] while(l1 or l2): if l1 == None: r.append(l2.val) l2 = l2.next continue if l2 == None: r.append(l1.val) l1 = l1.next continue x1 = l1.val x2 = l2.val if x1 <= x2: r.append(x1) l1 = l1.next else: r.append(x2) l2 = l2.next return r def mergeTwoList(self, l1, l2): if len(l1) == 0: return l2 if len(l2) == 0: return l1 r = [] i, j = 0, 0 while True: if i >= len(l1): return r + l2[j:] if j >= len(l2): return r + l1[i:] if l1[i] <= l2[j]: r.append(l1[i]) i += 1 else: r.append(l2[j]) j += 1 return r def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None if len(lists) == 1: return lists[0] first = True while(len(lists) > 1): newLists = [] i = 0 while(i < len(lists) - 1): if first: l = self.mergeTwoListNode(lists[i], lists[i + 1]) newLists.append(l) else: l = self.mergeTwoList(lists[i], lists[i + 1]) newLists.append(l) i += 2 if i == len(lists) - 1: if first: r = [] p = lists[-1] while(p): r.append(p.val) p = p.next newLists.append(r) else: newLists.append(lists[-1]) lists = newLists if first: first = False l = lists[0] if len(l) == 0: return None r = ListNode(l[0]) temp = r for i in range(1, len(l)): temp.next = ListNode(l[i]) temp = temp.next return r ''' 每两个列表排序合并成新的列表,所有新的列表放在一起,作为新的lists,如果len(lists) > 1,则继续 设m为lists的个数 时间大概是log2(m) * max(len(m)) 376 ms ''' class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None while(len(lists) > 1): newLists = [] i = 0 while(i < len(lists) - 1): a1 = lists[i] a2 = lists[i + 1] r = ListNode(0) temp = r while True: if a1 == None: temp.next = a2 break if a2 == None: temp.next = a1 break x1 = a1.val x2 = a2.val if x1 <= x2: a1 = a1.next temp.next = ListNode(x1) else: a2 = a2.next temp.next = ListNode(x2) temp = temp.next newLists.append(r.next) i += 2 if i == len(lists) - 1: newLists.append(lists[-1]) lists = newLists return lists[0] ''' 把前两个列表排序合并成新的列表,然后把新的列表与下一个比较, 超时 设m为lists的个数 时间大概是m * len(l1) + (m- 1) * len(l2) + (m - 2) * len(l3) + ... ''' class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None r = lists[0] for i in range(1, len(lists)): a1 = r a2 = lists[i] r = ListNode(0) temp = r while True: if a1 == None: temp.next = a2 break if a2 == None: temp.next = a1 break x1 = a1.val x2 = a2.val if x1 <= x2: a1 = a1.next temp.next = ListNode(x1) else: a2 = a2.next temp.next = ListNode(x2) temp = temp.next r = r.next return r
7a2ff7c720d5d51599867a0bd22344aa3462039f
kazuya075/c_of_school
/python/Py20200417/Py20200417/Py20200417.py
105
3.734375
4
d={'name':'guide','birthday':1964} ss="{0[birthday]}is{0[name]}'s birthday" ss=ss.format(d) print(ss)
ed61dd4fa36618fa3891b3c50820638ba3c46cdf
Thearakim/basic_python
/week01/ex/e20_decode.py
553
4.3125
4
a = str() string = input("Enter your encrypted message:\n>> ") if string == "": #if string empty print Nothing to decode print("Nothing to decode") else: for x in string: x = ord(x) #convert x to ord if x >= 65 and x+13 <= 103: x += 13 if x > 90: #103-13 because if plus 13 more gonna be out of characters x -= 26 elif x >= 97 and x+13 <= 135: x += 13 if x > 122: x -= 26 else: x = x a += chr(x) print(str(a))
ff29f225940677e543096fba0421f015e871df31
aricsanders/pyMez3
/Code/Analysis/Fitting.py
23,347
3.546875
4
#----------------------------------------------------------------------------- # Name: Fitting # Purpose: Functions and classes for fitting data # Author: Aric Sanders # Created: 9/9/2016 # License: MIT License #----------------------------------------------------------------------------- """ Fitting is a module containing classes and functions for fitting and simulating data. Examples -------- #!python >>line=FunctionalModel(variables='x',parameters='m b',equation='m*x+b') >>line(m=2,b=5,x=np.array([1,2,3])) <h3><a href="../../../Examples/html/Fitting_Example.html">Fitting Example</a></h3> Requirements ------------ + [sys](https://docs.python.org/2/library/sys.html) + [os](https://docs.python.org/2/library/os.html) + [re](https://docs.python.org/2/library/re.html) + [types](https://docs.python.org/2/library/types.html) + [numpy](https://docs.scipy.org/doc/) + [scipy](https://docs.scipy.org/doc/) + [sympy](http://www.sympy.org/en/index.html) Help --------------- <a href="./index.html">`pyMez.Code.Analysis`</a> <div> <a href="../../../pyMez_Documentation.html">Documentation Home</a> | <a href="../../index.html">API Documentation Home</a> | <a href="../../../Examples/html/Examples_Home.html">Examples Home</a> | <a href="../../../Reference_Index.html">Index</a> </div> """ #----------------------------------------------------------------------------- # Standard Imports import os import sys from types import * import re #----------------------------------------------------------------------------- # Third Party Imports try: from Code.Utils.Types import * except: print("The module pyMez.Code.Utils.Types was not found or had an error," "please check module or put it on the python path") raise ImportError try: import numpy as np except: print("The module numpy either was not found or had an error" "Please put it on the python path, or resolve the error") raise try: import sympy except: print("The module sympy either was not found or had an error" "Please put it on the python path, or resolve the error (http://www.sympy.org/en/index.html)") raise try: import scipy import scipy.optimize import scipy.stats except: print("The modules scipy.optimize and scipy.stats were not imported correctly" "Please scipy on the python path, or resolve the error " "(http://docs.scipy.org/doc/scipy/reference/index.html)") raise try: import matplotlib.pyplot as plt except: print("The module matplotlib was not found," "please put it on the python path") #----------------------------------------------------------------------------- # Module Constants #----------------------------------------------------------------------------- # Module Functions #TODO: These definitions of fits do not use the FittingFunction Class # These fits are all of the form f(parameters,variables) def line_function(a,x): "line function (y=a[1]x+a[0])" return a[1]*x+a[0] def lorentzian_function(a,x): "a[0]=amplitude,a[1]=center,a[2]=FWHM" return a[0]*1/(1+(x-a[1])**2/(a[2]**2)) def gaussian_function(a,x): " a[0]=amplitude, a[1]=center, a[2]=std deviation" return a[0]*scipy.exp(-(x-a[1])**2/(2.0*a[2]**2)) def least_squares_fit(function,xdata,ydata,initial_parameters): """Returns a parameter list after fitting the data x_data,y_data with the function in the form of f(parameter_list,x)""" error_function=lambda a, xdata, ydata:function(a,xdata)-ydata a,success=scipy.optimize.leastsq(error_function, initial_parameters,args=(np.array(xdata),np.array(ydata))) return a def calculate_residuals(fit_function,a,xdata,ydata): """Given the fit function, a parameter vector, xdata, and ydata returns the residuals as [x_data,y_data]""" output_x=xdata output_y=[fit_function(a,x)-ydata[index] for index,x in enumerate(xdata)] return [output_x,output_y] def build_modeled_data_set(x_list,function_list): """build_modeled_data_set takes an input independent variable and a list of functions and returns a data set of the form [..[xi,f1(xi),..fn(xi)]] it is meant to create a modeled data set. Requires that the list of functions is callable f(x) is defined""" out_data=[] for x in x_list: new_row=[] new_row.append(x) for function in function_list: if type(function(x)) in [np.ndarray,'numpy.array']: # to list is needed if the function returns np.array new_row.append(function(x).tolist()) else: new_row.append(function(x)) out_data.append(new_row) return out_data #----------------------------------------------------------------------------- # Module Classes class FunctionalModel(object): """FittingModel is a class that holds a fitting function, it uses sympy to provide symbolic manipulation of the function and formatted output. If called it acts like a traditional python function. Initialize the class with parameters, variables and an equation. Ex. line=FunctionalModel(variables='x', parameters='m b', equation='m*x+b'), to call as a function the parameters must be set. line(m=2,b=1,x=1) or line.set_parameters(m=1,b=2) line(1)""" def __init__(self,**options): defaults= {"parameters":None,"variables":None,"equation":None,"parameter_values":{}} self.options={} for key,value in defaults.items(): self.options[key]=value for key,value in options.items(): self.options[key]=value # fix any lists for item in ["parameters","variables"]: if isinstance(self.options[item], StringType): self.options[item]=re.split("\s+",self.options[item]) self.__dict__[item]=self.options[item] self.__dict__[item+"_symbols"]=sympy.symbols(self.options[item]) # this creates the python variables in the global namespace, may back fire with lots of variables for index,symbol in enumerate(self.__dict__[item+"_symbols"][:]): globals()[item[index]]=symbol self.options[item]=None self.equation=sympy.sympify(self.options["equation"]) self.function=sympy.lambdify(self.parameters+self.variables,self.equation,'numpy') self.parameter_values=self.options["parameter_values"] self.options["parameter_values"]={} def __call__(self,*args,**keywordargs): """Controls the behavior when called as a function""" return self.function(*args,**keywordargs) def set_parameters(self,parameter_dictionary=None,**parameter_dictionary_keyword): """Sets the parameters to values in dictionary""" if parameter_dictionary is None: try: parameter_dictionary=parameter_dictionary_keyword except: pass self.parameter_values=parameter_dictionary self.function=sympy.lambdify(self.variables,self.equation.subs(self.parameter_values),'numpy') def clear_parameters(self): """Clears the parmeters specified by set_parameters""" self.function=sympy.lambdify(self.parameters+self.variables,self.equation,'numpy') self.parameter_values={} def fit_data(self,x_data,y_data,**options): """Uses the equation to fit the data, after fitting the data sets the parameters. """ defaults= {"initial_guess":{parameter:0.0 for parameter in self.parameters},"fixed_parameters":None} self.fit_options={} for key,value in defaults.items(): self.fit_options[key]=value for key,value in options.items(): self.fit_options[key]=value def fit_f(a,x): self.clear_parameters() input_list=[] for parameter in a: input_list.append(parameter) input_list.append(x) return self.function(*input_list) # this needs to be reflected in fit_parameters a0=[] for key in self.parameters[:]: a0.append(self.fit_options["initial_guess"][key]) a0=np.array(a0) result=least_squares_fit(fit_f,x_data,y_data,a0) fit_parameters=result.tolist() fit_parameter_dictionary={parameter:fit_parameters[index] for index,parameter in enumerate(self.parameters)} self.set_parameters(fit_parameter_dictionary) def __div__(self, other): return self.__truediv__(other) def __add__(self,other): """Defines addition for the class, if it is another functional model add the models else just change the equation""" if isinstance(other,FunctionalModel): parameters=list(set(self.parameters+other.parameters)) variables=list(set(self.variables+other.variables)) #print("{0} is {1}".format("parameters",parameters)) #print("{0} is {1}".format("variables",variables)) equation=self.equation+other.equation #print("{0} is {1}".format("equation",equation)) else: parameters=self.parameters variables=self.variables equation=self.equation+other new_function=FunctionalModel(parameters=parameters,variables=variables,equation=equation) return new_function def __sub__(self,other): """Defines subtraction for the class""" if isinstance(other,FunctionalModel): parameters=list(set(self.parameters+other.parameters)) variables=list(set(self.variables+other.variables)) #print("{0} is {1}".format("parameters",parameters)) #print("{0} is {1}".format("variables",variables)) equation=self.equation-other.equation #print("{0} is {1}".format("equation",equation)) else: parameters=self.parameters variables=self.variables equation=self.equation-other new_function=FunctionalModel(parameters=parameters,variables=variables,equation=equation) return new_function def __mul__(self,other): """Defines multiplication for the class""" if isinstance(other,FunctionalModel): parameters=list(set(self.parameters+other.parameters)) variables=list(set(self.variables+other.variables)) #print("{0} is {1}".format("parameters",parameters)) #print("{0} is {1}".format("variables",variables)) equation=self.equation*other.equation #print("{0} is {1}".format("equation",equation)) else: parameters=self.parameters variables=self.variables equation=self.equation*other new_function=FunctionalModel(parameters=parameters,variables=variables,equation=equation) return new_function def __pow__(self,other): """Defines power for the class""" if isinstance(other,FunctionalModel): parameters=list(set(self.parameters+other.parameters)) variables=list(set(self.variables+other.variables)) #print("{0} is {1}".format("parameters",parameters)) #print("{0} is {1}".format("variables",variables)) equation=self.equation**other.equation #print("{0} is {1}".format("equation",equation)) else: parameters=self.parameters variables=self.variables equation=self.equation**other new_function=FunctionalModel(parameters=parameters,variables=variables,equation=equation) return new_function def __truediv__(self,other): """Defines division for the class""" if isinstance(other,FunctionalModel): parameters=list(set(self.parameters+other.parameters)) variables=list(set(self.variables+other.variables)) #print("{0} is {1}".format("parameters",parameters)) #print("{0} is {1}".format("variables",variables)) equation=self.equation/other.equation #print("{0} is {1}".format("equation",equation)) else: parameters=self.parameters variables=self.variables equation=self.equation/other new_function=FunctionalModel(parameters=parameters,variables=variables,equation=equation) return new_function def __str__(self): """Controls the string behavior of the function""" return str(self.equation.subs(self.parameter_values)) def compose(self,other): """Returns self.equation.sub(variable=other)""" if len(self.variables)==1: variables=other.variables parameters=list(set(self.parameters+other.parameters)) equation=self.equation.subs({self.variables[0]:other}) new_function=FunctionalModel(parameters=parameters,variables=variables,equation=equation) return new_function else: return None def to_latex(self): """Returns a Latex form of the equation using current parameters""" return sympy.latex(self.equation.subs(self.parameter_values)) def plot_fit(self,x_data,y_data,**options): """Fit a data set and show the results""" defaults={"title":True} plot_options={} for key,value in defaults.items(): plot_options[key]=value for key,value in options.items(): plot_options[key]=value self.fit_data(x_data,y_data,**plot_options) figure=plt.figure("Fit") plt.plot(x_data,y_data,label="Raw Data") plt.plot(x_data,self.function(x_data),'ro',label="Fit") plt.legend(loc=0) if plot_options["title"]: if plot_options["title"] is True: plt.title(str(self)) else: plt.title(plot_options["title"]) plt.show() return figure def d(self,respect_to=None,order=1): """Takes the derivative with respect to variable or parameter provided or defaults to first variable""" if respect_to is None: respect_to=self.variables[0] equation=self.equation.copy() for i in range(order): equation=sympy.diff(equation,respect_to) return FunctionalModel(parameters=self.parameters[:],variables=self.variables[:],equation=str(equation)) def integrate(self,respect_to=None,order=1): """Integrates with respect to variable or parameter provided or defaults to first variable. Does not add a constant of integration.""" if respect_to is None: respect_to=self.variables_symbols[0] equation=self.equation.copy() for i in range(order): equation=sympy.integrate(equation,respect_to) return FunctionalModel(parameters=self.parameters[:],variables=self.variables[:],equation=str(equation)) # todo: This feature does not work because of the namspace of the parameters and variables # I don't know what name sympify uses when it creates the equation # def series(self,variable_or_parameter,value=0,order=6): # """Calculates the symbolic series expansion of order around the variable or parameter value # of the functional model. Returns a new FunctionalModel""" # equation=sympy.series(self.equation,variable_or_parameter,value,order).removeO() # parameters=self.parameters[:] # variables=self.variables[:] # return FunctionalModel(equation=equation,variables=variables,parameters=parameters) def limit(self,variable_or_parameter,point): """Finds the symbolic limit of the FunctionalModel for the variable or parameter approaching point""" equation=sympy.limit(self.equation,variable_or_parameter,point) parameters=self.parameters[:] variables=self.variables[:] return FunctionalModel(equation=equation,variables=variables,parameters=parameters) class DataSimulator(object): """A class that simulates data. It creates a data set from a FunctionalModel with the parameters set, and an optional output noise. The attribute self.x has the x data and self.data has the result. The simulator may be called as a function on a single point or an numpy array.""" def __init__(self,**options): """Intializes the DataSimulator class""" defaults= {"parameters":None, "variables":None, "equation":None, "parameter_values":{}, "model":None, "variable_min":None, "variable_max":None, "number_points":None, "variable_step":None, "output_noise_type":None, "output_noise_width":None, "output_noise_center":None, "output_noise_amplitude":1., "random_seed":None, "x":np.array([])} self.options={} for key,value in defaults.items(): self.options[key]=value for key,value in options.items(): self.options[key]=value # set the self.model attribute if self.options["model"]: self.model=self.options["model"] else: # try and create the model from the options try: self.model=FunctionalModel(variables=self.options["variables"], parameters=self.options["parameters"], equation=self.options["equation"]) except: print("Could not form a model from the information given, either model has to be specified or" "parameters, variables and equation has to be specified") # todo: make an error specific to this case raise if self.options["parameter_values"]: self.model.set_parameters(self.options["parameter_values"]) self.x=self.options["x"] self.random_seed=self.options["random_seed"] output_noise_names=["type","center","width","amplitude"] for index,output_noise_name in enumerate(output_noise_names): self.__dict__["output_noise_{0}".format(output_noise_name)]=self.options["output_noise_{0}".format(output_noise_name)] self.set_output_noise() if self.options["variable_min"] and self.options["variable_max"]: self.set_x(variable_min=self.options["variable_min"], variable_max=self.options["variable_max"], number_points=self.options["number_points"], variable_step=self.options["variable_step"]) self.set_parameters=self.model.set_parameters self.clear_parameters=self.model.clear_parameters self.set_data() def set_x(self, variable_min=None, variable_max=None,number_points=None,variable_step=None): """Sets the dependent variable values, min, max and number of points or step""" if [variable_min,variable_max]==[None,None]: self.x=np.array([]) else: if variable_step: number_points=(variable_max-variable_min)/variable_step self.x=np.linspace(variable_max,variable_min,number_points) self.set_output_noise() def set_output_noise(self,output_noise_type=None,output_noise_center=None,output_noise_width=None,output_noise_amplitude=1.): """Set the output noise distrubution. Possible types are gaussian, uniform, triangular, lognormal, with the assumption all are symmetric """ output_noise_characteristics=[output_noise_type,output_noise_center,output_noise_width,output_noise_amplitude] output_noise_names=["type","center","width","amplitude"] for index,output_noise_characteristic in enumerate(output_noise_characteristics): if output_noise_characteristic: self.__dict__["output_noise_{0}".format(output_noise_names[index])]=output_noise_characteristic if self.output_noise_type is None or not self.x.any(): self.output_noise=np.array([]) else: # set the random seed np.random.seed(self.random_seed) # now handle the output types, all in np.random if re.search("gauss|normal",self.output_noise_type,re.IGNORECASE): self.output_noise=output_noise_amplitude*np.random.normal(self.output_noise_center, self.output_noise_width,len(self.x)) elif re.search("uni|square|rect",self.output_noise_type,re.IGNORECASE): self.output_noise=output_noise_amplitude*np.random.uniform(self.output_noise_center-self.output_noise_width/2, self.output_noise_width+self.output_noise_width/2, len(self.x)) elif re.search("tri",self.output_noise_type,re.IGNORECASE): self.output_noise=output_noise_amplitude*np.random.triangular(self.output_noise_center-self.output_noise_width/2, self.output_noise_center, self.output_noise_width+self.output_noise_width/2, len(self.x)) self.set_data() def set_data(self): if self.model.parameter_values: if self.output_noise.any(): out_data=self.model(self.x)+self.output_noise else: if self.x.any(): out_data=self.model(self.x) else: out_data=[] else: out_data=[] self.data=out_data def get_data(self): return self.data[:] def __call__(self,x_data): """Returns the simulated data for x=x_data, to have deterministic responses, set self.random_seed""" if type(x_data) not in [np.array]: if isinstance(x_data, ListType): x_data=np.array(x_data) else: x_data=np.array([x_data]) #print("{0} is {1}".format("x_data",x_data)) self.x=x_data self.set_output_noise() self.set_data() out=self.data[:] if len(out)==1: out=out[0] return out #----------------------------------------------------------------------------- # Module Scripts def test_linear_fit(data=None): """Tests fitting a data set to a line, the data set is assumed to be in the form [[x_data,y_data]]""" if data is None: #x_data=np.linspace(-100,100,100) x_data=[i*1. for i in range(100)] y_data=[2.004*x+3 for x in x_data] data=[x_data,y_data] #print(data) initial_guess=[1,0] results=least_squares_fit(line_function,data[0],data[1],initial_guess) print(("The fit of data is y={1:3.2g} x + {0:3.2g}".format(*results))) #----------------------------------------------------------------------------- # Module Runner if __name__ == '__main__': test_linear_fit()
9b52048b72f40f783aa89db51f56f111fca377d6
Yogesh-Singh-Gadwal/YSG_Python
/Core_Python/Day-7/5.py
130
3.71875
4
# Python a = 10 b = 20 if a == b: print('Both value are same .') else: print('Condition is false')
b49c3d38b867b774f24c12fa33ba8bf9b4c53f76
Gafanhoto742/Python-3
/Python (3)/Ex_finalizados/ex007.py
451
3.859375
4
#média aritmética nota1 = float(input('Primeira nota do aluno: ')) nota2 = float(input('Segunda nota do aluno: ')) soma = nota1 + nota2 media = soma /2 print('A média entre {} e {} [e igual a {:.2f}.'.format(nota1,nota2,media)) #segundo modo de fazer o mesmo exercio n1 = float(input('Primeiro nota do aluno: ')) n2 = float(input('Segunda nota do aluno: ')) media = (n1 + n2)/2 print('A média entre {} e {} [e igual a {:.2f}'.format(n1,n2,media))
9e244edca3f7b67893fc89daa0db8df13124a12c
angelvv/HackerRankSolution
/Python/02.Strings/17.FindAString.py
438
4.0625
4
def count_substring(string, sub_string): #return string.count(sub_string) # .count only count non-overlapping occurence return sum(1 for i in range(len(string)) if sub_string == string[i:i+len(sub_string)]) # interestingly, this doesn't throw error of "out of index" if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
395c15c74176a3ea6cac8324a1bef011cd0dc526
jgrafton/raspberrypi
/src/led_blink.py
982
3.765625
4
#!/usr/bin/env python ## led_blink.py # created by John Grafton import sys import time import signal import RPi.GPIO as GPIO try: # this is a demo, may get an error that channel is # already in use, disable GPIO.setwarnings(False) # use BCM GPIO 00..nn numbers GPIO.setmode(GPIO.BCM) # Setup GPIO channel 21 GPIO.setup(21, GPIO.OUT) # Output to pin 21 GPIO.output(21, GPIO.HIGH) # print instructions to user print 'GPIO LED Blink Example - Python' print 'LED should be blinking. Press Ctrl-C to stop.' # loop forever until user presses Ctrl-C while True: # sleep for 1 second time.sleep(1) # turn off LED GPIO.output(21, GPIO.LOW) # sleep for 1 second time.sleep(1) # turn on LED GPIO.output(21, GPIO.HIGH) # lather, risnse, repeat except KeyboardInterrupt: print 'Ctrl-C pressed, exiting!' GPIO.output(21, GPIO.LOW) sys.exit(0)
0906b4d38e31ce55502e82b84bfd869c44e47e14
love554468/leetcode
/solution/50_Pow_x_n.py
913
3.953125
4
class Solution: def myPow(self, x: float, n: int) -> float: """ x^10 = x^5 * x^5. Now we have odd power, but it is not a problem, we evaluate x^5 = x^2 * x^2 * x. Special Case: If we have n < 0 negative power, return positive power of 1/x. Base Case: If we have n = 0, return 1 as x^(0) = 1 If we have n = 1, return 1 as x^(0) = x Recursive Case: Now, we have two cases: for even and for odd n, where we evaluate power n//2, i.e: M = myPow(x, n//2) Even: return M*M Odd: return M*x*M """ #if n < 0, convert n > 0, convert x to 1/x if n < 0: return self.myPow(1/x, -n) #Base Case if n == 0: return 1 if n == 1: return x M = self.myPow(x, n//2) if (n%2 == 0): return M*M else: return M*x*M
0fe5f904a16806d949ab33f5b97743a109ce09e2
KevinKnott/Coding-Review
/Month 01/Week 03/Day 03/a.py
1,899
4.15625
4
# Diameter of Binary Tree: https://leetcode.com/problems/diameter-of-binary-tree/ # Given the root of a binary tree, return the length of the diameter of the tree. # The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. # The length of a path between two nodes is represented by the number of edges between them. # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # My thought is to go down the path with a dfs and start counting once we have hit a node with no children # Then every step up we add one and take the max of steps down or 1 class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: self.diameter = 0 def dfs(node): # If we hit a leaf node return 0 if node is None: return 0 # Get length to left and right of current node left = dfs(node.left) right = dfs(node.right) # If the length is greater than any so far make it the result self.diameter = max(self.diameter, left + right) # Return the max so far +1 for the current node (In case the longest diameter is met somewhere in the middle instead of going through the root) return max(left, right) + 1 dfs(root) return self.diameter # Score Card # Did I need hints? Yes I forgot that I need to compare the diameter to the left and the right before including the next value up # Did you finish within 30 min? 15 min # Was the solution optimal? Oh yeah this is a o(N) solution every node is visited one and that makes our stack space o of (N) or logn if it is a balanced tree # Were there any bugs? Yeah see the hint # 3 5 5 3 = 4
5b686552453f2ce0e2c94a499e19bb688324bc66
AmreshTripathy/Python
/67_pr8_08.py
147
4
4
def multiplication(n): for i in range(1, 11): print (f'{n} * {i} = {n * i}') n = int(input('Enter a number: ')) multiplication(n)
62a72dde23755fb918ee1e1fa73336fa6bbbb8f2
ShushantLakhyani/Python-Projects
/password_generator.py
1,253
4.25
4
#This programs output will create a password for you, as per your needs #you just have to enter the number of letters, numbers and symbols you need in the password import random letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] numbers = ['0','1','2','3','4','5','6','7','8','9'] symbols = ['!','@','#','$','%','^','&','*','(',')'] print("Welcome to the PyPassword Generator !") nr_letters = int(input("How many letters would you like in your password ? \n")) nr_symbols = int(input("How many symbols would you like ?")) nr_numbers = int(input("How many numbers would you like ? \n")) password = [] for char in range(1,nr_letters+1): password.append(random.choice(letters)) for char in range(1,nr_symbols+1): password += random.choice(numbers) for char in range(1,nr_symbols+1): password += random.choice(symbols) random.shuffle(password) password_original = "" for char in password: password_original += char print(f"Your password is: {password_original}")
fdfea37a69904a48d2c710c2ebe54b5d9e899145
Toetoise/python_test
/lesson1.py
3,219
3.96875
4
myCatName = "黑猫警长" age = 6 weight = 17.365 print('我的小猫的名字叫%s,它的年龄是%06d,它的体重是%.1f' % (myCatName, age, weight)) print(f'我的小猫的名字叫{myCatName},它的年龄是{age},它的体重是{weight}') print('我的小猫的名字叫{},它的年龄是{},它的体重是{}'.format(myCatName, age, weight)) num = 7 # int类型不可以被迭代not iterable str1 = 'wwww' t1 = (1, 2, 3, 4, 5) dic1 = {'name': '黑猫警长', 'age': '8'} # 只保留key # print(list(num)) print(list(str1)) print(list(t1)) print(list(dic1)) result = eval('35+22') # eval() 可以把字符串表达的数学式进行计算 print(result) li = [1, 2, 4, 4, 'cat', 'dog', 'cat'] new_set = set(li) # set()把转换成集合且去重了 print(new_set) new_li = list(new_set) print(new_li) # 达到去重的效果 a = 1 b = 2 c = 3 print(a, end='') # end结束符\n是换行,不要\n是不换行 print(b, end='\n') print(c) print(""" 你好, 我是何同学 """) # 三单引号或三双引号可以把换行的字符串完整的打印出来 name = "大家好我是何同学" print(name[3]) print(name[-2]) # 可以逆向取值 print(name[3:7:1]) # 切片取值,[起始:结束:步长],不包括结束位置的字符 我是何同 print(name[-7:-1:1]) # 逆向切片取值,不包括起始位置的字符 家好我是何同 print(name[::]) # 包含起始和结束位置 print(name[::-1]) # 倒置 print(name[-2:4:-1]) # 同何 str1 = '1 and 2 and 3' print(str1.find('and')) # 返回的是查找的字符串在字符串中起始位置 2 print(str1.find('and', 3, 12)) # 返回的是在指定区间内的字符串的位置 8 print(str1.find('4')) # 没有该字符串返回-1 print(str1.rfind('and')) # 从右往左找 print(str1.index('and')) # 与find相同 print(str1.count('and')) # 子字符串出现的次数 2 name = "大家好我是何同学" print(name.replace('家', '家家', 1)) # replace() [被替换的字符串, 替换的, 次数] 不输入次数默认是全部 大家家好我是何同学 print(str1.replace('and', 'or', 3)) # 次数大于默认子字符串数量时,取全部 1 or 2 or 3 print(name.split('好')) # split('字符串中的内容', 次数) 以内容左右切割字符串为列表 ['大家', '我是何同学'] print(str1.split(' ')) # ['1', 'and', '2', 'and', '3'] new_name = name.split('好') print('好'.join(new_name)) # 将列表加入到列表中 ''.join() 大家好我是何同学 # capitalize() 字符串的第一个字符大写 # title() 字符串中每一个单词首字母大写 # lower() 将字符串中大写转换成小写 # upper() 将所有小写转换成大写 # lstrip() 删除字符串左侧的空白字符 # rstrip() 删除字符串右侧的空白字符 # strip() 删除字符串左右两侧的空白字符 str1 = 'start' print(str1.ljust(10, '*')) # ljust()左对齐,[长度,字符] start***** 不够的长度以字符填充 print(str1.rjust(10, '$')) # rjust()右对齐 $$$$$start print(str1.center(10, '=')) # center()中心对齐 ==start===
8235c33a5753c8baebda701e9439ee83aba798c3
Argonauta666/coding-challenges
/interviews.school/02-loops/third-maximum-number.py
623
3.859375
4
# https://leetcode.com/problems/third-maximum-number/ from typing import List class Solution: def thirdMax(self, nums: List[int]) -> int: fm = sm = tm = None for num in nums: if fm is None or num > fm: tm = sm sm = fm fm = num elif num == fm: continue elif sm is None or num > sm: tm = sm sm = num elif num == sm: continue elif tm is None or num > tm: tm = num return fm if tm is None else tm
ac61186f91092f5a551b2fb1727c1faae2a1426b
Audarya07/eduAlgo
/edualgo/backtracking_algorithms/Rat_in_a_Maze.py
7,370
4.09375
4
# Rat in a Maze Problme via Backtracking # the function rat_in_a_maze() takes the maze as an input (as 0 and 1) # Source :- Top Left # Destination :- Bottom Right # Moves allowed is DOWN, UP, LEFT and RIGHT from __init__ import print_msg_box from time import time import sys sys.setrecursionlimit(150000) def rat_in_a_maze(maze, way=1, hint=False): # Main Function which takes the maze and way as an input start=time() if hint: rat_in_a_maze_hint() # By default, 1 is considered as walls and 0 is considered as way n=len(maze);m=len(maze[0]) # Dimentions of the maze wall= way^1 direction=[[1,0,'D'],[0,1,'R'],[-1,0,'U'],[0,-1,'L']] # Directions to move visited=[[0]*m for i in range(n)] # To maintain the already visited spot # Base Condition to check whether the source or destination contains a wall if wall in (maze[0][0], maze[n-1][m-1]): return 'Not Possible' temp=move_rat(0,0, n, m, maze, visited,way,direction,[]) ans="".join(temp[1]) if temp[0] else 'Not Possible' print("Time Taken := ", time()-start) return ans def move_rat(xx, yy, n, m, maze, visited,way, direction,ans): visited[xx][yy]=1 # If the rat reached the destination if(xx == n-1 and yy == m-1): return [1,ans] for i in range(4): row = xx + direction[i][0] col = yy + direction[i][1] if(0<=row<n and 0<=col<m and not visited[row][col] and maze[row][col]==way): ans+=[direction[i][2]] temp=move_rat(row,col,n,m,maze,visited,way,direction,ans) if temp[0]: return temp ans.pop() return [0,-1] def rat_in_a_maze_hint(): message=""" Rat in a Maze problem via Backtracking ------------------------------------------------------------------------------------------ Pupose: Consider a rat placed at (0, 0) in a maze of order N*M. It has to reach the destination at (N-1, M-1). Find a possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Maze is in the form of a binary matrix containing 0's and 1's only. By default 0 is considered as wall cell whereas 1 is considered to way cell. The rat can only on the way cell. Method: Backtracking Time Complexity: Worst case- O(2^N*M) Best case- O(N*M) Hint: Say the position of the rat is (X,Y). Then check for all the cells accessable through the current possition i.e (X+1,Y), (X-1,Y), (X,Y+1) and (X,Y-1) and see whether they are way of wall. If wall, then move the rat to that position and repeat the process. In case there is no possible move from the current position, backtrack the previous move and check for the next possible move and repeat the process until you encounter (N-1,M-1). Pseudocode: 1) Mantain a boolean matrix visited to keep a note on already visited node and a list of all possible moves from a given position i.e direction. 2) Check for the base case if destnation or source contains wall: return False else return move_rat(0,0,maze) 3) In the recursive function, first check whether the current position is the destination or not if current is destination return ans else check for all the possible move from that position if move is valid and not visited and next_move is way return move_rat(next_move) if no move is valid return False Visualization: maze=[[1,0,0], [1,1,1], [0,0,1]] Source := (0,0) Destination := (2,2) Wall:= X grapical representaion of maze: +-------+-------+-------+ | | | | | R | X | X | | | | | +-------+-------+-------+ | | | | | | | | | | | | +-------+-------+-------+ | | | | | X | X | | | | | | +-------+-------+-------+ Base Condition check, whether the the Source and destination are not wall Now the Rat is at (0,0) UP, move not valid DOWN, move valid +-------+-------+-------+ | | | | | * | X | X | | | | | +-------+-------+-------+ | | | | | R | | | | | | | +-------+-------+-------+ | | | | | X | X | | | | | | +-------+-------+-------+ Now the Rat is at (1,0) UP, already visited DOWN, invalid move, WALL RIGHT, valid move +-------+-------+-------+ | | | | | * | X | X | | | | | +-------+-------+-------+ | | | | | * | R | | | | | | +-------+-------+-------+ | | | | | X | X | | | | | | +-------+-------+-------+ Now the Rat is at (1,1) UP, invalid move, Wall DOWN, invalid move, WALL RIGHT, valid move +-------+-------+-------+ | | | | | * | X | X | | | | | +-------+-------+-------+ | | | | | * | * | R | | | | | +-------+-------+-------+ | | | | | X | X | | | | | | +-------+-------+-------+ Now the Rat is at (1,2) UP, invalid move, Wall DOWN, valid move +-------+-------+-------+ | | | | | * | X | X | | | | | +-------+-------+-------+ | | | | | * | * | * | | | | | +-------+-------+-------+ | | | | | X | X | R | | | | | +-------+-------+-------+ Now the Rat is at (2,2) this is the Destination cell, hence we will terminate the recursion Answer: DRRD For animated visulization:- https://github.com/karan236/Algorithm-Visualizer """ print_msg_box(message)
e3b98a4aca3905b51b594501d99bdf5e44e0e8d3
bitcraftlab/bots-n-plots
/ipynb/examples/02. Learning Python/botsnplots/module_demo.py
1,052
4.09375
4
""" Hello I am a module """ print "Executing stuff inside the module" some_string = "What ???" arbitrary_number = 123 def add(x, y): """ this function is mine """ return x + y def mul(x, z): """ this function is yours """ return x * z def exclaim(s, n=3): """ this function does something """ return s + "!" * n class MyPair: """ I am a class holding a pair of values """ # this is a class attribute, and it's kind of hidden __allPairs = [] def __init__(self, x, y): """ I am a method """ # init instance attributes self.x = x self.y = y # add this object to the list self.__allPairs.append(self) def __repr__(self): """ Display the object """ return "MyPair(%i, %i)" % (self.x, self.y) def flip(self): """ exchange x and y """ tmp = self.x self.x = self.y self.y = tmp @classmethod def getAll(cls): return cls.__allPairs[:]
5157e3a00a6bff09aceab6a1aa7db15b02b4add6
danwaterfield/LeetCode-Solution
/python/LinkedList/LinkedList Structure/LinkedList Structure.py
390
3.78125
4
# single-linked list class ListNode(object): def __init__(self, x): self.val = x self.next = None # double_linked list class DoubleListNode(object): """ A more specific implement for double-linked list is shown in recommend order-9: 707 Design Linked List """ def __init__(self, x): self.val = x self.pre = None self.next = None
85fff2cd731c8f10c13b49961400b688d408498d
LeRoiFou/mooc_instructions
/ex003_sizeCompany.py
919
3.765625
4
""" Écrire un programme qui calcule la taille moyenne (en nombre de salariés) des Petites et Moyennes Entreprises de la région. Les tailles seront données en entrée, chacune sur sa propre ligne, et la fin des données sera signalée par la valeur sentinelle -1. Cette valeur n’est pas à comptabiliser pour le calcul de la moyenne, mais indique que l’ensemble des valeurs a été donné. Après l’entrée de cette valeur sentinelle -1, le programme affiche la valeur de la moyenne arithmétique calculée. On suppose que la suite des tailles contient toujours au moins un élément avant la valeur sentinelle -1, et que toutes ces valeurs sont positives ou nulles. Editeur : Laurent REYNAUD Date : 18-07-2020 """ effectif = 0 somme = 0 nbresaisi = 0 while effectif != -1: effectif = float(input()) somme += effectif nbresaisi += 1 moyenne = (somme+1)/(nbresaisi-1) print(moyenne)
3c549bfd10dd2be72efab996beb013eff226cd3f
Baidaly/datacamp-samples
/14 - Data manipulation with Pandas/chapter 3 - Slicing and Indexing/7 - Slicing time series.py
1,121
4.28125
4
''' Slicing is particularly useful for time series since it's a common thing to want to filter for data within a date range. Add the date column to the index, then use .loc[] to perform the subsetting. The important thing to remember is to keep your dates in ISO 8601 format, that is, yyyy-mm-dd. Recall from Chapter 1 that you can combine multiple Boolean conditions using logical operators (such as &). To do so in one line of code, you'll need to add parentheses () around each condition. pandas is loaded as pd and temperatures, with no index, is available. ''' # Use Boolean conditions to subset temperatures for rows in 2010 and 2011 temperatures_bool = temperatures[(temperatures["date"] >= "2010-01-01") & (temperatures["date"] <= "2011-12-31")] print(temperatures_bool) # Set date as an index and sort the index temperatures_ind = temperatures.set_index("date").sort_index() # Use .loc[] to subset temperatures_ind for rows in 2010 and 2011 print(temperatures_ind.loc["2010":"2011"]) # Use .loc[] to subset temperatures_ind for rows from Aug 2010 to Feb 2011 print(temperatures_ind.loc["2010-08":"2011-02"])
3b5bdb41dfd14bab0fb964a11b7f1a62f0d3172d
Natnaelh/Algorithm-Problems
/Dynamic Programming/DagShortestPathDp.py
1,492
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 4 23:05:41 2020 @author: natnem """ class Graph(object): def __init__(self,G): self.graph = G def itervertices(self): return self.graph.keys() def Inverse_neighbors(self,u): neighbors = [] for x in self.itervertices(): for y in self.graph[x]: if y == u: neighbors.append(x) return neighbors def weight(self,u,v): return self.graph[u][v] class ShortestPathResult(object): def __init__(self): self.d = {} self.parent = {} def shortest_path(graph,s): result = ShortestPathResult() result.d[s] = 0 result.parent[s] = None for v in graph.itervertices(): sp_dp(graph,v,result) return result def sp_dp(graph, v , result): if v in result.d: return result.d[v] else: result.d[v] = float("inf") result.parent[v] = None for u in graph.Inverse_neighbors(v): newdistance = sp_dp(graph,u,result) + graph.weight(u,v) if newdistance < result.d[v]: result.d[v] = newdistance result.parent[v] = u return result.d[v] G= {"s":{"t":10,"y":5}, "t":{"x":1,"y":2}, "x":{"z":4}, "y":{"t":3,"z":2,"x":9}, "z":{"x":6,"s":7}} mygraph = Graph(G) s = "s" print(shortest_path(mygraph,s).d)
6a47ca3d047516b312792dc8b92cf583ab1a27c4
SOURAV-ROY/2020-PYTHON
/Sum.py
523
3.9375
4
# def add_two_number(first, second): # return first + second # # # number_1 = 10 # number_2 = 40 # sum_result = add_two_number(number_1, number_2) # print(f'{number_1} + {number_2} = {number_2 + number_1}') # print(f'{number_1} + {number_2} = {sum_result}') print("1") def complicated_logic(value_1, value_2): print(f"You Passed: {value_1}, {value_2}") number_1 = 10 number_2 = 40 print("2") # value = complicated_logic(number_1, number_2) complicated_logic(number_1, number_2) complicated_logic(5, 6) print("3")
5606958f15ed9a80214ac47040ca95fc42b285a2
tcandzq/LeetCode
/Sort/ContainsDuplicateIII.py
2,183
3.625
4
# -*- coding: utf-8 -*- # @File : ContainsDuplicateIII.py # @Date : 2020-02-18 # @Author : tc """ 220 存在重复元素III 给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。 示例 1: 输入: nums = [1,2,3,1], k = 3, t = 0 输出: true 示例 2: 输入: nums = [1,0,1,1], k = 1, t = 2 输出: true 示例 3: 输入: nums = [1,5,9,1,5,9], k = 2, t = 3 输出: false 桶排序: 用t+1作为桶的容量,动态删除距离大于k的桶元素 代码参考:https://leetcode.com/problems/contains-duplicate-iii/discuss/61639/JavaPython-one-pass-solution-O(n)-time-O(n)-space-using-buckets 思路参考:https://leetcode-cn.com/problems/contains-duplicate-iii/solution/cun-zai-zhong-fu-yuan-su-iii-by-leetcode/ """ from typing import List class Solution: # 超时 def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: n = len(nums) for i in range(n): for j in range(1,k+1): if i+j < n and abs(nums[i] - nums[i+j]) <= t: return True return False # 桶排序 def containsNearbyAlmostDuplicate2(self, nums: List[int], k: int, t: int) -> bool: if t < 0: return False n = len(nums) d = {} w = t + 1 for i in range(n): m = nums[i] // w if m in d: return True if m - 1 in d and abs(nums[i] - d[m-1]) < w: return True if m+1 in d and abs(nums[i] - d[m+1]) < w: return True d[m] = nums[i] if i >= k: # 动态删除桶中元素的索引距离大于k的元素, # 不用担心后面的元素可能需要这个桶里的元素,因为下一个元素 i+1 肯定与这个删除的桶内元素距离更远 del d[nums[i-k] // w] return False if __name__ == '__main__': nums = [1,0,1,1] k = 1 t = 2 solution = Solution() print(solution.containsNearbyAlmostDuplicate2(nums,k,t))
a96ac383f7e0f7f0a9301d31767244fcf8cd642b
trimardianto27/jobsheet-6
/LINK LIST DAN FILTER.py
644
3.6875
4
#!/usr/bin/env python # coding: utf-8 # In[6]: def multiply(x) : return (x*x) def add(x) : return (x+x) funcs = [multiply, add] for i in range(5): value = list(map(lambda x: x(i), funcs)) print (value) # In[9]: #List alfabet alfabet = 'a', 'b', 'c', 'e', 'i' 'k', 'o', 'z', # fungsi penyaring hurung vokal def filter_vocal (alfabet): vocal = ['a', 'i' 'u', 'e', 'o', ] if alfabet in vocal : return True else: return False vocal_terfilter = filter(filter_vocal ,alfabet) print ('Huruf vocal yang tersaring adalah:' ) for vocal in vocal_terfilter: print(vocal) # In[ ]:
d3f4049ebda4c62866aba9cb805f2ea00ed7e6a9
subodhss23/python_small_problems
/easy_probelms/does_number_exit.py
367
4
4
''' Create a function which validates whether a given number exists, and could represent a real life quality. Inputs will be given as a string.''' def valid_str_number(n): try: float(n) except: return False return True print(valid_str_number("3.2")) print(valid_str_number("324")) print(valid_str_number("54..4")) print(valid_str_number("number"))
435f45fb6908b48738cd99f36e2663b4e0ea4ba0
zdravkob98/Fundamentals-with-Python-May-2020
/Exercise Lists Basics/Bread Factory.py
1,153
3.6875
4
day_events = input().split('|') coins = 100 energy = 100 flag = True for e in day_events: event = e.split('-') command = event[0] num = int(event[1]) if command == 'rest': if energy >= 100: print(f'You gained {0} energy.') print(f'Current energy: {energy}.') elif energy + num >= 100: print(f'You gained {100 - energy} energy.') energy = 100 print(f'Current energy: {energy}.') else: print(f'You gained {num} energy.') energy += num print(f'Current energy: {energy}.') elif command == 'order': if energy >= 30: print(f'You earned {num} coins.') coins += num energy -= 30 else: print('You had to rest!') energy += 50 else: coins -= num if coins > 0: print(f'You bought {command}.') else: print(f'Closed! Cannot afford {command}.') flag = False break if flag == True: print(f'Day completed!') print(f'Coins: {coins}') print(f'Energy: {energy}')
36eac0b793a1d2abcd7318ba110ddf5f759afd74
shenxiaoxu/leetcode
/questions/1488. Avoid Flood in The City/avoid.py
1,635
4
4
''' Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake. Given an integer array rains where: rains[i] > 0 means there will be rains over the rains[i] lake. rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it. Return an array ans where: ans.length == rains.length ans[i] == -1 if rains[i] > 0. ans[i] is the lake you choose to dry in the ith day if rains[i] == 0. If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array. Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. (see example 4) ''' class Solution: def avoidFlood(self, rains: List[int]) -> List[int]: dry_days = [] res = [] rain_map = collections.defaultdict(int)#lake, time of latest fill for i, c in enumerate(rains): if c == 0: dry_days.append(i) res.append(1)#override later else: if c in rain_map: pos = bisect.bisect_right(dry_days, rain_map[c])#binary search for dry_days if pos == len(dry_days): return [] res[dry_days[pos]] = c# on that day we dry #c lake dry_days.pop(pos) rain_map[c] = i res.append(-1) return res
1d4ac51059b3081020345fb7f99b562dee11213c
ryndovaira/leveluppythonlevel1_300321
/topic_06_files/practice/files_3_save_set_to_file_json.py
1,015
3.6875
4
""" Функция save_set_to_file_json. Принимает 2 аргумента: строка (название файла или полный путь к файлу), словарь JSON (для сохранения). Сохраняет словарь (JSON) в файл. Загрузить словарь JSON (прочитать файл), проверить его на корректность. """ import json def save_set_to_file_json(my_path, my_json): with open(my_path, 'w') as f: json.dump(my_json, f, ensure_ascii=False, indent=2) if __name__ == '__main__': my_dict = { "Маша": [ 1, 2, 3 ], "ОЛОЛО": { "1": "one", "2": "two" }, "set": [ 9.844, 3.222 ] } path = 'json_simple.json' save_set_to_file_json(path, my_dict) with open(path, 'r') as file: json_loaded = json.load(file) print(json_loaded)
a01577f33de71ba1b6b676da877097817df15d43
20050924/All-projects
/Assignment 18 Tic Tac Toe 3.py
14,577
4.0625
4
#Michael Li #Programming 11 #2021/10/5 #Assignment 18, A tic tac toe game program that player aginst Ai. #Ai smarter(can place a X when ai is able to win) #have a bug when game ends it pops out a error(don't know how to fix: Internal error: bunch of codes file name etc and then OSError: [Errno 22] Invalid argument) from tkinter import * import random root = Tk() canvas = Canvas(root, height=666, width=666) canvas.pack() gamestate = ["","","","","","","","",""] print("click on a square and will create a circle there") print("Contians 3 circle's horizontaly,verticaly and oblique wins game, same with the computer") def O(event): global gamestate if event.x <= 222 and event.y <= 222 and gamestate[0] == "" : canvas.create_oval(22,22,200,200 ,width = 5) gamestate[0] = "O" X() elif event.x <= 444 and event.x >222 and event.y <= 222 and gamestate[1] == "": canvas.create_oval(242,22,422,200 ,width = 5) gamestate[1] = "O" X() elif event.x <=666 and event.x > 444 and event.y <= 222 and gamestate[2] == "": canvas.create_oval(464,22,644,200,width=5) gamestate[2] = "O" X() elif event.x<= 222 and event.y > 222 and event.y <=444 and gamestate[3] == "": canvas.create_oval(22,244,200,422,width=5) gamestate[3] = "O" X() elif event.x<= 444 and event.x >222 and event.y>222 and event.y <= 444 and gamestate[4] == "": canvas.create_oval(244,244,422,422,width=5) gamestate[4] = "O" X() elif event.x <=666 and event.x> 444 and event.y >222 and event.y <=444 and gamestate[5] == "": canvas.create_oval(466,244,644,422,width=5) gamestate[5] = "O" X() elif event.x <=222 and event.y >444 and event.y <=666 and gamestate[6] == "": canvas.create_oval(22,466,200,644,width=5) gamestate[6] = "O" X() elif event.x>222 and event.x<=444 and event.y >444 and event.y <=666 and gamestate[7] == "": canvas.create_oval(244,466,422,644,width=5) gamestate[7] = "O" X() elif event.x > 444 and event.x <666 and event.y>444 and event.y <=666 and gamestate[8] == "": canvas.create_oval(466,466,644,644,width=5) gamestate[8]= "O" X() #player clicked mouse and create a O on what ever square they click. if gamestate[0] == "O" and gamestate[1] == "O" and gamestate[2] == "O": print("Player win, game end") exit() elif gamestate[0] == "O" and gamestate[3] == "O" and gamestate[6] == "O": print("Player win,game end") exit() elif gamestate[0] == "O" and gamestate[4] == "O" and gamestate[8] == "O": print("Player win,game end") exit() elif gamestate[1] == "O" and gamestate[4] == "O" and gamestate [7] == "O": print("Player win,game end") exit() elif gamestate[2] == "O" and gamestate[5] == "O" and gamestate[8]== "O": print("Player win,game end") exit() elif gamestate[2] == "O" and gamestate [4] == "O" and gamestate[6]== "O": print("Player win,game end") exit() elif gamestate[3] == "O" and gamestate [4] == "O" and gamestate[5]== "O": print("Player win,game end") exit() elif gamestate[6] == "O" and gamestate [7] == "O" and gamestate[8]== "O": print("Player win,game end") exit() elif gamestate[0] != "" and gamestate[1] != "" and gamestate[2] != "" and gamestate[3] != "" and gamestate[4] != ""and gamestate[5] != ""and gamestate[6] != ""and gamestate[7] != ""and gamestate[8] != "": print("Tie,game end") exit() #check if player wins def createX1(): canvas.create_line(22,22,200,200 ,width = 5) canvas.create_line(200,22,22,200 ,width = 5) gamestate[0] = "X" def createX2(): canvas.create_line(244,22,422,200 ,width = 5) canvas.create_line(422,22,244,200 ,width = 5) gamestate[1]="X" def createX3(): canvas.create_line(466,22,644,200,width=5) canvas.create_line(644,22,466,200,width=5) gamestate[2]="X" def createX4(): canvas.create_line(22,244,200,422,width=5) canvas.create_line(200,244,22,422,width=5) gamestate[3]="X" def createX5(): canvas.create_line(244,244,422,422,width=5) canvas.create_line(422,244,244,422,width=5) gamestate[4]="X" def createX6(): canvas.create_line(466,244,644,422,width=5) canvas.create_line(644,244,466,422,width=5) gamestate[5]="X" def createX7(): canvas.create_line(22,466,200,644,width=5) canvas.create_line(200,466,22,644,width=5) gamestate[6]="X" def createX8(): canvas.create_line(244,466,422,644,width=5) canvas.create_line(422,466,244,644,width=5) gamestate[7]="X" def createX9(): canvas.create_line(466,466,644,644,width=5) canvas.create_line(644,466,466,644,width=5) gamestate[8]="X" #funtions to create X def X(): global gamestate while True: random_int = random.randint(0,8) if gamestate[6] == "X" and gamestate[3] == "X" and gamestate[0] == "": createX1() break elif gamestate[2]=="X" and gamestate[1]=="X" and gamestate[0] == "": createX1() break elif gamestate[4]=="X" and gamestate[8]=="X" and gamestate[0] == "": createX1() break elif gamestate[0]=="X" and gamestate[2]=="X" and gamestate[1] == "": createX2() break elif gamestate[4]=="X" and gamestate[7]=="X" and gamestate[1] == "": createX2() break elif gamestate[0]=="X" and gamestate[1]=="X" and gamestate[2] == "": createX3() break elif gamestate[4]=="X" and gamestate[6]=="X" and gamestate[2]=="": createX3() break elif gamestate[5]=="X" and gamestate[8]=="X" and gamestate[2]=="": createX3() break #squares 123 AI wins game elif gamestate[0]=="X" and gamestate[6]=="X" and gamestate[3]=="": createX4() break elif gamestate[4]=="X" and gamestate[5]=="X" and gamestate[3]=="": createX4() break elif gamestate[0]=="X" and gamestate[8]=="X" and gamestate[4]=="": createX5() break elif gamestate[3]=="X" and gamestate[5]=="X" and gamestate[4]=="": createX5() break elif gamestate[6]=="X" and gamestate[2]=="X" and gamestate[4]=="": createX5() break elif gamestate[7]=="X" and gamestate[1]=="X" and gamestate[4]=="": createX5() break elif gamestate[2]=="X" and gamestate[8]=="X" and gamestate[5]=="": createX6() break elif gamestate[3]=="X" and gamestate[4]=="X" and gamestate[5]=="": createX6() break #square 456 AI wins game elif gamestate[0]=="X" and gamestate[3]=="X" and gamestate[6]=="": createX7() break elif gamestate[8]=="X" and gamestate[7]=="X" and gamestate[6]=="": createX7() break elif gamestate[4]=="X" and gamestate[2]=="X" and gamestate[6]=="": createX7() break elif gamestate[1]=="X" and gamestate[4]=="X" and gamestate[7]=="": createX8() break elif gamestate[6]=="X" and gamestate[8]=="X" and gamestate[7]=="": createX8() break elif gamestate[0]=="X" and gamestate[4]=="X" and gamestate[8]=="": createX9() break elif gamestate[0]=="2" and gamestate[4]=="5" and gamestate[8]=="": createX9() break elif gamestate[0]=="6" and gamestate[4]=="7" and gamestate[8]=="": createX9() break #square 789 AI wins game elif gamestate[6] == "O" and gamestate[3] == "O" and gamestate[0] == "": createX1() break elif gamestate[2]=="O" and gamestate[1]=="O" and gamestate[0] == "": createX1() break elif gamestate[4]=="O" and gamestate[8]=="O" and gamestate[0] == "": createX1() break elif gamestate[0]=="O" and gamestate[2]=="O" and gamestate[1] == "": createX2() break elif gamestate[4]=="O" and gamestate[7]=="O" and gamestate[1] == "": createX2() break elif gamestate[0]=="O" and gamestate[1]=="O" and gamestate[2] == "": createX3() break elif gamestate[4]=="O" and gamestate[6]=="O" and gamestate[2]=="": createX3() break elif gamestate[5]=="O" and gamestate[8]=="O" and gamestate[2]=="": createX3() break if gamestate[6] == "O" and gamestate[3] == "O" and gamestate[0] == "": createX1() break elif gamestate[2]=="O" and gamestate[1]=="O" and gamestate[0] == "": createX1() break elif gamestate[4]=="O" and gamestate[8]=="O" and gamestate[0] == "": createX1() break elif gamestate[0]=="O" and gamestate[2]=="O" and gamestate[1] == "": createX2() break elif gamestate[4]=="O" and gamestate[7]=="O" and gamestate[1] == "": createX2() break elif gamestate[0]=="O" and gamestate[1]=="O" and gamestate[2] == "": createX3() break elif gamestate[4]=="O" and gamestate[6]=="O" and gamestate[2]=="": createX3() break elif gamestate[5]=="O" and gamestate[8]=="O" and gamestate[2]=="": createX3() break #squares 123 AI block player from winning elif gamestate[0]=="O" and gamestate[6]=="O" and gamestate[3]=="": createX4() break elif gamestate[4]=="O" and gamestate[5]=="O" and gamestate[3]=="": createX4() break elif gamestate[0]=="O" and gamestate[8]=="O" and gamestate[4]=="": createX5() break elif gamestate[3]=="O" and gamestate[5]=="O" and gamestate[4]=="": createX5() break elif gamestate[6]=="O" and gamestate[2]=="O" and gamestate[4]=="": createX5() break elif gamestate[7]=="O" and gamestate[1]=="O" and gamestate[4]=="": createX5() break elif gamestate[2]=="O" and gamestate[8]=="O" and gamestate[5]=="": createX6() break elif gamestate[3]=="O" and gamestate[4]=="O" and gamestate[5]=="": createX6() break #square 456 AI block player from winning elif gamestate[0]=="O" and gamestate[3]=="O" and gamestate[6]=="": createX7() break elif gamestate[8]=="O" and gamestate[7]=="O" and gamestate[6]=="": createX7() break elif gamestate[4]=="O" and gamestate[2]=="O" and gamestate[6]=="": createX7() break elif gamestate[1]=="O" and gamestate[4]=="O" and gamestate[7]=="": createX8() break elif gamestate[6]=="O" and gamestate[8]=="O" and gamestate[7]=="": createX8() break elif gamestate[0]=="O" and gamestate[4]=="O" and gamestate[8]=="": createX9() break elif gamestate[0]=="2" and gamestate[4]=="5" and gamestate[8]=="": createX9() break elif gamestate[0]=="6" and gamestate[4]=="7" and gamestate[8]=="": createX9() break #square 678 Ai block player from winning elif random_int == 0 and gamestate[0] == "" : createX1() break elif random_int == 1 and gamestate[1] == "": createX2() break elif random_int == 2 and gamestate[2] == "": createX3() break elif random_int == 3 and gamestate[3] =="": createX4() break elif random_int == 4 and gamestate[4]=="": createX5() break elif random_int == 5 and gamestate[5]=="": createX6() break elif random_int == 6 and gamestate[6]=="": createX7() break elif random_int == 7 and gamestate[7]=="": createX8() break elif random_int == 8 and gamestate[8]=="": createX9() break elif gamestate[0] != "" and gamestate[1] != "" and gamestate[2] != "" and gamestate[3] != "" and gamestate[4] != ""and gamestate[5] != ""and gamestate[6] != ""and gamestate[7] != ""and gamestate[8] != "": break #randomly draw X in 1 - 9 squares print(gamestate) #to show player why they lost in case they didn't realize that computer can win if gamestate[0]== "X" and gamestate[1]== "X" and gamestate[2] == "X": print("Computer win, game end") exit() elif gamestate[0]== "X" and gamestate[3]== "X" and gamestate[6] == "X": print("Computer win,game end") exit() elif gamestate[0]== "X" and gamestate[4] == "X"and gamestate[8] == "X": print("Computer win,game end") exit() elif gamestate[1] == "X" and gamestate[4]== "X" and gamestate [7] == "X": print("Computer win,game end") exit() elif gamestate[2]== "X" and gamestate[5]== "X" and gamestate[8]== "X": print("Computer win,game end") exit() elif gamestate[2]== "X" and gamestate [4]== "X" and gamestate[6]== "X": print("Computer win,game end") exit() elif gamestate[3]== "X" and gamestate [4]== "X" and gamestate[5]== "X": print("Computer win,game end") exit() elif gamestate[6] == "X"and gamestate [7]== "X" and gamestate[8]== "X": print("Computer win,game end") exit() #check if computer wins def draw_grid(canvas): canvas.create_line(0,0,0,666,666,666,666,0,0,0,width=5) n=0 for i in range(2): canvas.create_line(222+n,0,222+n,666,width=5) canvas.create_line(0,222+n,666,222+n,width=5) n+=222 # draw grid canvas.bind('<Button-1>', O) #acitivates funtion to draw O when mouse clicked in one the squares and also activates Ai to create a X draw_grid(canvas) root.update() root.geometry("666x666+400+400") root.mainloop()
a3d22f691a153f15207a0ecce9ad73e1d5242ae6
mertkasar/hackerrank-solutions
/algorithms/warmup/gem_stones.py
440
3.5625
4
import sys input_list = [inp for inp in sys.stdin.read().split("\n")] del input_list[0] def is_gem(element): for member in input_list: if element not in member: return False return True tested = [] gem_count = 0 for stone in input_list: for element in stone: if element not in tested: if is_gem(element): gem_count = gem_count + 1 tested.append(element) print(gem_count)
a90436ede3214073b017bdac07736e0e26d5c431
Aringan0323/Beginner-Projects
/PA4/Problem4.py
170
3.765625
4
def fun3(): v = 4 for i in range(1,6): for x in range(v): print(" ", end="") v = (v-1) for y in range(i): print("* ", end="") print() fun3()