blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
5ca0b430ee499b3972b3a27a1d3b229bad44327d
himangshupal719/spark_with_python
/8_python_crash_course/Python Crash Course.py
953
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: print("My name is {}".format('Himangshu')) # In[4]: print("My name is {}, my number is int {}, my number is string {}".format('Himangshu',10, '20')) # In[5]: print("First: {x} Second {y}".format(x='xxx', y='yyy')) # In[6]: print("First: {y} Second {x}".format(x='xxx', y='yyy')) # In[7]: mylist = ['a','b','c'] # In[8]: mylist # In[9]: type(mylist) # In[10]: mylist[0] # In[11]: mylist[2] # In[12]: mylist[-1] # In[13]: mylist[0]='new' # In[14]: mylist # In[15]: mylist.append('D') # In[16]: mylist # In[17]: mylist = [1,2,[100, 200]] # In[18]: mylist # In[19]: mylist[2] # In[20]: mylist[2][1] # In[21]: d = {'key1':'value1', 'key2':'value2'} # In[22]: d # In[23]: d['key1'] # In[24]: d['key2'] # In[25]: print(d) # In[26]: t = (1,2,3) # In[28]: {1,2,3} # In[29]: {11,22,33,11,22,33,44} # In[ ]:
2dfef24873bd2ce61d53d32a0f8bfbf4b6217a86
tangria/tangria
/MichaelTang_Dice_Challenge2.py
4,349
4.25
4
# File name: MichaelTang_Dice_Challenge2.py # Due date: Thursday, July 22, 2021 # Description: This is an extra extension of the "Dice" homework. # Not only will will print an integer number of # asterisks to represent the percentage instead # of a text-only output of how many times each "bin" # appeared within that round, but it will also break # down the details of the the totals of the die # combinations rolled that resulted in each bin value. # Dice - count totals in user-defined number of rounds import random class Bin(): def __init__(self, binIdentifier): # This method runs whenever you create a Bin object self.binIdentifier = binIdentifier self.oDict = {} # initialize the dictionary def reset(self): # This is called when you start or restart self.count = 0 # counter for each bin is set to 0 self.oDict = {} # reset the object's dictionary def increment(self, firstDie, secondDie): # Called when the roll total is the value of the binIdentifier self.count = self.count + 1 tempString = str(firstDie) + ' and ' + str(secondDie) tempReverseString = str(secondDie) + ' and ' + str(firstDie) # checking to see if key exists in dictionary # if tempString in self.oDict.keys() if tempString in self.oDict: self.oDict[tempString] = self.oDict[tempString] + 1 # the key "might" exist already in the dictionary, but in reverse order # from the aforementioned if statement # should this be the case, then increment based on the "reversed string" # otherwise, add a new key-value pair in the dictionary else: if tempReverseString in self.oDict: self.oDict[tempReverseString] = self.oDict[tempReverseString] + 1 else: self.oDict[tempReverseString] = 1 def show(self, nRoundsDone): if self.binIdentifier < 2: return # Called at the end to show the contents of this bin count = str(self.count) percentBin = (self.count/nRoundsDone) * 100 percentBin = int(percentBin) printStars = '*' * percentBin percentBin = str(percentBin) print(str(self.binIdentifier) + ': ' + printStars + ' ' + percentBin + '%(' + count + ')') for i in self.oDict: # perform string concatenations & conversions for the print statement # ahead of time so that the print statement is simple to put together rollComboCount = self.oDict[i] rollComboCount = str(rollComboCount) percentCombo = (self.oDict[i]/self.count) * 100 percentCombo = int(percentCombo) percentComboStr = str(percentCombo) print(' ' + str(i) + ': ' + rollComboCount + ' = ' + percentComboStr + ' %') # Build a list of Bin objects binList = [] # start off as the empty list # Here, you need to write a loop that runs 13 times (0 to 12) # In the loop create a Bin object, and store the object in the list of Bins # (We won't use binList[0] or binList[1]) # using a "for" loop, create Bin objects 0-12 # each time an Bin object is created, store it in list "binList" for i in range(13): oBin = Bin(i) binList.append(oBin) # add the object to the list so that the list will have a total of 12 objects while True: nRounds = input('How many rounds do you want to do? (or Enter to exit): ') if nRounds == '': break nRounds = int(nRounds) # Tell each bin object to reset itself for oBin in binList: oBin.reset() # For each round (build a loop): # roll two dice # calculate the total # and tell the appropriate bin object to increment itself for i in range(1,nRounds): # each dice's range is from 1-6 dice1 = random.randrange(1,7) dice2 = random.randrange(1,7) diceSum = dice1 + dice2 binList[diceSum].increment(dice1, dice2) print() print('After', nRounds, 'rounds:') # Tell each bin to show itself for oBin in binList: oBin.show(nRounds) print() print('OK bye')
1037ec97946801049e01e48dd802f708750e1e97
Gayatri-Prathyusha/cspp1-assignments
/M5/GuessMyNumber/guess_my_number.py
1,165
4.34375
4
"""Guess My Number Exercise """ def main(): """ Main function""" least = 0 low = 50 high = 100 guess = "Is your secret number: " print("Please think of a number between 0 and 100!") print(guess + str(least) + "?") s_request = input("$$$Enter 'h' to indicate the guess is too high. $$$$Enter 'l'\ to indicate the guess is too low.$$$$$ Enter 'c' to indicate I guessed correctly. ") # In this problem, you'll create a program that guesses a secret number! while s_request != 'c': if s_request == 'h': high = low low = int((low + least)/2) elif s_request == 'l': least = low low = int((low + high)/2) else: print("******Sorry, I did not understand your input.*********") print(guess + str(low) + "?") s_request = input("##Enter 'h' to indicate the guess is too high.## \ Enter 'l' to indicate the guess is too low.#### \ ###Enter 'c' to indicate I guessed correctly.### ") if s_request == 'c': print("Game over. Your secret number was:" + str(low)) main()
14e1cc3f05ba91652e0e7f7df645330fd84586ee
onnozweers/scripts
/replace-text-block
1,293
4.21875
4
#!/bin/python # This script replaces text in a file. The search text and replacement text # are in two other, separate files. import os import sys import argparse parser=argparse.ArgumentParser( description='''Searches through a text file for a block of text and replaces it with another text block.''') parser.add_argument('change_file', help='File to be changed') parser.add_argument('search_text_file', help='File that contains the text to search for') parser.add_argument('replacement_text_file', help='File that contains the new (replacement) text') args=parser.parse_args() # Read in the search text with open(args.search_text_file, 'r') as search_text_file : search = search_text_file.read() # Read in the replacement text with open(args.replacement_text_file, 'r') as replacement_text_file : replacement = replacement_text_file.read() # Read in the file to be changed with open(args.change_file, 'r') as change_file : filedata = change_file.read() # Replace the target string (only first occurrence) newfiledata = filedata.replace(search, replacement, 1) if newfiledata == filedata : print("File not changed: " + str(args.change_file)); sys.exit(1); # Write the file out again with open(args.change_file, 'w') as change_file: change_file.write(newfiledata)
245f36325b74490294d90370bfc72446531fa039
koichi21/LeetCode
/contest/brick_wall.py
694
3.734375
4
#!/usr/local/bin/python class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ # store number of bricks for each column d = {} for r in wall: sum = 0 for b in r[:-1]: sum += b if sum not in d: d[sum] = 1 else: d[sum] += 1 # if d: return len(wall) - max(d.values()) else: return len(wall) # test a = [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]] sol = Solution() print sol.leastBricks(a)
84b986d1dd1efb4b244656b81467015868d1697d
rairai77/Machine-Learning-and-AI
/My Machine Learning Courseware/Clustering/K-Means Clustering/kmc.py
1,475
3.578125
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split # Importing the data-set dataset = pd.read_csv('Clustering/K-Means Clustering/Mall_Customers.csv') x = dataset.iloc[:, [3, 4]].values # Using the elbow method to find the optimal number of clusters from sklearn.cluster import KMeans wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters=i, random_state=0) kmeans.fit(x) wcss.append(kmeans.inertia_) plt.plot(range(1,11), wcss) plt.title('The Elbow Method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') plt.show() # Applying k-means to the mall dataset kmeans = KMeans(n_clusters=5, random_state=0) y_kmeans = kmeans.fit_predict(x) # Visualising the clusters plt.scatter(x[y_kmeans == 0, 0], x[y_kmeans == 0, 1], s=100, c='red', label='Careful') plt.scatter(x[y_kmeans == 1, 0], x[y_kmeans == 1, 1], s=100, c='blue', label='Standard') plt.scatter(x[y_kmeans == 2, 0], x[y_kmeans == 2, 1], s=100, c='green', label='Target') plt.scatter(x[y_kmeans == 3, 0], x[y_kmeans == 3, 1], s=100, c='cyan', label='Careless') plt.scatter(x[y_kmeans == 4, 0], x[y_kmeans == 4, 1], s=100, c='magenta', label='Sensible') plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='yellow', label='Centroids') plt.title('Clusters') plt.xlabel('Annual Income') plt.ylabel('Spending Score') plt.legend() plt.show()
6cb040fbd1da9d1ef1c4f4596f7e26657a04c4da
myotheone/machine_learning_101
/lesson5_optimization/gradient_descent_optimization_intro.py
7,113
3.640625
4
#-*- coding:utf-8 -*- import numpy as np import matplotlib.pyplot as plt def evaluate_gradient(loss_function, data, params): """计算loss_function对params的梯度,根据data的大小有不同策略。 """ pass #batch gradient descent #目标函数是凸函数,保证收敛到全局最优点 #目标函数是非凸函数,保证收敛到局部最优点 #重复计算,每次都计算全部样本的梯度,在迭代轮次之间,可能会重复计算相同的梯度 #无法在线更新 #for i in range(nb_epochs): # params_grad = evaluate_gradient(loss_function, data, params) # params = params - learning_rate * params_grad #stochastic gradient descent #每次选择1个样本,计算梯度。 #导致每次的梯度变化比较大,梯度的方差比较大。loss下降的不是很平滑。可以指数降低lr #有机会跳出鞍点 #计算简单,可以支持在线更新 #for i in range(nb_epochs): # np.random.shuffle(data) # for example in data: # params_grad = evaluate_gradient(loss_function, example, params) # params = params - learning_rate * params_grad #mini-batch gradient descent #综合利用了batch和stochastic的优点 #降低stochastic的梯度方差,loss下降更平滑。 #能利用矩阵计算达到降低计算复杂度的问题 #for i in range(nb_epochs): # np.random.shuffle(data) # for batch in get_batches(data, batch_size=50): # params_grad = evaluate_gradient(loss_function, batch, params) # params = params - learning_rate * params_grad #梯度下降法的缺点: #1.学习速率很难确定,需要交叉验证(CV) #2.学习速率调度问题。某些场景下,需要对学习速率进行衰减。预定义衰减策略没有利用到数据的信息 #3.所有参数的学习速率是一致的。特征稀疏程度不一样,需要不同的学习速率,对于较少出现的特征,需要增加学习速率,对于较多的特征,需要降低学习速率 #跳出鞍点 #momentum #冲量算法,物理意义表示力F作用一段时间t后的效果:F*t = Mv #v_now = rho * v_prev + lr * d_now(params) #params = params - v_now #v_prev = v_now #收敛速度更快,loss的变化的方差更小 #nesterov accelerated gradient #v_now = rho * v_prev + lr * d_now(params - rho * v_prev) #params = params - v_now #上述方法解决的是,学习方向的问题,可以动态调整学习速率 #下面介绍解决动态调整学习速率的问题 #adagrad jeff dean #g_t_i = d(theta_t-1_i) #theta_t_i = theta_t-1_i - lr / (math.sqrt(G_t-1_ii) + epsilon) * g_t_i #G_t_ii = sigma_k=0^t g_k_i * g_k_i #G是对角矩阵,每个对角线上的元素是过去梯度的平方和 #为什么要除以根号G,目前暂时不明朗。试验结果不加根号的话,效果反而很差 #学习速率越来越小,最后出现参数不更新的情况 #RMSprop, hinton #对G矩阵做指数加权平均,G_t = gamma * G_t-1 + (1 - gamma) * g_t * g_t #Adam #将冲量法和自适应学习速率法结合 #方向g_t = beta1 * g_t-1 + (1 - beta1) * d_now(theta) #学习速率衰减银子G_t = beta2 * G_t-1 + (1 - beta2) * d_now(theta) * d_now(theta) #g_t = g_t / (1 - beta1 ** t) 偏差修正,原因:因为如果beta取值较大的情况下,g和G会取趋向于0的值,除以1-beta**t是为了使得g_t是梯度的无偏估计,对G同理 #G_t = G_t / (1 - beta2 ** t) #theta_t = theta_t-1 - lr / (math.sqrt(G_t-1_ii) + epsilon) * g_t #推荐值:lr=0.002 beta1 = 0.9 beta2=0.999, eps=1e-8 #AdaMax #将学习速率衰减的2次方换成p次方,p越大,数值会越不稳定,why? #p->无穷大时,数值稳定 #G_t = beta2 ** p * G_t-1 + (1 - beta2 ** p) * d_now(theta) ** p #p->无穷大时,上式等于下式 #G_t = max(beta2 * G_t-1, math.abs(d_now(theta))) #theta_t = theta_t-1 - lr / G_t * g_t #推荐值:lr=0.002 beta1 = 0.9 beta2=0.999 # def SGD(X, y, params, learning_rate=0.1): params_gradient = eval_gradient(X, y, params) params -= lr * params_gradient return params def momentum(X, y, params, velocity=0.0, gamma=0.9, learning_rate=0.1): params_gradient = eval_gradient(X, y, params) velocity = gamma * velocity + learning_rate * params_gradient params -= velocity return params, velocity def nag(X, y, params, velocity=0.0, gamma=0.9, learning_rate=0.1): params_gradient = eval_gradient(X, y, params - gamma * velocity) velocity = gamma * velocity + learning_rate * params_gradient params -= velocity return params, velocity def adagrad(X, y, params, G=0, eps=1e-8, learning_rate=0.1): params_gradient = eval_gradient(X, y, params) G += params_gradient ** 2 params -= learning_rate / np.sqrt(G + eps) * params_gradient return params, G def RMSprop(X, y, params, G=0, gamma=0.9, eps=1e-8, learning_rate=0.1): params_gradient = eval_gradient(X, y, params) G = gamma * G + (1 - gamma) * params_gradient ** 2 params -= learning_Rate / np.sqrt(G + eps) * params_gradient return params, G def adam(X, y, params, correction=False, iter_num=1, velocity=0, beta1=0.9, G=0, beta2=0.99, eps=1e-8, learning_rate=0.1): params_gradient = eval_gradient(X, y, params) velocity = beta1 * velocity + (1 - beta1) * params_gradient G = beta2 * G + (1 - beta2) * params_gradient ** 2 if correction: velocity /= (1 - beta1 ** iter_num) G /= (1 - beta2 ** iter_num) params -= learning_rate / (np.sqrt(G) + eps) * velocity return params, velocity, G import numpy as np import matplotlib.pyplot as plt # 目标函数:y=x^2 def func(x): return np.square(x) # 目标函数一阶导数:dy/dx=2*x def dfunc(x): return 2 * x def GD_momentum(x_start, df, epochs, lr, momentum): """ 带有冲量的梯度下降法。 :param x_start: x的起始点 :param df: 目标函数的一阶导函数 :param epochs: 迭代周期 :param lr: 学习率 :param momentum: 冲量 :return: x在每次迭代后的位置(包括起始点),长度为epochs+1 """ xs = np.zeros(epochs+1) x = x_start xs[0] = x v = 0 for i in range(epochs): dx = df(x) # v表示x要改变的幅度 v = - dx * lr + momentum * v x += v xs[i+1] = x return xs def demo2_GD_momentum(): line_x = np.linspace(-5, 5, 100) line_y = func(line_x) plt.figure('Gradient Desent: Learning Rate, Momentum', figsize=(20, 20)) x_start = -5 epochs = 6 lr = [0.01, 0.1, 0.6, 0.9] momentum = [0.0, 0.1, 0.5, 0.9] color = ['k', 'r', 'g', 'y'] row = len(lr) col = len(momentum) size = np.ones(epochs+1) * 10 size[-1] = 70 for i in range(row): for j in range(col): x = GD_momentum(x_start, dfunc, epochs, lr=lr[i], momentum=momentum[j]) plt.subplot(row, col, i * col + j + 1) plt.plot(line_x, line_y, c='b') plt.plot(x, func(x), c=color[i], label='lr={}, mo={}'.format(lr[i], momentum[j])) plt.scatter(x, func(x), c=color[i], s=size) plt.legend(loc=0) plt.show() if __name__ == "__main__": demo2_GD_momentum()
73d50ea906a2a2ffa5f826b203fa6bda7c475328
valboldakov/design-patterns
/python/observer/observer.py
1,473
3.515625
4
from abc import ABC class Message: def __init__(self, temp: int, hum: int): self.temp = temp self.hum = hum def __str__(self): return f"{self.temp} {self.hum}" class IObserver(ABC): def update(self, message: Message): pass class IPublisher(ABC): def add_observer(self, observer: IObserver): pass def remove_observer(self, observer: IObserver): pass def notify(self): pass class WeatherData(IPublisher): def __init__(self): self._temp = 0 self._hum = 0 self._observers = set() def add_observer(self, observer: IObserver): self._observers.add(observer) def remove_observer(self, observer: IObserver): self._observers.remove(observer) def notify(self): msg = Message(temp=self._temp, hum=self._hum) for observer in self._observers: observer.update(msg) def update_data(self): self._temp = self._temp + 1 self._hum = self._hum + 1 self.notify() class WeatherScreen(IObserver): def update(self, message: Message): print(message) if __name__ == '__main__': weatherData = WeatherData() screen1 = WeatherScreen() screen2 = WeatherScreen() weatherData.add_observer(screen1) weatherData.add_observer(screen2) weatherData.update_data() weatherData.update_data() weatherData.remove_observer(screen1) weatherData.update_data()
d4ef0a70459caa67cac1ada094391340da6900c3
deryacortuk/maths-equations
/dec.py
316
3.703125
4
def is_prime(x): i = 2 while(x>i): if(x%i==0): return False i +=1 return True def generator(): i =2 while True: if(is_prime(i)): yield i i +=1 for number in generator(): if(number>100): break print(number )
60cb5bfb90f850e2303d5563e4d688c10f495854
basic-maths-exercises/negation-5
/main.py
527
3.609375
4
import numpy as np def thereExists( A ) : v = 0 for a in A : if a > 4 : v = 1 return v def negationThereExists( A ) : # Your code goes here # This code allows you to test the functions you have written print(thereExists([3,4,5,6,7,8,9]), "the proposition is true for this set") print(negationThereExists([0,1,2,3]), "the negation is true for this set") print(thereExists([0,1,2,3]), "the proposition is false for this set") print(negationThereExists([5,6,7,8,9,10]), "the negation is false for this set")
54db70eb164699e963b624d2d527f4dd3a22ebb2
saraswati87/pythonprogram
/python5.py
230
3.84375
4
str = str(input("enter number ")) list=str.split(",") n = len(list) list.sort() if n % 2 == 0: median1 = list[n//2] median2 = list[n//2 - 1] median = (median1 + median2)/2 else: median = list[n//2] print(median)
5a6187d9f2d13ba5dd74f26b441704f106731faa
create92/CodingTestPractice
/greedy/greedy3-5.py
1,194
3.625
4
''' <문제> 곱하기 혹은 더하기:문제 조건 입력조건 : 첫째 줄에 여러 개의 숫자로 구성된 하나의 문자열 S가 주어집니다. (1 <= S의 길이 <= 20) 출력조건 : 첫째 줄에 만들어질 수 있는 가장 큰 수를 출력합니다. ''' # 해결법 # 0이 들어온 경우, 곱하면 값이 0이 되기 때문에 무조건 더해줌 # 1이 들어온 경우, 곱하면 값이 그대로이기 때문에 더해줘서 증가시켜줌 # 시작은 항상 0으로 # 길이 1 이상 20 이상인 경우 input = str(input()) totalSum = 0 if input.len() < 1 || input.len() > 20: print("입력값 유효성 체크 다시 확인바람(1 이상 20 이하)") else: for char in input: if char == "0" or char == "1": totalSum += int(char) else: totalSum *= int(char) print(totalSum) # 해답 data = input() # 첫 번째 문자를 숫자로 변경하여 대입 result = int(data[0]) for i in range(1, len(data)): # 두 수 중에서 하나라도 '0' 혹은 '1'인 경우, 곱하기 보다는 더하기 수행 num = int(data[i]) if num <= 1 or result <= 1: result += num else: result 8= num print(result)
ec8ef1ca5c815f84165dc4742a275dbd04de04ad
coder6586/Names_generator
/names generator.py
511
3.515625
4
import string, random def simple_names(): letter1=random.choice(string.ascii_uppercase) letter2=random.choice(string.ascii_lowercase) letter3=random.choice(string.ascii_lowercase) letter4=random.choice(string.ascii_lowercase) letter5=random.choice(string.ascii_lowercase) letter6=random.choice(string.ascii_lowercase) letter7=random.choice(string.ascii_lowercase) name= letter1+letter2+letter3+letter4+letter5+letter6+letter7 return(name) print(simple_names())
e07a76123cbbeb002263d9e2aafb61ed43b1b124
alyizzet/Python_Programming_Exercises
/main (3).py
1,531
3.609375
4
class Person: def __init__(self, fn, ln): self.first_name = fn self.last_name = ln self.address = None #addresses stored by strings def set_address(self, adr): self.address = adr #strings class BankAccount: def __init__(self, sort_code, account_number): self.sort_code = sort_code self.account_number = account_number def set_sort_code(self, sort_code): self.sort_code = sort_code def get_sort_code(self): return self.sort_code def set_account_number(self, account_number): self.account_number = account_number def get_account_number(self): return self.account_number def get_account_data(self): return f'{self.sort_code} {self.account_number}' class IndividualBankAccount(BankAccount): def __init__(self, sort_code, account_number, owner): super().__init__(sort_code, account_number) self.owner = Person(owner.first_name,owner.last_name) def get_account_data(self): return f'{self.owner.first_name} {self.owner.last_name} {self.sort_code} {self.account_number}' class SharedBankAccount(BankAccount): def __init__(self, sort_code, account_number, owners): super().__init__(sort_code, account_number) self.l = [] for i in range(len(owners)): self.l.append(owners[i]) def get_account_data(self): return f'{self.l[0].first_name} {self.l[0].last_name}, {self.l[1].first_name} {self.l[1].last_name}, {self.sort_code} {self.account_number}'
807b7bc89aecea4311f7b7c52d31e553a9317306
vostrikov-ov/Geekbrains_01
/Lesson_2/theme1_2.py
1,076
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Используя цикл, запрашивайте у пользователя число, пока оно не станет больше 0, но меньше 10. После того, как пользователь введет корректное число, возведите его в степень 2 и выведите на экран. Например, пользователь вводит число 123, вы сообщаете ему, что число неверное, и говорите о диапазоне допустимых. И просите ввести заново. Допустим, пользователь ввел 2, оно подходит. Возводим его в степень 2 и выводим 4. ''' while(True): result = int(input('Введите число: ')) if 0 < result < 10: print(result**2) break else: print('Введено неправильное число. Задайте число из диапазона от 0 до 10.')
a848d3dea3572923b8ee40ef7a64ad6b4bafdf0d
jeremiahmarks/dangerzone
/scripts/python/anagrams/wordsy.py
1,666
3.875
4
wordss=open('words.txt') matching_words={} words_without_letters={} alphabet=('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') def no_e(word): for letter in word: if letter == 'e': return return word def check_dict(): #matching_words=[] for i in range (100): line=wordss.readline() cword=line.strip() passer=no_e(cword) if passer==None: pass else: matching_words.append(passer) print matching_words def nolet(word,outcast): for letter in word: for char in outcast: if letter == char: return return word def heck_dict(): #matching_words=[] #bad=raw_input('please input undesired letters') for line in wordss: for bad in alphabet: cword=line.strip() passer=nolet(cword,bad) if passer==None: pass else: if passer not in matching_words: matching_words[passer]=bad else: matching_words[passer]+=bad if bad not in words_without_letters: words_without_letters[bad]=passer+" ," else: words_without_letters[bad]+=passer #print matching_words def listoletters(word): listed=matching_words[word] for letter in listed: print (letter+" is not in "+word) def wordswithout(letter) listed=words_without_letters[letter] for word in listed: print (word+" does not have "+letter)
92bed25d026b6c669946a2c8d8a7f7ee4558e0de
pengyuhou/git_test1
/leetcode/654. 最大二叉树.py
535
3.640625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def constructMaximumBinaryTree(self, nums) -> TreeNode: if not nums: return index = nums.index(max(nums)) left = nums[:index] right = nums[index + 1:] a = TreeNode(nums[index]) a.left = self.constructMaximumBinaryTree(left) a.right = self.constructMaximumBinaryTree(right) return a
4dabb7b168a1ef4236e8b54fa7a6add3cacc6534
marie8bit/ChainsawRecordsSQLAlch
/ui.py
1,841
4.21875
4
#This program uses parameterized SQL statement to manage an SQLite3 database file #to store chainsaw throwing records. #The user is able to add, edit, insert, and delete records from the database import records, choiceProcessor, dbManager def main(): #initializes database or reads data from the database file dbManager.setup() quit = 'q' choice = None #allow users to loop through choices until they quit while choice != quit: choice = display_menu_get_choice() choiceProcessor.handle_choice(choice) #displays options to user def display_menu_get_choice(): '''Display choices for user, return users' selection''' print(''' 1. Show records 2. Add a new record 3. Update a record 4. Delete a record q. Quit ''') choice = input('Enter your selection: ') return choice #validates user input data def getPositiveInt(string): #loops until it gets valid user data while True: #handles common user input errors try: id = int(string) if id >= 0: return id else: print('Please enter a positive number ') string = input() except ValueError: print('Please enter an integer number') string = input() #allows user to update the catch data for a record def getUpdateChoice(): print(''' Choose a record to update ''') dbManager.showAll() print('Enter the name of the record holder ') print('whose catch record has changed: ') choice = input() #verifize the record exists before trying to update it if (dbManager.getRecord(choice)): dbManager.updateRec(choice) else: print('Record not found, please try again') if __name__ == '__main__': main()
f5d7e069e2a079778727092fbeb4b2d9f26d7433
ParadigmPlusPlus/Course-Material
/Lesson-3/BooleanAsCondition.py
228
3.9375
4
boolean1 = True and True boolean2 = True and False boolean3 = False and False boolean4 = True or True boolean5 = True or False boolean6 = False or False if boolean1: # change boolean1 to boolean2, 3, 4, 5, 6 print("Hello")
d86613e525186d8334bf5dcfa82d3b631c911d8b
tcandzq/LeetCode
/UnionFindSet/SurroundedRegions.py
2,650
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/8/31 11:25 # @Author : tc # @File : SurroundedRegions.py """ 题号 130 被围绕的区域 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 Input: X X X X X O O X X X O X X O X X 运行你的函数后,矩阵变为: X X X X X X X X X X X X X O X X 解释: 被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。 本题有3种解法: 1.DFS 2.BFS 3.并查集 思路:先解决边界上的'O'或与边界上的相连通的'O'情况,然后再统一处理。 参考:https://leetcode-cn.com/problems/surrounded-regions/solution/dfs-bfs-bing-cha-ji-by-powcai/ """ from typing import List class Solution: # DFS解法 def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if not board or not board[0]: return row = len(board) col = len(board[0]) # 这个dfs的代码可以拿来做模板 def dfs(i, j): board[i][j] = 'B' for x,y in [(-1,0),(0,-1),(1,0),(0,1)]: tmp_i = x + i tmp_j = y + j # 注意这里的边界是1和row,或者0和row - 1 if 0 <= tmp_i <= row - 1 and 0 <= tmp_j <= col - 1 and board[tmp_i][tmp_j] == 'O': dfs(tmp_i, tmp_j) # 下面开始对边界情况进行处理 for j in range(col): # 第一行 if board[0][j] == 'O': dfs(0, j) if board[row - 1][j] == 'O': # 最后一行 dfs(row - 1, j) for i in range(row): if board[i][0] == 'O': # 第一列 dfs(i,0) if board[i][col - 1] == 'O': # 最后一列 dfs(i, col - 1) for i in range(0,row): for j in range(0,col): if board[i][j] == 'O': board[i][j] = 'X' if board[i][j] == 'B': board[i][j] = 'O' # BFS解法 # 并查集解法 if __name__ == '__main__': board = [ ['X', 'X', 'X', 'X'], ['X', 'O', 'O', 'X'], ['X', 'X', 'O', 'X'], ['X', 'O', 'X', 'X'] ] solution = Solution() print(solution.solve(board))
7577025c179ee57c6608e6502d1e68fec02cb2cf
shektor/pyman-numerals
/roman_numeral.py
1,596
3.625
4
def convert(number): numerals = { 1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M', } units = [1000, 500, 100, 50, 10, 5, 1] numeral = '' while number > 0: round_one_sig = number if number > 9: tens = 1 while round_one_sig > 9: round_one_sig = int(round_one_sig / 10) tens = tens * 10 round_one_sig = round_one_sig * tens if round_one_sig in numerals: numeral += numerals[round_one_sig] number -= round_one_sig else: for index, unit in enumerate(units): if unit % 10 == 0: minor_unit = units[index + 2] abbreviated_unit = unit - minor_unit if round_one_sig == abbreviated_unit: numeral += numerals[minor_unit] + numerals[unit] number -= abbreviated_unit break if round_one_sig > unit: if index != 0: previous_unit = units[index - 1] abbreviated_unit = previous_unit - unit if round_one_sig == abbreviated_unit: numeral += numerals[unit] + numerals[previous_unit] number -= abbreviated_unit break numeral += numerals[unit] number -= unit break return numeral
735dd148da99f579f79c69a93cdc1663c2044875
TheGrateSalmon/Side-Projects
/Shift Cipher.py
2,379
4.53125
5
# This program allows a user to encode and decode messages through the use of a shift cipher. # June 12th, 2018 def encrypt(key , message , alphabet): # this function takes a "message" as a string and encrypts it by shifting the characters of the string forward by an integer key # keep only a-z characters of the message and initialize the reduced message red_message = '' for char in message: if char.lower() in alphabet: red_message += char # initialize the final, encrypted string result_string = '' # traverse the string, shifting the characters by the key, and appending to the result string for char in red_message: ind = alphabet.index(char.lower()) new_ind = (ind + key) % 26 # mod 26 because of the alphabet result_string += alphabet[new_ind] print("Your encrypted message is:") print(result_string.upper()) return(result_string) def decrypt(key , message , alphabet): # this function takes an encrypted, string message and decrypts it using an integer key # format the message message.lower() result_string = '' for char in message.lower(): ind = alphabet.index(char) new_ind = (ind - key) % 26 result_string += alphabet[new_ind] print('Your decrypted message is:') print(result_string) return(result_string) def main(): alphabet = ['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'] process = input('Would you like to encrypt ("e") or decrypt ("d") (enter "done" to exit)?\t') while process != 'done': if process == 'e': message = input("What would you like to encrypt?\t") key = int(input("How many places would you like to shift the characters by?\t")) print() enc = encrypt(key , message , alphabet) else: message = input("What would you like to decrypt (only letters)?\t") key = int(input("How many places would you like to shift the characters by?\t")) print() dec = decrypt(key , message , alphabet) print("\n\n\n") process = input('Would you like to continue to encrypt ("e") or decrypt ("d") (enter "done" to exit)?') main()
db6f2d7a220119e10baf8221d67d221a13b5915a
Ham5terzilla/python
/2nd Lesson/2.py
305
3.53125
4
# Ввести с клавиатуры координаты двух точек (A и B) на # плоскости (вещественные числы). Вычислить длину отрезка AB Ax, Ay, Bx, By = map(float, input().split()) print(round(((Ax - Bx) ** 2 + (Ay - By) ** 2) ** 0.5, 2))
30f3239eb87bebf37503a94635d306a3969d8225
ATUL786pandey/python_prac_codewithharry
/loop_prac02.py
286
3.546875
4
''' write a program to greet all the person in the list l1 and which start with s l1=["Harry","sohan","sachin","shailesh","sahil"] ''' l1=["Harry","sohan","sachin","shailesh","sahil"] for i in l1: if i.startswith("s"): print("good Evening have a nice day", i)
8a0428f6d56daa9170b448410aa423fa5a4def92
ERICCYS/Coursera-Algorithm-Toolbox
/Week 3 Greedy/Maximum_Salary.py
763
3.65625
4
def input_info(): n = int(input()) number_strings = input().split() lengths = [] for number_string in number_strings: lengths.append(len(number_string)) max_length = max(lengths) info = [] for number_string in number_strings: info_piece = [] info_piece.append(number_string) for i in range (max_length): info_piece.append(int(number_string[i % len(number_string)])) info_piece.append((number_string[-1])) info.append(info_piece) for i in range ((len(info_piece) - 1),0,-1): info = sorted(info, key = lambda info: info[i]) return info def max_salary(info): max_salary = '' for i in range ((len(info) - 1), -1, -1): max_salary += info[i][0] max_salary = int(max_salary) print(max_salary) info = input_info() max_salary(info)
8a28b4b43825bd5a09d6308cf9e43bb5711229e6
aryajar/Louplus
/game.py
590
3.984375
4
sticks = 21 print("There are 21 sticks. you can take 1-4 number of sticks at a time") print("Whoever take the last sticks will lose") while True: sticks_taken = int(input("Take sticks(1-4):")) if sticks_taken >4 or sticks <1: print("Wrong choice") continue else: print("You take {} number of sticks".format(sticks_taken)) print("Computer took {} number of sticks".format(5 - sticks_taken)) sticks -= 5 print("Sticks left", sticks) if sticks==1: print("Yout took the last stick, you loose") break
364331d0699661d03cc4bc33daaf9f1c27878dbf
UMBC-CMSC-Hamilton/cmsc201-spring2021
/variables.py
7,780
4.65625
5
# Let's do a little bit of review. (pound-sign, hash tag) start a single-line comment # the Python interpreter basically ignores the comment lines. # Multiline comments are done like this: """ This is a multi-line comment (basically) we can use it for that purpose. Actually: A multi-line string Do I need to comment my code? Yes Do I need to comment nearly as much as these lecture files? no. """ """ Review variables A variable is really an abstraction of a memory location (or multiple memory locations) in RAM. We give these variables names so we can refer to them. Rules for variable naming: 1) has to start with underscore _ or letter (upper or lower case) 2) has to be made up of numbers, letters, underscores Coding Standards for Python: 1) snakecase: variables are lower case and underscores 2) you should have meaningful variable names 3) spell out words when it makes sense (when its not way way way too long) 4) obvious abbreviations are ok. 5) avoid single letter variables except as loop indices. this_integer my_string favorite_number In this class, assume our coding standard is this one, snake_case camelCase No underscores, words spelled out, first word lower case, all others first letter capitalized myInteger thisVariable """ pi = 3.1415926535 radius = 5 area_of_circle = pi * radius ** 2 # don't do this, no one will know what the heck this is... x = 31 * radius + 2 * pi - area_of_circle ** 2 # you in a week or your TA won't know what this is... # What are the four "primitive" variable types in python? # integers (either positive or negative * whole number, 0) my_integer = 5 # float is the second type of variable # float == floating point # there's a decimal in it. my_float = 1.6789 also_a_float = 5.0 # if you ever need a float, but it's also an integer, put a .0 # last time people mentioned doubles. Python doesn't have a double because its float is # actually far more precise than the C++ float type. (secretly it may even be a C++ double) # converting from a float to integer is a pure truncation (rounding down) print(int(5.9), int(5.2), int(5.0001), int(5.0)) # let's talk about strings! a_string = 'you can use this kind of delimiter' # single ' double_tick_string = "you can also use this delimiter" # double " print(type(a_string), type(double_tick_string)) # type you aren't going to use in this class. But here i'm using it to show you that it's # the same type. # python doesn't really have characters, it does have length 1 strings # you can add strings natively in python first_string = 'hello' second_string = "Python" """ String Concatenation: Two (or more) strings are put/added together into a single new string. """ addition = first_string + second_string print(addition) # boolean type """ Boole Boolean logic = True, False, and, or, not. """ True False # flag variables are variables that wait until something happens, then you flip them # when you flip them, you detect that in an if statement and do something about it. server_connected = True # if the "server" were ever disconnected, you'd set this to false and then try to fix that continue_playing = True # the game is going until this set to False then the game is over... # python gives you the keywords and or not """ or is true when either one is true or A T F B T T T F T F """ print(True or True, True or False, False or True, False or False) """ Truth Tables and is true when both are true and A T F B T T F F F F """ print(True and True, True and False, False and True, False and False) # && == logical and operator in C++ "and" is the logical and in Python """ Truth Tables not is true when both are true not is different from "and" and "or" Not "unary operator" = operator that eats a single argument and /or are "binary operators" = they eat two arguments. +, -, *, / , //, and, or ternary operator C++ a ? b : c; tests a, if true, then b else c; hex operator would be 16 arguments... that's a lot A T F not A F T """ print(not True, not False) """ not has higher precedence than and/or and/or have equal precedence precedence = which operation happens first Order of operations for and/or/not Potentially not what you mean without parens... 3 + 2 * 5 (3 + 2) * 5 3 + (2 * 5) PEMDAS = sorta right., PEDMSA, PEMDSA, PEDMAS, whatever PE(MD)(AS) Multiplication and division have equal precedence addition and subtraction have equal precedence. PN(AO) - order of operations Please Never Attack Objects - order of operations for logic Please Never Order Asparagus - two equivalent nonsense bits. """ a = True b = False # i don't know what this is going to do, unless we believe the OrderOfOps print(not b or a, (not b) or a, not (b or a)) """ Let's take a break from logic for a second and talk about integer division vs floating division. in python, if you have two integers and you divide them, let's see what happens: """ print(5 / 3) """ Hmmm.. a float popped out, that isn't right. Sometimes you definitely don't want this to happen. If you want the result to remain an integer, do this: """ print(5 // 3) # this is extremely useful because sometimes you ABSOLUTELY need an integer print(int(5 / 3)) # hmmm... the result here was -1, what the heck? print(-1 // 3) # 0, 1, 2 // 3 == 0, so -1, -2, -3 // 3 == -1 # the result is actually different for negative numbers... ugh... print(int(-1/3)) # if you're dealing with negatives, just understand what it does, use the one you want # double division symbol is integer division. # integer division can actually take floats as well, it behaves weirdly sometimes... print(3.2 // 1.6) # this is extra nonsense that you should avoid using. """ Last 20 minutes will be about if statements... yay? So far we've learned about printing, inputting, and variables... if statements are the basic way that computers/programming languages make decisions. """ a_word = input('Tell me a word: ') """ Syntax - what is syntax? Structure formal grammar of a language it's where words go S-V In python: Each if statement "sentence" has an if at the start, colon at the end. everything between if and : needs to evaluate to True or False """ # notice here, this is not = (single) this is a double equals sign (==) # programming languages have a different symbol for "test if this thing is equal" == # vs. assign that <-- that # that = this if a_word == 'robot': print('You have said robot, I accept this.') # a-block # pretty good print('The program is ending, goodbye.') # b-block x = int(input('Tell me an integer: ')) y = int(input('Tell me another integer: ')) if x < y: print('y is bigger') if x > y: print('x is bigger') if x == y: print('x is the same as y') # this is an example of where we are using logical operator to chain two conditions if a_word == 'salami' and x > 5: print('Some random thing happened to be true, also salami') # flag variables happy = False # more code here if a_word == "happy": happy = True # this remembers it for later # much more code here # later on in your code you can check if happy was set to true. print(happy) # a lot of times, happy then decide some later if statement/while loop # determines how the program works from there.
17dbf5b3017224bc8481494cc89ef3549c467eb4
dlordtemplar/python-projects
/Functions/gcd.py
621
3.984375
4
''' Implement a function gcd(x, y) that computes the greatest common divisor of x and y. (1 Point) >>> gcd(8, 12) 4 ''' # ... your code ... def gcd(num1, num2): if (num1 > num2): greaterNum = num1 lesserNum = num2 else: greaterNum = num2 lesserNum = num1 remainder = lesserNum result = -1 while (remainder != 0): result = remainder remainder = greaterNum % remainder return result if __name__ == '__main__': print('gcd') print('Test1', gcd(8, 12) == 4) print('Test2', gcd(42, 56) == 14) print('Test3', gcd(1071, 1029) == 21)
22b700b93fd884e5c7433f915236c0cb13355b62
mason-landry/sudoku
/sudoku/board.py
2,423
3.828125
4
import numpy as np class Board: def __init__(self, size=9): # Define size of sudoku grid (default is 9x9) self.size = size self.board = [] # Fill grid with zeros to start for i in range(self.size): self.board.append(np.zeros(self.size, dtype=int)) def update(self, val, i, j): self.board[i][j] = val def show(self): for i in self.board: print(*i) def find_next_empty(self): '''Finds next empty space in puzzle board, reading left to right and top to bottom. Params: None Output: r - row index c - column index ''' for r in range(self.size): for c in range(self.size): if self.board[r][c] == 0: return r,c def validate(self, val, r, c): '''Validates whether the value 'val' works in the space r,c Params: val - Number between 1 and 9 to test r - row index c - column index ''' # Check row for i in range(self.size): if self.board[r][i] == val and c != i: return False # Check column for i in range(self.size): if self.board[i][c] == val and r != i: return False # Check box box_x = c // 3 box_y = r // 3 for i in range(box_y*3, box_y*3 + 3): for j in range(box_x * 3, box_x*3 + 3): if self.board[i][j] == val and (i,j) != (r,c): return False return True def solve(self): ''' Recursive solving algorithm. Updates matrix with valid solutions and resets if it hits a problem ''' # Get r,c indices if empty space idx = self.find_next_empty() if idx: r,c = idx # Loop to try numbers 1 through 10 in each empty space for i in range(1, self.size + 1): if self.validate(i, r, c): self.update(i,r,c) # Check if the remaining spaces can be solved with this solution: if self.solve(): # Recursion! return True self.update(0,r,c) else: # no more empty spaces, puzzle must be solved! return True return False
1f68b5fadcaee11b1ea9dc20a469564b5bfb4bde
rafaelperazzo/programacao-web
/moodledata/vpl_data/7/usersdata/99/5255/submittedfiles/esferas.py
285
3.71875
4
# -*- coding: utf-8 -*- from __future__ import division A=input('Digite o peso da esfera A:') B=input('Digite o peso da esfera B:') C=input('Digite o peso da esfera C:') D=input('Digite o peso da esfera D:') if (A==B+C+D) and (B+C==D) and (B==C): print('S') else: print('N')
9e68d3d693f232855a729256d7a1592b73354b07
rileychapman/SoftDes
/random/hello.py
147
3.703125
4
def hello(x): if x >= 0 and x <= 100: print "hello" elif x>100 and x < 500: print "goodby" elif x >= 600 and x<=1000: print "ciao"
509d316dc4a3cbab41808d750dd468bff16f9ba7
saipoojavr/saipoojacodekata
/a'sb's1change.py
180
4.03125
4
astr=input() count=0 for i in range(0,len(astr)): if(astr[i]=="a" or astr[i]=="b"): count+=1 if(count==len(astr) or count==len(astr)-1): print("yes") else: print("no")
4f31726dd8618e6253dc0738768097daa9f089c2
jeevy222/Hashing-1
/groupanagrams_revision.py
656
3.796875
4
def groupanagrams(strs): result =[] dic = {} for word in strs: sortkey = ''.join(sorted(word)) if sortkey not in dic: dic[sortkey]=[word] else: dic[sortkey].append(word) for item in dic.values(): result.append(item) return result ''' loop through the given array of words and sort each word, for every iteration check if the word is present in the dictionary or not. If not then add key as sorted word and value as the word ,else just append the word. Finally iterate through values of dictionary and append values in a result list and return result. tc and sc will be o(n) and [o(n)+o(n)]==o(n)'''
2b78c804cf4cf3ccbad8f27ef00712131ddeb105
ssaurabhjawa/Auto-Crop-Image
/auto-crop.py
5,785
3.703125
4
from time import time import cv2 import matplotlib.pyplot as plt import numpy as np def auto_crop(file_name): """ Input argument: file_name (Image file name, e.g., 'rose.tif') This function will auto crop the given image using image processing technique Output: ROI """ # Start timer start_time = time() # Read an image img = cv2.imread(file_name, cv2.IMREAD_UNCHANGED) height = img.shape[0] width = img.shape[1] # Check image is grayscale or not if len(img.shape) == 2: gray_img = img.copy() else: # Convert bgr image to grayscale image gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # To find upper threshold, we need to apply Otsu's thresholding upper_thresh, thresh_img = cv2.threshold(gray_img, thresh=0, maxval=255, type=cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Calculate lower threshold lower_thresh = 0.5*upper_thresh # Apply canny edge detection canny = cv2.Canny(img, lower_thresh, upper_thresh) # Finding the non-zero points of canny pts = np.argwhere(canny>0) # Finding the min and max points y1,x1 = pts.min(axis=0) y2,x2 = pts.max(axis=0) # Crop ROI from the givn image roi_img = img[y1:y2, x1:x2] # Printing image dimensions, execution time print(f'Original image dimensions: {width}x{height}') print(f'Execution time: {time()-start_time} sec') # Display images fig = plt.figure() fig.suptitle('Auto Cropping using Canny Edge Detection', fontsize=16) fig.add_subplot(1,3, 1).set_title('Orginal image') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) fig.add_subplot(1,3, 2).set_title('Apply canny edge detection') plt.imshow(cv2.cvtColor(canny, cv2.COLOR_BGR2RGB)) fig.add_subplot(1,3, 3).set_title('ROI') plt.imshow(cv2.cvtColor(roi_img, cv2.COLOR_BGR2RGB)) plt.show() return roi_img def image_attributes(img): """ Input argument: img (Opencv mat) This function will display the following image attributes: - Height and Width - Color Channel - DPI - Max/Min/Average Intensity Values Output: image attributes """ height = img.shape[0] width = img.shape[1] if len(img.shape) == 2: no_of_channels = 1 else: no_of_channels = img.shape[2] bit_depth = no_of_channels*8 storage_size = int((height*width*bit_depth)/8) # Calculate intensity value min_intensity = img.min(axis=0).min(axis=0) max_intensity = img.max(axis=0).max(axis=0) average_intensity = img.mean(axis=0).mean(axis=0).astype(int) print(f'- Image dimensions: {width}x{height}') print(f'- Height (rows): {height} pixels') print(f'- Width (columns): {width} pixels') print(f'- No. of pixels: {height*width}') print(f'- Color channels: {no_of_channels}') print(f'- Bit depth: {bit_depth}') print(f'- Storage size (without compression)): {storage_size} bytes') print('- Intensity Values') if no_of_channels == 1: print(f'\tMin Intensity: {min_intensity}') print(f'\tMax Intensity: {max_intensity}') print(f'\tAverage Intensity: {average_intensity}') elif no_of_channels == 3: print(f'\tMin Intensity (Blue): {min_intensity[0]}') print(f'\tMax Intensity (Blue): {max_intensity[0]}') print(f'\tAverage Intensity (Blue): {average_intensity[0]}') print(f'\tMin Intensity (Green): {min_intensity[1]}') print(f'\tMax Intensity (Green) {max_intensity[1]}') print(f'\tAverage Intensity (Green): {average_intensity[1]}') print(f'\tMin Intensity (Red): {min_intensity[2]}') print(f'\tMax Intensity (Red) {max_intensity[2]}') print(f'\tAverage Intensity (Red): {average_intensity[2]}') def image_features(img): """ Input argument: img (Opencv mat) This function will display the following image features: - Edges - Corners / interest points - Blobs / regions of interest points - Ridges Output: display image features """ # Apply canny edge detection canny_img = cv2.Canny(img, 50, 200) # Check image is grayscale or not if len(img.shape) == 2: gray_img = img.copy() img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) else: # Convert bgr image to grayscale image gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Get heatmap image heatmap_img = cv2.applyColorMap(gray_img, cv2.COLORMAP_JET) # Corners detection corner_img = img.copy() gray_img_float = np.float32(gray_img) dst = cv2.cornerHarris(gray_img_float,2,3,0.04) dst = cv2.dilate(dst, None) # Threshold for an optimal value corner_img[dst>0.01*dst.max()]=[0,0,255] ridge_filter = cv2.ximgproc.RidgeDetectionFilter_create() ridges_img = ridge_filter.getRidgeFilteredImage(img) # Display image features fig = plt.figure() fig.suptitle('Image Features', fontsize=16) fig.add_subplot(2,2, 1).set_title('Edges') plt.imshow(cv2.cvtColor(canny_img, cv2.COLOR_BGR2RGB)) fig.add_subplot(2,2, 2).set_title('Corners') plt.imshow(cv2.cvtColor(corner_img, cv2.COLOR_BGR2RGB)) fig.add_subplot(2,2, 3).set_title('Ridges') plt.imshow(cv2.cvtColor(ridges_img, cv2.COLOR_BGR2RGB)) fig.add_subplot(2,2, 4).set_title('Heatmap') plt.imshow(cv2.cvtColor(heatmap_img, cv2.COLOR_BGR2RGB)) plt.show() if __name__ == '__main__': file_name = 'butterfly.jpg' roi_img = auto_crop(file_name) print('ROI attributes:-') image_attributes(roi_img) image_features(roi_img)
69aae714a43d91429bc8032871dbd8af61fad072
FeiY74/python-memo
/useful.py
128
3.953125
4
# delete one character from a string def missing_char(str, n): if ( n >= 0 and n <= len(str)): return str[:n] + str[n+1:]
f1936d6834c5b8f697f1821a72122b15cb58be9f
cqkh42/advent-of-code
/aoc_cqkh42/year_2020/day_10.py
1,365
3.90625
4
""" Solutions for day 10 of 2020's Advent of Code """ import functools from typing import List, Tuple def _sort_adapters(adapters) -> List[int]: adapters = [0, *sorted(adapters), max(adapters) + 3] return adapters def _chain_adapters(adapters) -> Tuple[int]: chain = [0] * (max(adapters) + 1) for num in adapters: chain[num] = tuple( next_num for next_num in adapters if 1 <= next_num - num <= 3 ) return tuple(chain) @functools.lru_cache(None) def _num_routes(num, chain) -> int: if not chain[num]: return 1 else: return sum(_num_routes(x, chain) for x in chain[num]) def part_a(data) -> int: """ Solution for part a Parameters ---------- data: str Returns ------- answer: int """ adapters = [int(num) for num in data.split('\n')] adapters = _sort_adapters(adapters) differences = [right-left for left, right in zip(adapters, adapters[1:])] return differences.count(1) * differences.count(3) def part_b(data, **_) -> int: """ Solution for part b Parameters ---------- data: str Returns ------- answer: int """ adapters = [int(num) for num in data.split('\n')] adapters = _sort_adapters(adapters) chain = _chain_adapters(adapters) return _num_routes(0, chain)
1d14fb09d21362ed7089e3c4d0cd0698f4a33ecf
codeAligned/Leet-Code
/src/P-056-Merge-Intervals.py
940
3.859375
4
''' P-056 - Merge Intervals Given a collection of intervals, merge all overlapping intervals. For example,Given[1,3],[2,6],[8,10],[15,18],return[1,6],[8,10],[15,18]. Tags: Array, Sort ''' # Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge(self, intervals): ret = [] intervals.sort(key = lambda x : x.start) for interval in intervals: if not ret or interval.start > ret[-1].end: ret.append(interval) else: ret[-1].end = max(ret[-1].end, interval.end) return ret s = Solution() l = [ Interval(1, 2), Interval(2, 3), Interval(3, 6), Interval(8, 10), Interval(15, 18) ] for item in s.merge(l): print item.start, item.end
3de5125be7aea69888ec9989e80ca40d839bfcba
BrundaBR/solutions
/watermelon.py
69
3.671875
4
n=int(input()) if (n)%2==0 and n!=2: print("YES") else: print("NO")
74c262b059ff80a9754f0fc3ab0a42cb568cd042
stag152766/gb_ik_python
/Lesson6/les_6_task_1.py
3,748
4.03125
4
# 1. Подсчитать, сколько было выделено памяти под переменные в # программах, разработанных на первых трех уроках. # Выберите 3 любые ваши программы для подсчёта. import sys from Lesson6.task_4 import show_size print(sys.version, sys.platform) # 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] win32 # 8. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого). # Вариант 1 # type=<class 'int'>, size=14, object=123 # type=<class 'int'>, size=16, object=124231 # type=<class 'int'>, size=14, object=1 # a = int(input('Введите первое число: ')) # b = int(input('Введите второе число: ')) # c = int(input('Введите третье число: ')) # # if (b < a < c) or (c < a < b): # print(f'Среднее число: {a}') # elif (a < b < c) or (c < b < a): # print(f'Среднее число: {b}') # else: # print(f'Среднее число: {c}') # # show_size(a) # show_size(b) # show_size(c) # Вариант 2 # type=<class 'list'>, size=44, object=[123, 124231, 1] # type=<class 'int'>, size=14, object=123 # type=<class 'int'>, size=16, object=124231 # type=<class 'int'>, size=14, object=1 # type=<class 'int'>, size=14, object=1 # type=<class 'int'>, size=16, object=124231 # print('Введите три натуральных числа: ') # lst = [int(input()) for n in range(3)] # # max_num = max(lst) # min_num = min(lst) # # for num in lst: # if num != max_num and num != min_num: # print(f'Среднее: {num}') # # show_size(lst) # show_size(min_num) # show_size(max_num) # Вывод наиболее эффективная по использованию памяти программа в 1 варианте # 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. # Вариант 1 # type=<class 'int'>, size=16, object=123456 # type=<class 'str'>, size=26, object=6 # type=<class 'str'>, size=27, object=65 # type=<class 'str'>, size=28, object=654 # type=<class 'str'>, size=29, object=6543 # type=<class 'str'>, size=30, object=65432 # type=<class 'str'>, size=31, object=654321 # Результат: 654321 # s = '' # show_size(s) # # num = int(input('Введите число: ')) # show_size(num) # # while num != 0: # s += str(num % 10) # show_size(s) # num //= 10 # print(f'Результат: {s}') # Вариант 2 # type=<class 'list'>, size=52, object=['1', '2', '3', '4', '5', '6'] # type=<class 'str'>, size=26, object=1 # type=<class 'str'>, size=26, object=2 # type=<class 'str'>, size=26, object=3 # type=<class 'str'>, size=26, object=4 # type=<class 'str'>, size=26, object=5 # type=<class 'str'>, size=26, object=6 # type=<class 'list'>, size=52, object=['6', '5', '4', '3', '2', '1'] # type=<class 'str'>, size=26, object=6 # type=<class 'str'>, size=26, object=5 # type=<class 'str'>, size=26, object=4 # type=<class 'str'>, size=26, object=3 # type=<class 'str'>, size=26, object=2 # type=<class 'str'>, size=26, object=1 # type=<class 'str'>, size=31, object=654321 n1 = list(input('Введите целое число: ')) show_size(n1) n1.reverse() show_size(n1) n2 = "".join(n1) show_size(n2) print(n2) # Вывод наиболее эффективная по использованию памяти программа в 1 варианте
c93b30cbc764609d46114bfddc543283659c160d
CRomanIA/Python_Undemy
/Seccion_17_Pruebas_Automaticas/Sec17cap63.py
714
3.734375
4
#Doctest - Generar pruebas dentro de la documentacion def sumar(numero1, numero2): """ Esto es la documentacion de este metodo Recibe dos numeros como parametros y devuelve su suma Se genera la prueba en los comentarios (No olvidar en el mayor que, darle un espacio) (suma correcta) >>> sumar(4,3) 7 (suma correcta) >>> sumar(5,4) 9 (suma incorrecta) >>> sumar(1,3) 7 """ return numero1 + numero2 resultado = sumar(2,4) print(resultado) #ir al cmd y dirigirse al directorio donde está este metodo. ejecutarlo por consola y ver el resultado (debiese dar 6) #Para ejecutar prueba de comentario en la consola del cmd... import doctest doctest.testmod()
5d05866f01932ca1225eb03685aa9466a67eb016
PooPooPidoo/SimpleCalculate
/calc.py
2,095
4.03125
4
import math as m import re def op(x,y,operator): if(checknum(x,y)): if operator == '+': return x+y, if operator == '-': return x-y, if operator == '*': return x*y, if operator == "/" and y != 0: return x/y, if operator == "/" and y == 0: return ["division by zero",] else: return "bad expression" def parse(str): numbers = [] operators = 0 operator = '' flag = False num = '' # re.sub(str, '', ' ') if str[0] in '-+': num += str[0] str = str[1:len(str)] for symbol in str: if symbol == ' ': continue if symbol in '123456789.0': flag = True num += symbol continue else: if symbol in '+-*/': operators += 1 if operators > 1: symbol = '' if operators == 1: operator = symbol numbers.append(float(num)) num = '' flag = False continue if not flag: print("Bad expression") return if operators < 1: print("No operators found") return numbers.append(float(num)) if operators==1 and flag==True and len(numbers)>1: return numbers, operator def checknum(*args): for var in args: if type(var) is float: pass else: print("at least one value is not a number") return False return True def main(): print("Welcome to the standart calc!") print("Type two numeric values with an operation between") while True: expr = input() if expr != '': try: numbers, operator = parse(expr) except TypeError: print("Bad Expression") except ValueError: print("Bad Expression") else: print(op(numbers[0], numbers[1], operator)[0]) main()
1ba17acff10e50ab6d05383c8e72f4682f4a9dbf
goalong/lc
/v1/231.power-of-two.132672777.ac.py
699
3.65625
4
# # [231] Power of Two # # https://leetcode.com/problems/power-of-two/description/ # # algorithms # Easy (40.65%) # Total Accepted: 164.3K # Total Submissions: 404.2K # Testcase Example: '1' # # # Given an integer, write a function to determine if it is a power of two. # # # Credits:Special thanks to @jianchao.li.fighter for adding this problem and # creating all test cases. # class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ # 3 star if n <= 0: return False while n >= 2: if n % 2 == 1: return False n = n // 2 return True
4837192069da7a2efe08ad3acb3bf8c6ae5641ca
helenmfoster/MLProject
/wikipage.py
2,286
3.828125
4
import re import wikipedia from paragraph import Paragraph class Wikipage: """Representation of wikipedia article""" def __init__(self, subject): """ subject (string) : subject of desired wikipedia article """ self.subject = subject self.page = wikipedia.page(self.subject) self.sections = self.page.sections self.paragraphs = [] def get_section(self, index): """ Returns the corresponding section with utf-8 encoding""" return re.sub('<[^<]+?>', '', self.sections[index].encode("utf-8")) def get_header(self, index): """ Formats the corresponding section as wikipedia plaintext does""" section = self.get_section(index) return "= " + section + " =" def write_paragraph(self, section_number, content): """ Writes paragraph to paragraph diction with section as key, content as value""" if section_number == 0: title = "Summary" else: title = self.get_section(section_number - 1) paragraph = Paragraph(section_number, title, content) self.paragraphs.append(paragraph) def clean_paragraphs(self): """ Removes sections that are empty """ clean_paragraphs = [] counter = 0 for paragraph in self.paragraphs: content = paragraph.content if len(content) > 1: paragraph.index = counter counter += 1 clean_paragraphs.append(paragraph) self.paragraphs = clean_paragraphs def split_paragraphs(self): """Splits up a wikipedia article into sections and writes to dictionary""" content = self.page.content.encode("utf-8").split("\n") section_number = 0 num_sections = len(self.sections) current_header = self.get_header(section_number) current_content = [] for line in content: if current_header in line: self.write_paragraph(section_number, current_content) current_content = [] section_number += 1 if section_number < num_sections: current_header = self.get_header(section_number) else: break elif len(line.strip()) > 0: current_content.append(line) self.write_paragraph(section_number, current_content) self.clean_paragraphs() return self.paragraphs #w = Wikipage("Albert Einstein") #print w.split_paragraphs()
77424d1c1779fbf14aa3a3953a97ab00f80624ce
AlceniContreras/Project-Euler
/Prob17.py
1,290
3.625
4
#-*- coding: utf-8 -*- # Number letter counts # -------------------- stop = 1000 num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \ 11: 'Eleven', 12: 'Twelve', 13:'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', \ 19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', 90: 'Ninety'} def under_100(n): try: return num2words[n] except KeyError: try: tens, units = divmod(n, 10) return num2words[tens*10] + num2words[units].lower() except KeyError: return 'Out of range' def spell_numbers(x): if x == 1000: spelled = 'One thousand' elif 100 <= x < 1000: hundreds, remainder = divmod(x, 100) spelled = num2words[hundreds] + ' hundred' if remainder != 0: spelled += ' and ' + under_100(remainder).lower() elif x < 100: spelled = under_100(x) else: spelled = 'Out of range' return spelled spelled = [spell_numbers(i) for i in range(1, stop + 1)] temp = "" for num in spelled: temp += num temp = temp.replace(" ", "") print(len(temp))
4badcb8924dda4d68dd28af4e5868f3145e829f0
iamserda/cuny-ttp-algo-summer2021
/victorLi/assignments/subsets/lc78/lc78.py
348
4.125
4
# Problem Statement # # Given a set with distinct elements, find all of its distinct subsets. def find_subsets(nums): subsets = [] # TODO: Write your code here return subsets def main(): print("Here is the list of subsets: " + str(find_subsets([1, 3]))) print("Here is the list of subsets: " + str(find_subsets([1, 5, 3]))) main()
9a99e019e0277ed5cbf5b89f497e623aa880ea03
c212/spring2021-a310-labs
/march/lecture-march-08/BST-tests.py
627
4.15625
4
from BST import * num = 6 a = BST(num) print("Start from empty, insert ", num) a.display() num = 3 print("----Now insert ", num) a.insert(BST(num)) a.display() print("---And insert 2:") a.insert(BST(2)) a.display() numbers = [7, 9, 0, 8, 1, 4, 5] print("---And insert (in order): ", numbers) for num in numbers: a.insert(BST(num)) a.display() # Start from empty, insert 6 # 6 # ----Now insert 3 # 6 # / # 3 # ---And insert 2: # 6 # / # 3 # / # 2 # ---And insert (in order): [7, 9, 0, 8, 1, 4, 5] # __6 # / \ # 3 7_ # / \ \ # _2 4 9 # / \ / # 0 5 8 # \ # 1
4d1b637106732f7fda208190676d5a02dd740b67
kirillherz/Python-learning
/Алгоритмы/Finding_loop_in_the list.py
1,746
3.84375
4
class Node: def __init__(self, data, next): self.data = data self.next = next class List: def __init__(self): self._head = None self._tail = None self._size = 0 self._nextHead = None def add(self, data): newNode = Node(data, None) if self._size == 0: self._nextHead = newNode self._head = newNode self._tail = newNode else: self._tail.next = newNode self._tail = newNode self._size += 1 def findNode(self, searchIndex): currentIndex = 0 node = self._head prevNode = None while currentIndex != searchIndex: prevNode = node node = node.next currentIndex += 1 return node def addLoop(self, index, data): newNode = Node(data, self.findNode(index)) self._tail.next = newNode self._tail = newNode def next(self): data = self._nextHead.data self._nextHead = self._nextHead.next return data def FindLoop(self): slow = self._head.next fast= self._head.next.next isLoop = True while slow != fast: slow = slow.next fast = fast.next.next if (slow == None) or (fast == None): isLoop = False break index = None if isLoop: index = 0 slow = self._head while slow != fast: slow = slow.next fast = fast.next index += 1 return index l = List() l.add(0) l.add(1) l.add(2) l.add(3) l.add(4) l.add(5) l.addLoop(0,6) print(l.FindLoop())
02f1cb665fd3c8cd9427c4f069d2954a2bfc15d7
yossibaruch/learn_python
/learn_python_the_hard_way/ex28.py
1,037
4.1875
4
if True and True: print("1 True") if False and True: print("2 True") if 1 == 1 and 2 == 1: print("3 True") if "test" == "test": print("3 True") if 1 == 1 or 2 != 1: print("4 True") if True and 1 == 1: print("5 True") if False and 0 != 0: print("6 True") if True or 1 == 1: print("7 True") if "test" == "testing": print("8 True") if 1 != 0 and 2 == 1: print("9 True") if "test" != "testing": print("10 True") if "test" == 1: print("11 True") if not (True and False): print("12 True") if not (1 == 1 and 0 != 1): print("13 True") if not (10 == 1 or 1000 == 1000): print("14 True") if not (1 != 10 or 3 == 4): print("15 True") if not ("testing" == "testing" and "Zed" == "Cool Guy"): print("16 True") if 1 == 1 and (not ("testing" == 1 or 1 == 0)): print("17 True") if "chunky" == "bacon" and (not (3 == 4 or 3 == 3)): print("18 True") if 3 == 3 and (not ("testing" == "testing" or "Python" == "Fun")): print("19 True")
9ed7f42bd65b9d70d7a44e0620fa25f8906c991c
RyoTakei/Spark
/Day1/lists.py
552
4.25
4
listOne = ["juice", "Tomatos", "Potatos", "Bananas"] firstItem = listOne[0] print("The first item is", firstItem) listOne[0] = "Green Juice" print("The First item is now", listOne[0]) # print 1 up to 3 but NOT including 3 print(listOne[1:3]) listOne.append("Onions") print(listOne) listOne.insert(1, "Pickle") print("insert() ", listOne) listOne.remove("Pickle") print("\nremove()", listOne) listOne.sort() print("\nsort()", listOne) listOne.reverse() print("\nreverse()", listOne) del listOne[4] print("\ndel", listOne) print(len(listOne))
79821243a964cdda26ecf8c585cd86c737f34677
alen6697/leetcode-practice
/FlowerPlantingWithNoAdjacent.py
872
3.578125
4
class Solution(object): def gardenNoAdj(self, n, paths): """ :type n: int :type paths: List[List[int]] :rtype: List[int] """ graph = defaultdict(set) for u, v in paths: graph[u].add(v) graph[v].add(u) res= [0] * (n + 1) for i in range(1, n + 1): # traverse all the node # check connected neighbors' color available={1, 2, 3, 4} for n in graph[i]: # traverse all neighbors of the node if res[n] in available: # if neighbor n has been colored by a number available.remove(res[n]) # remove the number since we can't color by this number res[i] = available.pop() # color this node with the color which is different from neighbors return res[1:]
f9c6d45b826238d664b58656f918fd42691f12bf
MatthewC221/Algorithms
/flatten_tree.py
1,072
3.9375
4
# Leetcode: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/ # This is pretty difficult imo. You want to keep all the right subtrees in the stack, keep # moving through left subtrees. # One way to think about it is, The left children come first. Then the right. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): prev = None def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return None right_tree = [] while root: while root.left: if root.right: right_tree.append(root.right) root.right = root.left root.left = None root = root.right if (root and root.right is None and right_tree): root.right = right_tree.pop() root = root.right
8dc97f5a3c5be932fce0f81510bc9f10a4b66c36
shaleenb/music-analysis
/src/data/scrape_billboard.py
3,485
3.671875
4
"""Scrape Billboard Charts This script scrapes Wikipedia to get a dataframe of the Billboard year-end Hot 100 songs. Functions: prepare_driver() -> selenium.webdriver.Chrome scrape_for_year(driver, year) -> pandas.DataFrame scrape_for_range(driver, start_year, end_year) -> pandas.DataFrame """ from tqdm import tqdm import pandas as pd from selenium.webdriver import Chrome from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.common.exceptions import TimeoutException url_template = "https://en.wikipedia.org/wiki/Billboard_Year-End_Hot_100_singles_of_{year}" def prepare_driver() -> Chrome: """Creates a ChromeDriver object. It has been configured to not load images. Returns: driver (selenium.webdriver.Chrome): The ChromeDriver object. """ chrome_options = Options() prefs = {"profile.managed_default_content_settings.images": 2} chrome_options.add_experimental_option("prefs", prefs) driver = Chrome(options=chrome_options) return driver def scrape_for_year(driver: Chrome, year: int) -> pd.DataFrame: """Scrapes Wikipedia for Year end Billboard Hot 100 songs for the given year Args: driver (selenium.webdriver.Chrome): Selenium ChromeDriver object year (int): Year for which data should be scraped Returns: df_billboard (pd.DataFrame): Contains the rank, title and artist name for each song """ url = url_template.format(year=year) driver.get(url) # Wait for the page to load try: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "wikitable"))) except TimeoutException: print("Skipping year {}".format(year)) return pd.DataFrame() # Get table element table_element = driver.find_element_by_class_name("wikitable") # Get all rows inside the table table_rows = table_element.find_elements_by_tag_name("tr")[1:] data = [] for row in table_rows: # Get all children of the row element rank, song, artist = map(lambda x: x.text, row.find_elements_by_xpath("*")) data.append({"rank": rank, "song": song.strip('"'), "artist": artist}) df_hot100 = pd.DataFrame(data=data) return df_hot100 def scrape_for_range(driver: Chrome, start_year: int, end_year: int) -> pd.DataFrame: """Scrapes Wikipedia for Year end Billboard Hot 100 songs for the years in range [start_year, end_year). Uses scrape_for_year. Args: driver (selenium.webdriver.Chrome): Selenium ChromeDriver object start_year (int): Starting year (inclusive) end_year (int): Ending year (exclusive) Returns: df_billboard (pd.DataFrame): Contains the year, rank, title and artist name for each song """ df_billboard = pd.DataFrame() for year in tqdm(range(start_year, end_year)): df_year = scrape_for_year(driver, year) df_billboard = df_billboard.append(df_year) return df_billboard def main(): """This script scrapes Wikipedia to get a dataframe of the Billboard year-end Hot 100 songs """ driver = prepare_driver() df_billboard = scrape_for_range(driver, start_year=1960, end_year=2020) df_billboard.to_csv("../../data/raw/billboard.csv", index=False) if __name__ == "__main__": main()
cc73c3e7a3847d685cd4fc3c673ffb65eca769c3
Python-aryan/Hacktoberfest2020
/Python/CeaserCipher.py
990
3.515625
4
import os class CaesarCipher: text = "" key = [] def read_text(self, filename): file = open(filename, 'r') content = file.read() self.text = content def read_key(self, filename): file = open(filename, 'r') content = file.read() self.key = content.split() def encrypt(self, shift): result = [] for i in range(0, len(self.text)): position = ord(self.text[i])%32 result.append(self.key[(shift + position) % 26]) result = "".join(result) return result def main(): curr_dir = os.getcwd() Cypher = CaesarCipher() Cypher.read_text(curr_dir + "\message.txt") Cypher.read_key(curr_dir + "\key.txt") print("Enter shift value: ") shift = input() print("Original Message: " + Cypher.text) print("Encrypted Message: " + Cypher.encrypt(int(shift))) if __name__ == "__main__": main()
d722d346c7c041d1bb286a8306e7479a25cc62cd
ravi4all/PythonJune_Morning
/Advance_Python/TimeComplexity.py
154
3.5
4
import time start = time.time() a = [] for i in range(0,100000000): a.append(i) ##print(a) end = time.time() print("Time", end-start)
6c62114cff4ca7ce96439d156b31d9574c26f9d6
Casey0Kane/data-structures
/src/quick_sort.py
1,169
4.0625
4
"""Merge sort data structure implementation.""" def quick_sort(numbers): """Recursively split list and returns quickd list.""" if len(numbers) <= 1: return numbers left, right = [], [] for num in numbers[1:]: if num < numbers[0]: left.append(num) else: right.append(num) return quick_sort(left) + [numbers[0]] + quick_sort(right) if __name__ == '__main__': # pragma: no cover from timeit import Timer best = Timer( 'quick_sort([x for x in range(100)])', "from __main__ import quick_sort" ) worst = Timer( 'quick_sort([x for x in range(100)][::-1])', "from __main__ import quick_sort; from random import randint" ) print(""" Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. """) print("#================= best case search 10000x ==============#") print(best.timeit(number=1000)) print('') print("#================= worse case search 10000x==============#") print(worst.timeit(number=1000)) print('')
ae5ac014409e42093ef55ddb0fc0c8c49d91daa6
mike6321/dataStructure_algorithm
/Homework05/Problem02.py
547
3.546875
4
class MaxHeap: def __init__(self): self.data = [None] def insert(self, item): #마지막에 노드 추가 self.data.append(item) # 마지막 인덱스 기억 i = len(self.data) -1 # 루트까지 지속해서 만복 while i >1 : if self.data[i] > self.data[i//2]: # 부모 노드의 번호 : m//2 self.data[i],self.data[i//2] = self.data[i//2],self.data[i] i = i//2 else: break def solution(x): return 0
df22b839f420d96fcb6460ef65fd67320514e932
sudhamshu4testing/AutomateTheBoringStuffUsingPython
/ExerciseFour.py
389
4.21875
4
# Ending a program early with sys.exit() """However you can cause the program to terminate, or exit, by calling the sys.exit() function. Since this function is in the sys module, you have to import sys before your program can use it """ import sys while True: print ('Type exit to exit. ') response = input() if response == 'exit': sys.exit() print ('You typed ' + response + '.')
62d73a184557931cd2ebf5eb1186659bbf94b206
randian666/MPython3
/demo/collections.py
2,527
4.0625
4
#!/usr/bin/env python3 from collections import namedtuple,deque,defaultdict,OrderedDict,Counter ''' collections是Python内建的一个集合模块,提供了许多有用的集合类。 1、namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。 2、使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。 deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈 3、使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict 4、使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。如果要保持Key的顺序,可以用OrderedDict 5、Counter是一个简单的计数器 ''' # namedtuple是用来表示一个坐标 Point = namedtuple('Point', ['x', 'y']) p=Point(1,2) print(p.x) print(p.y) #deque deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素 q=deque(['a','b','c']) q.append('x') q.appendleft('y') print(q.pop()) print(q) #defaultdict 除了在Key不存在时返回默认值,defaultdict的其他行为跟dict是完全一样的。 dd=defaultdict(lambda: 'N/A') dd["key"]='dddd' print(dd["key"]) print(dd['key1']) #OrderedDict od=OrderedDict() od['a']=1 od['b']=2 od['c']=3 print(list(od.keys())) # OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key: class LastUpdatedOrderedDict(OrderedDict): def __init__(self, capacity): super(LastUpdatedOrderedDict, self).__init__() self._capacity = capacity def __setitem__(self, key, value): containsKey = 1 if key in self else 0 if len(self) - containsKey >= self._capacity: last = self.popitem(last=False) print('remove:', last) if containsKey: del self[key] print('set:', (key, value)) else: print('add:', (key, value)) OrderedDict.__setitem__(self, key, value) last=LastUpdatedOrderedDict(2) last['b']=2 last['c']=3 print(last.popitem()) print(last) # Counter 统计字符出现的个数 count=Counter(); for ch in 'programming': count[ch]=count[ch]+1; print(count)
275c32a7df30977aee876d5f248da8bfa6afa7c7
dhruvarora93/Algorithm-Questions
/Stacks and Queues/Sliding Window Maximum.py
478
3.75
4
from collections import deque def sliding_window_max(nums,k): output = [] queue = deque() for end in range(len(nums)): while queue and nums[end] > queue[-1]: queue.pop() queue.append(nums[end]) start = end - k + 1 if start < 0: continue output.append(queue[0]) if nums[start] == queue[0]: queue.popleft() return output print(sliding_window_max([1,3,-1,3,5,3,6,7],3))
70ec0ca1b09b4c98b555cb348d5b5837ae0d9760
radomirbrkovic/algorithms
/sort/exercises/02_sort-an-array-of-0s-1s-and-2s.py
639
4.03125
4
# Sort an array of 0s, 1s and 2s https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/ def sort012(arr): lo = 0 hi = len(arr) - 1 mid = 0 while mid <= hi: if arr[mid] == 0: arr[lo], arr[mid] = arr[mid], arr[lo] lo += 1 mid += 1 elif arr[mid] == 1: mid += 1 else: arr[mid], arr[hi] = arr[hi], arr[mid] hi -= 1 return arr def printArray(arr): for i in arr: print(i) arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] arr = sort012(arr) print("Array after segregation") printArray(arr)
7d40c2b681365f8bd374f21aafee543b7e852844
tomaszbobrucki/numeric_matrix
/Problems/Incomplete implementation/task.py
216
3.75
4
def startswith_capital_counter(names): counter = 0 for name in names: if name[0].isupper(): counter += 1 return counter # print(startswith_capital_counter(["Alice", "bob", "John"]))
91074d66b59d3da8df309b4a60b86f5d167b54bd
vridecoder/Python_Projects
/indiceslist/main.py
152
3.5
4
from indices import Indices list1=['I','am','Vrinda','Singh'] list2=[0,2] indices=Indices() indices.index(list1,list2) print(indices.index(list1,list2))
1996e97eb5f766b56303a8b090e2bd98dcfb54e5
DanielQFK/Python-Exercise
/Python-Exercise-05.py
867
4.0625
4
# list # some exercises about List Name = ["alex" , "TIM" , "Christian" , "ryan" , "joHN" ] print(Name) # The output would be = ['alex', 'TIM', 'Christian', 'ryan', 'joHN'] print(Name[1].lower()) # The output would be = tim print(Name[0].title()) # The output would be = Alex print(Name[-1].lower()) # The output would be = john print(Name[-2].title()) # The output would be = Ryan print(Name[2].upper()) # The output would be = CHRISTIAN Number = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10] print(Number) # The output would be = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(Number[4]*Number[7]) # The output would be = 40 print(Number[6]/Number[0]) # The output would be = 7.0 print(Number[3]**Number[2]) # The output would be = 64 print(Number[9]+Number[5]) # The output would be = 16 print(Number[3]-Number[1]) # The output would be = 2
b4760b848bbd96c4d0ac7a4dcdbca62e5c210b04
aadityasingh/AI
/Graph_L1/unidirectional_search.py
1,596
3.609375
4
from time import time import pickle # this makes an array of all the words in the file array_of_text_from_file = open('words.txt').read().split() f = open('saved_graph.p', 'rb') try: n_hash = pickle.load(f) finally: f.close() # Finds the shortest path between two words in the graph root = input('Enter starting word: \n') dest = input('Enter destination: \n') t1 = time() q = [] dist_parent_hash = {} for w in array_of_text_from_file: dist_parent_hash[w] = [-1, ''] dist_parent_hash[root] = [0, ''] q.append(root) count = 0 max_q_length = 0 while len(q) > 0: if len(q) > max_q_length: max_q_length = len(q) x = q.pop(0) if x == dest: break count += 1 neighbors = n_hash[x] for n in neighbors: if dist_parent_hash[n][0] == -1: dist_parent_hash[n][0] = dist_parent_hash[x][0] + 1 dist_parent_hash[n][1] = x q.append(n) t2 = time() if dist_parent_hash[dest][0] == -1: print('The word "' + dest + '" is not connected to the word "' + root + '".') else: connection = [] d = dist_parent_hash[dest][0] word_to_add = dest while d > -1: connection.append(word_to_add) d -= 1 word_to_add = dist_parent_hash[word_to_add][1] print("The connection between the two words is: ") i = len(connection) - 1 while i > -1: print(connection[i]) i -= 1 print("The connection is " + str(len(connection) -1) + " edges long.") print("It took " + str(t2-t1) + " seconds for the search to run.") print("The program cycled through " + str(count) + " words.") print("The maximum queue length is " + str(max_q_length) + ".")
9e4a6be6568cc21e02be5465d673438219047364
iblezya/Python
/Semana 2/Cuarentena/cond7.py
622
3.8125
4
while (True): try: promedio = int(input('Ingrese su promedio: ')) if 20 >= promedio >= 16: print('Usted tiene un promedio Bueno.') elif 16 > promedio >= 10: print('Usted tiene un promedio Regular.') elif 10 > promedio >=6: print('Usted tiene un promedio Deficiente.') elif 6 > promedio >= 0: print('Usted tiene un promedio Pésimo.') else: print('Ingrese su promedio desde 0 hasta 20.') continue break except ValueError: print('Error. Intente de nuevo.')
4051402ed070add66e1b318cd81d57271a5a3862
omnivaliant/High-School-Coding-Projects
/ICS3U1/Assignment #9 1D Lists/IntGroup.py
17,397
4.28125
4
#Author: Mohit Patel #Date: January 6, 2015 #Purpose: To create a program which makes use of the list. #------------------------------------------------------------# import random from tkinter import* root = Tk() root.title("IntGroup") root.config(width=1000,height=500,bg="sky blue") Size1 = StringVar() Size1.set(0) Size2 = StringVar() Size2.set(0) Seq1 = IntVar() Seq1.set(0) Seq2 = IntVar() Seq2.set(0) Answer = StringVar() Answer.set("") IntGroup1 = StringVar() IntGroup1.set("Please choose a sequence and size for both of the int groups.") IntGroup2 = StringVar() IntGroup2.set("") firstTime = True # IntGroup class # Fields: # size: An integer representing the size of the IntGroup. # list: A list representing the integer values of the IntGroup. # Methods: # __str__: Returns the intGroup in the format of list and then size. # initAsNum: Initializes the list with values determined by the size. # initAsSequence: Initializes the list with consecutive and ascending values. # initAsFib: Initializes the list with fibonacci numbers. # calcTotal: Calculates the total of the values in the list. # calcMean: Calculates the average value of the list. # findLargest: Returns the largest element of the list. # calcFreq: Calculates the frequency of a given value. # insertAt: Inserts a value in the given position of the list. # removeAt: Removes a value in the given position of the list. # removeAll: Removes all values from the list. # findFirst: Returns the position of the first value in the list. # reverse: Inverts the order of the list; first items become last, and last items become first. # isSorted: Determines if the list is in ascending order. # merge: Combines two sorted intGroups into a new intGroup with all elements and sorted. # __eq__: Returns if two intGroups are equal. # __le__: Determines if the first intGroup is less than or equal to the second intGroup. # __lt__: Determines if the first intGroup is less than the second intGroup. # __ge__: Determines if the first intGroup is greater than or equal to the second intGroup. # __gt__: Determines if the first intGroup is greater than the second intGroup. # __ne__: Determines if the first intGroup is not equal to the second intGroup. # __add__: Returns an unsorted list with the contents of the first and second intGroups. class IntGroup: # Constructor # Parameters: A given size, corrected to 0. def __init__(self,size=0): if not(str(size).isdigit()): size = 0 elif size < 0: size = 0 self.size = size self.list = [] for count in range(0,self.size): self.list.append(random.randint(0,size)) # __str__ # Purpose: Converts the intGroup object into a string. # Parameters: None. def __str__(self): return str(self.list) + " size: " + str(self.size) # initAsNum # Purpose: Initializes the list with values determined by the size. # Parameters: Size. def initAsNum(self,userSize=0): self.size = userSize self.list = [] for intCount in range(1,userSize + 1): self.list.append(userSize) # initAsSequence # Purpose: Initializes the list with consecutive and ascending values. # Parameters: Size. def initAsSequence(self,userSize=0): self.size = userSize self.list = [] for intCount in range(1,userSize+1): self.list.append(intCount) # initAsFib # Purpose: Initializes the list with fibonacci numbers. # Parameters: Size. def initAsFib(self,userSize=0): self.size = userSize self.list = [] twoBefore = 1 oneBefore = 1 for intCount in range(1,userSize+1): if len(self.list) == 0: self.list.append(1) oneBefore = 1 elif len(self.list) == 1: self.list.append(1) twoBefore = 1 else: current = oneBefore + twoBefore twoBefore = oneBefore oneBefore = current self.list.append(current) # calcTotal # Purpose: Returns the sum of the values in the list. # Parameters: None. def calcTotal(self): total = 0 for count in range(0,self.size): total = total + self.list[count] return total # calcMean # Purpose: Returns the mean of the values in the list. # Parameters: None. def calcMean(self): return self.calcTotal() / self.size # findLargest # Purpose: Returns the value of the largest item on the list. # Parameters: None. def findLargest(self): largest = -1 for count in range(0,self.size): if self.list[count] > largest: largest = self.list[count] return largest # calcFreq # Purpose: Returns the frequency of the given value. # Parameters: A number, which will have it's frequency determined. def calcFreq(self,inputNumber): freq = 0 for count in range(0,self.size): if self.list[count] == inputNumber: freq = freq + 1 return freq # insertAt # Purpose: Inserts a given value at the given position. # Parameters: A position and a value. def insertAt(self,position,value): if position < 0: position = 0 elif position >= self.size: position = self.size - 1 self.list.insert(position,value) self.size = self.size + 1 # removeAt # Purpose: Removes a value in the given position. # Parameters: The position of the removed item. def removeAt(self,position): if position < 0: position = 0 elif position >= self.size: position = self.size - 1 del self.list[position] self.size = self.size - 1 # removeAll # Purpose: Removes all the values in the list of the given value. # Parameters: The value to be removed from the list. def removeAll(self,value): if value in self.list: count = 0 while count < self.size: if value == self.list[count]: self.removeAt(count) else: count = count + 1 # findFirst # Purpose: Returns the position of the first value found in the list. # Parameters: The value to be found. def findFirst(self,value): count = 0 found = -1 while found == -1 and count < self.size: if self.list[count] == value: found = count else: count = count + 1 return found # reverse # Purpose: Inverts the order of the list, making the first objects become last, and vice versa. # Parameters: None. def reverse(self): for count in range(0,self.size): self.insertAt(count,self.list[self.size-1]) self.removeAt(self.size-1) # isSorted # Purpose: Returns if the list is sorted. # Parameters: None. def isSorted(self): sort = True if self.size > 1: for count in range(0,self.size-1): if self.list[count] > self.list[count+1]: sort = False return sort # merge # Purpose: Returns an intGroup that is the sorted sum of two intGroups. # Parameters: The second intGroup. def merge(self,secondIntGroup): mergedGroup = IntGroup(0) if self.isSorted() and secondIntGroup.isSorted(): firstCount = 0 secondCount = 0 mergedCount = 0 while (firstCount < self.size) or (secondCount < secondIntGroup.size): if firstCount < self.size and secondCount < secondIntGroup.size: if self.list[firstCount]<secondIntGroup.list[secondCount]: mergedGroup.insertAt(mergedCount,self.list[firstCount]) firstCount = firstCount + 1 else: mergedGroup.insertAt(mergedCount,secondIntGroup.list[secondCount]) secondCount = secondCount + 1 elif secondCount < secondIntGroup.size: mergedGroup.insertAt(mergedCount,secondIntGroup.list[secondCount]) secondCount = secondCount + 1 else: mergedGroup.insertAt(mergedCount,self.list[firstCount]) firstCount = firstCount + 1 mergedCount = mergedCount + 1 mergedGroup.insertAt(0,mergedGroup.list[-1]) mergedGroup.removeAt(len(mergedGroup.list)-1) return mergedGroup # __eq__ # Purpose: Determines if the first list is equal to the second list. # Parameters: The second IntGroup. def __eq__(self,secondIntGroup): return self.list == secondIntGroup.list # __le__ # Purpose: Determines if the first list is less than or equal to the second list. # Parameters: The second IntGroup. def __le__(self,secondIntGroup): return self.list <= secondIntGroup.list # __lt__ # Purpose: Determines if the first list is less than the second list. # Parameters: The second IntGroup. def __lt__(self,secondIntGroup): return self.list < secondIntGroup.list # __ge__ # Purpose: Determines if the first list is greater than or equal to the second list. # Parameters: The second IntGroup. def __ge__(self,secondIntGroup): return self.list >= secondIntGroup.list # __gt__ # Purpose: Determines if the first list is greater than the second list. # Parameters: The second IntGroup. def __gt__(self,secondIntGroup): return self.list > secondIntGroup.list # __ne__ # Purpose: Determines if two intgroups are not equal to each other. # Parameters: The second IntGroup. def __ne__(self,secondIntGroup): return self.list != secondIntGroup.list # __add__ # Purpose: Returns a list that is the sum of two IntGroups. # Parameters: The second IntGroup. def __add__(self,secondIntGroup): return self.list + secondIntGroup.list #Author: Mohit Patel #Date: January 10, 2015 #Purpose: To display two intGroups, given default initiating values. #Parameters: None. #Return Value: The visible intGroups. def showIntGroup(): global firstTime global producedIntGroup1 global producedIntGroup2 if firstTime == True: firstTime = False lblIntGroup2.place(x=400,y=150) btnEq.place(x=400,y=250) btnLe.place(x=450,y=250) btnLt.place(x=500,y=250) btnGe.place(x=550,y=250) btnGt.place(x=600,y=250) btnNe.place(x=650,y=250) btnAdd.place(x=700,y=250) btnMerge.place(x=750,y=250) lblThirdOutput.place(x=400,y=350) size1 = Size1.get() if not(size1.isdigit()): IntGroup1.set("Please enter a valid integer.") elif int(size1) < 0: IntGroup1.set("Please enter a positve size 1 value.") elif int(size1) > 44: IntGroup1.set("Please enter your size 1 in the range of 0 to 44.") else: size1 = int(size1) group1 = IntGroup() if Seq1.get() == 0: group1.initAsSequence(size1) elif Seq1.get() == 1: group1.initAsNum(size1) else: group1.initAsFib(size1) IntGroup1.set(group1) producedIntGroup1 = group1 size2 = Size2.get() if not(size2.isdigit()): IntGroup2.set("Please enter a valid integer for size 2.") elif int(size2) < 0: IntGroup2.set("Please enter a positve value for size 2.") elif int(size2) > 44: IntGroup2.set("Please enter your size 2 in the range of 0 to 44.") else: size2 = int(size2) group2 = IntGroup() if Seq2.get() == 0: group2.initAsSequence(size2) elif Seq2.get() == 1: group2.initAsNum(size2) else: group2.initAsFib(size2) IntGroup2.set(group2) producedIntGroup2 = group2 def createAnswer(answer): global producedIntGroup1 global producedIntGroup2 result = "" firstGroup = producedIntGroup1 secondGroup = producedIntGroup2 if answer == "=": result = (firstGroup == secondGroup) elif answer == "<=": result = (firstGroup <= secondGroup) elif answer == "<": result = (firstGroup < secondGroup) elif answer == ">=": result = (firstGroup >= secondGroup) elif answer == ">": result = (firstGroup > secondGroup) elif answer == "!=": result = (firstGroup != secondGroup) if result == 0: result = " " + answer + " is False" else: result = " " + answer + " is True" if answer == "+": result = firstGroup + secondGroup if len(result) > 44: result = "Too large to merge!" else: result = str(result) elif answer == "merge": result = firstGroup.merge(secondGroup) if result.size > 44: result = "Too large to merge!" else: result = str(result) Answer.set(result) producedIntGroup1 = IntGroup(0) producedIntGroup2 = IntGroup(0) frameOptions1 = Frame(root,width=300,height=200,bg="green",bd=10,relief="groove") frameOptions1.place(x=0,y=0) btnSequence1 = Radiobutton(frameOptions1,width=30,height=1,bg="SpringGreen2",bd=10,relief="groove",text="Consecutive Sequence",anchor=W,variable=Seq1,value=0,font=("Arial","8","bold")) btnSequence1.place(x=10,y=10) btnNum1 = Radiobutton(frameOptions1,width=30,height=1,bg="SpringGreen2",bd=10,relief="groove",text="Repetitive Sequence",anchor=W,variable=Seq1,value=1,font=("Arial","8","bold")) btnNum1.place(x=10,y=60) btnFib1 = Radiobutton(frameOptions1,width=30,height=1,bg="SpringGreen2",bd=10,relief="groove",text="Fibbonacci Sequence",anchor=W,variable=Seq1,value=2,font=("Arial","8","bold")) btnFib1.place(x=10,y=110) lblSize1 = Label(frameOptions1,bd=5,relief="groove",text="Size of first IntGroup:",font=("Arial","8","bold")) lblSize1.place(x=10,y=152) entrySize1 = Entry(frameOptions1,width=15,bd=5,relief="groove",textvariable=Size1,font=("Arial","8","bold")) entrySize1.place(x=150,y=152) frameOptions2 = Frame(root,width=300,height=200,bg="green",bd=10,relief="groove") frameOptions2.place(x=0,y=200) btnSequence2 = Radiobutton(frameOptions2,width=30,height=1,bg="SpringGreen2",bd=10,relief="groove",text="Consecutive Sequence",anchor=W,variable=Seq2,value=0,font=("Arial","8","bold")) btnSequence2.place(x=10,y=10) btnNum2 = Radiobutton(frameOptions2,width=30,height=1,bg="SpringGreen2",bd=10,relief="groove",text="Repetitive Sequence",anchor=W,variable=Seq2,value=1,font=("Arial","8","bold")) btnNum2.place(x=10,y=60) btnFib2 = Radiobutton(frameOptions2,width=30,height=1,bg="SpringGreen2",bd=10,relief="groove",text="Fibbonacci Sequence",anchor=W,variable=Seq2,value=2,font=("Arial","8","bold")) btnFib2.place(x=10,y=110) lblSize2 = Label(frameOptions2,bd=5,relief="groove",text="Size of second IntGroup:",font=("Arial","8","bold")) lblSize2.place(x=10,y=152) entrySize2 = Entry(frameOptions2,width=15,bd=5,relief="groove",textvariable=Size2,font=("Arial","8","bold")) entrySize2.place(x=150,y=152) btnGo = Button(root,width=28,height=4,command=lambda:showIntGroup(),text="Create IntGroups!",font=("Arial","12","bold"),bg="firebrick1",bd=10,relief="groove") btnGo.place(x=0,y=400) lblIntGroup1 = Label(root,textvariable=IntGroup1,width=49,height=5,anchor=W,font=("Arial","12","bold"),wraplength=500,bg="DarkGoldenrod1",bd=10,relief="groove") lblIntGroup1.place(x=400,y=50) lblIntGroup2 = Label(root,textvariable=IntGroup2,width=49,height=5,anchor=W,font=("Arial","12","bold"),wraplength=500,bg="DarkGoldenrod2",bd=10,relief="groove") btnEq = Button(root,command=lambda:createAnswer("="),width=5,height=5,text="=",font=("Arial","12","bold"),bg="DarkGoldenrod3",bd=5,relief="groove") btnLe = Button(root,command=lambda:createAnswer("<="),width=5,height=5,text="<=",font=("Arial","12","bold"),bg="DarkGoldenrod3",bd=5,relief="groove") btnLt = Button(root,command=lambda:createAnswer("<"),width=5,height=5,text="<",font=("Arial","12","bold"),bg="DarkGoldenrod3",bd=5,relief="groove") btnGe = Button(root,command=lambda:createAnswer(">="),width=5,height=5,text=">=",font=("Arial","12","bold"),bg="DarkGoldenrod3",bd=5,relief="groove") btnGt = Button(root,command=lambda:createAnswer(">"),width=5,height=5,text=">",font=("Arial","12","bold"),bg="DarkGoldenrod3",bd=5,relief="groove") btnNe = Button(root,command=lambda:createAnswer("!="),width=5,height=5,text="Not \n =",font=("Arial","12","bold"),bg="DarkGoldenrod3",bd=5,relief="groove") btnAdd = Button(root,command=lambda:createAnswer("+"),width=5,height=5,text="+",font=("Arial","12","bold"),bg="DarkGoldenrod3",bd=5,relief="groove") btnMerge = Button(root,command=lambda:createAnswer("merge"),width=14,height=5,text="merge",font=("Arial","12","bold"),bg="DarkGoldenrod3",bd=8,relief="groove") lblThirdOutput = Label(root,textvariable=Answer,width=49,height=5,anchor=W,font=("Arial","12","bold"),wraplength=500,bg="orange3",bd=10,relief="groove")
93e7ede69748b5bc35fc1805d9007f62ff5ff5bd
anniephilip23/Guvi
/Python/numberguessinggame.py
310
3.890625
4
import random a = random.randrange(10) i = 5 while (i!=0): n = int(input("enter any number between 0 to 10: ")) if a==n: print ("u have entered correct number") break else: print ("enter any other numb. Your life left is ",i-1) i=i-1 print ("gameover the number is",a)
357e5590312a5fad8a2dad3e0ff543442fbed97d
quieterbwhite/quieter_python
/python/01_getattr.py
3,130
4.125
4
Python中的getattr()函数详解 ref: http://www.cnblogs.com/pylemon/archive/2011/06/09/2076862.html 函数本身的doc getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. 告诉我这个函数的作用相当于是 object.name 试了一下getattr(object,name)确实和object.name是一样的功能.只不过这里可以把name作为一个变量去处理 书上的例子很好的说明了这个函数的功用 使用getattr可以轻松实现工厂模式。 例:一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出 import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" %format) return output_function(data) 这个例子中可以根据传入output函数的format参数的不同 去调用statsout模块不同的方法(用格式化字符串实现output_%s) 返回的是这个方法的对象 就可以直接使用了 如果要添加新的格式 只需要在模块中写入新的方法函数 在调用output函数时使用新的参数就可以使用不同的格式输出 确实很方便 为了加深对getattr函数的理解 转载一篇英文的说明 Python’s getattr function is used to fetch an attribute from an object, using a string object instead of an identifier to identify the attribute. In other words, the following two statements are equivalent: value = obj.attribute value = getattr(obj, "attribute") If the attribute exists, the corresponding value is returned. If the attribute does not exist, you get an AttributeError exception instead. The getattr function can be used on any object that supports dotted notation (by implementing the __getattr__ method). This includes class objects, modules, and even function objects. path = getattr(sys, "path") doc = getattr(len, "__doc__") The getattr function uses the same lookup rules as ordinary attribute access, and you can use it both with ordinary attributes and methods: result = obj.method(args) func = getattr(obj, "method") result = func(args) or, in one line: result = getattr(obj, "method")(args) Calling both getattr and the method on the same line can make it hard to handle exceptions properly. To avoid confusing AttributeError exceptions raised by getattr with similar exceptions raised inside the method, you can use the following pattern: try: func = getattr(obj, "method") except AttributeError: ... deal with missing method ... else: result = func(args) The function takes an optional default value, which is used if the attribute doesn’t exist. The following example only calls the method if it exists: func = getattr(obj, "method", None) if func: func(args) Here’s a variation, which checks that the attribute is indeed a callable object before calling it. func = getattr(obj, "method", None) if callable(func): func(args)
cc6670398e9dc00ea1ed938f1924d4c39f87aa42
puruckertom/esa_python
/scripts/commands08_classes.py
1,410
4.0625
4
#create the Rabbit class, starts with 10 hit points class Rabbit(object): def __init__(self, name): self.name = name self.hit_points = 10 def hop(self): self.hit_points = self.hit_points - 1 print "%s hops one node, now has %i hit points." % (self.name, self.hit_points) def eat_carrot(self): self.hit_points = self.hit_points + 3 print "%s munches a carrot, now has %i hit points." % (self.name, self.hit_points) #create some Rabbits were = Rabbit("Were-Rabbit") harvey = Rabbit("Harvey Rabbit") jessica = Rabbit("Jessica Rabbit") dir(jessica) #Rabbits hop around and eat carrots were.hop() jessica.eat_carrot() harvey.hop() jessica.hop() were.eat_carrot() #Create a Frog class that extends the rabbit class class Frog(Rabbit): # create a new croak method def croak(self): self.hit_points = self.hit_points - 1 print "%s croaks, now has %i hit points." % (self.name, self.hit_points) # override the eat_carrot method def eat_carrot(self): print "%s cannot eat a carrot, it is too big!." % (self.name) # create an eat_fly method def eat_fly(self): self.hit_points = self.hit_points + 2 print "%s eats a fly, now has %i hit points." % (self.name, self.hit_points) # Create a frog frogger = Frog("Frogger") # Do frog stuff frogger.croak() frogger.eat_carrot() frogger.eat_fly() frogger.hop()
3ad24b2429a98c184344206826cc7362a541fdb6
Miguel-de-Castro/MultilayerPerceptron
/MLP.py
4,397
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed May 12 14:58:10 2021 @author: Victor Nobre """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from activation_function import sigmoid from activation_function import sigmoidDerivada #REDE NEURAL PARA REALIZAR O TREINAMENTO. #ENCONTRANDO ARQUIVOS DATASETS PARA TREINAMENTO. datasets = pd.read_csv('datasets/treinamento.csv.csv') #DETERMINANDO VALORES DE ENTRADAS E SAÍDAS. Valoresentradas = datasets.iloc[:,:4].values entradas = Valoresentradas Valoressaidas = datasets.iloc[:,4:7].values saidas = np.empty([130, 3], dtype=int) for i in range(130): saidas[i] = Valoressaidas[i] #DETERMINANDO PESOS. Pesosiniciais = 2*np.random.random((4,3)) - 1 pesos0 = Pesosiniciais Pesoscamadaoculta = 2*np.random.random((3,3)) - 1 pesos1 = Pesoscamadaoculta #DETERMINANDO TAXAS DE APRENDIZAGEM E PRECISÃO. taxaAprendizagem = 0.1 precisão = 1 #DETERMINANDO QUANTIDADE DE ÉPOCAS E ERRO MÉDIO PARA SIMULAÇÃO. epocas = int(input('Digite a quantidade de épocas desejada para realizar os treinamentos: ')) mediatotal = 0 #FUNÇÃO DE TREINAMENTO. for j in range(epocas): camadaEntrada = entradas somaSinapse0 = np.dot(camadaEntrada, pesos0) camadaOculta = sigmoid(somaSinapse0) somaSinapse1 = np.dot(camadaOculta, pesos1) camadaSaida = sigmoid(somaSinapse1) erroCamadaSaida = saidas - camadaSaida mediaAbsoluta = mediatotal mediaAbsoluta = np.mean(np.abs(erroCamadaSaida)) derivadaSaida = sigmoidDerivada(camadaSaida) deltaSaida = erroCamadaSaida * derivadaSaida pesos1Transposta = pesos1.T deltaSaidaXPeso = deltaSaida.dot(pesos1Transposta) deltaCamadaOculta = deltaSaidaXPeso * sigmoidDerivada(camadaOculta) camadaOcultaTransposta = camadaOculta.T pesosNovo1 = camadaOcultaTransposta.dot(deltaSaida) pesos1 = (pesos1 * precisão) + (pesosNovo1 * taxaAprendizagem) camadaEntradaTransposta = camadaEntrada.T pesosNovo0 = camadaEntradaTransposta.dot(deltaCamadaOculta) pesos0 = (pesos0 * precisão) + (pesosNovo0 * taxaAprendizagem) if j == epocas-1: print("O PERCENTUAL DE ERRO FOI DE: %" + str(mediaAbsoluta)) print("FORAM REALIZADAS {} ÉPOCAS" .format(j+1)) #PLOTANDO RESULTADOS. x = erroCamadaSaida[:10,0:1] y = erroCamadaSaida[:10,1:2] z = y - x plt.plot(x,'bo', y,'go',z,'r--' ) plt.show() #REDE NEURAL PARA REALIZAR OS TESTES. #ENCONTRANDO ARQUIVOS DATASETS PARA TESTES. datasets = pd.read_csv('datasets/teste.csv.csv') #DETERMINANDO VALORES DE ENTRADAS E SAÍDAS. Valoresentradas = datasets.iloc[:,:4].values entradas = Valoresentradas Valoressaidas = datasets.iloc[:,4:7].values saidas = np.empty([18, 3], dtype=int) for i in range(18): saidas[i] = Valoressaidas[i] #DETERMINANDO PESOS. Pesosiniciais = 2*np.random.random((4,3)) - 1 pesos0 = Pesosiniciais Pesoscamadaoculta = 2*np.random.random((3,3)) - 1 pesos1 = Pesoscamadaoculta #DETERMINANDO TAXAS DE APRENDIZAGEM E PRECISÃO. taxaAprendizagem = 0.1 precisão = 1 #DETERMINANDO QUANTIDADE DE ÉPOCAS PARA SIMULAÇÃO. epocas = 10000 #FUNÇÃO DE TREINAMENTO. for j in range(epocas): camadaEntrada = entradas somaSinapse0 = np.dot(camadaEntrada, pesos0) camadaOculta = sigmoid(somaSinapse0) somaSinapse1 = np.dot(camadaOculta, pesos1) camadaSaida = sigmoid(somaSinapse1) erroCamadaSaida = saidas - camadaSaida mediaAbsoluta = np.mean(np.abs(erroCamadaSaida)) derivadaSaida = sigmoidDerivada(camadaSaida) deltaSaida = erroCamadaSaida * derivadaSaida pesos1Transposta = pesos1.T deltaSaidaXPeso = deltaSaida.dot(pesos1Transposta) deltaCamadaOculta = deltaSaidaXPeso * sigmoidDerivada(camadaOculta) camadaOcultaTransposta = camadaOculta.T pesosNovo1 = camadaOcultaTransposta.dot(deltaSaida) pesos1 = (pesos1 * precisão) + (pesosNovo1 * taxaAprendizagem) camadaEntradaTransposta = camadaEntrada.T pesosNovo0 = camadaEntradaTransposta.dot(deltaCamadaOculta) pesos0 = (pesos0 * precisão) + (pesosNovo0 * taxaAprendizagem) #MATRIZ FINAL DO RESULTADO APÓS TESTES. print("O RESULTADO FINAL APÓS {} ÉPOCAS É DE: " .format(epocas)) print(deltaSaida) print('ONDE PARA CADA RESULTADO NEGATIVO SERÁ CONSIDERADO 0 E PARA CADA RESULTADO POSITIVO SERÁ CONSIDERADO 1')
682d6cac25f7ff72ca40d7281d38b5cb17355a34
GITlibin1025/pyLearn
/leiandduixiang.py
695
4.03125
4
''' 类和对象 按照以下提示尝试定义一个矩形类并生成类实例对象。 属性:长和宽版权属于 方法:设置长和宽 -> setRect(self),获得长和宽 -> getRect(self),获得面积 -> getArea(self) 提示:方法中对属性的引用形式需加上 self,如 self.width'xdu ''' class Rectangle(): def setRect(): print('请输入矩形的长和宽') global a global b a = input('长:') b = input('宽:') def getRect(): print("这个矩形的长是 %s" % a ) print("这个矩形的宽是 %s" % b ) def getArea(): Area = int(a)*int(b) print("这个矩形的面积是 %d " % Area) Rectangle.setRect() Rectangle.getRect() Rectangle.getArea()
c41cf49d568bee4f2e2caaf24483b0e032b247eb
pjz987/2019-10-28-fullstack-night
/Assignments/andrew/python/lab11_v1.py
146
3.640625
4
operation = input("What operation would you like to do?") num_1 = int(input("Enter first number.")) num_2 = int(input("Enter second number."))
888f4cdff7b44b1bc7608228979f91bd05fd1747
Tinakhandelwal/Sample-Python-Programs
/plotting.py
399
3.6875
4
import matplotlib.pyplot as plt import numpy as np # Create sample data for plotting. Eg: sine wave t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) # Create figure and axes for plotting fig, ax = plt.subplots() ax.plot(t, s) # Include axis info and title ax.set(xlabel='time (s)', ylabel='Sine value', title='This is a sample sine wave plot') ax.grid() # Display the plot plt.show()
a629186411b817b192a94853bfc1f9d7c304b3ee
junbyungchan/python
/lec06_class/inheritance01.py
4,408
4.03125
4
""" 상속(inheritance): 부모 클래스로부터 데이터(field)와 기능(method)를 물려받아서 자식 클래스에서 사용할 수 있도록 하는 개념 - parent(부모), super(상위), base(기본) class - child(자식), sub(하위), derived(유도) class """ from math import pi # 모든 class의 조상은 object이다. # 그래서 생략이 가능하다. # class Shape(object): --> 원래 이 표현인데 생략을 한다. class Shape: def __init__(self,x=0,y=0): print('Shape __init__ 호출') self.x = x self.y = y def __repr__(self): return f'Shape(x={self.x},y={self.y})' def move(self,dx,dy): self.x += dx self.y += dy # 면적 계산하는 메소드 def area(self): """ # Shape 객체는 넓이를 계산할 수 없고, # Shape의 sub 타입들인 Rectangle, Circle 객체가 # 각자의 방식으로 넓이를 계산해야 됨. :return: 도형의 넓이 """ raise NotImplementedError('반드시 override') def draw(self): """ 넓이를 계산하는 area() 메소드를 사용해서 도형 내부를 그려주는 메소드 :return: None """ print(f'Drawing {self.area()}....') # 상속: # class child명(parent명): # class의 body class Rectangle(Shape): # Child 클래스에서 __init__ 메소드를 작성하지 않은 경우에는 # 파이썬 인터프리터가 Parent 클래스의 __init__ 메소드를 # 호출해서 부모 객체를 자동으로 생성함. # 개발자가 Child 클래스에서 __init__ 메소드를 정의한 경우에는 # 파이썬 인터프리터가 Parent 클래스의 __init__ 메소드를 # 자동으로 호출하지 않음. # child 클래스에서 parent 클래스의 __init__ 메소드를 명시적으로 반드시 호출해야함! def __init__(self,w,h,x=0,y=0): # child의 __init__ 메소드는 4개 print('Rectangle.__init__ 호출') super().__init__(x,y) # 부모클래스의 __init__호출 self.w = w self.h = h #override : 부모 클래스로부터 상속받은 메소드를 # 자식 클래스에서 재정의하는 것 def __repr__(self): # 부모의 class 있는 __repr__의 메소드 위에 # 자식의 class 있는 __repr__의 메소드를 덮어 씌운다. return f'사각형 (가로:{self.w} / 세로: {self.h} / x:{self.x} / y:{self.y})' # super() ---> 부모의 주소.__intit__) # child 에서 init을 명시하면 parent의 init을 자동으로 호출해주지 않는다. def area(self): # Shape 클래스에도 area() 메소드가 있지만 # override를 사용해서 덮어쓰기를 해서 area()를 오버라이드했다. return self.w * self.h class Circle(Shape): # class Circle(Shape, object): ---> 다중상속 def __init__(self,r,x,y): # r: 원의 반지금 , (x,y) : 원의 중심의 좌표 print('Circle.__init__ 호출') # 함수 호출 순서를 보기위한 출력문 # super 클래스의 __init__ 메소드를 반드시(!) 호출해야 함. super().__init__(x,y) # 부모 클래스의 __init__ 호출 # Shape.__init__(self,x,y) super().__init__()과 같은 코드이지만 # 클래스이름.__init__(self) 파라미터에서 self를 반드시 명시해줘야한다. # self 생략 불가 # sub 클래스만 갖는 field를 초기화 self.r = r # 반지름 초기화 def __repr__(self): return f'( Circle: 반지름 :{self.r} / 중심점 좌표: ({self.x},{self.y}) )' def area(self): return (self.r **2) * pi if __name__ == '__main__': # test 코드를 만드는 이유 # 다른 클래스에서 import 할때 다른 클래스에서도 실행되지 않게 하기 위해서 shape1 = Shape(0,0) print(shape1) shape1.move(1,2) print(shape1) rect1 = Rectangle(w=3,h=4,x=0,y=0) print('rect1 타입:' , type(rect1)) print('rect1:',rect1) # override한 __repr__ 메소드가 호출됨. rect1.move(-1,-2) # 부모에게서 상송받은 move 메소드가 호출됨. print(rect1) print('---------------------------') circle1 = Circle(r=5,x=8,y=10) print('circle1 type: ', type(circle1)) print(circle1) rect1.draw() circle1.draw()
bc59f11551bc8dec1f75e5fb8e6a45dd27b0cd2f
2ptO/code-garage
/icake/test_q2.py
841
4
4
import unittest import q2 class TestQ2(unittest.TestCase): def test_positive_nums(self): inputs = [7, 5, 4, 2, 6] expectedResult = 210 actualResult = q2.get_highest_product_of_three(inputs) self.assertEqual(expectedResult, actualResult, "Invalid highest product of 3") def test_negative_nums(self): inputs = [7, 5, -4, 2, -6] expectedResult = 168 actualResult = q2.get_highest_product_of_three(inputs) self.assertEqual(expectedResult, actualResult, "expected:{} actual:{}".format(expectedResult, actualResult)) def test_small_input_list_raises_error(self): inputs = [1] with self.assertRaises(ValueError): q2.get_highest_product_of_three(inputs) if __name__ == "__main__": unittest.main()
e5414ab736dfd9cf8498101d0f42a4257daf21ae
eclipse-ib/Software-University-Professional-Advanced-Module
/September 2020/02-Tuples-and-Sets/01-Count-Same-Values.py
242
3.671875
4
string = tuple(float(_) for _ in input().split()) dict_nums = {} for i in string: if i not in dict_nums: dict_nums[i] = 1 else: dict_nums[i] += 1 [print(f"{key} - {value} times") for key, value in dict_nums.items()]
1b29def20e469bf5eb9563bc7667cb3a896aaf1a
s-rigaud/Restaurant-Management-System
/app/tooltip.py
1,632
3.546875
4
from tkinter import ttk, Toplevel, Button __all__ = ["ToolTip"] class ToolTipSkeletton: def __init__(self, widget, text): self.widget = widget self.tipwindow = None self.x = 0 self.y = 0 self.text = text style = ttk.Style() style.configure( "tooltip.TLabel", font="tahoma 10 normal", foreground="#000", background="#fff", justify="left", borderwidth=3, ) def showtip(self): "Display text in tooltip window" if self.tipwindow or not self.text: return x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 57 y = y + cy + self.widget.winfo_rooty() + 27 self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(True) tw.attributes("-topmost", True) tw.wm_geometry(f"+{x}+{y}") label = ttk.Label(tw, text=self.text, style="tooltip.TLabel") label.pack(ipadx=1) def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() class ToolTip: def __init__(self, widget, text: str): self.toolTip = ToolTipSkeletton(widget, text) widget.bind("<Enter>", self.enter) widget.bind("<Leave>", self.leave) def enter(self, event): self.toolTip.showtip() def leave(self, event): self.toolTip.hidetip() if __name__ == "__main__": root = Tk() button = Button(root, text="click me") button.pack() ToolTip(button, "Hi") root.mainloop()
e7bf9d7f7d696b6681587607d95a36d431ef937a
daniel-reich/turbo-robot
/Ygt4LGupxDAqXNrhS_8.py
1,284
3.828125
4
""" Given a grid of numbers, return a grid of the **Spotlight Sum** of each number. The spotlight sum can be defined as the total of all numbers immediately surrounding the number on the grid, including the number in the total. ### Examples spotlight_map([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) ➞ [ [12, 21, 16], [27, 45, 33], [24, 39, 28] ] spotlight_map([ [2, 6, 1, 3, 7], [8, 5, 9, 4, 0] ]) ➞ [ [21, 31, 28, 24, 14], [21, 31, 28, 24, 14] ] spotlightMap([[3]]) ➞ [[3]] ### Notes * Note that all numbers have a spotlight sum, including numbers on the edges. * All inputs will be valid grid (all rows will have the same length). """ def spotlight_map(grid): if not grid: return [] rows, cols = len(grid), len(grid[0]) res = [[0]*cols for _ in range(rows)] neighbours = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]] ​ for r in range(rows): for c in range(cols): total = 0 for i, j in neighbours: if 0 <= r+i < rows and 0 <= c+j < cols: total += grid[r+i][c+j] res[r][c] = total return res
8a7b3f44c1ba00c575ebd8bc0f8d715e0e4c51d1
SamiaAitAyadGoncalves/codewars-1
/Python/8kyu/I love you, a little , a lot, passionately.py
718
3.75
4
# https://www.codewars.com/kata/57f24e6a18e9fad8eb000296 # # Who remembers back to their time in the schoolyard, when girls would take a # flower and tear its petals, saying each of the following phrases each time # a petal was torn: # # I love you # a little # a lot # passionately # madly # not at all # # When the last petal was torn there were cries of excitement, dreams, # surging thoughts and emotions. # # Your goal in this kata is to determine which phrase the girls would say # for a flower of a given number of petals, where nb_petals > 0. def how_much_i_love_you(n): arr = ['I love you', 'a little', 'a lot', 'passionately', 'madly', 'not at all'] return arr[((n-1) % 6)]
4a932ddcb102926ee6944f53d8f17392148d17f9
ljc520313/PythonDemo
/com/example/hanshu4.py
559
3.796875
4
# str1 = '上海自来水来自海上' # str1 = '如来佛祖' str1 = input('输入一个句子判断是否是回文:') str_list = list(str1) str_list1 = str_list # str_list1 = list(str1) str_list.reverse() # reverse()只作用于列表不作用于字符串 print(str_list) print(str_list1) if str_list1 == str_list: print('字符串%s是回文联'%str1) else: print('字符串%s不是回文联'%str1) # 方法2 # k=0 # for i in range(0,len(str)//2): # if str[i] == str[len(str)-1-i]: # k+=1 # # if(len(str)//2==k): # print(k)
46e83d4333489db5c4d3ded70ef4a95b56ccf1e7
takayuki211/atcoder
/abc049/c/main.py
601
3.9375
4
#!/usr/bin/env python3 import re s = input() while True: # re.subを使うと処理時間超過した。 # s = re.sub('dream$|dreamer$|erase$|eraser$','',s) # リストのスライスを利用するほうが高速 l = len(s) if s.rfind('dream') == l-5: s = s[:-5] elif s.rfind('dreamer') == l-7: s = s[:-7] elif s.rfind('erase') == l-5: s = s[:-5] elif s.rfind('eraser') == l-6: s = s[:-6] else: break # ※文字を逆にすれば先頭から操作できる。 if len(s)==0: print('YES') else: print('NO')
d2140b64b01b0412aef4dcbb037ef3747018bce4
naveen6797/Git_tutorials
/even add number.py
141
3.859375
4
Number=5.5445654545 if(Number%2==0): print('even number') elif(Number%2==1): print('odd number') else: print('others')
9a56df4140e4559196a259d7974ea64c61872592
abushonn/py
/technion2020/assignment1/ex1_1_purchase.py
1,267
3.84375
4
''' Input================== print('A:') a_price= float(input()) a_quant= int(input()) print('B:') b_price= float(input()) b_quant= int(input()) print('C:') c_price= float(input()) c_quant= int(input()) print('D:') d_price= float(input()) d_quant= int(input()) ====================== ''' (a_price, a_quant) = (11.1, 1) (b_price, b_quant) = (22.1, 2) (c_price, c_quant) = (33.1, 3) (d_price, d_quant) = (44.1, 4) print('a : %s, %s '%( str(a_price), str(a_quant))) print('b: %s, %s '%( str(b_price), str(b_quant))) print('c : %s, %s '%( str(c_price), str(c_quant))) print('d: %s, %s '%( str(d_price), str(d_quant))) def main(a_price, a_quant, b_price, b_quant, c_price, c_quant, d_price, d_quant): is_valid = (a_price <= 50) and (b_price <= 30) and (d_quant >= 1 ) and (a_quant + c_quant <= 5) total_sum = (a_price*a_quant) + (b_price*b_quant) + (c_price*c_quant) + (d_price*d_quant) total_quant = a_quant + b_quant + c_quant + d_quant avg_price = total_sum / total_quant valid_message = "%s, %s, %s" % (total_sum, total_quant, avg_price) message_dict = {True : valid_message, False : 'Invalid purchase'} print(message_dict[is_valid]) main(a_price, a_quant, b_price, b_quant, c_price, c_quant, d_price, d_quant)
e3bb7ac63f92bd6ea411cf0bef933e4b43044df7
blavis21/Python-Book-1-Orientation
/ch4-Dictionary/dictionary.py
2,097
4.5625
5
# PRACTICE: Dictionary of Words """ Create a dictionary with key value pairs to represent words (key) and its definition (value) """ word_definitions = dict() """ Add several more words and their definitions Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python" """ word_definitions["testing"] = "this is me testing wtf is going on" word_definitions["maybe"] = "idk if this is working" word_definitions["hmm"] = "let's see" """ Use square bracket lookup to get the definition two words and output them to the console with `print()` """ print(word_definitions["testing"]) print(word_definitions["maybe"]) """ Loop over dictionary to get the following output: The definition of [WORD] is [DEFINITION] The definition of [WORD] is [DEFINITION] The definition of [WORD] is [DEFINITION] """ for key, value in word_definitions.items(): print(f"The definition of {key} is {value}") # PRACTICE: English Idioms idioms = { "Penny": ["A", "penny", "for", "your", "thoughts"], "Injury": ["Add", "insult", "to", "injury"], "Moon": ["Once", "in", "a", "blue", "moon"], "Grape": ["I", "heard", "it", "through", "the", "grapevine"], "Murder": ["Kill", "two", "birds", "with", "one", "stone"], "Limbs": ["It", "costs", "an", "arm", "and", "a", "leg"], "Grain": ["Take", "what", "someone", "says", "with", "a", "grain", "of", "salt"], "Fences": ["I'm", "on", "the", "fence", "about", "it"], "Sheep": ["Pulled", "the", "wool", "over", "his", "eyes"], "Lucifer": ["Speak", "of", "the", "devil"], } for key, value in idioms.items(): val = " ".join(value) print(f'{key}: {val}') # CHALLENGE: The Family Dictionary my_family = { "sister": { "name": "Sarah", "age": 43 }, "mother": { "name": "Judy", "age": 76 }, "father": { "name": "Ray", "age": 79 } } for fam_member, details in my_family.items(): print(f'{details["name"]} is my {fam_member} and is {str(details["age"])} years old') # ADVANCED CHALLENGE: Stock Portfolio
0455aeef947db1484039034ebc4f1acd29e76c1c
ambivert143/PythonProgram
/enume.py
215
3.703125
4
class Enum: def __init__(self,list): self.list = list def enume(self): for index, val in enumerate(self.list,start=1): print(index,val) e1 = Enum([5,15,45,4,53]) e1.enume()
d38d221e4c91ddd862cf15086c6ac9cedbe94281
zarkle/code_challenges
/leetcode/buy_sell_stock_iii.py
1,024
3.515625
4
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/ # passes 189/200 test cases class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 profit = [] low = prices[0] high = None for i in range(1, len(prices)): if prices[i] <= prices[i - 1]: if high: profit.append(high - low) high = None low = prices[i] else: high = prices[i] if high: profit.append(high - low) profit.sort() if len(profit) > 1: return profit[-1] + profit[-2] elif len(profit) == 1: return profit[0] else: return 0 # test case: # [1,2,3,4,5] returns 4 # [1,2,4,2,5,7,2,4,9,0] returns 13 (code above returns 12, so not passing this test case)
bf2d85594dbc51b9b27063c50bc501eaa12d16d8
agustashd/Learning-Python
/matriz_datos_NxM.py
2,274
3.875
4
#!/usr/bin/env python3 """Ingresar N lotes de M datos. Calcule el promedio de cada lote e infórmelo en pantalla. Además muestre el dato máximo y el promedio mínimo y a qué número de lote pertenece cada uno. """ def carga_matriz(cant_lotes, cant_datos): "Función que sirve para cargar la matriz de NxM." matriz = [] for i in range(cant_lotes): lote = [] for j in range(cant_datos): dato = int(input('Ingrese el dato: ')) lote.append(dato) matriz.append(lote) return matriz def calcule_promedios(matriz): """Función que recibe una matriz y devuelve una lista con los promedios de cada fila""" promedios = [] for lote in matriz: promedio = 0 for item in lote: promedio = promedio + item promedio = promedio / len(lote) promedios.append(promedio) return promedios def busca_maximo(matriz): """Función que busca el máximo de una matriz y devuelve ese valor y al último lote al que pertence.""" maximo = matriz[0][0] nro_lote = 0 for i, lote in enumerate(matriz): for valor in lote: if valor > maximo: maximo = valor nro_lote = i + 1 return maximo, nro_lote def busca_minimo(lista): "Función que busca y devuelve el valor mínimo de una lista." minimo = lista[0] lote = 0 for i, item in enumerate(lista): if item < minimo: minimo = item lote = i return minimo, lote + 1 if __name__ == '__main__': N = int(input('Cantidad de lotes a ingresar (N): ')) M = int(input('Cantidad de datos por lote (M): ')) matriz_datos = carga_matriz(cant_lotes=N, cant_datos=M) promedios = calcule_promedios(matriz=matriz_datos) print('Los promedios son: ') for promedio in promedios: print(promedio) dato_maximo, lote_dato_max = busca_maximo(matriz=matriz_datos) print('El dato ingresado máximo es: ', dato_maximo) print('\tY pertenece al lote N°: ', lote_dato_max) promedio_minimo, lote_promedio_min = busca_minimo(lista=promedios) print('El promedio mínimo es vale ', promedio_minimo) print('\tY pertenece al lote ', lote_promedio_min)
7a6b666cf6d3cad36fb8e3f1e397d1bae8fd4aa7
erichuang2015/python-examples
/算法/04统计单词出现次数.py
715
3.96875
4
#!/usr/bin/env python3 # coding: utf-8 """统计字符串单词出现次数,不区分大小写。 """ import re from collections import Counter def main(): # 去除多余标点 pattern = re.compile(r'[,.!?]') # 第一种方式,自定义算法 s = 'I love python, python is simple and powerful!' d = {} for letter in pattern.sub(' ', s.lower()).split(): d[letter] = d.get(letter, 0) + 1 print(sorted(d.items(), key=lambda x: x[1], reverse=True)) # 打印出现次数最多的单词 print(max(d.items(), key=lambda x: x[1])[0]) # 第二种方式,使用 Counter print(Counter(pattern.sub(' ', s.lower()).split())) if __name__ == '__main__': main()
9a63728319bc7a007e3edcc2acf916c0e32b988a
Arunken/PythonScripts
/2_Python Advanced/8_Pandas/10_Sorting.py
1,643
4.46875
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 21 14:30:07 2018 @author: SilverDoe """ ''' There are two kinds of sorting available in Pandas : 1. By Label 2. By Actual Value ''' '''================== Sorting By Label ========================================''' import pandas as pd import numpy as np unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1']) # based on row index sorted_df=unsorted_df.sort_index(axis=0,ascending=True)# ascending order. # ascending is true by default,axis = 0 by default print(sorted_df) sorted_df = unsorted_df.sort_index(axis=0,ascending=False) # descending order print(sorted_df) #based on columns sorted_df=unsorted_df.sort_index(axis=1,ascending=True)# ascending order print(sorted_df) sorted_df = unsorted_df.sort_index(axis=1,ascending=False) # descending order print(sorted_df) '''=================== Sorting By Value =======================================''' ''' Like index sorting, sort_values() is the method for sorting by values. It accepts a 'by' argument which will use the column name of the DataFrame with which the values are to be sorted ''' import pandas as pd import numpy as np unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]}) # based on a specific column sorted_df = unsorted_df.sort_values(by='col1') print(sorted_df) # based on multiple columns sorted_df = unsorted_df.sort_values(by=['col1','col2']) print(sorted_df) # specifying sorting alorithm sorted_df = unsorted_df.sort_values(by='col1' ,kind='mergesort') # mergesort, heapsort and quicksort print(sorted_df)
f298e7715358c8343efbb37ab916f919ddd8f8d7
nish0910/face-detect
/main.py
589
3.96875
4
#code to detect face in an image import cv2 #contain face features face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") #for reading the image img = cv2.imread("IMG_20201211_175249.jpg") #convertng the image into gray scale image gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #search the coordianates of the face faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4) for x,y,w,h in faces: #method to create a rectangular face box img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),3) cv2.imshow("img", img) cv2.waitKey()
5f689e1b405405e44fbf8835c968b96972a81bbf
inyong37/Study
/V. Algorithm/i. Book/모두의 알고리즘 with 파이썬/Chapter 16.py
857
3.578125
4
# -*- coding: utf-8 -*- # Modified Author: Inyong Hwang ([email protected]) # Date: *-*-*-* # 모두의 알고리즘 with 파이썬 # Chapter 16. 미로 찾기 알고리즘 def solve_maze(g, start, end): qu = [] done = set() qu.append(start) done.add(start) while qu: p = qu.pop(0) v = p[-1] if v == end: return p for x in g[v]: if x not in done: qu.append(p + x) done.add(x) return '?' maze = { 'a': ['e'], 'b': ['c', 'f'], 'c': ['b', 'd'], 'd': ['c'], 'e': ['a', 'i'], 'f': ['b', 'g', 'j'], 'g': ['f', 'h'], 'h': ['g', 'l'], 'i': ['e', 'm'], 'j': ['f', 'k', 'n'], 'k': ['j', 'o'], 'l': ['h', 'p'], 'm': ['i', 'n'], 'n': ['m', 'j'], 'o': ['k'], 'p': ['l'] } print(solve_maze(maze, 'a', 'p'))
5cccf972d231ea79e6945106606164e7eb8199c1
Satoshi-Daikuhara/Python
/csvopen.py
3,288
3.828125
4
import csv import pandas as pd csv_file = open("./Book1.csv", "r", encoding="ms932", errors="", newline="" ) #リスト形式 l = csv.reader(csv_file, delimiter=",", doublequote=True, lineterminator="\r\n", quotechar='"', skipinitialspace=True) #辞書形式 d = csv.DictReader(csv_file, delimiter=",", doublequote=True, lineterminator="\r\n", quotechar='"', skipinitialspace=True) # header = next(l) # # print(header) # for row in l: # # rowはList # # row[0]で必要な項目を取得することができる # print(row) # # for r in d: # #rowはdictionary # #row["column_name"] or row.get("column_name")で必要な項目を取得することができる # print(r) csv_input = pd.read_csv(filepath_or_buffer="C:\\Users\\tie306098\PycharmProjects\Progrece\Book1.csv", encoding="ms932", sep=",") # # インプットの項目数(行数 * カラム数)を返却します。 # print(csv_input.size) # # 指定したカラムだけ抽出したDataFrameオブジェクトを返却します。 # print(csv_input[["商品名", "販売単価"]]) # #値を二次元配列形式?で返却します。 # #返却される型は、numpy.ndarray # print(csv_input.values) # #行インデックス、カラムインデックスの順番で指定して項目の値を取得できます。 # print(csv_input.values[0, 1]) # #頭から指定行数分取得 # #返却される型は、pandas.core.frame.DataFrame # print(csv_input.head(3)) # # #後ろから指定行数分取得 # #返却される型は、pandas.core.frame.DataFrame # print(csv_input.tail(3)) # #行数を確認 # print(len(csv_input)) # # #カラム数を確認 # print(len(csv_input.columns)) # # #次元の確認 # print(csv_input.shape) # #カラム情報 # print(csv_input.columns) # print(csv_input.columns[3]) # #データアクセスの方法いろいろ # #loc[rows, columns] # #全行選択の場合、rowsは「:」を指定 # print(csv_input.loc[:,["商品名", "販売単価"]]) # print(csv_input.loc[1:2,["商品名", "販売単価"]]) #2行目3行目 # # #iloc[rows番号, columns番号] # #全行選択の場合、rowsは「:」を指定 # #インデックスの指定方法に注意 # print(csv_input.iloc[:, 3])#3カラム目を全行 # print(csv_input.iloc[0:3, 3:5]) #3,4カラム目だけを1行~3行目まで抽出 # # #ix # #カラム名、カラム番号のどちらでも使用可能 # print(csv_input.ix[0:3, ["商品名", "販売単価", "仕入単価"]]) #1行目~4行目 # print(csv_input.ix[0:3, 3:6]) #1行目~3行目 # # 指定した条件で抽出 # print(csv_input[csv_input["販売単価"] > 1500]) # # 複数条件の組み合わせの場合 # # and条件は「&」を使用 # print(csv_input[(csv_input["販売単価"] > 1500) & (csv_input["販売個数"] > 3)]) # # orr条件は「|」を使用 # print(csv_input[(csv_input["販売単価"] > 1500) | (csv_input["販売個数"] > 3)]) # # 抽出条件には、以下のような指定方法もあります # print(csv_input.query("販売単価 > 1500")) # # 複数の値を指定する # print(csv_input[(csv_input["商品名"].isin(["ロロ", "へアップX5"]))]) csv_input["追加カラム"] = ["test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", ] print(csv_input)
5679bb60958ce0460eea76e090ab411a5ca59ff9
hariedo/wafer
/py/lib/timelines.py
5,219
3.984375
4
# timelines - a data model for events to be compared and rendered ''' A data model for events to be compared and rendered. SYNOPSIS >>> import timelines >>> line = timelines.Timeline('Japanese Eras') >>> line.add( timelines.Mark(1600, 'battle of sekigahara' ) >>> line.add( 'tokugawa shogunate', timelines.Mark(1603, 'tokugawa ieyasu takes power'), timelines.Mark(1867, 'shogunate abolished') ) >>> line.add( timelines.Mark(1853, 'perry sails into tokyo bay' ) ABSTRACT A general-purpose data model for tracking a number of time-sorted events for the purpose of drawing on a timeline. A timeline is composed of events or marks on the timeline at specified times. The data type for a timestamp is left to the caller, as long as the types are comparable. Thus, it's possible to standardize on floating point numbers, strings, or time/date structures, depending on the need of the caller. Some libraries have a special "timespan" type of event that gives a start and end time as a single mark. Instead, this library allows nested timelines, so a timespan is just a sub-timeline with its own starting and ending events. AUTHOR: Ed Halley ([email protected]) 12 June 2016 ''' class Thing (object): # An abstract base class for simple named objects that are tagged # with arbitrary keywords. Specialized classes can reserve specific # arguments for their own use, and send all other named arguments # here. No attempt is made to keep names unique at this level. def __init__(self, name, tags=None): self.name = name if tags is None: tags = [ ] self.tags = set(tags) class Mark (Thing): '''A single point on a timeline, with keywords to categorize.''' DEFAULT = 'star' MARKERS = { 'star': '*', 'spot': 'o', 'plus': '+', 'left': '<', 'right': '>' } def __init__(self, when, name, fuzzy=False, marker=None, tags=None): super(Mark, self).__init__(name, tags) self.when = when self.fuzzy = fuzzy if marker is None: marker = Mark.DEFAULT if marker.lower() in Mark.MARKERS: marker = Mark.MARKERS[marker] self.marker = marker def __cmp__(self, other): try: return cmp(self.when, other.when) except: pass return cmp(self.when, other) class Timeline (Thing): '''A collection of marks or other timelines. Whenever a mark or a sub-timeline is added to this timeline, the span of events is kept updated to aid in rendering. ''' def __init__(self, name, tags=None, *things): self.lines = set([]) self.marks = set([]) self.first = None self.final = None self.parent = None for each in things: self.add(each) def find(self, tags=None): '''Find Mark objects in this timeline or its sub-timelines. If given a collection of tags, only Mark objects with at least one of the given tags are returned. ''' if tags is None: found = self.marks.copy() else: tags = set(tags) found = set([]) for each in self.marks: if each.tags.intersection(tags): found.add(each) for each in self.lines: found = found.union(each.find(tags=tags)) return found def stretch(self, thing): # Update the first/final range references to include the given. if isinstance(thing, Timeline): if thing.first is not None: if self.first is None or thing.first < self.first: self.first = thing.first if thing.final is not None: if self.final is None or thing.final > self.final: self.final = thing.final if isinstance(thing, Mark): if self.first is None or thing.when < self.first.when: self.first = thing if self.final is None or thing.when > self.final.when: self.final = thing if self.parent is not None: self.parent.stretch(thing) def add(self, thing): '''Add another Mark or Timeline as a child of this line.''' if isinstance(thing, Timeline): thing.parent = self self.lines.add(thing) if isinstance(thing, Mark): self.marks.add(thing) self.stretch(thing) if self.parent is not None: self.parent.stretch(self) #---------------------------------------------------------------------------- if __name__ == '__main__': line = Timeline('example') a = Mark('2014-04-01', 'assignment made official', tags=['Halley']) b = Mark('2015-11-11', 'first flight', tags=['MRJ90']) line.add(a) assert line.first is a assert line.final is a line.add(b) assert line.first is a assert line.final is b assert len(line.find()) == 2 assert a in line.find(tags=['Halley']) assert not b in line.find(tags=['Halley']) print('timelines.py: all internal tests on this module passed.')
6ebb521d57eff7ea4961beff987cc142d4a02700
emotrix/Emotrix
/emotrix/helpers.py
934
3.890625
4
# -*- coding: utf-8 -*- import math import random def average(data): return sum(data) * 1.0 / len(data) def variance(data): avg = average(data) var = map(lambda x: (x - avg)**2, data) return average(var) def standard_deviation(data): return math.sqrt(variance(data)) def get_variance_range(n, m, amplt): """ Gets an approximation of the bounds for the variance of a data set whose amplitude is amplt. The algorithm generates n random values betwen 0 and amplt. Over this n random values, calculates the variance. Then, it repeats this process m times and finally, gets the minimun and maximum calculated variance. """ deviations = [] for i in range(0, m): data = [] for i in range(0, n): val = random.randint(0, amplt) data.append(val) deviations.append(variance(data)) return min(deviations), max(deviations)
5443329a7d0392e3b238b2cd370f546411e3d5ec
Arto1597/bedu-data02-team
/Pozole.py
2,302
4.0625
4
""" numeros = [13,23,45,6,67,123] def numero_par (numero): return numero*3 #Definir la función numero_par = list(map(numero_par, numeros)) print(numero_par) lista=[45,50,91,80,54] def multiplo_de_5(numeros): if numeros % 5 ==0: return print("es normal") else: return print("sigue") multiplo_de_5 = list(filter(multiplo_de_5, lista)) precios=[34,50,45,100,450,230] def precios_con_iva(numero): return round(numero * 1.16,2) precios_con_iva= list(map(precios_con_iva, precios)) def precios_con_descuento(numero): if numero > 50 and numero < 100: return numero else: 0 precios_con_descuento = list(filter(precios_con_descuento, precios_con_iva)) porcentaje_precios_descuento= round((len(precios_con_descuento)/len(precios_con_iva)*100),2) print(precios_con_descuento) print(f'porcentaje_precios_descuento {porcentaje_precios_descuento} %') """ #El dueño de la tienda en linea pozole mio, necesita saber # cuantos de sus productos son acredores a paquetes de envió de $90 o $150. #Los productos con precio con IVA que rebasen los $150 deberán ocupar el paquete de envió de $90. # Por lo contrario usaran el paquete de $150. precios_sin_iva = [3, 148, 74, 71, 4, 83, 95, 20, 61, 10, 69, 67, 23, 164, 97, 67, 144, 200, 38, 90, 200, 162, 6, 180, 65, 71, 90, 182, 16, 132, 182, 108, 90, 196, 48, 2, 158, 88, 39, 39, 54, 80, 89, 3, 90, 170, 88, 71, 142, 45, 81, 194, 36, 39, 30, 33, 38, 44, 134, 43, 12, 52, 170, 162, 192, 83, 18, 176, 120, 28, 86, 188, 51, 11, 96, 13, 198, 34, 66, 23, 200, 62, 194, 91, 51, 26, 152, 186, 86, 38, 46, 66, 83, 66, 40, 2, 20, 12, 91, 53] def precios_con_iva(numeros): return round(numeros*1.16,2) precios_con_iva = list(map(precios_con_iva, precios_sin_iva)) #paquetes de envio catalogados con $90 def paquete_1_90(numeros): if numeros> 150: return True paquete_1_90 = list(filter(paquete_1_90, precios_con_iva)) def paquete_2_150(numeros): if numeros < 150: return True paquete_2_150 = list(filter(paquete_2_150, precios_con_iva)) paq_90 = round( len(paquete_1_90)/len(precios_con_iva),2)* 100 paq_150 = round(len(paquete_2_150)/len(precios_con_iva),2)*100 print(f'porcentaje con paquete de envío $90:{paq_90} %') print(f'Porcentaje con paquete de envío $150: {paq_150}%')
737b1e679bf4ab0d395cb4184e30423f0389da23
pabin/university_recommendation
/recommender/graph_plot.py
1,488
3.5
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') def graph_plot(): csv_filepathname = "/home/raj/PycharmProjects/university_recommendation/" \ "database/clean70k.csv" names = ['University', 'Major', 'Degree', 'Season', 'Decision', 'GPA', 'Verbal', 'Quant', 'AWA', 'TOEFL', 'Status', 'Comments', 'Comments_Cont'] df2 = pd.read_csv(csv_filepathname, names=names, header=None) def retrieve_data(university_name): df1 = df2[(df2['University'] == university_name) & (df2['Decision'] == 'Accepted')] df3 = df1.head(120) print (df1['Decision'].value_counts(dropna=False)) x = np.array(df3.ix[:, 5:6]) y = np.array(df3.ix[:, 6:7]) return x, y colors1 = ("red") colors2 = ("green") x, y = retrieve_data('Stanford University') Stanford_University = plt.scatter(x, y, s=90, c=colors1, alpha=0.90, marker='o') x, y = retrieve_data('Lamar University') Lamar_University = plt.scatter(x, y, s=90, c=colors2, alpha=0.90, marker='v', label='Line 2') plt.legend([Stanford_University, Lamar_University], ["Stanford University", "Lamar University"], loc="upper left") plt.ylim(ymin=130, ymax=175) plt.xlim(xmin=2, xmax=4.2) plt.xlabel('GPA') plt.ylabel('GRE_Verbal') plt.title('Variation of GPA & GRE Verbal Score among Universities') plt.show() return
fcd3c07b1de76e1a7b7dcdd73d8e4c7997613428
sabrinako/advent-2020
/day-4/solution.py
3,923
3.5
4
""" --- Day 4: Passport Processing --- First puzzle answer: 204 Second puzzle answer: 179 """ import re def validate_regex_fields(regex, value): return re.search(regex, value) def validate_in_range(range, value): """ range is a tuple """ return range[0] <= int(value) <= range[1] def validate_year_field(name, value): year_ranges = { "byr": (1920, 2002), "iyr": (2010, 2020), "eyr": (2020, 2030) } regex_pass = validate_regex_fields("[0-9]{4}", value) range_pass = validate_in_range(year_ranges[name], value) return (regex_pass and range_pass) def validate_passport_fields(field_name, field_value): """ byr (Birth Year) - four digits; at least 1920 and at most 2002. iyr (Issue Year) - four digits; at least 2010 and at most 2020. eyr (Expiration Year) - four digits; at least 2020 and at most 2030. hgt (Height) - a number followed by either cm or in: If cm, the number must be at least 150 and at most 193. If in, the number must be at least 59 and at most 76. hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f. ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth. pid (Passport ID) - a nine-digit number, including leading zeroes. cid (Country ID) - ignored, missing or not. """ if field_name == 'byr' and validate_year_field("byr", field_value): return True elif field_name == 'iyr' and validate_year_field("iyr", field_value): return True elif field_name == 'eyr'and validate_year_field("eyr", field_value): return True elif field_name == 'hgt' and validate_regex_fields("([0-9]{2,3}cm|in)", field_value): if "cm" in field_value: range_pass = validate_in_range((150,193), field_value[:-2]) elif "in" in field_value: range_pass = validate_in_range((59,76), field_value[:-2]) if range_pass: return True elif field_name == 'hcl' and validate_regex_fields("(#[a-f|0-9]{6})", field_value): return True elif field_name == 'ecl': acceptable_ecl = "amb blu brn gry grn hzl oth" if field_value in acceptable_ecl: return True elif field_name == 'pid' and validate_regex_fields("([0-9]{9})", field_value): return True return False def validate_passport_full(): """ Solution for part 2, similar to part 1 but also validates the actual values of the fields with helper functions """ acceptance_criteria = ['byr', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid'] with open("input.txt") as file: total_valid = 0 file_split = file.read().split("\n\n") passport_list = [line.replace("\n", " ").split(" ") for line in file_split] for passport in passport_list: criteria_met = 0 for field in passport: # gonna be honest and say i don't really know why but the last # passport returns an empty string within the list, which unless # caught with this, gets counted as valid, which apparently it shouldn't be if field == '': criteria_met = 0 else: field_split = field.split(":") if field_split[0] in acceptance_criteria and validate_passport_fields(field_split[0], field_split[1]): criteria_met += 1 if criteria_met == 7: print(passport) total_valid += 1 return total_valid def validate_passports(): """ Solution for part 1 """ # this is missing cid, which is the field that does not exist on north pole credentials and # stops them from being valid passports acceptance_criteria = ['byr', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid'] with open("input.txt") as file: total_valid = 0 file_split = file.read().replace("\n", " ").split(" ") passport_list = [line.split(" ") for line in file_split] for passport in passport_list: criteria_met = 0 for field in passport: if field.split(":")[0] in acceptance_criteria: criteria_met += 1 if criteria_met == 7: total_valid += 1 return total_valid if __name__ == "__main__": result = validate_passports() print(result) result2 = validate_passport_full() print(result2)
65653fff3310ed48e4ab465e503ca3a300871b09
candlelogbi/100DProjects
/Day46_47.py
482
3.65625
4
class Library: def __init__(self,book,shelf): self.book=book self.shelf=shelf class science_section(Library): def __init__(self,book,shelf,name): super().__init__(book,shelf) self.name=name def printInfo(self): print("book:", self.book,"self:",self.shelf,"name",self.name) obj=science_section(300,45,"Physics books") obj.printInfo() obj2=science_section(20,4,"Physics books") obj2.printInfo()
5e8be0abc82879f927f1b2c9b2ee70e8b56bf558
pfs-0512/python_practice
/Dotinstall/myapp.py
226
3.96875
4
# print([i for i in range(10)]) # print([i * 3 for i in range(10) if i % 2 == 0]) # print((i * 3 for i in range(10) if i % 2 == 0)) print(i * 3 for i in range(10) if i % 2 == 0) print({i * 3 for i in range(10) if i % 2 == 0})
c8c3e5e7a344f554b32517f7d1c56129f032de2c
sjpark-dev/python-practice
/problems/programmers/level_1_to_2/p8.py
495
3.796875
4
# 최대공약수와 최소공배수 import math def solution(n, m): # x = gcd(n,m) x = math.gcd(n, m) y = n * m // x answer = [x, y] return answer # def gcd(n, m): # n_set = set() # m_set = set() # for i in range(1, n+1): # if n % i == 0: # n_set.add(i) # for i in range(1, m+1): # if m % i == 0: # m_set.add(i) # cd = n_set & m_set # return max(cd) if __name__ == '__main__': print(solution(2, 5))