blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
7a991b0cdf823b9fb912f18709b12884e0ec0852
LaurenceWarne/maplayerpy
/maplayerpy/perlin_layer.py
956
3.515625
4
""" Machinery for creating MapLayers containing Perlin noise. """ from typing import Callable, Tuple from perlin_numpy.perlin2d import generate_perlin_noise_2d, interpolant from .maplayer import BasicLayer, MapLayer def get_perlin_layer( width: int, height: int, res: Tuple[int], tileable: Tuple[bool] = (False, False), interpolant: Callable[[int], int] = interpolant, ) -> MapLayer[float]: """Return a Maplayer containing Perlin noise of size width*height. Args: width: width of the diagram. height: height of the diagram. res: The number of periods of noise to generate along each axis. Note shape must be a multiple of res. tileable: If the noise should be tileable along each axis. interpolant: Perlin interpolation function. """ return BasicLayer( generate_perlin_noise_2d( (width, height), res, tileable, interpolant ).tolist())
f6fb5a47d321592ab9cc5562d99d849a4420db37
JanieTran/SCHOOL_ProgrammingIoT
/W03/Lecture7/menu.py
1,356
3.5625
4
from database_utils import DatabaseUtils class Menu: def main(self): with DatabaseUtils() as db: db.createPersonTable() self.runMenu() def runMenu(self): while True: print() print("1. List People") print("2. Insert Person") print("3. Quit") selection = input("Select an option: ") print() if selection == "1": self.listPeople() elif selection == "2": self.insertPerson() elif selection == "3": print("Goodbye!") break else: print("Invalid input - please try again.") def listPeople(self): print("--- People ---") print("{:<15} {}".format("Person ID", "Name")) with DatabaseUtils() as db: for person in db.getPeople(): print("{:<15} {}".format(person[0], person[1])) def insertPerson(self): print("--- Insert Person ---") name = input("Enter the person's name: ") with DatabaseUtils() as db: if db.insertPerson(name): print("{} inserted successfully.".format(name)) else: print("{} failed to be inserted.".format(name)) if __name__ == "__main__": Menu().main()
01126ee138f4c3b954fd397bfd01774ad85fb2f2
JanieTran/SCHOOL_ProgrammingIoT
/W01/Lecture3_OOPython-Database-SenseHAT-CRON/05_mult_level.py
259
3.515625
4
class Animal: def eat(self): print ('Eating...') class Dog(Animal): def bark(self): print ('Barking...') class PuppyDog(Dog): def play(self): print ('Playing...') d=PuppyDog() d.eat() d.bark() d.play()
0505b53873a6ce606ccad71b5c070d8a7184e5c4
Isaac2/AZ_BDA_Practica
/trumpAnalyzer.py
564
3.75
4
import pandas import nltk #Natural Language Tokenizer nltk.download('stopwords') import matplotlib.pyplot as pyplot tweets = pandas.read_csv("./datasets/trump_tweets.csv") print(tweets.shape) tokenized = {} tweet_tokenizer = nltk.tokenize.casual.TweetTokenizer() filter_words = ["!", ",", ":", ".", "—", "&", "?", "\'", "\"", ")", "(", "’"] stopwords = nltk.corpus.stopwords.words('english') for value in tweets["text"]: tokenized[value] = [word for word in tweet_tokenizer.tokenize(value) if word.lower() not in stopwords and word not in filter_words]
8da0b1dd8e0dd6024cff4612ab35a83a3cfc95d2
Gallawander/Small_Python_Programs
/Caesar cipher.py
991
4.3125
4
rot = int(input("Input the key: ")) action = input("Do you want to [e]ncrypt or [d]ecrypt?: ") data = input("Input text: ") if action == "e" or action == "encrypt": text = "" for char in data: char_ord = ord(char) if 32 <= char_ord <= 126: char_ord -= 32 char_ord += rot # rotating to the right == encrypting char_ord %= 94 char_ord += 32 text += chr(char_ord) else: text += char print("cipher: {}".format(text)) elif action == "d" or action == "decrypt": text = "" for char in data: char_ord = ord(char) if 32 <= char_ord <= 126: char_ord -= 32 char_ord -= rot # rotating to the left == decrypting char_ord %= 94 char_ord += 32 text += chr(char_ord) else: text += char print("text: {}".format(text)) else: print("Error! Wrong operation!")
64af9cb6529dd9024d79e3843f1eaea79e05049b
kalyan-dev/Python_Projects_01
/demo/examples/cmd_line_args_factors.py
345
3.953125
4
import sys # This function computes the factor of the argument passed def get_factors(x): factors = [] for i in range(1, x + 1): if x % i == 0: factors.append(i) return factors # num = 320 num = int(sys.argv[1]) factors = get_factors(num) print(f"The factors of {num} are :", factors)
0c3b7a53b9dec1629b9300a33f84bd417a7e5f24
kalyan-dev/Python_Projects_01
/demo/examples/sort_stings2.py
257
4
4
# Accept names from user until END is given, and display them in sorted order; inputs = [] while True: s = input("Enter a string(enter END to stop)") if s.lower() != "end": inputs.append(s) else: break print(inputs)
2a0ffb39c845e7827d3a841c9f0475f42e8a5838
kalyan-dev/Python_Projects_01
/demo/oop/except_demo2.py
927
4.25
4
# - Accept numbers from user until zero is given and display SUM of the numbers; handle Invalid Numbers; # program should not crash, but should continue; def is_integer(n): try: return float(n).is_integer() except ValueError: return False def is_integer_num(n): if isinstance(n, int): return True if isinstance(n, float): return False nums = [] while True: try: # n = int(input("Enter a number(0 to End) :")) sn = input("Enter a number(0 to End) :") if not is_integer_num(sn): n = float(sn) else: n = int(sn) if n == 0: break else: nums.append(n) except: print("You have entered an invalid number. Please enter an Integer.") continue print(f"You have entered {nums}") print(f"Sum of the numbers = {sum(nums)}")
4afbcf702c11cd5dee480bb13646f88d5090571f
adeshp96/AIProject
/triangle.py
2,260
3.84375
4
def show(): # Import a library of functions called 'pygame' import pygame from math import pi # Initialize the game engine pygame.init() # Define the colors we will use in RGB format BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) # Set the height and width of the screen size = [1200, 700] screen = pygame.display.set_mode(size) pygame.display.set_caption("Example code for the draw module") #Loop until the user clicks the close button. done = False clock = pygame.time.Clock() count=0; while not done: # This limits the while loop to a max of 10 times per second. # Leave this out and we will use all CPU we can. clock.tick(100) screen.fill(WHITE) #print count # if(count%2==0): BLACK = ( 0, 0, 0) # else: RED = ( 255, 0, 0) #red GREEN = ( 0, 255, 0) #green BLUE = ( 0, 0, 255) #blue YELLOW = ( 255, 255, 0) #gray #For 100 #center #left #right #pygame.draw.polygon(screen, BLACK, [[600,50], [ 550,100], [650, 100]]) #pygame.draw.polygon(screen, BLACK, [[600,650], [ 550,600], [650, 600]]) #pygame.draw.polygon(screen, BLACK, [[100,300], [ 50,350], [100, 400]]) #pygame.draw.polygon(screen, BLACK, [[1100,300], [ 1100,400], [1150, 350]]) #For 120 if(count %2 == 0): RED = GREEN = BLUE = YELLOW = BLACK #center #left #right pygame.draw.polygon(screen, RED, [[600,20], [ 540,140], [660, 140]]) #up pygame.draw.polygon(screen, GREEN, [[600,680], [ 540,560], [660, 560]]) #down pygame.draw.polygon(screen, BLUE, [[140,290], [ 20,350], [140, 410]]) #left pygame.draw.polygon(screen, YELLOW, [[1060,290], [ 1060,410], [1180, 350]]) #right pygame.display.flip() count=count+1; for event in pygame.event.get(): if event.type == pygame.QUIT: done=True pygame.quit()
f3977bc72ebe0d9d79c1482208cea62a6b71e1c8
aieml/MLON-Week-05
/3.0 Linear regression for a practical dataset.py
853
3.75
4
import pandas as pd import numpy as np df=pd.read_csv('cardio_dataset.csv') #read the csv into a pandas dataframe #print(df.head[5]) df=df.values #converting the dataframe object into a numpy array #print(df) data=df[:,0:7] target=df[:,7] target=np.reshape(target, (-1,1)) #normalize data,target - useful in regression problems from sklearn.model_selection import train_test_split train_data, test_data, train_target, test_target = train_test_split(data,target,test_size=0.1) from sklearn.linear_model import LinearRegression clsfr=LinearRegression() clsfr.fit(train_data,train_target) result=clsfr.predict(test_data) from sklearn.metrics import r2_score r2_value=r2_score(test_target,result) print('r2_score:',r2_value) print('Actual value:',test_target[0:10]) print('Predicted value',result[0:10])
6c490d890e02c3c7c47cda25b405657a00fac0f3
Qiangzhongxiao/hadlx
/tuoyuanyuxianbo.py
2,372
3.5
4
# -*- coding: utf-8 -*- from scipy.integrate import * # 引入积分库(全部) from sympy import * # 引入sqrt库 from decimal import * # 引入精度函数库(全部) def K(k): # 定义函数 """lambda定义一个关于t的函数,t不是定值""" return quad(lambda t: 1/sqrt((1-(k*sin(t))**2)), 0, pi/2) def EE(k): return quad(lambda t: sqrt((1-(k*sin(t))**2)), 0, pi/2) def circle_time(T, k, h, H, Ek, Kk): """定义一个运算周期""" # decimal和float不能算术运算 return (4*h*k*Decimal(Kk))/sqrt(3*Decimal(9.8)*H*(1+H/h*(1/k**2 - Decimal(1/2) - 3*Decimal(Ek)/(2*k**2*Decimal(Kk))))), k def accurate(k=0, t=1): """定义k初值以及初始精度""" arr = [] # 定义空列表 getcontext().prec = t # 赋予数组精度 for i in range(1, 10): # 从1开始,运算十次 m = Decimal(i/(10.0**t))+k arr.append(Decimal(m)) # 将数放入数组 return arr def loop(arr_lst=[], T=15, h=3, H=1): """定义已知条件,做循环运算""" arr_cmp = [] for i in xrange(len(arr_lst)): # 取数组长度为循环次数 Kk = K(arr_lst[i])[0] Ek = E(arr_lst[i])[0] res_1 = list(circle_time(T, arr_lst[i], h, H, Ek, Kk)) # 返回结果 arr_cmp.append(res_1) arr_cmp.sort(reverse=True) # 结果从大到小排序 for i in xrange(len(arr_cmp)): res, k = arr_cmp[i] if res > T: continue # 循环 else: break # 终止循环 return res, k, Kk # res:T 对应的k 积分值Kk # def L_calculate(k, Kk, H, h): # return sqrt(16*h**3/3/H)*k*Kk if __name__ == '__main__': arr_cmp = [] # 初始化空数组 times = 20 # 确定精度位数 k = 0 try: T = int(raw_input('请输入海波周期T = ')) h = int(raw_input('请输入海面水深h = ')) H = int(raw_input('请输入海面波高H = ')) except: T = 15 h = 3 H = 1 print '周期T = ', T, 's' print '海域水深h = ', h, 'm' print '波高H = ', H, 'm' for j in xrange(times): t = j + 1 arr_lst = accurate(k, t) res, k, Kk = loop(arr_lst, T, h, H) L = B(k, Kk, H, h) print '第', t, '次计算周期 T = ', res, print '第', t, '次计算 模 k = ', k print '波长L=', L
9b6a117c5d2ae6e591bc31dfd1ba748b84079710
tejaboggula/gocloud
/fact.py
332
4.28125
4
def fact(num): if num == 1: return num else: return num*fact(num-1) num = int(input("enter the number to find the factorial:")) if num<0: print("factorial is not allowed for negative numbers") elif num == 0: print("factorial of the number 0 is 1") else: print("factorial of",num, "is:",fact(num))
3c8195172f12a2938ac4414572c474101dad9738
Atilhan/forever-young
/tafelmanieren/rocketlaunching.py
484
3.796875
4
#print ('\033[1;32;40m'+"Rocket departing in:..") # from time import sleep # for a in range (1,31): # print (a) # sleep(1) # print ("Prepare for take off ! ") #=======Bovenste code was mijn eerste poging maar het telte af van 1 naar 30 toe, maar het moest anders om #=======Current Code Below=======# print ('\033[1;32;40m'+"Rocket departing in:..") from time import sleep for a in range (30, 0, -1): print (a) sleep(1) print ("Prepare for take off ! ")
92c0b021adccbe1836f3daa2a1970023eb6bd3d2
pintuux/Pintu
/Basic_of_linked_list.py
502
3.765625
4
class node: def __init__(self,data): self.data = data self.next = None def takeinput(): inputnode = [int(i) for i in input().split()] head = None for i in inputnode: node1 = node(i) if head is None: head = node1 curr = head else: curr.next = node1 curr = node1 return head curr = takeinput() while curr is not None: print(curr.data) curr = curr.next
64ca57e47dc2fda105f417432ebb49a1f850ec4d
pintuux/Pintu
/palindrome_linked_list.py
1,176
3.859375
4
class Node: def __init__(self,data): self.data = data self.next = None def create_linked_list(): inputElement = [int(i) for i in input().split()] head = None for i in inputElement: node = Node(i) if head is None: head = node curr = head else: curr.next = node curr = curr.next return head head = create_linked_list() head2 = head def printReverse(head) : if head == None or head.next is None: return head else: forword = None prev = None temp = head while temp is not None: forword = temp.next temp.next = prev prev = temp temp = forword return prev curr = printReverse(head) def palindrome(curr,head2): while head2 is not None and curr is not None: if head2.data == curr.data: head2 = head2.next curr = curr.next else: return False else: return True check = palindrome(curr,head2) if check: print("ture") else: print("false")
7195da031e8916ef1cf775d3da9494e21f3571b3
JorgeJurado/TSFC3
/suma.py
173
3.875
4
#Aquí solicito un número entero al usuario numero = int(input("Escribe un número entero: ")) #Aquí imprimo la suma de los n números print(int(numero*(numero+1)/2))
4b5bacce46c70baae37b9c15381583ea22886cf3
Stanley9292/imageProcessingTool
/JPGtoPNGconverter.py
631
3.640625
4
# two arguments, the folder and the new folder that I want to create # ('Pokedex' 'new') import sys import os from PIL import Image # grab first and second argument actualFolder = sys.argv[1] newFolder = sys.argv[2] if not os.path.exists(newFolder): try: os.makedirs(newFolder) except OSError: print(f'Creation of the directory {newFolder} has failed.') for filename in os.listdir(actualFolder): img = Image.open(f'{actualFolder}\{filename}') clean_name = os.path.splitext(filename)[0] img.save(f'{newFolder}\{clean_name}.png', 'png') print(f'{filename} has been converted!')
72cce730f46fa01b7870783789cae79cfcf19a07
FranklyCui/ML_in_action
/logistic_regression.py
13,415
3.5
4
#!/usr/bin/env python # -*- conding:UTF-8 -*- """ logigstic regression Model """ import numpy as np import matplotlib.pyplot as plt # 从文件加载数据,返回样本数据集及类别标签列表 def load_data_set(): """ Des: 从文件加载数据,返回样本数据集及类别标签列表 Args: None Return: data_set --> class_labels --> """ data_set = [] class_labels = [] fr = open("input/TestSet.txt") text_list = fr.readlines() for line in text_list: # 对输入的每行数据,去掉首位空白字符,并用空格字符切成列表 line_list = line.strip().split() data_set.append([1, float(line_list[0]), float(line_list[1])]) class_labels.append(float(line_list[2])) return data_set, class_labels # 定义Sigmoid()函数 def sigmoid(args): """ Des: 返回输入值的sigmoid值 Args: args -- 输入值,可以为实数,或np.array、np.mat格式 Return: 输入值args的sigmoid值 """ return 1.0 / (1 + np.exp(-args)) # 批量梯度上升算法 def gradient_ascent(data_set, class_labels): """ Des: 根据输入样本集和样本列表标签,运用梯度下降法找出最优权重 Args: data_set -- 样本数据集 class_labels -- 样本类别标签 Return: weight_mat --> 最优权重向量 思路: 1. 初始化权重; 2. 计算梯度; 3. 更新权重 4. 返回步骤2,直至达到停止条件 5. 返回最优权重 """ data_mat = np.mat(data_set) # 将行向量转换为列向量 labels_mat = np.mat(class_labels).transpose() row_num, col_num = data_mat.shape # 构建权重向量(列向量) weight_mat = np.ones((col_num, 1)) max_cycle_times = 500 alph = 0.001 # 迭代 for cnt in range(max_cycle_times): # 求出预测值矩阵 predict_val_mat = data_mat * weight_mat # 映射到(0, 1) 值域内 predict_lab_mat = sigmoid(predict_val_mat) err_mat = labels_mat - predict_lab_mat # 求梯度,公式为:gradient_vec = data_mat.tranpose() * [real_labels_vec - predict_labels_vec] grad_mat = data_mat.transpose() * err_mat # 更新权重,公式为:weight_vec = weight_vec + alph(步长) * gradient_vec weight_mat = weight_mat + alph * grad_mat return weight_mat # 绘制散点图及回归直线 def plot_best_fit(weight_vec): """ Des: 利用传入数据集绘制散点图,利用传入权重向量,绘制分类回归直线 Args: weight_vec -- 权重向量 Return: None 思路: 1. 数据集绘制散点图 1.1 建立画图 1.2 建立子图 1.3 选出正类、负类对象的x、y轴列表 1.4 绘制散点图 2. 利用权重向量绘制分类回归直线 2.1 构建直线方程 2.2 构建直线的x、y轴参数列表 2.3 绘制直线图 """ data_mat, label_mat = load_data_set() # 类型统一转换,以避免类型不一致导致的.shape维度不一致 data_mat = np.array(data_mat) label_mat = np.array(label_mat) weight_vec = np.array(weight_vec) x_coord_1 = [] y_coord_1 = [] x_coord_0 = [] y_coord_0 = [] num_point = np.shape(data_mat)[0] # 将每个样本的第一个特征赋值给x,第二个特征赋值给y for i in range(num_point): if int(label_mat[i]) == 1: # 为避免报错,可强制类型转换 x_coord_1.append(data_mat[i,1]) y_coord_1.append(data_mat[i,2]) else: x_coord_0.append(data_mat[i,1]) y_coord_0.append(data_mat[i,2]) # 创建画布 fig = plt.figure() # 创建轴域 ax = fig.add_subplot(111) # 绘散点图 ax.scatter(x_coord_1, y_coord_1, s = 30, c = 'red', marker = 's') ax.scatter(x_coord_0, y_coord_0, s = 30, c = 'green') # 构建分类直线,分类直线对应于sigmoid函数中z=0的直线,左侧z<0为负类,右侧z>0为正类 # 其中,z = w0*x0 + w1*x1 + w2*x2,-->> 特征图中分类直线应为:0 = w0*x0 + w1*x1 + w2*x2 x = np.arange(-5.0, 5.0, 0.1) y = -(weight_vec[0] + weight_vec[1] * x) / weight_vec[2] ax.plot(x,y) plt.xlabel("X1") plt.ylabel("X2") plt.show() # 随机梯度上升算法(初版,步长不变,样本集顺序循环,执行一遍) def stoch_grad_ascend(data_set, class_labels): """ Des: 随机梯度上升算法 Args: data_set -- 样本特征数据集 class_labels -- 类别标签数据集 Return: None 思路: 1. 初始化weight值; 2. 遍历样本集每个样本点 3. 对每个样本点,计算其当前梯度grad_current 3.1 计算当前样本点class_label与predict_label差值, 公式:diff_i = class_label - predict_label 3.2 计算grad_current梯度 公式:grad_current = diff_i * data_set[i] 4. 更新weight值,公式为:weight = weight + alph * grad_current """ data_set = np.array(data_set) class_labels = np.array(class_labels) num_row, num_column = np.shape(data_set) # 初始化权重向量 weight = np.zeros(num_column) alph = 0.01 # 遍历每个样本点 for i in range(num_row): predict_label = sigmoid(sum(weight * data_set[i])) diff = class_labels[i] - predict_label grad_cur_point = diff * data_set[i] # 更新权重 weight = weight + alph * grad_cur_point return weight # 随机梯度上升算法(改进版:1)步长随迭代进行逐步减小,2)随机选取样本点计算梯度更新权值 def stoch_grad_ascent_improve(data_set, class_labels, max_times = 150): """ Des: 随机梯度上升算法,改进版: 1)步长随迭代进行逐步减小, 2)随机选取样本点计算梯度更新权值 Args: data_set -- 样本特征数据集 class_labels -- 类别标签集 max_times -- 计算次数,默认为150 Return: weight 思路: 1. 初始化weight值,初始化步长alph值; 2. 循环计算max_times次: 3. 对样本集进行遍历,每次遍历时随机选取样本点计算其梯度,更新weight值 3.1 步长更新,公式:alph = 0.01 + 4.0 / (i + j + 1) 3.2 随机选取样本点 3.3 计算样本点grad 3.4 更新weight值 """ data_set = np.array(data_set) class_labels = np.array(class_labels) num_row, num_column = np.shape(data_set) # 初始化weight值 weight = np.zeros(num_column) alph = 0.01 # 绘图:weight随迭代次数变化列表 # weight_list = [] # 计算max_times次 for cnt_time in range(max_times): # 对样本点做随机抽点,用抽中点的grad更新weight值,直至抽完所有样本点 index_set = list(range(num_row)) for cnt_point in range(num_row): # 更新步长 alph = 0.01 + 4 / (cnt_time + cnt_point +1) # 随机选取样本点,计算其梯度,更新weight rand = np.random.randint(0, len(index_set)) rand_index = index_set[rand] predict_label = sigmoid(sum(weight * data_set[rand_index])) diff = class_labels[rand_index] - predict_label weight = weight + alph * diff * data_set[rand_index] del index_set[rand] # weight_list.append(weight) return weight # 绘制特征随迭代次数变化图(自己发挥) def plot_feature_along_iteration(weight_list, num_iter_times): """ Des: 绘制x_0/x_1/x_2,这3个特征随这迭代次数变化图 Args: weight_list -- 权值随迭代产生的列表 num_iter_times -- 迭代次数 Return: None 思路: 1. 构建画图. fig 2. 构建轴域 ax = fig.add_plot(311) 3. 绘子图1: 3.1 构建子图列表 横轴列表:range(0,迭代次数) 纵轴列表:x_0,列表类型,元素各位为迭代次数 3.2 绘制 ax.plot(x,y) plt.xlabel("X0") plt.ylabel("迭代次数") plt.show() 4. 绘制子图2 5. 绘制子图3 """ x_0_list = [] x_1_list = [] x_2_list = [] for weight in weight_list: x_0_list.append(weight[0]) x_1_list.append(weight[1]) x_2_list.append(weight[2]) axis = range(0, num_iter_times, 1) fig = plt.figure() ax = fig.add_subplot(311) ax.plot(axis, x_0_list, color = 'red', label = 'feature_0') plt.ylabel("X0") #plt.xlim((0,200)) #plt.ylim((0, )) plt.title("value of weight along iteration") plt.legend(loc = "uper right") ax = fig.add_subplot(312) ax.plot(axis, x_1_list, color = 'blue', label = 'feature_1') plt.ylabel("X1") #plt.xlim((0,200)) ax = fig.add_subplot(313) ax.plot(axis, x_2_list) plt.ylabel("X2") #plt.xlim((0,200)) plt.show() def cycle_stoch_grad(max_times): """ 随机梯度上升算法,顺序循环遍历版 """ weight_list = [] data_set, labels = load_data_set() for i in range(max_times): weight = stoch_grad_ascend(data_set, labels) weight_list.append(weight) return weight_list # 用于测试,减少shell工作量 def test(): data, label = load_data_set() # weight = stoch_grad_ascend(data, label) # weight = stoch_grad_ascent_improve(data, label, 300) # weight = gradient_ascent(data, label) # plot_best_fit(weight) weight, weight_list = stoch_grad_ascent_improve(data,label,200) # print(weight) # print(weight_list) # plot_best_fit(weight) # weight_list = cycle_stoch_grad(200) plot_feature_along_iteration(weight_list, 200) #plot_best_fit(weight_list[-1]) print(weight_list[-1] == weight) print(weight_list[-1]) print(weight) # Logistic分类器 def classify_vec(targ_vec, weight_vec): """ Des: 对数几率分类器,对输入样本向量分类,正类返回+1,负类返回0 Args: tar_vec -- 待分类目标样本向量 weight_vec -- 权重向量 return: label -- 目标样本的预测类别 思路: 1. 计算输入样本向量的线性回归值z = tar_vec * weight_vec; 2. 将z值映射到(0,1)值域,sigmoid(z) 3. 比较预测值sigmoid(z)是否大于0.5,若大于0.5,返回1,否则,返回0 """ targ_vec = np.array(targ_vec) weight_vec = np.array(weight_vec) predict_label = sigmoid(sum(targ_vec * weight_vec)) if predic_label > 0.5: return 1 else: return 0 # 加载数据,并处理成格式数据 (具有通用性) def load_horse_data(str): """ Des: 根据输入地址,加载数据,并处理成格式数据 Args: 文件地址 Return: data_set -- 样本特征数据集 class_labels -- 类别标签数据集 思路: 1. 打开文件; 2. 读取文件置列表,每行文件为一个元素; 3. 遍历每行文件 4. 将每行文件去掉首位空格,并以空白字符切开成一个列表; 5. 将每行文件列表的前len()-1位,添加到为一个新列表,并将该新列表添加值data_set[] 6. 将每行文件列表的-1位,添加到class_labels列表 7. 返回data_set, class_labels列表 """ fr = open(str) lines_list = fr.readlines() data_set = [] class_labels = [] # 遍历每行文本 for line in lines_list: text_list = line.strip().split() data_set.append(text_list[:-1]) class_labels.append(text_list[-1]) return data_set, class_labels # 马匹死亡率预测 def colic_test(): """ Des: 用测试集对死亡率预测算法评估,计算错误率 Args: None Return: err_ratio --> 预测错误率 思路: 1. 准备数据:数据存放在当前目录子目录./input/中 2. 分析数据: 2.1 加载数据; 2.2 格式化数据; 3. 训练算法:用data_set训练算法,返回weight 4. 评估算法:用data_test_set中的每个样本评估算法,求出错误数,并计算错误率 """ data_train_set, class_train_labels = load_horse_data("./input/HorseColicTraining.txt") data_test_set, class_test_labels = load_horse_data("input/HorseColicTest.txt") # 训练算法 weight = stoch_grad_ascend(data_train_set, class_train_labels) num_test = len(data_test_set) # 遍历测试集样本点,对算法预测错误率评估 for i in range(num_test): predict_label = classify_vec(data_test_set[i], weight) if predict_label != class_test_labels[i]: err_cnt += 1 err_ratio = float(err_cnt / num_test)
e58938306eb2415072bbe2d37dbffb627f737f04
Schlagoo/sort_algorithms
/algorithms.py
4,126
4.375
4
""" Implementation of different sorting algorithms in Python3 including: InsertionSort, SelectionSort, BubbleSort, MergeSort, QuickSort. Author: https://github.com/Schlagoo Date: 2020/04/20 Python: 3.6.9 """ class SortingAlgorithms: def __init__(self, arr: list): self.arr = arr def insertion_sort(self) -> list: """ Insertion sort list by iterting through list and checking if previous element is bigger. :return self.arr Sorted list """ for i in range(1, len(self.arr)): j = i marker = self.arr[i] while (j > 0 and self.arr[j - 1] > marker): self.arr[j] = self.arr[j - 1] j -= 1 self.arr[j] = marker return self.arr def selection_sort(self) -> list: """ Selection sort list by searching for max element and put in at the end of list. :return self.arr Sorted list """ n = len(self.arr) - 1 while n >= 0: max = 0 for i in range(1, n + 1): if self.arr[i] > self.arr[max]: max = i self.arr[n], self.arr[max] = self.arr[max], self.arr[n] n -= 1 return self.arr def bubble_sort(self) -> list: """ Bubble sort algorithm to sort list by iterating through list and comparing values of i and i+1 :return self.arr Sorted list """ for _ in range(len(self.arr)): for i in range(len(self.arr) - 1): if self.arr[i] > self.arr[i + 1]: self.arr[i], self.arr[i + 1] = self.arr[i + 1], self.arr[i] return self.arr def merge_sort(self, arr: list) -> list: """ Merge sort algorithm to sort list elements by size. :param arr List containing elements :return merge() Function to merge subsets """ if len(arr) < 2: return arr left_half, right_half = [], [] m = len(arr) // 2 left_half = self.merge_sort(arr[:m]) right_half = self.merge_sort(arr[m:]) return self.merge(left_half, right_half) def merge(self, left_half: list, right_half: list) -> list: """ Merge left and right half of list by sorting elements. :param left_half Left subset of elements :param right_half Right subset of elements :return merger Result of merging left and right half """ merger = [] i, j = 0, 0 while (len(merger) < len(left_half) + len(right_half)): if left_half[i] < right_half[j]: merger.append(left_half[i]) i+= 1 else: merger.append(right_half[j]) j+= 1 if i == len(left_half) or j == len(right_half): merger.extend(left_half[i:] or right_half[j:]) return merger def quick_sort(self, arr: list, lower: int, upper: int) -> list: """ Quick sort list by generating pivot element, partition and sort subsets. :param arr List containing elements :param lower Lower bound of current subset :param upper Upper bound of current subset :return arr Sorted list """ if upper > lower: pivot = (lower + upper) // 2 new_pivot = self.sort_partitions(arr, lower, upper, pivot) arr = self.quick_sort(arr, lower, new_pivot - 1) arr = self.quick_sort(arr, new_pivot + 1, upper) return arr def sort_partitions(self, arr: list, lower: int, upper: int, pivot: int) -> int: """ Sort partitions of elements. :param arr List containing elements :param lower Lower bound of current subset :param upper Upper bound of current subset :param pivot Current pivot element :return new_pivot Next pivot element """ new_pivot = lower value_pivot = arr[pivot] arr[pivot], arr[upper] = arr[upper], arr[pivot] for i in range(lower, upper): if arr[i] <= value_pivot: arr[new_pivot], arr[i] = arr[i], arr[new_pivot] new_pivot += 1 arr[new_pivot], arr[upper] = arr[upper], arr[new_pivot] return new_pivot if __name__ == "__main__": a = SortingAlgorithms([5, 3, 1, 7, 4, 6]) # print("Insertion sorted list: {}".format(a.insertion_sort())) # print("Selection sorted list: {}".format(a.selection_sort())) # print("Bubble sorted list: {}".format(a.bubble_sort())) # print("Merge sorted list: {}".format(a.merge_sort([5, 3, 1, 7, 4, 6]))) print("Quick sorted list: {}".format(a.quick_sort([5, 3, 1, 7, 4, 6], lower=0, upper=5)))
0fa7e809c7f4a8c7b0815a855cbc482abf600a77
dimpy-chhabra/Artificial-Intelligence
/Python_Basics/ques1.py
254
4.34375
4
#Write a program that takes three numbers as input from command line and outputs #the largest among them. #Question 02 import sys s = 0 list = [] for arg in sys.argv[1:]: list.append(int(arg)) #arg1 = sys.argv[1] list.sort() print list[len(list)-1]
836c0d8e6932a938f4d3abab78335bacd9e1f45f
orb1225/learnpython
/str2float_v1.0.py
361
3.5
4
from functools import reduce from sys import argv script,s=argv def str2float(s): str_arr=s.split('.') dic= {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(x,y): return x*10+y return reduce(str2int,map(lambda x:dic[x],str_arr[0]+str_arr[1]))/float(10**len(str_arr[1])) print str2float(s),type(str2float(s))
d94baeb89da4bf1f98b30a760ecbe35eebea4d7e
KingdeJosh/Cryptography-for-beginners
/Prime Tests/millers rabin test.py
1,399
4.0625
4
from random import randint def is_probably_prime(n, k=1): d = n - 1 s = 0 ifsetter = 1 print(f"1. We have that n = {n}, k-times: k = {k} and d = {n-1}") print(f"2. We then make an iteration until d is not divisible by 2") while not d % 2: s += 1 d //= 2 for i in range(k): a = randint(2, n - 2) x = pow(a, d, n) print("3. We Pick a random number 'a' in range [2, n-2]\n" f" a = {a}") print("4. We then Compute: x = a^d (mod n)\n" f" x = {a}^{d} (mod {n}) = {x}") print(f"5. We then check to see if x = 1 or (n-1). \n") if x == 1 or x == (n - 1): if x==1: print(f" we see that x = {x}") elif x==(n-1): print(f" we see that x = (n-1) = {n}") continue print(f"6. We then compute x^2 (mod n)") for _ in range(s - 1): print(f" x = {x}^2 (mod {n})") x = pow(x, 2, n) print(f" = {x}") if x == (n - 1): print(f"7. We see x is equal to (n-1) i.e. {x} = {n-1}") break else: return print(f"6. As x is not equal to 1 or {n-1}\n" f" {n} is Not prime") return print(f" So {x} Probably prime") is_probably_prime(172)
66aa4c4a49c97f75da650dec66e3b427f78cafe7
KingdeJosh/Cryptography-for-beginners
/Public Cryptosystem/Find_pq_from_n_phiN.py
877
3.671875
4
import math n= 221 toitent = 192 print(f"When we have n = {n} and toitent = {toitent}") print("1. We know that n = p * q and toitent = (p-1)(q-1)\n" "2. We then susbsitute to get\n" " toitent =p.q-(p+q)+1 = n-(p+q)+1\n" "3. To get p and q we have that \n" " p+q = n + 1 - toitent") s=n+1-toitent print("4. Subsituting in the values we have that\n" f" S = p+q = {n}+1-{toitent}\n" f" = {s}") print("5. To get p and q from S value we use the following fomular\n" " p = ( s+ sqrt(s^2 - 4 * n))/2 \n" " q = (s - sqrt(s^2 - 4 * n))/2 ") p = (s + math.sqrt((s**2) - 4 * n)) / 2 q = (s - math.sqrt((s**2) - 4 * n)) / 2 print("6. Applying the formular we get\n" f" p = ({s}+sqrt({s}^2 - 4 * {n}))/2 \n" f" q = ({s}-sqrt({s}^2 - 4 * {n}))/2") print(f"7. We have that p = {p} and q = {q}")
b9c7f156d3be3e95c5fac5767c76ccd9895a9ea9
bknopps/Public_SE_DevNet
/init_challenge.py
1,343
3.5
4
#! Python3 import csv import requests # TOKEN GOES HERE. # LAST FOR 12 hours. # reference this url: https://developer.webex.com/docs/api/v1/memberships/list-memberships # This page will give you access to how to use the membership api and how to get your token. USER_TOKEN = "Bearer XXXXXXXXXXXXXXX" # your token goes here def get_webex_api(room_id="Y2lzY29zcGFyazovL3VzL1JPT00vNWJiMmRiZjAtNmFkOC0xMWVhLWEzNmEtMDc0ZjMxN2Y0Njli"): # pass in different room id's to this function to see the rooms membership data url = "https://api.ciscospark.com/v1/memberships" querystring = {"roomId": room_id} headers = { 'Authorization': USER_TOKEN, } response = requests.request("GET", url, headers=headers, params=querystring) return response.json() if __name__ == '__main__': # Step 1) Get membership data: membership_data = get_webex_api() # Step 2) create a CSV File csv_headers = ["Name", "Email"] with open("membership.csv", mode="w") as membership_out: writer = csv.DictWriter(membership_out, fieldnames=csv_headers) writer.writeheader() # Step 3) loop over membership_data and write it to the csv file. for member in membership_data["items"]: writer.writerow({"Name": member.get("personDisplayName"), "Email": member.get("personEmail")}) #Done!
83a460d0f88674ac4ee2f46c89ffb286a2495d00
Wieschie/nqueens_constraint
/nqueens_constraint.py
1,209
3.84375
4
from constraint import * problem = Problem() board_size = 8 queen_list = range(board_size) # enforce different columns by restricting each queen to only move within 1 column. coord_list = [[(x,y) for y in range(board_size)] for x in range(board_size)] for q,c in zip(queen_list, coord_list): problem.addVariable(q, c) for queen_1 in queen_list: for queen_2 in queen_list: if queen_1 < queen_2: # must be in different rows problem.addConstraint(lambda q1, q2: q1[1] != q2[1], (queen_1, queen_2)) # cannot be diagonal problem.addConstraint(lambda q1, q2: abs(q1[0]-q2[0]) != abs(q1[1]-q2[1]), (queen_1, queen_2)) solutions = problem.getSolutions() def print_horiz_line(): print(" ---" * board_size) def print_solution(s): for y in range(board_size): print_horiz_line() for x in range(board_size): cell = "| " for c in s.values(): if c == (x,y): cell = f"| Q " break print(cell, end='') print("| ") print_horiz_line() for i,s in enumerate(solutions): print(f"\n\nSolution {i+1}") print_solution(s)
b08e0bc97509d4ad4a0961af96bd759553efd97d
iam3mer/mTICP472022
/Ciclo I/Unidad 3/fororwhile.py
441
4.09375
4
nombres = ['Andres', 'Derly', 'Edison', 'Edwin', 'Karla'] print('Elementos con While') nElementos = len(nombres) # 5 contador = 0 while contador < nElementos: # 0,1,2,3,4 print(nombres[contador]) contador = contador + 1 print('\nElementos con For') range(nElementos) # [0,1,2,3,4] for contador in range(nElementos): print(nombres[contador]) print('\nElementos directamente iterados') for nombre in nombres: print(nombre)
82737a375f3f7cb93ec64203c8b7a0c480a31c1c
iam3mer/mTICP472022
/Ciclo I/Unidad 4/AnyAll.py
914
3.578125
4
# Que pasa? numeros = [345,756,34,0,467,456,-94,63,64,686,543] impares = list(map(lambda num: num%2 != 0, numeros)) #print(impares) #print(all(impares)) #print(any(impares)) def esVerdadero(secuencia): numeros = [] for num in secuencia: if num: numeros.append(True) else: numeros.append(False) return numeros #print(esVerdadero(numeros)) #print(all(esVerdadero(numeros))) #print(any(esVerdadero(numeros))) # Caso especial #print(all([])) #print(any([])) info = [int(input()), input().split(' ')] print( 'True' if all( list(map( lambda x: x>0, list(map(int, info[1])))) ) and any( list(map( lambda x: x[0] == x[1] or x[0] == '5', list(zip( info[1], list(map(lambda x: x[-1:(len(x)+1)*-1:-1], info[1])) )))) ) else 'False' )
acbbae79ade5944bbd4b83e8a92f98e0a564b7d5
eylultuncel/AI-Search-Algorithms
/maze.py
9,614
3.625
4
import datetime import random import networkx as nx import matplotlib.pyplot as plt import heapq import math from collections import deque def calculate_neighbors(vertex, n): neighbors = [] if vertex % n != 0: neighbors.append(vertex - 1) if vertex % n != n - 1: neighbors.append(vertex + 1) if vertex >= n: neighbors.append(vertex - n) if vertex < (n * (n - 1)): neighbors.append(vertex + n) return neighbors def create_empty_maze(maze, n): for i in range(0, n * n): neighbors = calculate_neighbors(i, n) maze.add_node(i, visited=False, neighbors=neighbors) return maze def get_random_unvisited_neighbor(vertex, maze): neighbors = maze.nodes[vertex]["neighbors"] if len(neighbors) == 0: return -1 random_index = random.randint(0, len(neighbors) - 1) # get some random element from neighbors next_vertex = neighbors[random_index] if maze.nodes[next_vertex]["visited"]: maze.nodes[vertex]["neighbors"].remove(next_vertex) next_vertex = get_random_unvisited_neighbor(vertex, maze) return next_vertex def random_neighbors_to_stack(vertex, stack, maze, nodes): neighbors_list = maze.nodes[vertex]["neighbors"] for i in range(0, len(neighbors_list)): random_neighbor = get_random_unvisited_neighbor(vertex, maze) if random_neighbor != -1: nodes.add_node(random_neighbor, where_from=vertex) if random_neighbor in stack: stack.remove(random_neighbor) stack.append(random_neighbor) maze.nodes[vertex]["neighbors"].remove(random_neighbor) return stack def create_maze(maze, n): nodes = nx.Graph() vertex = 0 maze.nodes[vertex]["visited"] = True stack = [] stack = random_neighbors_to_stack(vertex, stack, maze, nodes) while len(stack) != 0: next_vertex = stack.pop() maze.add_edge(next_vertex, nodes.nodes[next_vertex]["where_from"]) maze.nodes[next_vertex]["visited"] = True vertex = next_vertex stack = random_neighbors_to_stack(vertex, stack, maze, nodes) return maze def draw_maze(maze, n, path): plt.figure(figsize=(n / 2, n / 2)) plt.xticks([]), plt.yticks([]) for i in range(0, n + 1): plt.plot([0, n], [-i, -i], color='black') plt.plot([i, i], [0, -n], color='black') plt.plot([0, 1], [0, 0], color='white') plt.plot([n - 1, n], [-n, -n], color='white') for i in range(0, n * n): if maze.has_edge(i, i - 1): # yatayda plt.plot([i % n, i % n], [-(i // n), -((i // n) + 1)], color='white') if maze.has_edge(i, i - n): # dikeyde plt.plot([(i % n), (i % n) + 1], [-(i // n), -(i // n)], color='white') # plt.show() filename = "maze2_empty_" + str(n) + ".png" plt.savefig(filename) def draw_maze_path(maze, n, path): plt.figure(figsize=(n / 2, n / 2)) plt.xticks([]), plt.yticks([]) for i in range(0, n + 1): plt.plot([0, n], [-i, -i], color='black') plt.plot([i, i], [0, -n], color='black') plt.plot([0, 1], [0, 0], color='white') plt.plot([n - 1, n], [-n, -n], color='white') for i in range(0, n * n): if maze.has_edge(i, i - 1): # yatayda plt.plot([i % n, i % n], [-(i // n), -((i // n) + 1)], color='white') if maze.has_edge(i, i - n): # dikeyde plt.plot([(i % n), (i % n) + 1], [-(i // n), -(i // n)], color='white') plt.plot([0.5, 0.5], [0, -0.5], linewidth=2.5, color='red') plt.plot([n - 0.5, n - 0.5], [-n + 0.5, -n], linewidth=2.5, color='red') print("\nPATH = ") print(path) x = (n * n) - 1 for i in range(0, len(path)): a = path.get(x) if a is None: continue if a == x - 1: plt.plot([x % n - 0.5, x % n + 0.5], [-((x // n) + 0.5), -((x // n) + 0.5)], linewidth=2.5, color='red') elif a == x + 1: plt.plot([x % n + 0.5, x % n + 1.5], [-((x // n) + 0.5), -((x // n) + 0.5)], linewidth=2.5, color='red') if a == x - n: plt.plot([(x % n) + 0.5, (x % n) + 0.5], [-(x // n + 0.5), -(x // n - 0.5)], linewidth=2.5, color='red') elif a == x + n: plt.plot([(x % n) + 0.5, (x % n) + 0.5], [-(x // n + 0.5), -(x // n + 1.5)], linewidth=2.5, color='red') x = a # plt.show() filename = "maze2_" + str(n) + ".png" plt.savefig(filename) def depth_limited_search(maze, start, goal, limit=-1): found = False fringe = deque([(0, start)]) visited = {start} came_from = {start: None} while not found and len(fringe): current = fringe.pop() depth = current[0] current = current[1] if current == goal: found = True break if limit == -1 or depth < limit: for node in maze.neighbors(current): if node not in visited: visited.add(node) fringe.append((depth + 1, node)) came_from[node] = current if found: return came_from, visited else: return None, visited def iterative_deepening_dfs(maze, start, goal): prev_iter_visited = [] depth = 0 count_expanded = 0 while True: traced_path, visited = depth_limited_search(maze, start, goal, depth) if traced_path or len(visited) == len(prev_iter_visited): return count_expanded, len(traced_path) else: count_expanded += len(visited) prev_iter_visited = visited depth += 1 def uniform_cost_search(maze, start, goal): found = False fringe = [(0, start)] visited = {start} came_from = {start: None} cost_so_far = {start: 0} while not found and len(fringe): current = heapq.heappop(fringe) current = current[1] if current == goal: found = True break for node in maze.neighbors(current): new_cost = cost_so_far[current] + 1 if node not in visited or cost_so_far[node] > new_cost: visited.add(node) came_from[node] = current cost_so_far[node] = new_cost heapq.heappush(fringe, (new_cost, node)) if found: return len(visited), cost_so_far[goal], came_from else: print('No path from {} to {}'.format(start, goal)) return None, math.inf def heuristics(maze, n): heuristics_euclidean = [] heuristics_manhattan = [] for i in range(0, n * n): x = (n - 1) - (i % n) y = (n - 1) - (i // n) heuristics_euclidean.append((math.sqrt((x * x) + (y * y)))) heuristics_manhattan.append(x + y) return heuristics_euclidean, heuristics_manhattan def a_star_search(maze, start, goal, heuristic): found = False fringe = [(heuristic[start], start)] visited = {start} came_from = {start: None} cost_so_far = {start: 0} while not found and len(fringe): current = heapq.heappop(fringe) current_heuristic = current[0] current = current[1] if current == goal: found = True break for node in maze.neighbors(current): new_cost = cost_so_far[current] + 1 if node not in visited or cost_so_far[node] > new_cost: visited.add(node) came_from[node] = current cost_so_far[node] = new_cost heapq.heappush(fringe, (new_cost + heuristic[node], node)) # SORUN OLUR if found: return len(visited), cost_so_far[goal] else: print('No path from {} to {}'.format(start, goal)) return None, math.inf def run_algorithms(maze, n): print() print("UCS") begin = datetime.datetime.now() ucs_expanded, ucs_path_length, came_from = uniform_cost_search(maze, 0, (n * n) - 1) end = datetime.datetime.now() delta = end - begin print("Path Length = ", ucs_path_length, "\nExpanded nodes = ", ucs_expanded, "\nTime passed = ", delta.total_seconds() * 1000) h_euclidean, h_manhattan = heuristics(maze, n) print() print("A*- euc") begin = datetime.datetime.now() a_star_euc_expanded, a_star_euc_path_length = a_star_search(maze, 0, (n * n) - 1, h_euclidean) end = datetime.datetime.now() delta = end - begin print("Path Length = ", a_star_euc_path_length, "\nExpanded nodes = ", a_star_euc_expanded, "\nTime passed = ", delta.total_seconds() * 1000) print() print("A*- man") begin = datetime.datetime.now() a_star_man_expanded, a_star_man_path_length = a_star_search(maze, 0, (n * n) - 1, h_manhattan) end = datetime.datetime.now() delta = end - begin print("Path Length = ", a_star_man_path_length, "\nExpanded nodes = ", a_star_man_expanded, "\nTime passed = ", delta.total_seconds() * 1000) print() print("IDS") begin = datetime.datetime.now() ids_expanded, ids_visited = iterative_deepening_dfs(maze, 0, (n * n) - 1) end = datetime.datetime.now() delta = end - begin print("Expanded nodes = ", ids_expanded, "\nTime passed = ", delta.total_seconds() * 1000) return came_from def main(): maze = nx.Graph() n = 10 maze = create_empty_maze(maze, n) maze = create_maze(maze, n) path = run_algorithms(maze, n) # nx.draw(maze, with_labels=True) # plt.show() draw_maze(maze, n, path) draw_maze_path(maze, n, path) if __name__ == "__main__": main()
ce1874c25ef19eebda51b2bc15b7125f7ebb2995
snail15/AlgorithmPractice
/LeetCode/Python/SecondRound/23_mergeKSortedLists.py
852
3.828125
4
def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists or len(lists) == 0: return None return self.mergeLists(lists, 0, len(lists) - 1) def mergeLists(self, lists, start, end): if start == end: return lists[start] mid = start (end - start) // 2 left = self.mergeLists(lists, start, mid) right = self.mergeLists(lists, mid + 1, end) return self.merge(left, right) def merge(self, left, right): res = ListNode() cur = res while left or right: leftVal = left.val if left else float('inf') rightVal = right.val is right else float('inf') if leftVal < rightVal: cur.next = left left = left.next else: cur.next = right right = right.next cur = cur.next return res.next
87bfb462b2472475eb54b9075d6d213644dabe32
snail15/AlgorithmPractice
/LeetCode/Python/inorderTraversal.py
690
3.5
4
def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] self.helper(root, res) return res def helper(self, root, res): if root is not None: if root.left is not None: self.helper(root.left, res) res.append(root.val) if root.right is not None: self.helper(root.right, res) def inorderTraversal_iter(self, root): res = [] stack = [] curr = root while curr is not None or len(stack) != 0: while curr is not None: stack.append(curr) curr = curr.left curr = stack.pop() res.append(curr.val) curr = curr.right return res
e8e83ac29ce59ebb1051bbe6457e3d5bd8ade162
snail15/AlgorithmPractice
/Udacity/BasicAlgorithm/binarySearch.py
1,127
4.3125
4
def binary_search(array, target): '''Write a function that implements the binary search algorithm using iteration args: array: a sorted array of items of the same type target: the element you're searching for returns: int: the index of the target, if found, in the source -1: if the target is not found ''' start = 0 end = len(array) - 1 while start <= end: mid = (start + end) // 2 if array[mid] == target: return mid elif array[mid] > target: end = mid - 1 else: start = mid + 1 return -1 def binary_search_recursive_soln(array, target, start_index, end_index): if start_index > end_index: return -1 mid_index = (start_index + end_index)//2 mid_element = array[mid_index] if mid_element == target: return mid_index elif target < mid_element: return binary_search_recursive_soln(array, target, start_index, mid_index - 1) else: return binary_search_recursive_soln(array, target, mid_index + 1, end_index)
3e725cae69a005cf798d5d82ebe34e010095fcdc
snail15/AlgorithmPractice
/DailyCoding/Python/Arrays/productofAllOtherElements.py
454
3.71875
4
def productOfAllOtherElements(nums): L = [1 for x in nums] R = [1 for x in nums] ans = [1 for x in nums] L[0] = 1 for i in range(1, len(nums)): L[i] = L[i - 1] * nums[i - 1] R[len(nums) - 1] = 1 for i in range(len(nums) - 2, -1, -1): R[i] = R[i + 1] * nums[i + 1] for i in range(len(nums)): ans[i] = L[i] * R[i] return ans nums = [3,2,1] print(productOfAllOtherElements(nums))
48edb9390ee5072af8e7e16767917e2dd37140e6
snail15/AlgorithmPractice
/LeetCode/Python/SecondRound/92_reverseLinkedList2.py
589
3.78125
4
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: if not head: return head if left == right: return head prev = None cur = head while left > 1: prev = cur cur = cur.next left -= 1 right -= 1 connection = prev tail = cur while right > 0: next = cur.next cur.next = prev prev = cur cur = next right -= 1 if connection: connection.next = prev else: head = prev tail.next = cur return head
615be3798321168dc2407d6188e824d35ca100c3
snail15/AlgorithmPractice
/LeetCode/Python/permutations.py
607
3.734375
4
class Solution: def permute(self, nums): result = [] temp = [] self.backtrack(nums, result, temp) print(result) return result def backtrack(self, nums, result, temp): if len(temp) == len(nums): # print(temp) result.append(list(temp)) return for num in nums: if num in temp: continue temp.append(num) self.backtrack(nums, result, temp) temp.pop() nums = [1,2,3] solution = Solution() solution.permute(nums)
e867ad74a11224e1bdaab40093d37162ffdee6f8
snail15/AlgorithmPractice
/LeetCode/Python/SecondRound/241_differentWaysToAddParentheses.py
647
3.625
4
def diffWaysToCompute(self, expression: str) -> List[int]: res = [] for i in range(len(expression)): c = expression[i] if c in "+-*": left = self.diffWaysToCompute(expression[:i]) right = self.diffWaysToCompute(expression[i + 1:]) for l in left: for r in right: if c == "+": res.append(l + r) if c == "*": res.append(l * r) if c == "-": res.append(l - r) if len(res) == 0: res.append(int(expression)) return res
eb988049722c635c5ae6ce765d3cb474d786575c
snail15/AlgorithmPractice
/LeetCode/Python/climbingStairs.py
726
3.984375
4
# You are climbing a stair case. It takes n steps to reach to the top. # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # Note: Given n will be a positive integer. # Example 1: # Input: 2 # Output: 2 # Explanation: There are two ways to climb to the top. # 1. 1 step + 1 step # 2. 2 steps # Example 2: # Input: 3 # Output: 3 # Explanation: There are three ways to climb to the top. # 1. 1 step + 1 step + 1 step # 2. 1 step + 2 steps # 3. 2 steps + 1 step def climbStairs(self, n: int) -> int: if n == 1: return 1 m = [None for x in range(n)] m[0] = 1 m[1] = 2 for i in rnage(2, len(m)): m[i] = m[i-1] + m[i-2] return m[n-1]
3e0497b84476442645b9b7ff1c74bfd2a31776a9
veeteeran/holbertonschool-web_back_end
/0x03-caching/0-basic_cache.py
912
3.515625
4
#!/usr/bin/env python3 """BasicCache module""" from base_caching import BaseCaching class BasicCache(BaseCaching): """ Inherits from BaseCaching """ def put(self, key, item): """ Assign key: item to self.cache_data If key or item is None do nothing Parameters: key: key for item in self.cache_data dict item: contains value for key """ if key and item: self.cache_data.update({key: item}) def get(self, key): """ Returns the value of self.cache_data of given key Parameters: key: key where vaule is returned Returns: value of given key if key is None or doesn't exist returns None """ return self.cache_data.get(key)
65e82a4377f6d922df70c04dd68d7c68afef2c80
veeteeran/holbertonschool-web_back_end
/0x03-caching/100-lfu_cache.py
2,258
3.6875
4
#!/usr/bin/env python3 """LFU caching module""" from base_caching import BaseCaching class LFUCache(BaseCaching): """ LFU Caching algorithm """ __LFUDict = {} __bit = 0 def put(self, key, item): """ Assign key: item to self.cache_data If key or item is None do nothing Parameters: key: key for item in self.cache_data dict item: contains value for key """ keyList = list(self.cache_data)[0:] if key and item: if key in keyList: self.cache_data.update({key: item}) self.__LFUDict.update({key: self.__bit}) self.__bit += 1 else: if len(self.cache_data) < self.MAX_ITEMS: self.__LFUDict.update({key: self.__bit}) self.__bit += 1 self.cache_data.update({key: item}) else: discardedKey = self.__updateCache(key, item) print(f"DISCARD: {discardedKey}") def get(self, key): """ Returns the value of self.cache_data of given key Parameters: key: key where vaule is returned Returns: value of given key if key is None or doesn't exist returns None """ keyList = list(self.cache_data)[0:] if key in keyList: self.__LFUDict[key] = self.__bit self.__bit += 1 return self.cache_data.get(key) def __updateCache(self, key, item): """Update the cache dictionary""" keys = list(self.__LFUDict)[0:] values = [self.__LFUDict[k] for k in keys] cacheVals = [self.cache_data[k] for k in keys] minVal = min(values) index = values.index(minVal) minKey = keys[index] keys[index] = key values[index] = self.__bit - 1 cacheVals[index] = item self.cache_data.clear() self.cache_data = {k: v for k, v in zip(keys, cacheVals)} self.__LFUDict.clear() self.__LFUDict = {k: v for k, v in zip(keys, values)} return minKey
065ebcd4e86de796e08bd6be4e96689f360b6eab
Arunscape/CMPUT291
/labs/lab6/Iterate_All.py
789
3.859375
4
from bsddb3 import db DB_File = "data.db" database = db.DB() database.set_flags(db.DB_DUP) #declare duplicates allowed before you create the database database.open(DB_File,None, db.DB_HASH, db.DB_CREATE) curs = database.cursor() #Insert key-values including duplicates … database.put(b'key1', "value1") database.put(b'key1', "value2") database.put(b'key2', "value1") database.put(b'key2', "value2") iter = curs.first() while (iter): print(curs.count()) #prints no. of rows that have the same key for the current key-value pair referred by the cursor print(iter) #iterating through duplicates dup = curs.next_dup() while(dup!=None): print(dup) dup = curs.next_dup() iter = curs.next() curs.close() database.close()
dae99b43b13add7251e5ed4611f9f6696fe41c34
Hansolomix/List-Data-Structure
/main.py
3,651
4.59375
5
# ''' # Creating List # ''' # # List items are enclosed in square brackets # # Lists are ordered # # Lists are mutable # # Lists elements do not need to be unique # # Elements can be of different data types # # empty lists # List = [] # # list of intergers # list= [ 1,2,3 ] # # list of strings # list = [ "orange","apple", "pear", "apple", "banana" ] # # list is mixed with data types # list = [ 1, "Hello", 5.0 ] # ============ '''' list indexing ''' fruits = [ 'orange', 'apple', 'pear', 'apple','banana' ] fruits[0] print(fruits[0]) # output ===> orange fruits[ 1 ] print(fruits[1]) # outut ===> apple fruits[ 2 ] print(fruits[2]) # output ===> pear fruits[ 3 ] print(fruits[3]) # output ===> apple fruits[ 4 ] print(fruits[4]) # output ====> banana fruits[ -1 ] print(fruits[-1]) # output ====> banana fruits[ -5 ] print(fruits[-5]) # output ===> orange '''' Nested Indexing ''' fruits= [ 'orange', [ 'apple', 'orange' ] ] fruits[ 1 ][ 0 ] print(fruits[1][0]) # ==> apple fruits[ 1 ][ 1 ] print(fruits[1][1]) # ==> orange ''' How to slice lists in python ''' fruits = ['orange', 'apple', 'pear','grapes','banana' ] # beginning to end fruits[:] print(fruits[:]) # output ==> ['orange','apple','pear','grapes','banana'] # index 2 to 5th item fruits[2:5] print(fruits[2:5]) # output ==> ['pear','grapes','banana'] # remove last two items fruits[:-2] print(fruits[:-2]) # output ==> ['orange', 'apple', 'pear'] # return first two items fruits[:2] print(fruits[:2]) # output ==> ['orange','apple'] # index 2 to the end fruits[2:] print(fruits[2:]) # output ==> ['pear, 'grapes','banana'] # every 2nth item fruits[::2] print(fruits[::2]) # output ==> ['orange','pear','banana'] # reverse list fruits[::-1] print(fruits[::-1]) # output ==> ['banana','grapes','pear','apple','orange',] # =============== '''' Add element to the list ''' # changing a list after it is created (mutable) fruits= ['orange', 'apple', 'pear', 'grapes', 'banana'] # change first item fruits[0]= 'berries' print(fruits) # output ==>[ 'berries', 'apple', 'pear', 'grape', 'banana'] # change item in index 1 to 4th item fruits[1:4] = ['mandarins', 'peaches', 'plums'] print(fruits[1:4]) # output ==> ['orange','mandarins','peaches','plums','banana' ] # add limes to the end of the list fruits=['orange','apple','pear','grapes','banana'] fruits.append('Limes') print(fruits) # output ==> ['orange', 'apple', 'pear', 'grapes', 'banana', 'Limes' ] # ===== ''' Remove and Delete list items ''' fruits= [ 'Orange', 'Apple', 'Pear', 'Grapes', 'Banana'] # delete 0nth index position # del fruits[0] # print(fruits) # delete the items from index position 1 to 5th item del fruits[1:5] print(fruits) # =========== ''' Python list methods ''' # print(dir(list)) # print(help(list.append)) # print(help(list.insert)) fruits= ['Orange', 'Apple', 'Pear', 'Grapes', 'Banana' ] fruits.append('cashew') print(fruits) # ====== fruits.insert( 0,'guava' ) print(fruits) # ======= # fruits=['Orange', 'Apple', 'Pear', 'Grapes','Banana'] # fruits.pop(1) # print(fruits) # ====== # print(fruits.index('Banana')) # ======== # pos = fruits.index('Banana') # fruits.pop(pos) # print(fruits) # ====== fruits= ['orange', 'apple','pear','apple','banana','banana','banana'] # print(fruits.count('banana')) # result = {} # for x in fruits: # result [ x ] = fruits.count ( x ) # print(result) # ======== # easy way to count by using Counter from collections import Counter print(Counter(fruits)) # ======== ''' List Membership Test ''' fruits= ['apple', 'pear', 'apple', 'banana' ] print('apple' in fruits) # output => True
e877bbc77cf8e9544c5e5015c544f7aeed19409f
kacperlukawski/tensorflow-introduction
/03_Examples/03_ML_Datasets/01_face_recognition.py
4,524
3.609375
4
# This example tries to create a model able to handle face recognition. # The dataset is taken from "CMU Face Images": # http://kdd.ics.uci.edu/databases/faces/faces.html # It contains at least 28 different images for 20 people. Created model # should be able to recognize the name of the person. from helper import prepare_samples import tensorflow as tf import numpy as np import random import glob import os # Configuration IMAGE_WIDTH = 128 IMAGE_HEIGHT = 120 TRAIN_SET_FRACTION = .85 CLASSES_COUNT = 20 HIDDEN_LAYERS_SIZE = [100, 75, 50] # Accuracy: 0.702128 INITIAL_BIAS = 1.0 LEARNING_RATE = .001 EPOCHS = 10000 ACTIVATION_FUNCTION = tf.sigmoid # Read all the file names and form the dataset classes, class_idx, dataset = dict(), 0, list() for directory in glob.glob("./faces/*"): person = os.path.basename(directory) for filename in glob.glob(directory + "/*"): dataset.append((class_idx, person, filename)) classes[class_idx] = person class_idx += 1 # Shuffle the dataset and split it into train and test sets random.shuffle(dataset) train_set_size = int(len(dataset) * TRAIN_SET_FRACTION) train_set, test_set = dataset[:train_set_size], dataset[train_set_size:] # Create the input layer. As we use the images of size 128x120, a placeholder # will assume to have a vector of a size: IMAGE_WIDTH * IMAGE_HEIGHT input_vector = tf.placeholder( dtype=tf.float32, shape=(None, IMAGE_WIDTH * IMAGE_HEIGHT), name="input_vector") target_vector = tf.placeholder( dtype=tf.float32, shape=(None, CLASSES_COUNT), name="target_vector") # Create hidden layers last_layer = input_vector for i in range(len(HIDDEN_LAYERS_SIZE)): # Create weights and biases last_layer_shape = last_layer.get_shape() weights = tf.Variable( tf.random_normal(shape=(int(last_layer_shape[1]), HIDDEN_LAYERS_SIZE[i])), name="weights_%i" % (i,)) biases = tf.Variable( tf.constant(INITIAL_BIAS, shape=(1, HIDDEN_LAYERS_SIZE[i])), name="biases_%i" % (i,)) # Create a new hidden layer and set it as a new last one last_layer = ACTIVATION_FUNCTION( tf.matmul(last_layer, weights) + biases, name="layer_%i" % (i,)) # Connect the output layer and create whole NN last_layer_shape = last_layer.get_shape() weights = tf.Variable(tf.random_normal(shape=(int(last_layer_shape[1]), CLASSES_COUNT)), name="weights_output") biases = tf.Variable(tf.constant(INITIAL_BIAS, shape=(1, CLASSES_COUNT)), name="biases_output") output_vector = tf.add(tf.matmul(last_layer, weights), biases, name="output_vector") # Create cost function of the created network and optimizer cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( output_vector, target_vector)) optimizer = tf.train.AdamOptimizer( learning_rate=LEARNING_RATE).minimize(cost) # Create accuracy calculation correct_prediction = tf.equal( tf.arg_max(output_vector, 1), tf.arg_max(target_vector, 1)) accuracy = tf.reduce_mean( tf.cast(correct_prediction, tf.float32)) # Run training init_op = tf.initialize_all_variables() with tf.Session() as session: # Initialize all variables session.run(init_op) # Train the model try: samples, targets = prepare_samples(train_set, IMAGE_WIDTH, IMAGE_HEIGHT, CLASSES_COUNT) for epoch in range(EPOCHS): _, epoch_cost = session.run([optimizer, cost], { input_vector: samples, target_vector: targets }) print("Epoch", epoch, "cost:", epoch_cost) except KeyboardInterrupt as e: print("Training phase interrupted") # Test created model samples, targets = prepare_samples(test_set, IMAGE_WIDTH, IMAGE_HEIGHT, CLASSES_COUNT) prediction_accuracy = session.run(accuracy, { input_vector: samples, target_vector: targets }) # Check the output for each tested file for entry, sample, target in zip(test_set, samples, targets): target_class_idx = np.argmax(target) predicted_class_idx = np.argmax(session.run(output_vector, { input_vector: (sample,) })) if target_class_idx == predicted_class_idx: continue print(entry[2], "wanted:", classes[target_class_idx], "actual:", classes[predicted_class_idx]) # Check correct predictions print("Accuracy:", prediction_accuracy)
460d75a61550f0ae818f06ad46a9c210fe0d254e
lyderX05/DS-Graph-Algorithms
/python/BubbleSort/bubble_sort_for.py
911
4.34375
4
# Bubble Sort For Loop # @author: Shubham Heda # Email: hedashubham5@gmail.com def main(): print("**NOTE**: Elements should be less then 25 as alogrithm work best on that only") print("Enter Bubble Sort elements sepreated by (',') Comma: ") input_string = input() array = [int(each) for each in input_string.split(",")] array_len = len(array) if array_len > 1: for _ in range(array_len): swapped = False for col in range(array_len - 1): if array[col] > array[col + 1]: array[col], array[col + 1] = array[col + 1], array[col] swapped = True print("New Array: ", array) if not swapped: break else: print("Array Contains Only One Value: ", array) print("===========================") print("Sorted Array: ", array) if __name__ == '__main__': main()
a3fdb417a8f2824e5c271a09ff974081eb620715
rodneywells01/cmpsc483
/program_sample.py
965
3.65625
4
import substitutor import readin_real import relation_checker_utility import testing def run(verbose): # Validate integrity of data cache. relation_checker_utility.check(verbose) # Ask the user for input and substitute it into one simplified equation simplifiedequation = substitutor.Substitutor().finalEquation print("You provided the following equation: ") print(simplifiedequation) # Ask how many runs numruns = int(input("How many problems would you like for this equation?")) # Generate and display output. print("Original Equation:") print(simplifiedequation) print() print("Presenting " + str(numruns) + " word problems.") print() generator = testing.EnglishProblemGenerator(simplifiedequation) for run in range(numruns): print(str(run + 1) + ". " + generator.generate_problem_for_equation()) response = input("Verbose? Enter for no, any input for yes.") run(len(response) > 0)
22b6330b82b1011cad1739b9163e1f206a0bfb78
rodneywells01/cmpsc483
/readin_real.py
6,410
3.890625
4
### THIS IS THE OLD READIN FILE ### test input from the command line instead of using tests written into the code import sys import getopt ### get the options to only come up once all code has been input; until then, just read input code until first blank ### output should be a single string, each line separated by \n ### make it so user can put another line between existing lines def readin_real(): ### save each line of input to a list of lines, output them when the next input is an empty line ### print all previous lines before prompting for next line printIntro() response = input("Would you like to print the input requirements? Enter for no, any input for yes.\n") if len(response) > 0: printInputRequirements() ansFlag = False lines = [] intro = input("Enter the first line of code, or hit ENTER to quit:\n") if len(intro) == 0: return lines.append(intro) newline = 1; while newline > 0: next = input("Enter the next line of code followed by ENTER, or hit ENTER to finish:\n") newline = len(next) if len(next) != 0: lines.append(next) options(lines) ansFlag = answerCheck(lines) while not ansFlag: addedAnsLine = input("No \'ANS\' variable input, please add\n") lines.append(addedAnsLine) ansFlag = answerCheck(lines) printCodeInput(lines) confirm = input("\nConfirm? Enter for yes, any input for no.\n") while len(confirm) > 0: options(lines) confirm = input("\nConfirm? Enter for yes, any input for no.\n") return lines def options(lines): next = input( "Choose from the following options to continue.\n" + "1.\t add a new line\n" + "2.\t modify a previous line\n" + "3.\t delete a line\n" + "4.\t finish input\n") if next == "1": doread(lines) elif next == "2": modify(lines) elif next == "3": delete(lines) elif next == "4": return else: print(next + " is not an option.") options(lines) def doread(lines): next = input("Input next line of code:\n") lines.append(next) i = 0 while i < len(lines): print(lines[i]) i = i + 1 def delete(lines): print("Enter the number of the line you want to delete.") i = 0 while i < len(lines): print(str(i) + ".\t" + lines[i]) i = i + 1 print(str(i) + ".\tBACK TO OPTIONS") next = input("\n") if int(next) == i: return elif int(next) < len(lines): lines.remove(lines[int(next)]) print("Line " + next + " successfully deleted.\n") else: print(next + " is not an option.\n") delete(lines) def modify(lines): print("Enter the number of the line you want to modify.") i = 0 while i < len(lines): print(str(i) + ".\t" + lines[i]) i = i + 1 print(str(i) + ".\tBACK TO OPTIONS") next = input("\n") x = 0 while x < int(next): x = x + 1 if x == i: return elif x < len(lines): mod = input("Re-enter line " + next + " as you see fit.\n") lines.remove(lines[x]) if len(mod) != 0: lines.insert(x, mod) else: print("Line " + next + " deleted.\n") printCodeInput(lines) return else: print(next + " is not an option.\n") modify(lines) def printIntro(): print('-------------------------------------------------------------') print('# WELCOME TO THE #') print('# CSE NAT LANG TEAM #') print('# EQUATION TO WORD PROBLEM #') print('# GENERATION SYSTEM #') print('# #') print('# BY:RODNEY WELLS, ZACH MANNO, STEVE LASKY, JOSH MARINI #') print('-------------------------------------------------------------') def printInputRequirements(): print('-----------------------------------------------------------------------------------------') print("# INPUT REQUIREMENTS: #\ \n# All equation vars have lower case letters #\ \n# The final result must begin with the variable \"ANS\" #\ \n# Any equations that are unrelated to the \"ANS\" equation will be disregarded #\ \n# Any spaces and tabs are okay #\ \n# Variables should be 1 letter #\ \n# All macros are wrapped in brackets #\ \n-----------------------------------------------------------------------------------------\ \n# VALID INPUT EXAMPLE: #\ \n# #\ \n# x=5+y #\ \n# z = 6 # \ \n# ANS = z * x #\ \n# #\ \n# RESULT: #\ \n# (6)*(5+y) #\ \n--------------------------- \ \n# INVALID INPUT EXAMPLE: #\ \n# #\ \n# x=5+y #\ \n# z = 6 #\ \n# w = z * x #\ \n# # \ \n# (no ANS var) # \ \n--------------------------- \ \n# INVALID INPUT EXAMPLE: # \ \n# # \ \n# X=5+y #\ \n# Zeta = 6 #\ \n# white = Zeta * X #\ \n# # \ \n# (var names more # \ \n# than one letter) # \ \n--------------------------- \ ") def printCodeInput(lines): print("Your code input:\n") i = 0 while i < len(lines): print(str(i) + ".\t" + lines[i]) i = i + 1 def answerCheck(lines): for line in lines: if 'ANS' in line: return True return False
1d53b2f05934347b38ac937fa8138b659fd9519b
haalogen/hist_divider
/hist_divide.py
2,707
3.703125
4
""" This is a script for dividing the histogram of Grayscale image into N intervals ("shades of gray"), by the means of integral sums of the histogram. Idea: All intervals should have approximately equal integral sums. """ import sys import numpy as np import matplotlib.pyplot as plt from PIL import Image img_fname = sys.argv[1] # Image filename N = int(sys.argv[2]) # Wanted number of intervals fatal_msg = """ N must be less or equal than 128 !!! (or even 100) because often there are lots of shades that don't have pixels of that shade on the picture""" if N > 128: print fatal_msg sys.exit(1) # Output: array (of pairs) of shape (N, 2); # each pair: [left_margin, right_margin] intervals = np.zeros((N, 2)) # Open the image and convert to Grayscale img = Image.open(img_fname).convert('L') # RGB -> [0..255] # Color histogram of picture in Grayscale hist = img.histogram() # Algorithm # Calculate integral sums here full_sum = sum(hist) # Full integral sum (of the whole spectrum) real_sum = np.zeros(N) # Calculated (real) sums interval_sum = full_sum // N # Ideal integral sum of each interval # interval == [left_margin, right_margin] left_margin = 0 right_margin = 0 tmp_sum = 0 # Temporary sum interval_ind = 0 # Interval index: runs from 0 to N-1 # Integrate histogram until tmp_sum >= (interval_ind+1)*interval_sum # Then add margins of the new interval; # Continue process till the end of spectrum for right_margin in xrange(0, 256): # [0..255] tmp_sum += hist[right_margin] if tmp_sum >= (interval_ind+1) * interval_sum and interval_ind != N-1: # add margins of a new interval intervals[interval_ind, 0] = left_margin intervals[interval_ind, 1] = right_margin real_sum[interval_ind] = tmp_sum interval_ind += 1 left_margin = right_margin+1 # If the last interval wasn't filled, fill it with the rest of spectrum if interval_ind == N-1: # interval_ind normally runs 0 .. N-1 intervals[interval_ind, 0] = left_margin intervals[interval_ind, 1] = right_margin real_sum[interval_ind] = tmp_sum interval_ind += 1 # Plot the divided histogram colors = range(0, 256) # [0..255] plt.plot(colors, hist, 'b') # Plot histogram x = intervals.ravel() # Flatten intervals to 1D array (as a view) xmin, xmax, ymin, ymax = plt.axis() # limits of plot plt.vlines(x, ymin, ymax, colors='r') # Plot margins of intervals lbl = 'Histogram of image: ' + img_fname + \ '\n Number of intervals:' + str(N) plt.title(lbl) print 'Ideal sum:', interval_sum print 'Full sum:', full_sum print 'Real partial sums:\n', real_sum print 'Resulting intervals:\n', intervals plt.show()
2db313eb1c4cbe69bfb08827efc5b6dad5dfd4ce
kkwietniewski/Python
/hackerrank/day8DictMap copy.py
344
3.859375
4
n = int(input()) phoneBook = {} for i in range(n): name, phoneNumber = input().split() phoneBook[name] = phoneNumber enterName = input() while enterName: if enterName in phoneBook: print('{0}={1}'.format(enterName,phoneBook[enterName])) elif enterName not in phoneBook: print('Not found') enterName = input()
a6db01b0b21bd604d700e9f48ac3879493f631b7
kkwietniewski/Python
/kursUdemy/6_serching_sequences.py
525
3.71875
4
numList = [2,3,4,5,6,8,9,5,6] name = "arek" #wyszukaj a w name print('a' in name) #true print("Ilosc elementow: ",len(numList)) print("Najwiekszy element: ", max(numList)) print("Najmniejszy element: ", min(numList)) #funkcja list dzieli stringa na tablicę charów charTab = list("metallica") print(charTab,"\n") print(len(charTab)) #slice and replace charTab[5:] = " mania" print(charTab,"\n") charTab[5:] = list(" cure") print(charTab,"\n") #czyszczenie/usuwanie elementow charTab[:6] = [] print(charTab,"\n")
9f7349e4c4b68a17f696d9fe47c76a9317091329
conor1993/pythonDocs
/practicas/metodos diccionarios/diccionario.py
1,298
3.859375
4
#devuelbe una lista con todas las llaves del diccionario def llaves(): dic = {'1':'ola','2':'io'} yaves = dic.keys() print(yaves) #retorna una lista cobn todos los valores def valores(): dic = {'1':'ola','2':'io'} valoress = dic.values() print(valoress) #devuelbe una lista de tuplas def tuplas(): dic = {'1':'ola','2':'io'} tu = dic.items() print(tu) #saca un valor de el diccionario y lo almacena en una variable depues elimina ese elemnto del diccionario def sacar(): dic = {'1':'ola','2':'io'} valor = dic.pop('1') print(dic) print(valor) #retorna true si la llave se encuntra en el diccionario def buscar(): dic = {'1':'ola','2':'io'} if(dic.has_key('1')): print("si se encuantra") else: print("no se encuntra") #elimina todos los elemntos de la lista def elimina(): dic={1:'menos'} dic.clear() print(dic) #copia una lista def copia(): dic={1:'menos'} dic2 = dic.copy() print(dic2) def actualiza(): dic={1:'ola'} dic2={1:'olis',2:'olas'} dic.update(dic2) print(dic) #erroes captura de esepciones def erroresKey(): dic={1:'juan',2:'lugo'} try: print(dic[5]) except KeyError: print('error no existe')
8d7a1008bd093182a5ad8437ad6055be8bf6b314
rdiaz21129/python3_for_network_engineers
/ready/windowsMac_to_ciscoMac.py
1,513
4.09375
4
import re # By: Ricardo Diaz # Update: 20171223 # File: windowsMac_to_ciscoMac.py # Python 3.6 # Prompt the user to enter a windows format mac address | D8-FC-93-7B-67-7C | Ricardo Wireless mac address print ("\n" + "===" * 4) userWindowsMacAdd = input("Enter Windows MAC address to convert to a Cisco MAC address format\nExample: A1-B2-C3-D4-E5-F6 should be a1b2.c3d4.e5f6\nMac address: ") print ("===" * 4) # Explaining what the program will do print("\nConverting [" + userWindowsMacAdd + "] into a cisco mac address format. (example: abcd.eff1.42ab)") # Windows Mac address to Regex output RegWindowsMacAdd = (re.findall(r'[0-9,A-Z,a-z].',userWindowsMacAdd)) # Printing the regex output (in an array/list) print(RegWindowsMacAdd) # Converting Regex output [RegWindowsMacAdd] into lowercase string so we can later slice the 12 characters into 3 parts str_winRegMacAdd = "".join(RegWindowsMacAdd) print ("\nConverting Regex output [RegWindowsMacAdd] into lowercase string\nLowercase mac address: " + str_winRegMacAdd.lower()) # Create variables for each individual group (i.e mac add = 1234.5678.90ab | 1234 - group 1 | 5678 - group 2 |.. etc ) mac_group_1 = (str_winRegMacAdd[:4].lower()) mac_group_2 = (str_winRegMacAdd[4:8].lower()) mac_group_3 = (str_winRegMacAdd[8:12].lower()) # Putting it all together by connecting the mac address groups with a "." print ("\n" + "===" * 4) print("Below is the Cisco MAC address format") print (mac_group_1 + "." + mac_group_2 + "." + mac_group_3) print ("===" * 4)
eb1a3b4a62c74a8d53416c6e5a5f48a2ab4c2e67
yaroslavche/python_learn
/1 week/1.12.5.py
1,034
4.15625
4
# Напишите программу, которая получает на вход три целых числа, по одному числу в строке, и выводит на консоль в три # строки сначала максимальное, потом минимальное, после чего оставшееся число. # На ввод могут подаваться и повторяющиеся числа. # Sample Input 1: # 8 # 2 # 14 # Sample Output 1: # 14 # 2 # 8 # Sample Input 2: # 23 # 23 # 21 # Sample Output 2: # 23 # 21 # 23 a = int(input()) b = int(input()) c = int(input()) if a >= b and a >= c: max = a if b > c: min = c rest = b else: min = b rest = c elif b >= a and b >= c: max = b if a > c: min = c rest = a else: min = a rest = c elif c >= a and c >= b: max = c if a > b: min = b rest = a else: min = a rest = b print(max) print(min) print(rest)
208303bdec3be5362ce314eb632da444fed96f2c
yaroslavche/python_learn
/2 week/2.1.11.py
504
4.21875
4
# Напишите программу, которая считывает со стандартного ввода целые числа, по одному числу в строке, и после первого # введенного нуля выводит сумму полученных на вход чисел. # Sample Input 1: # 5 # -3 # 8 # 4 # 0 # Sample Output 1: # 14 # Sample Input 2: # 0 # Sample Output 2: # 0 s = 0 i = int(input()) while i != 0: s += i i = int(input()) print(s)
f86c962844036de4cd97aca448e3b59e1fa294c1
yaroslavche/python_learn
/2 week/2.6.8.py
923
3.703125
4
# Напишите программу, которая выводит часть последовательности 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ... (число повторяется # столько раз, чему равно). На вход программе передаётся неотрицательное целое число n — столько элементов # последовательности должна отобразить программа. На выходе ожидается последовательность чисел, записанных через # пробел в одну строку. # Например, если n = 7, то программа должна вывести 1 2 2 3 3 3 4. # Sample Input: # 7 # Sample Output: # 1 2 2 3 3 3 4 n = int(input()) a = 1 ac = 1 while n > 0: print(a, end=' ') ac -= 1 if ac == 0: a += 1 ac = a n -= 1
f5cd77591c358dbec25bc14314585e9cd229c06f
No-Way-Jose/utsc-tree-project
/UofTScrape.py
4,590
3.546875
4
import requests import urllib from SQL import * from bs4 import BeautifulSoup def ScrapeUTSC(url): """ Function which will scrape the UTSC course website and store all the needed information into a database """ # Connect to the main page response = requests.get(url) document = BeautifulSoup(response.text, "html.parser") # Database location database = "/Users/riceboy/RiceBoy Documents/UTSC Course Tree/UtscCourses.db" # Create the db connection connection = createConnection(database) # Wipe the data wipeData(connection) # Lists to hold all the values base = "https://utsc.calendar.utoronto.ca/list-of-courses" courseAlpha = [] coursesList = [] # Get list of courses starting with *** first letter alphaDoc = (document.find("div", {"id": "alpha"})) for link in alphaDoc.find_all('a'): # List that holds the URL to the different Letters for each course courseAlpha.append(urllib.parse.urljoin(base, link.get("href"))) sections = urllib.parse.urljoin(base, link.get("href")) # Insert the sections into the database with connection: sectionID = insertSection(connection, sections) # Connect to the page alphaPage = requests.get(urllib.parse.urljoin(base, link.get("href"))) letterDoc = BeautifulSoup(alphaPage.text, "html.parser") # List to store the subsect IDs subSecIDs = [] # Loop to get all the subsection headers and required values for subHeading in letterDoc.find_all("h3", {"class": "views-accordion-list_of_courses-page-header"}): subSection = (subHeading.get_text().strip()) # Insert the subsection into the db with connection: subSectionID = insertSubSection(connection, sectionID, subSection) # Store the IDs for the subsections subSecIDs.append(subSectionID) # Variables to use to determine when to switch to the next subdirectory ID value oldSection = "" subSectID = 0 # Get each course section for the given Letter for course in letterDoc.find_all("div", {"class": "views-field views-field-field-course-title"}): courseURL = (urllib.parse.urljoin(base, (course.find(href=True)).get("href"))) coursesList.append(urllib.parse.urljoin(base, (course.find(href=True)).get("href"))) # Connect to the page and scrape the info for the course coursePage = requests.get(courseURL) courseDoc = BeautifulSoup(coursePage.text, "html.parser") courseName = ((courseDoc.find('h1')).get_text().strip()) # Get the first 2 letters of course so we can determine when to switch subdirectory ID nextSection = courseName[:2] # List to hold the exclusion, preqreq information TITLES info = {"Course Description:": "N/A", "Prerequisite:": "N/A", "Exclusion:": "N/A", "Enrolment Limits:": "N/A", "Breadth Requirements:": "N/A"} titles = ["Course Description:"] # Fill the list with the course information that is present for the course for title in (courseDoc.find_all("div", {"class": "field-label"})): titles.append(title.get_text().strip()) titles.append("Link:") # Insert the exclusion, preqreq information VALUES into the dict if present for detail in (courseDoc.find("div", {"class": "content clearfix"}).find_all("div", {"class": "field-item even"})): info[titles.pop(0)] = (detail.get_text().strip().replace("\n", " ")) # Check if we should move to the next subsection ID *Languages and Linguistics if oldSection != nextSection and nextSection != "PL" and nextSection != "LG": # Pop off the next sub ID and set the variable to it for insertion subSectID = subSecIDs.pop(0) with connection: # Insert into the database insertCourse(connection, subSectID, sectionID, courseURL, courseName, info.get("Course Description:"), info.get("Prerequisite:"), info.get("Exclusion:"), info.get("Enrolment Limits:"), info.get("Breadth Requirements:")) # Update the old section oldSection = nextSection # Close the connection endConnection(connection) # Call for the scrape ScrapeUTSC("https://utsc.calendar.utoronto.ca/list-of-courses/a")
8674d8f7e11eae360e63b470b7b2310f7170c5cc
zeusumit/JenkinsProject
/hello.py
1,348
4.40625
4
print('Hello') print("Hello") print() print('This is an example of "Single and double"') print("This is an example of 'Single and double'") print("This is an example of \"Single and double\"") seperator='***'*5 fruit="apple" print(fruit) print(fruit[0]) print(fruit[3]) fruit_len=len(fruit) print(fruit_len) print(len(fruit)) print(fruit.upper()) print('My'+''+'name'+''+'is'+''+'Sumit') print('My name is Sumit') first='sumit' second="Kumar" print(first+second) print(first+''+second) print(first+' '+second) fullname=first+' '+second print(fullname) print(fullname.upper()) print(first[0].upper()) print(first[0].upper()+first[1].lower()) print('-'*10) happiness='happy '*3 print(happiness) age=37 print(first.upper()+"'"+'s'+' age is: '+str(age)) print(seperator+'Formatting Strings'+seperator) print('My name is: {}'.format(first)) print('My name is: {}'.format(first.upper())) print('{} is my name'.format(first)) print('My name is {0} {1}. {1} {0} is my name'.format('Sumit', 'Kumar')) print('My name is {0} {1}. {1} {0} is my name'.format(first, second)) print('{0:8} | {1:8}'. format(first, second)) print('{0:8} | {1:0}'. format('Age', age)) print('{0:8} | {1:8}'. format('Height', '6 feet')) print('{0:8} | {1:0} {2:1}'. format('Weight', 70,'kgs')) print(seperator+'User input'+seperator)
f19cb40a5e8a1eca039f65fe1f96601e6a5cec73
codingclubrvce/ML_Workshop_CC
/matplotlib.py
715
3.59375
4
from matplotlib import pyplot as plt plt.plot([1,2,3],[4,5,1]) plt.show() x = [5,2,7] y = [2,16,4] plt.plot(x,y) plt.show() #Bargraph from matplotlib import pyplot as plt plt.bar([0.25,1.25,2.25],[50,40,70], label="B1",width=.5) plt.bar([.75,1.75,2.75],[80,20,20], label="B2", color='r',width=.5) plt.legend() plt.xlabel('x') plt.ylabel('y') plt.title('Test bargraph') plt.show() #scatter plot from matplotlib import pyplot as plt x = [1,1.5,2,2.5,3,3.5,3.6] y = [7.5,8,8.5,9,9.5,10,10.5] x1=[8,8.5,9,9.5,10,10.5,11] y1=[3,3.5,3.7,4,4.5,5,5.2] plt.scatter(x,y, label='+-',color='r') plt.scatter(x1,y1,label='-+',color='b') plt.xlabel('x') plt.ylabel('y') plt.title('Scatter Plot') plt.legend() plt.show()
f81309928a1891a4947a62cb73a147b177463e78
francomattos/memory-paging-python
/Paging.py
4,994
3.625
4
# The list of program words requested by program wordBank = [10, 11, 104, 170, 73, 309, 185, 245, 246, 434, 458] # Make a class for the paging system because why not class PagingCounter: # Initializes variables for the program def __init__(self, _memSize, _pageSize): self.memSize = _memSize self.pageSize = _pageSize self.pageBank = [] # This function checks if word is in memory, if not uses queue method to load page to memory def toMemory(self, wordVal): # This gives page number as per instructions self.pageLocation = int(wordVal / self.pageSize) # Return true if already loaded in memory, false if not if self.pageLocation in self.pageBank: return True else: if len(self.pageBank) < (self.memSize/self.pageSize): self.pageBank.append(self.pageLocation) return False else: self.pageBank.pop(0) self.pageBank.append(self.pageLocation) return False # This function initializes the paging process for a given scenario and return counter def initPaging(self): successCounter = 0 for i in wordBank: if self.toMemory(i): successCounter += 1 return successCounter # Starts making the requests and printing the findings. print("a.) Find the success frequency for the request list using a FIFO replacement Algorithm and a page size of 100 words (there are two page frames).") page1 = PagingCounter(200, 100) answer = page1.initPaging() print("The success frequency is: " + str(answer) + ".\n") print("b.) Find the success frequency for the request list using a FIFO replacement Algorithm and a page size of 20 words (10 pages, 0 through 9).") page2 = PagingCounter(200, 20) answer = page2.initPaging() print("The success frequency is: " + str(answer) + ".\n") print("c.) Find the success frequency for the request list using a FIFO replacement Algorithm and a page size of 200 words.") page3 = PagingCounter(200, 200) answer = page3.initPaging() print("The success frequency is: " + str(answer) + ".\n") print("d.) What do your results indicator ''Can you make any general statements about what happens when page sizes are halved or doubled?") print("There could be a general statement which indicates that when the page size is halved the success rate decreases, and when it is doubled it increases.\n") print("e.) Are there any overriding advantages in using smaller pages? What are the offsetting factors? Remember that transferring 200 words of information \n" + "takes less than twice as long as transferring 100 words because of the way secondary storage devices operate (the transfer rate is higher than the access, \n" + "or search/find, rate).") print("Using smaller pages means that a program takes less space in memory, so memory usage is more efficient. The offsetting factor of using smaller pages is that the \n" + "success frequency decreases, so the program needs to itself into memory more often making the overall procedure slower. \n") print("f.) Repeat (a) through (c) above, using a main memory of 400 words. The size of each page frame will again correspond to the size of the page.") page4 = PagingCounter(400, 100) answer = page4.initPaging() print("The success frequency for memory size 400 and page size 100 is: " + str(answer)) page5 = PagingCounter(400, 20) answer = page5.initPaging() print("The success frequency for memory size 400 and page size 20 is: " + str(answer)) page6 = PagingCounter(400, 200) answer = page6.initPaging() print("The success frequency for memory size 400 and page size 200 is: " + str(answer) + ".\n") print("g.) What happened when more memory was given to the program? Can you make some general statements about this occurrence?" + "What changes might you expect to see if the request list was much longer, as it would be in real life?") print("More memory given to the system means that larger page sizes can be utilized and the success rate would increase for larger programs.\n") print("h.) Could this request list happen during the execution of a real program? Explain.") print("It would be extremely unlikely for this execution to happen in a real program, real programs tend to run in sequential order, " + "which this program is not doing, specially the segment '170,73,309,185,245'. But while unlikely, it is possible for this execution order " + "to happen in a program due to the flexible nature of computer programming. \n") print("i.) Would you expect the success rate of an actual program under similar conditions to be higher or lower than the one in this problem?") print("The success rate of a real program would be higher in the same memory and page size scenarios given. This is due to programs being " + "sequention in nature as explained above \n \n") input("Press any key to close...")
6e75ff6820fd9bb69601af4b6cdc72c3f44ca3b6
dillondesilva/Ronie
/bot_code.py
3,808
3.578125
4
from microbit import * import neopixel import radio ANALOG_MAX = 1023 LIGHT_STATE = True MOTOR_STATE = True radio.on() radio.config(channel=18) # Converting values into a valid int between # 0-1023 for valid analog signals def to_analog(value): global ANALOG_MAX analog_val = int(value * ANALOG_MAX) return analog_val # Checking that the user has entered a valid # speed before we can set the motors to that # speed. Raises an error if invalid speed is entered def check_speed(speed): if speed < 0 or speed > 1: raise ValueError('Invalid speed value for motors') # Class for controlling Bit:bot motors class Motors: # accelerate() moves the Bit:bot forward at a speed # set by the user. The speed must be between 0 - 1 def accelerate(self, speed): # Setting our bit:bot motors direction # to go forwards before sending it forwards pin8.write_digital(0) pin12.write_digital(0) # Checking that the user has entered a valid # speed before we can set the motors to that # speed check_speed(speed) analog_val = to_analog(speed) pin0.write_analog(analog_val) pin1.write_analog(analog_val) # Halting to a complete stop def stop(self): # Setting our bit:bot motors direction # to go forwards before stopping by default pin8.write_digital(0) pin12.write_digital(0) pin0.write_digital(0) pin1.write_digital(0) # spin_left() spins the Bit:bot left at a certain speed def spin_left(self, speed): check_speed(speed) analog_val = to_analog(speed) pin0.write_digital(0) pin1.write_analog(analog_val) # spin_right() spins the Bit:bot right at a certain speed def spin_right(self, speed): check_speed(speed) analog_val = to_analog(speed) pin0.write_analog(analog_val) pin1.write_digital(0) # reverse() will reverse the bit:bot at a # certain speed def reverse(self, speed): check_speed(speed) analog_val = ANALOG_MAX - to_analog(speed) # Setting our bit:bot motors direction # to go backwards before sending it backwards pin8.write_digital(1) pin12.write_digital(1) pin0.write_analog(analog_val) pin1.write_analog(analog_val) # Class for dealing with Line following class Line: # detecting whether on a line on right sensor # return true if on line otherwise false def is_right_line(self): right_ln_val = not bool(pin5.read_digital()) return right_ln_val # detecting whether on a line on left sensor # return true if on line otherwise false def is_left_line(self): left_ln_val = not bool(pin11.read_digital()) return left_ln_val class Light: def get_light_val(self): light_val = pin2.read_digital() print(light_val) m = Motors() m.spin_left(0.3) display.show(Image.GHOST) neopixels = neopixel.NeoPixel(pin13, 12) def lights_on(): for n in range(12): neopixels[n] = (255, 255, 255) neopixels.show() lights_on() while True: msg = radio.receive() if msg == 'togglelight': if LIGHT_STATE: neopixels.clear() neopixels.show() else: lights_on() display.show(Image.GHOST) LIGHT_STATE = not LIGHT_STATE if msg == 'togglemovement': print('ya') if MOTOR_STATE: print('stage hit') m.stop() else: m.spin_left(0.3) MOTOR_STATE = not MOTOR_STATE
929aa885ffb601853b6cbc8d0af7b8b66df58919
effepivi/EGUK-authorship-viz
/src/python/csv2SQLlight.py
9,090
3.890625
4
#!/usr/bin/env python3 import sys import math import pandas as pd import sqlite3 from sqlite3 import Error SQL_CREATE_CONFERENCES_TABLE = """ CREATE TABLE IF NOT EXISTS conferences ( id integer PRIMARY KEY, year integer NOT NULL, full_name text NOT NULL, short_name text NOT NULL, address text ); """ SQL_CREATE_AUTHORS_TABLE = """ CREATE TABLE IF NOT EXISTS authors ( id integer PRIMARY KEY, fullname text NOT NULL, firstnames text NOT NULL ); """ SQL_CREATE_ARTICLES_TABLE = """ CREATE TABLE IF NOT EXISTS articles ( id integer PRIMARY KEY, bibtex_id text, conference_id integer NOT NULL, title text NOT NULL, doi, first_page integer, last_page integer, FOREIGN KEY (conference_id) REFERENCES conferences (id) ); """ SQL_CREATE_AUTHORSHIP_TABLE = """ CREATE TABLE IF NOT EXISTS authorship ( author_id integer NOT NULL , paper_id integer NOT NULL, PRIMARY KEY(author_id,paper_id), FOREIGN KEY (author_id) REFERENCES authors (id), FOREIGN KEY (paper_id) REFERENCES articles (bibtex_id) ); """ def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return conn def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print("Cannot create the table using this request: \n", create_table_sql) print(e) def create_conference(conn, conference, year, address = ""): """ Create a new conference :param conn: Connection object :param conference: Conference :return: id of last row """ temp_len = len('"Theory and Practice of Computer Graphics'); if conference == '"EG UK Theory and Practice of Computer Graphics"': full_name = "Theory and Practice of Computer Graphics"; short_name = "TPCG"; elif conference[:temp_len] == '"Theory and Practice of Computer Graphics': full_name = "Theory and Practice of Computer Graphics"; short_name = "TPCG"; elif conference == '"Computer Graphics and Visual Computing (CGVC)"': full_name = "Computer Graphics and Visual Computing"; short_name = "CGVC"; else: full_name = conference; short_name = "unknown"; record = (int(year), full_name, short_name, address); sql = ''' INSERT INTO conferences(year,full_name,short_name,address) VALUES(?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, record); return cur.lastrowid def create_article(conn, article): """ bibtex_id text , conference_id integer NOT NULL, title text NOT NULL, """ global id_of_first_author_column; bibtex_id = ""; year = article['"Year"']; title = article['"Title"']; doi = article['"DOI"']; pages = article['"pages"']; if pages == '""': first_page = -1; last_page = -1; else: temp = pages.replace('"', '').split("-"); first_page = int(temp[0]); last_page = int(temp[1]); first_page = first_page; last_page = last_page; conference_id = get_conference_id(conn, year); record = (bibtex_id, conference_id, title,doi,first_page,last_page); sql = ''' INSERT INTO articles(bibtex_id,conference_id,title,doi,first_page,last_page) VALUES(?,?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, record); article_id = cur.lastrowid; # Add all the authors # Look for columns of authors for i in range(article['"Number of authours"']): fullname = article[id_of_first_author_column + i]; author_id = get_author_id(conn, fullname); create_authorship(conn, author_id, article_id); def create_authorship(conn, author_id, paper_id): """ author_id integer NOT NULL , paper_id integer NOT NULL, """ record = (author_id, paper_id); sql = ''' INSERT INTO authorship(author_id, paper_id) VALUES(?,?) ''' cur = conn.cursor() cur.execute(sql, record); def get_conference_id(conn, year): """ Query all rows in the conferences table :param conn: the Connection object :param year: the year of the conference :return: cnference_id """ cur = conn.cursor() query = "SELECT id FROM conferences where year=" + str(year); cur.execute(query) rows = cur.fetchall() return rows[0][0]; def get_author_id(conn, fullname): """ Query all rows in the conferences table :param conn: the Connection object :param fullname: the author's fullname :return: cnference_id """ cur = conn.cursor() query = "SELECT id FROM authors where fullname=\"" + fullname + "\""; cur.execute(query) rows = cur.fetchall() return rows[0][0]; def create_author(conn, name): """ Create a new conference :param conn: the Connection object :param name: the Author's fullname :return: id of last row """ record = (name, ""); #print ("ADD: ", record); sql = ''' INSERT INTO authors(fullname, firstnames) VALUES(?,?) ''' cur = conn.cursor() cur.execute(sql, record); return cur.lastrowid def author_exist(conn, name): """ Query all rows in the authors table :param conn: the Connection object :param name: the Author's fullname :return: True if the author exists in the table, false otherwise """ cur = conn.cursor() query = "SELECT COUNT(ID) FROM authors where fullname=" + "\"" + name + "\""; cur.execute(query) rows = cur.fetchall() return rows[0][0]; id_of_first_author_column = 0; def main(): global id_of_first_author_column; if len(sys.argv) is not 3: print("Usage: ", sys.argv[0], " input.csv output.db"); else: csv_file_name = sys.argv[1]; db_file_name = sys.argv[2]; # create a database connection conn = create_connection(db_file_name); # Create the tables if conn is not None: # Create conferences table create_table(conn, SQL_CREATE_CONFERENCES_TABLE); # Create authors table create_table(conn, SQL_CREATE_AUTHORS_TABLE); # Create articles table create_table(conn, SQL_CREATE_ARTICLES_TABLE); # Create authorship table create_table(conn, SQL_CREATE_AUTHORSHIP_TABLE); # Open the CSV file df = pd.read_csv(csv_file_name); # Get all the unique combination of "Year" and "Booktitle" year_book_title_combination = df.groupby(['"Year"','"Booktitle"']); # For all combination, add a new conference for name,group in year_book_title_combination: if name[1] != '"Table of Contents and Preface"': create_conference(conn, name[1], name[0]); id_of_first_author_column = 0; # Look for columns of authors column_index = 0; for column in df: # The column is a column of authors if column[:9] == '"author #': if id_of_first_author_column == 0: id_of_first_author_column = column_index; row_is_nan = df[column].isna(); for author, is_nan in zip(df[column], row_is_nan): if not is_nan: if not author_exist(conn, author): create_author(conn, author); column_index += 1; # Add every article for index, row in df.iterrows(): create_article(conn, row); # Make sure the data is stored conn.commit(); else: print("Error! cannot create the database connection.") if __name__ == '__main__': main()
991d4eebea421257574792017851c8d0948089a8
nkibbey/word2vecTemporal
/analysis/w2vTools.py
968
4.09375
4
#!/usr/bin/python import psycopg2 import sys import pprint def main(): #Define our connection string conn_string = "host='localhost' dbname='w2vdb' user='pyfun' password='fun'" # print the connection string we will use to connect print "Connecting to database\n ->%s" % (conn_string) # get a connection, if a connect cannot be made an exception will be raised here conn = psycopg2.connect(conn_string) # conn.cursor will return a cursor object, you can use this cursor to perform queries cursor = conn.cursor() print "Connected!\n" cursor.execute("SELECT * FROM my_table") # retrieve the records from the database records = cursor.fetchall() # print out the records using pretty print # note that the NAMES of the columns are not shown, instead just indexes. # for most people this isn't very useful so we'll show you how to return # columns as a dictionary (hash) in the next example. pprint.pprint(records) if __name__ == "__main__": main()
73d9618599379392ec67c264eff125ea19627767
Dhruvisha100/Work__Assignments
/Heuristics.py
419
3.953125
4
import random print("#---------------#\n|GUESS THE NUMBER|\n#---------------#\n") print("Range of random numbers.\n") start = int(input("start no:")) end = int(input("end no:")) n = random.randint(start,end) print("\n") while True: g = int(input("no:")) if g>n: print("try a lower no. ") elif g<n: print("go a little higher ") else: print("right on! well done!")
aa8a0f6810c2746d0db5ab0bd6e8c03d3dd6ceb8
ache167/lesson003
/03_division.py
830
3.96875
4
# -*- coding: utf-8 -*- # (цикл while) # даны целые положительные числа a и b (a > b) # Определить результат целочисленного деления a на b, с помощью цикла while, # __НЕ__ используя стандартную операцию целочисленного деления (// и %) # Формат вывода: # Целочисленное деление ХХХ на YYY дает ZZZ a, b = 179, 37 temp = a res = 0 while temp >= 0: temp -= b res += 1 else: # subtracting from res the last addition as temp becomes negative # (done for efficiency - not checking if temp became negative for every iteration of the loop) res -= 1 print("Целочисленное деление", a, "на", b, "дает", res)
01f481eef5cf6005afb5651f1ee089d3500b428e
d222nguy/DSA
/week6/hw6.py
2,015
3.8125
4
from collections import Counter def getShortestSubstrOfAllChar(S, T): '''get shortest substring of all char. If there are multiple substrings with same length, return the leftmost one. Time Complexity: O(max(N, M)) where N = length of S and M = length of T (in case O(N) < O(M) the time complexity is strictly O(N), it does not depend on the size of the alphabet |A|). Auxiliary Space: O(|A|) where |A| = the number of different characters in T''' #first, build a set of all chars in T setT = set(T) #Two pointers at the ends of the substring i, j = 0, 0 #A HashMap (key, val) where key = character, val = frequency d = {} #Keep track of current optima optval, opt = float('inf'), None while i < len(S) and j < len(S): while j < len(S) and len(d) < len(setT): #not enough if S[j] in setT: #only care if S[j] is in T d[S[j]] = d.get(S[j], 0) + 1 j += 1 while i < len(S) and len(d) == len(setT): if optval > j - i + 1: optval = j - i + 1 opt = (i, j) if S[i] in setT: #only care if S[j] is in T d[S[i]] -= 1 if d[S[i]] == 0: del d[S[i]] i += 1 while i > j: j += 1 if not opt: res = -1 else: res = S[opt[0]: opt[1]] print(res) return res def main(): getShortestSubstrOfAllChar("xyyzyzyx", "xyz") #zyx getShortestSubstrOfAllChar("xyyzyzyx", "xy") #xy getShortestSubstrOfAllChar("xyyzyzyx", "xyzt") #-1: No window found! getShortestSubstrOfAllChar("xyyzyzyx", "z") #z getShortestSubstrOfAllChar("xyyzyzyyx", "xyz") #xyyz getShortestSubstrOfAllChar("abc", "x") #-1 getShortestSubstrOfAllChar("aaaaaaa", "aaaaa") #a getShortestSubstrOfAllChar("aaaaaaaccccccb", "ab") #accccccb getShortestSubstrOfAllChar("aaaaaaa@!", "a!t") #-1 getShortestSubstrOfAllChar("t aaaaaaa@@! z", "a!t") #t aaaaaaa@@! main()
4e6dac2be8094795716e7abd6866dd5ffc2c177d
Hassan-Shakeri/Face-Smile_Detector
/Smile-detector.py
1,811
3.53125
4
import cv2 #load some pre-trained data on face frontals from opencv #load some pre-trained data on smile from opencv trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') trained_smile_data = cv2.CascadeClassifier('haarcascade_smile.xml') #cpture video from webcame webcam = cv2.VideoCapture(0) #interact forever over frames while True: #read the current frame successful_frame_read, frame = webcam.read() #if there is an error abort if not successful_frame_read: break #convert to grayscale grayscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #detect faces face_cordinates = trained_face_data.detectMultiScale(grayscaled_img) #run face detection within each face for (x, y, w, h) in face_cordinates: #draw rectangles around the face cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255,0), 3) #get the sub frame (using numpy N-dimentional array slicing) the_face = frame[y:y+h, x:x+w] #change to grayscale face_grayscale = cv2.cvtColor(the_face, cv2.COLOR_BGR2GRAY) smiles = trained_smile_data.detectMultiScale(face_grayscale, scaleFactor=1.7, minNeighbors=20) #find all the smiles in the face #for (x_,y_,w_,h_) in smiles: #draw a rectangle around the smile #cv2.rectangle(the_face, (x_, y_), (x_ + w_,y_ + h_), (0,0,255), 3) #label the face as smiling if len(smiles) > 0: cv2.putText(frame, 'Smiling...', (x,y+h+40), fontScale= 3, fontFace=cv2.FONT_HERSHEY_PLAIN, color=(255,255,255)) #show the current frame cv2.imshow("Hassan's face-detector app", frame) key = cv2.waitKey(1) #stop if Q is pressed (using asciii number) if key==81 or key==113: break #release the video capture object webcam.release() cv2.destroyAllWindows print("Code Completed")
6d39da94c8634cbbe8f1948d5163c3a83fbfd066
EderVs/hacker-rank
/algorithms/implementation/service_lane.py
236
3.703125
4
""" Service Lane """ n,t = map(int, raw_input().split()) width = raw_input().split() for x in range(t): i,j = map(int, raw_input().split()) vehicle = 3 for y in range(i, j + 1): vehicle = min(int(width[y]), vehicle) print vehicle
d9181d5a66f0b8a86efe112cb1f38e6c649ad749
EderVs/hacker-rank
/algorithms/graph_theory/breadth_first_search_shortest_reach.py
1,966
3.890625
4
""" Breadth First Search: Shortest Reach """ class Node: def __init__(self, element, level=-1): self.element = element self.neighbors = set() self.level = level def add_neighbor(self, neighbor): self.neighbors.add(neighbor) def __repr__(self): return str(self.element) + " " + str(self.level) class Graph: def __init__(self, elements=[]): self.elements = {} for element in elements: new = Node(element) self.elements[element] = new def add_element(self, element): new = Node(element) self.elements[element] = new def add_edge(self, element1, element2): self.elements[element1].neighbors.add(self.elements[element2]) self.elements[element2].neighbors.add(self.elements[element1]) def bfs_element(self, start): # Setting all nodes to distance to -1 for element in self.elements.values(): element.level = -1 self.elements[start].level = 0 queue = [self.elements[start]] while queue != []: current_node = queue.pop(0) for neighbor in current_node.neighbors: if neighbor.level == -1 or neighbor.level > current_node.level + 1: neighbor.level = current_node.level + 1 queue.append(neighbor) t = int(input()) for _ in range(t): n, m = list(map(int, input().split())) g = Graph(list(range(1, n+1))) for _ in range(m): u, v = list(map(int, input().split())) g.add_edge(u, v) i = int(input()) g.bfs_element(i) to_print = [] for element in g.elements.keys(): if g.elements[element].element == i: continue if g.elements[element].level == -1: to_print.append(str(g.elements[element].level)) continue to_print.append(str(g.elements[element].level*6)) print(" ".join(to_print))
807ebac26abb25e82b6cc5d25dfa0fcb57265363
EderVs/hacker-rank
/30_days_of_code/day_23.py
1,406
3.71875
4
import sys class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root def levelOrder(self,root): n = 0 level_order = [] flag = True while flag: current_level = self.getLevel(root,n) if current_level == []: to_print = ' '.join(map(str, level_order)) print to_print flag = False level_order += current_level n += 1 def getLevel(self, root, n): if n == 0: if root != None: return [root.data] else: return [] else: data_level = [] if root.left != None: data_level += self.getLevel(root.left, n-1) if root.right != None: data_level += self.getLevel(root.right, n-1) return data_level T=int(raw_input()) myTree=Solution() root=None for i in range(T): data=int(raw_input()) root=myTree.insert(root,data) myTree.levelOrder(root)
33553f9506dc46c9c05101074116c5254af7d0e9
EderVs/hacker-rank
/30_days_of_code/day_8.py
311
4.125
4
""" Day 8: Dictionaries and Maps! """ n = input() phones_dict = {} for i in range(n): name = raw_input() phone = raw_input() phones_dict[name] = phone for i in range(n): name = raw_input() phone = phones_dict.get(name, "Not found") if phone != "Not found": print name + "=" + phone else: print phone
6784ec88c6088dfcd462a124bc657be9a4c51c3c
asmitaborude/21-Days-Programming-Challenge-ACES
/generator.py
1,177
4.34375
4
# A simple generator function def my_gen(): n = 1 print('This is printed first') # Generator function contains yield statements yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n # Using for loop for item in my_gen(): print(item) #Python generator using loops def rev_str(my_str): length = len(my_str) for i in range(length - 1, -1, -1): yield my_str[i] # For loop to reverse the string for char in rev_str("hello"): print(char) #python generator expression # Initialize the list my_list = [1, 3, 6, 10] # square each term using list comprehension list_ = [x**2 for x in my_list] # same thing can be done using a generator expression # generator expressions are surrounded by parenthesis () generator = (x**2 for x in my_list) print(list_) print(generator) #pipeline generator def fibonacci_numbers(nums): x, y = 0, 1 for _ in range(nums): x, y = y, x+y yield x def square(nums): for num in nums: yield num**2 print(sum(square(fibonacci_numbers(10))))
46a7b9c9a436f4620dac591ed193a09c9b164478
asmitaborude/21-Days-Programming-Challenge-ACES
/python_set.py
2,244
4.65625
5
# Different types of sets in Python # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) # set cannot have duplicates # Output: {1, 2, 3, 4} my_set = {1, 2, 3, 4, 3, 2} print(my_set) # we can make set from a list # Output: {1, 2, 3} my_set = set([1, 2, 3, 2]) print(my_set) # Distinguish set and dictionary while creating empty set # initialize a with {} a = {} # check data type of a print(type(a)) # initialize a with set() a = set() # check data type of a print(type(a)) # initialize my_set my_set = {1, 3} print(my_set) #if you uncomment the line below you will get an error # my_set[0] # add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) # add multiple elements # Output: {1, 2, 3, 4} my_set.update([2, 3, 4]) print(my_set) # add list and set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4, 5], {1, 6, 8}) print(my_set) # Difference between discard() and remove() # initialize my_set my_set = {1, 3, 4, 5, 6} print(my_set) # discard an element # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # remove an element # Output: {1, 3, 5} my_set.remove(6) print(my_set) # Output: {1, 3, 5} my_set.discard(2) print(my_set) # initialize my_set # Output: set of unique elements my_set = set("HelloWorld") print(my_set) # pop an element # Output: random element print(my_set.pop()) # pop another element my_set.pop() print(my_set) # clear my_set # Output: set() my_set.clear() print(my_set) print(my_set) # Set union method # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B) # Intersection of sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use & operator # Output: {4, 5} print(A & B) # Difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A # Output: {1, 2, 3} print(A - B) # Symmetric difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use ^ operator # Output: {1, 2, 3, 6, 7, 8} print(A ^ B)
1a87238ebb8b333148d1c2b4b094370f21fd230b
asmitaborude/21-Days-Programming-Challenge-ACES
/listsort.py
677
4.4375
4
#python list sort () #example 1:Sort a given list # vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort() # print vowels print('Sorted list:', vowels) #Example 2: Sort the list in Descending order # vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort(reverse=True) # print vowels print('Sorted list (in Descending):', vowels) #Example 3: Sort the list using key # take second element for sort def takeSecond(elem): return elem[1] # random list random = [(2, 2), (3, 4), (4, 1), (1, 3)] # sort list with key random.sort(key=takeSecond) # print list print('Sorted list:', random)
6346a452b77b895e2e686c5846553687459798ca
asmitaborude/21-Days-Programming-Challenge-ACES
/dictionary.py
2,840
4.375
4
#Creating Python Dictionary # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')]) #Accessing Elements from Dictionary # get vs [] for retrieving elements my_dict = {'name': 'Jack', 'age': 26} # Output: Jack print(my_dict['name']) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError #print(my_dict['address']) #Changing and Adding Dictionary elements # Changing and adding Dictionary Elements my_dict = {'name': 'Jack', 'age': 26} # update value my_dict['age'] = 27 #Output: {'age': 27, 'name': 'Jack'} print(my_dict) # add item my_dict['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} print(my_dict) # Removing elements from a dictionary # create a dictionary squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove a particular item, returns its value # Output: 16 print(squares.pop(4)) # Output: {1: 1, 2: 4, 3: 9, 5: 25} print(squares) # remove an arbitrary item, return (key,value) # Output: (5, 25) print(squares.popitem()) # Output: {1: 1, 2: 4, 3: 9} print(squares) # remove all items squares.clear() # Output: {} print(squares) # delete the dictionary itself del squares # Throws Error #print(squares) #Some Python Dictionary Methods # Dictionary Methods marks = {}.fromkeys(['Math', 'English', 'Science'], 0) # Output: {'English': 0, 'Math': 0, 'Science': 0} print(marks) for item in marks.items(): print(item) # Output: ['English', 'Math', 'Science'] print(list(sorted(marks.keys()))) #Python Dictionary Comprehension # Dictionary Comprehension squares = {x: x*x for x in range(6)} print(squares) # Dictionary Comprehension with if conditional odd_squares = {x: x*x for x in range(11) if x % 2 == 1} print(odd_squares) #Other Dictionary Operations #Dictionary Membership Test # Membership Test for Dictionary Keys squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: True print(1 in squares) # Output: True print(2 not in squares) # membership tests for key only not value # Output: False print(49 in squares) ## Iterating through a Dictionary squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} for i in squares: print(squares[i]) # Dictionary Built-in Functions squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: False print(all(squares)) # Output: True print(any(squares)) # Output: 6 print(len(squares)) # Output: [0, 1, 3, 5, 7, 9] print(sorted(squares))
21cfa8b9d6ac84ac69fc918fd051d435761c4e1d
smeissa2019/Python-Work
/madlibs.py
334
3.5625
4
#%% import random y = 1 z=[] verbs = ["Jump","plays","run"] adj =["beautiful", "amazing","pretty"] while y >= 1: if len(z) == 0 : sentence = print("yes " + random.choice(adj) + " cats " + random.choice(verbs)) sentence.append(z) else: len(z) == 10: sentence = print("STOP") sentence.append(z) exit() print(z)
47aaf63216e1ec638a15e367002a05757115f486
jhonasiv/rl-algorithms
/src/rlalgs/utils/functions.py
536
3.640625
4
import math def constant_decay_function(variable, rate): result = variable * rate return result def exponential_function(a, x, k, b, exp): """ Exponential function where y = a * e^(-k * (x / b)^exp) """ result = a * math.exp(-k * (x / b) ** exp) return result def casted_exponential_function(a, x, k, b, exp): """ Exponential function where x is casted to int y = a * e^(-k * int((x / b)^exp)) """ result = a * math.exp(-k * int((x / b) ** exp)) return result
4251f4947d792d20ea20f870c9603886e1b77703
sarahdorich/data-pipelines
/common/util/DateTimeMethods.py
3,074
4.375
4
#!/usr/bin/python """ Helper methods for manipulating dates, times and datetimes """ import datetime def get_curr_date_str(date_format="%Y-%m-%d"): """ Get the current date as a string Returns: date_str: (str) current date """ date_str = datetime.date.today().strftime(date_format) return date_str def get_curr_datetime_str(date_format="%Y-%m-%d %H:%M:%S"): """ Get the current datetime as a string Returns: datetime_str: (str) current datetime """ datetime_str = datetime.datetime.now().strftime(date_format) return datetime_str def add_days_to_date_str(date_in_str, days_to_add, date_format='%Y-%m-%d'): """ Adds days to a date string Args: date_in_str: (str) input date days_to_add: (int) days to add to the input date date_format: (str) format of the input and return date Returns: date_out_str: (str) output date """ date_in_dt = datetime.datetime.strptime(date_in_str, date_format) time_increment = datetime.timedelta(days=days_to_add) date_out_dt = date_in_dt + time_increment date_out_str = date_out_dt.strftime(date_format) return date_out_str def subtract_days(date_init_str, date_final_str, date_format='%Y-%m-%d'): """ Returns date_final_str - date_init_str in days Args: date_init_str: (str) initial date date_final_str: (str) final date date_format: (str) format of the input dates Returns: time_delta.days: (int) difference between the initial and final dates in days """ date_init_dt = datetime.datetime.strptime(date_init_str, date_format) date_final_dt = datetime.datetime.strptime(date_final_str, date_format) time_delta = date_final_dt - date_init_dt return time_delta.days def is_date1_lteq_date2(date1_str, date2_str, date_format='%Y-%m-%d'): """ Returns whether date1 <= date2 is True or False Args: date1_str: (str) date on left hand side of <= date2_str: (str) date on right hand side of <= date_format: (str) format of the input dates Returns: out_bool: (bool) indicates whether date1 <= date2 is True or False """ date1_dt = datetime.datetime.strptime(date1_str, date_format) date2_dt = datetime.datetime.strptime(date2_str, date_format) out_bool = date1_dt <= date2_dt return out_bool def get_month_of_date(date_str, date_format='%Y-%m-%d'): """ Returns the month of date Args: date_str (str): input date date_format (str): format of the input date Returns: date_dt.month (int): month of year """ date_dt = datetime.datetime.strptime(date_str, date_format) return date_dt.month def get_year_of_date(date_str, date_format='%Y-%m-%d'): """ Returns the year of a date Args: date_str (str): input date date_format (str): format of the input date Returns: date_dt.year (int): year """ date_dt = datetime.datetime.strptime(date_str, date_format) return date_dt.year
4d8330c764402d59e5d37990c90adddc1c49fa2e
sarahdorich/data-pipelines
/common/util/OSHelpers.py
2,463
3.703125
4
#!/usr/bin/python """ Helpers for operating system functions Contains methods to get directory paths and other operating system functions. """ import os from os.path import expanduser from sys import platform def get_user_home_dir(): """ Get user's home directory Returns the user's home directory. Args: Returns: home_dir: (str) user's home directory """ home_dir = expanduser("~") return home_dir def get_curr_dir(): """ Get the current working directory Returns the current working directory. Args: Returns: curr_dir: (str) current working directory """ curr_dir = os.getcwd() return curr_dir def create_dir(dir_path): """ Create a directory Creates a directory. Args: dir_path: (str) full path to the directory you'd like to create Returns: """ try: os.mkdir(dir_path) except OSError: print("Creation of the directory %s failed!" % dir_path) else: print("Successfully created the directory %s " % dir_path) def get_log_dir(): """ Get the full path of the log directory Returns the directory where logs are stored. This is just the user's home directory > Log Returns: log_dir: (str) log directory """ home_dir = get_user_home_dir() log_dir = home_dir + os.sep + 'Log' if os.path.isdir(log_dir)==False: # check to see if the Log directory exists, if not create it print("The log directory, %s, does not yet exist. Let's create it... " % log_dir) create_dir(log_dir) return log_dir def get_log_filepath(app_name='Python App'): """ Get the full path of a log file Returns the filepath where logs are stored. This is just the user's home directory > Log > app_name. Args: app_name: (string) name of application Returns: log_filepath: (string) full path to the logging file """ log_dir = get_log_dir() log_filepath = log_dir + os.sep + app_name return log_filepath def get_operating_system(): """ Get operating system Returns: operating_system (str): name of the operating system """ operating_system = None if platform == "linux" or platform == "linux2": operating_system = "linux" elif platform == "darwin": operating_system = "osx" elif platform == "win32": operating_system = "windows" return operating_system
4357dbcb6514fcee1cffee063b8c428099fde8d5
angelo-bento/estudo-dirigido
/patinet.py
220
3.703125
4
time = int( input ('quanto tempo de uso?')) time_ex = int (time - 10 / (5 * 0.2) ) if time <= 10: print("o valor a ser pago é de R$5,00") elif time > 10: print("o valor a ser pago é de:", 5 + time_ex)
1aa0d9c1f2fb80624e2d954ecbe203e8700db010
dkodotcom/tinker
/range_sort.py
938
3.96875
4
# partial functions from functools import partial def func(u,v,w,x): return u*4 + v*3 + w*2 + x p = partial(func,5,6,7) print(p(8)) # (5*4)+(6*3)+(7*2)+8 = 60 #range() function my_list = ['one', 'two', 'three', 'four', 'five'] my_list_len = len(my_list) for i in range(0, my_list_len): print(my_list[i]) # will print up to the given range, being the length, 5 drill_one = [0,1,2,3,] for i in range(4): print(drill_one[i]) # first index is start, second stop, and third the increments for i in range(3,-1,-1): print(i) for i in range(8,0,-2): print(i) # insertion sort def insertionSort(array): for i in range(1,len(array)): thisvalue = array[i] position = i while position>0 and array[position-1]>thisvalue: array[position]=array[position-1] position = position-1 array[position]=thisvalue array = [67, 45, 2, 13, 1, 998] insertionSort(array) print(array)
f6e0028e7494a12f7b1074b71d397be98a8717d1
venessaliu1031/Data-structure-and-algorithm
/2. data structure/assignments/week4_binary_search_trees/find_pattern (1).py
1,117
3.5
4
# coding: utf-8 # In[34]: # python3 def read_input(): return (input().rstrip(), input().rstrip()) def print_occurrences(output): print(' '.join(map(str, output))) def pre_hash(text, P, p, x): T = len(text) S = text[T-P:] H = [0]*(T-P+1) H[T-P] = poly_hash(S, p, x) y = 1 for i in range(1, P+1): y = (y*x)%p for i in reversed(range(0, T-P)): H[i] = (x*H[i+1]+ord(text[i])-y*ord(text[i+P]))%p return H def poly_hash(S, p, x): polyhash = 0 for i in reversed(range(0,len(S))): polyhash = (polyhash*x + ord(S[i]))%p return polyhash def get_occurrences(pattern, text): # indexes T = len(text) P = len(pattern) p = T*P+100000 x = 26 results = [] pHash = poly_hash(pattern, p, x) H = pre_hash(text, P, p, x) for i in range(T-P+1): cur_substr = text[i:i+P] if pHash == H[i] and cur_substr == pattern: results.append(i) return results if __name__ == '__main__': print_occurrences(get_occurrences(*read_input()))
2498c6484f6ffc45f55d86d28de3dbcedcd44b77
venessaliu1031/Data-structure-and-algorithm
/1. algorithm toolbox/assignments/week2_algorithmic_warmup/my answers/Fibonacci number.py
168
3.8125
4
# coding: utf-8 # In[10]: #Fibonacci number a = int(input()) a1 = 0 a2 = 1 n = 0 i = 0 while(i < a-1): n = a1 + a2 a1 = a2 a2 = n i += 1 print(n)
7e51e69f780afe7149e9e2a8b3179c10ef27d254
venessaliu1031/Data-structure-and-algorithm
/2. data structure/assignments/week1_basic_data_structures/majority (2).py
1,469
3.625
4
# coding: utf-8 # In[40]: # Uses python3 import sys def get_majority_element(a, lo, hi): #if left == right: # return -1 #if left + 1 == right: # return a[left] if len(a) == 1: return a[0] if lo == hi: return -1 if lo+1 == hi: return a[lo] # recurse on left and right halves of this slice. mid = (hi+lo)//2 left = get_majority_element(a, lo, mid) right = get_majority_element(a, mid+1, hi) # if the two halves agree on the majority element, return it. if left == right: return left # otherwise, count each element and return the "winner". left_count = sum(1 for i in range(lo, hi+1) if a[i] == left) right_count = sum(1 for i in range(lo, hi+1) if a[i] == right) #if left_count >= len(a)//2 and left_count >= right_count: # return left #elif right_count >= len(a)//2 : return right #else: return -1 if left_count > right_count: return left elif right_count > left_count: return right else: return -1 return left if left_count > right_count else right #return -1 if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) #n = 10 #a = [2, 124554847, 2 ,941795895, 2, 2, 2, 2, 792755190, 756617003] #print(get_majority_element(a, 0, n-1)) if get_majority_element(a, 0, n-1) != -1: print(1) else: print(0)
d3f3c62467f05f78b4fab31052c2de257d2d327f
chihuahua/egg-eating-sentiment-cfeelit-classifier
/providers/AfinnProvider.py
949
3.53125
4
# # The provider for the Afinn lexicon. Provides a dictionary # mapping from stemmed word -> 0, 1, 2 (NEG, POS, NEU) # @author Dan # Oct. 11, 2013 # import Provider class AfinnProvider(Provider.Provider): def __init__(self): ''' Creates a new provider for Subjectivity ''' Provider.Provider.__init__(self, 'afinn') def makeDictionary(self): ''' Makes the dictionary. @return the dictionary. ''' afinn_lexicon = dict(map(lambda (k,v): (self.stemmer.stem(k), self.num_to_polar(int(v))), [line.split('\t') for line in open("data/afinn_lexicon.txt")])) self.dict = afinn_lexicon def num_to_polar(self, x): ''' Helper function for making dictionary. @x The number for which to obtain the polarity. ''' if x > 0: return Provider.POSITIVE elif x < 0: return Provider.NEGATIVE else: return Provider.NEUTRAL
b44f99acf2ae8f902543f1bec5df4b59d764be4f
rmit-s3607407-Tony-Huang/ai1901-connectfour
/connectfour/agents/monte_carlo.py
3,068
3.671875
4
import copy import math import random class Node: """ Data structure to keep track of our search """ def __init__(self, state, parent=None): self.visits = 1 self.reward = 0.0 self.state = state self.children = [] self.children_move = [] self.parent = parent def add_child(self, child_state, move): child = Node(child_state, self) self.children.append(child) self.children_move.append(move) def update(self, reward): self.reward += reward self.visits += 1 def fully_explored(self): if len(self.children) == len(self.state.legal_moves()): return True return False def MTCS(maxIter, root, factor, player_id): """ Args: maxIter: How many iterations to run the search for root: The `Node` object that begins the search. Is at first the current state of board. factor: ?? (unknown) player_id: The id of the player, which will be used to mark a token placement Returns: A new instance of `Board` that includes the best move found. """ for _ in range(maxIter): front, turn = tree_policy(root, player_id, factor) reward = default_policy(front.state, turn) backup(front, reward, turn) ans = best_child(root, 0) # print([(c.reward / c.visits) for c in ans.parent.children]) return ans def tree_policy(node, turn, factor): while not node.state.terminal() and node.state.winner() == 0: if not node.fully_explored(): return expand(node, turn), -turn else: node = best_child(node, factor) turn *= -1 return node, turn def expand(node, turn): tried_children_move = [m for m in node.children_move] possible_moves = node.state.legal_moves() for move in possible_moves: if move not in tried_children_move: row = node.state.try_move(move) new_state = copy.deepcopy(node.state) new_state.board[row][move] = turn new_state.last_move = [row, move] break node.add_child(new_state, move) return node.children[-1] def best_child(node, factor): bestscore = -10000000.0 best_children = [] for c in node.children: exploit = c.reward / c.visits explore = math.sqrt(math.log(2.0 * node.visits) / float(c.visits)) score = exploit + factor * explore if score == bestscore: best_children.append(c) if score > bestscore: best_children = [c] bestscore = score return random.choice(best_children) def default_policy(state, turn): count = 100 while not state.terminal() and state.winner() == 0 and count > 0: state = state.next_state_rand(turn) turn *= -1 count -= 1 return state.winner() def backup(node, reward, turn): while node is not None: node.visits += 1 node.reward -= turn * reward node = node.parent turn *= -1 return
f1e73874c9d09a51aa7b9c4a5890fe3cb34f5622
parth-sp02911/My-Projects
/Parth Patel J2 2019 problem.py
1,161
4.125
4
#Parth Patel #797708 #ICS4UOA #J2 problem 2019 - Time to Decompress #Mr.Veera #September 6 2019 num_of_lines = int(input("Enter the number of lines: ")) #asks the user how many lines they want and turns that into an integer output_list = [] #creates a list which will hold the values of the message the user wants for line in range(num_of_lines): #creates a for loop which will repeat as many times, as the user inputed in the "num_of_lines" variable user_input = (input("Enter the message: ")).split() #in the loop I ask the user to enter the message they want and split it by the space (turning it into a list) num_of_char = int(user_input[0]) #I create a variable which will hold the number of times the user wants their character repeated char = user_input[1] #i create a variable which will hold the character the user wants to be repeated output_list.append(char * num_of_char) #I make the program repeat the character as many times as the user wants and then append it to the final output list for element in output_list: print(element) #I print all the elements in the list
c0ce66694cb465c7dfea14c54b0e876461eb084a
Ahmmed44/coursera-adswp
/Course5/Week3/Assignment_3.py
4,444
4.28125
4
import networkx as nx path = ('C:/Users/manma/Google Drive/GitHub/' 'Coursera-Applied-Data-Science-with-Python/Course5/Week3/') G1 = nx.read_gml(path + 'friendships.gml') def answer_one(): """ Find the degree centrality, closeness centrality, and normalized betweeness centrality (excluding endpoints) of node 100. This function should return a tuple of floats (degree_centrality, closeness_centrality, betweenness_centrality). """ deg_c = nx.degree_centrality(G1)[100] clo_c = nx.closeness_centrality(G1)[100] bet_c = nx.betweenness_centrality(G1)[100] return (deg_c, clo_c, bet_c) def answer_two(): """ Suppose you are employed by an online shopping website and are tasked with selecting one user in network G1 to send an online shopping voucher to. We expect that the user who receives the voucher will send it to their friends in the network. You want the voucher to reach as many nodes as possible. The voucher can be forwarded to multiple users at the same time, but the travel distance of the voucher is limited to one step, which means if the voucher travels more than one step in this network, it is no longer valid. Apply your knowledge in network centrality to select the best candidate for the voucher. """ deg_c_all = nx.degree_centrality(G1) max_degree_node = max(deg_c_all.items(), key=lambda x: x[1]) return max_degree_node[0] def answer_three(): """ Now the limit of the voucher’s travel distance has been removed. Because the network is connected, regardless of who you pick, every node in the network will eventually receive the voucher. However, we now want to ensure that the voucher reaches the nodes in the lowest average number of hops. How would you change your selection strategy? Write a function to tell us who is the best candidate in the network under this condition. """ clo_c_all = nx.closeness_centrality(G1) max_clo_node = max(clo_c_all.items(), key=lambda x: x[1]) return max_clo_node[0] def answer_four(): """ Assume the restriction on the voucher’s travel distance is still removed, but now a competitor has developed a strategy to remove a person from the network in order to disrupt the distribution of your company’s voucher. Your competitor is specifically targeting people who are often bridges of information flow between other pairs of people. Identify the single riskiest person to be removed under your competitor’s strategy? """ bet_c_all = nx.betweenness_centrality(G1) max_bet_node = max(bet_c_all.items(), key=lambda x: x[1]) return max_bet_node[0] G2 = nx.read_gml(path + 'blogs.gml') def answer_five(): """ Apply the Scaled Page Rank Algorithm to this network. Find the Page Rank of node 'realclearpolitics.com' with damping value 0.85. """ pg_rank = nx.pagerank(G2, alpha=0.85) pg_rank_node = pg_rank['realclearpolitics.com'] return pg_rank_node def answer_six(): """ Apply the Scaled Page Rank Algorithm to this network with damping value 0.85. Find the 5 nodes with highest Page Rank. """ pg_rank = nx.pagerank(G2, alpha=0.85) sorted_pg_rank = sorted(pg_rank.items(), reverse=True, key=lambda x: x[1]) top_5 = sorted_pg_rank[:5] top_5_blogs = [blog for blog, pg_rank in top_5] return top_5_blogs def answer_seven(): """ Apply the HITS Algorithm to the network to find the hub and authority scores of node 'realclearpolitics.com'. """ hits = nx.hits(G2) hub_score = hits[0]['realclearpolitics.com'] auth_score = hits[1]['realclearpolitics.com'] return (hub_score, auth_score) def answer_eight(): """ Apply the HITS Algorithm to this network to find the 5 nodes with highest hub scores. """ hits = nx.hits(G2) sorted_hubs = sorted(hits[0].items(), reverse=True, key=lambda x: x[1]) top_5 = sorted_hubs[:5] top_5_hubs = [blog for blog, hub_score in top_5] return top_5_hubs def answer_nine(): """ Apply the HITS Algorithm to this network to find the 5 nodes with highest authority scores. """ hits = nx.hits(G2) sorted_auths = sorted(hits[1].items(), reverse=True, key=lambda x: x[1]) top_5 = sorted_auths[:5] top_5_auths = [blog for blog, auth_score in top_5] return top_5_auths answer_nine()
b20b082c9401fdf1d6322f30b0d9abb4c721582b
Ahmmed44/coursera-adswp
/Course3/Week3/Assignment+3.py
7,835
4.28125
4
# coding: utf-8 # --- # # _You are currently looking at **version 1.2** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-machine-learning/resources/bANLa) course resource._ # # --- # # Assignment 3 - Evaluation # # In this assignment you will train several models and evaluate how effectively they predict instances of fraud using data based on [this dataset from Kaggle](https://www.kaggle.com/dalpozz/creditcardfraud). #   # Each row in `fraud_data.csv` corresponds to a credit card transaction. Features include confidential variables `V1` through `V28` as well as `Amount` which is the amount of the transaction.  #   # The target is stored in the `class` column, where a value of 1 corresponds to an instance of fraud and 0 corresponds to an instance of not fraud. # In[1]: import numpy as np import pandas as pd # ### Question 1 # Import the data from `fraud_data.csv`. What percentage of the observations in the dataset are instances of fraud? # # *This function should return a float between 0 and 1.* # In[41]: def answer_one(): df = pd.read_csv('fraud_data.csv') return (df['Class'].value_counts() / len(df)).loc[1] answer_one() # In[11]: # Use X_train, X_test, y_train, y_test for all of the following questions from sklearn.model_selection import train_test_split df = pd.read_csv('fraud_data.csv') X = df.iloc[:,:-1] y = df.iloc[:,-1] X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # ### Question 2 # # Using `X_train`, `X_test`, `y_train`, and `y_test` (as defined above), train a dummy classifier that classifies everything as the majority class of the training data. What is the accuracy of this classifier? What is the recall? # # *This function should a return a tuple with two floats, i.e. `(accuracy score, recall score)`.* # In[17]: def answer_two(): from sklearn.dummy import DummyClassifier from sklearn.metrics import recall_score dummy = DummyClassifier(strategy='most_frequent').fit(X_train, y_train) y_pred_dummy = dummy.predict(X_test) dummy_accuracy = dummy.score(X_test, y_test) dummy_recall = recall_score(y_test, y_pred_dummy) return (dummy_accuracy, dummy_recall) answer_two() # ### Question 3 # # Using X_train, X_test, y_train, y_test (as defined above), train a SVC classifer using the default parameters. What is the accuracy, recall, and precision of this classifier? # # *This function should a return a tuple with three floats, i.e. `(accuracy score, recall score, precision score)`.* # In[19]: def answer_three(): from sklearn.metrics import recall_score, precision_score from sklearn.svm import SVC clf = SVC().fit(X_train, y_train) y_pred_clf = clf.predict(X_test) clf_accuracy = clf.score(X_test, y_test) clf_recall = recall_score(y_test, y_pred_clf) clf_precision = precision_score(y_test, y_pred_clf) return (clf_accuracy, clf_recall, clf_precision) answer_three() # ### Question 4 # # Using the SVC classifier with parameters `{'C': 1e9, 'gamma': 1e-07}`, what is the confusion matrix when using a threshold of -220 on the decision function. Use X_test and y_test. # # *This function should return a confusion matrix, a 2x2 numpy array with 4 integers.* # In[42]: def answer_four(): from sklearn.metrics import confusion_matrix from sklearn.svm import SVC clf = SVC(C=1e9, gamma=1e-07).fit(X_train, y_train) y_scores_clf = clf.decision_function(X_test) y_predicition_220 = y_scores_clf > -220 return confusion_matrix(y_test, y_predicition_220) answer_four() # ### Question 5 # # Train a logisitic regression classifier with default parameters using X_train and y_train. # # For the logisitic regression classifier, create a precision recall curve and a roc curve using y_test and the probability estimates for X_test (probability it is fraud). # # Looking at the precision recall curve, what is the recall when the precision is `0.75`? # # Looking at the roc curve, what is the true positive rate when the false positive rate is `0.16`? # # *This function should return a tuple with two floats, i.e. `(recall, true positive rate)`.* # In[86]: def answer_five(): # %matplotlib notebook from sklearn.linear_model import LogisticRegression from sklearn.metrics import precision_recall_curve, roc_curve, auc # from matplotlib import pyplot as plt logit = LogisticRegression().fit(X_train, y_train) #P-R Curve y_pred_logit = logit.predict(X_test) precision, recall, thresholds = precision_recall_curve(y_test, y_pred_logit) closest_zero = np.argmin(np.abs(thresholds)) closest_zero_p = precision[closest_zero] closest_zero_r = recall[closest_zero] #ROC Curve y_score_logit = logit.decision_function(X_test) fpr_logit, tpr_logit, _ = roc_curve(y_test, y_score_logit) roc_auc_logit = auc(fpr_logit, tpr_logit) # plt.figure() # plt.xlim([0.0, 1.01]) # plt.ylim([0.0, 1.01]) # plt.plot(precision, recall, label='Precision-Recall Curve') # plt.plot(closest_zero_p, closest_zero_r, 'o', markersize = 12, fillstyle = 'none', c='r', mew=3) # plt.xlabel('Precision', fontsize=16) # plt.ylabel('Recall', fontsize=16) # plt.axes().set_aspect('equal') # plt.show() # plt.figure() # plt.xlim([-0.01, 1.00]) # plt.ylim([-0.01, 1.01]) # plt.plot(fpr_logit, tpr_logit, lw=3, label='LogRegr ROC curve (area = {:0.2f})'.format(roc_auc_logit)) # plt.xlabel('False Positive Rate', fontsize=16) # plt.ylabel('True Positive Rate', fontsize=16) # plt.title('ROC curve (Fraud Detection)', fontsize=16) # plt.legend(loc='lower right', fontsize=10) # plt.plot([0, 1], [0, 1], color='navy', lw=3, linestyle='--') # plt.axes().set_aspect('equal') # plt.show() #list(zip(y_test, y_pred_prob[:,1])) return (0.83, 0.94) answer_five() # ### Question 6 # # Perform a grid search over the parameters listed below for a Logisitic Regression classifier, using recall for scoring and the default 3-fold cross validation. # # `'penalty': ['l1', 'l2']` # # `'C':[0.01, 0.1, 1, 10, 100]` # # From `.cv_results_`, create an array of the mean test scores of each parameter combination. i.e. # # | | `l1` | `l2` | # |:----: |---- |---- | # | **`0.01`** | ? | ? | # | **`0.1`** | ? | ? | # | **`1`** | ? | ? | # | **`10`** | ? | ? | # | **`100`** | ? | ? | # # <br> # # *This function should return a 5 by 2 numpy array with 10 floats.* # # *Note: do not return a DataFrame, just the values denoted by '?' above in a numpy array. You might need to reshape your raw result to meet the format we are looking for.* # In[107]: def answer_six(): from sklearn.model_selection import GridSearchCV from sklearn.linear_model import LogisticRegression logit = LogisticRegression() grid_values = {'penalty':['l1', 'l2'], 'C':[0.01, 0.1, 1, 10, 100]} grid_logit_rec = GridSearchCV(logit, param_grid=grid_values, scoring='recall') grid_logit_rec.fit(X_train, y_train) return grid_logit_rec.cv_results_['mean_test_score'].reshape(5,2) answer_six() # In[108]: # Use the following function to help visualize results from the grid search def GridSearch_Heatmap(scores): get_ipython().magic('matplotlib notebook') import seaborn as sns import matplotlib.pyplot as plt plt.figure() sns.heatmap(scores.reshape(5,2), xticklabels=['l1','l2'], yticklabels=[0.01, 0.1, 1, 10, 100]) plt.yticks(rotation=0); #GridSearch_Heatmap(answer_six()) # In[ ]:
b9db06ba03fa3d7a3d5982ff10a7208d996ba4a1
spaceguy01/PythonProjects
/Tkinterkg.py
1,241
4
4
""" Using Tkinter to create a kg -> grams, US pounds,and ounces calculator """ from tkinter import * """ Open a Tkinter GUI window """ window = Tk() """ Defining Calculator program """ def kg_to(): try: grams = float(e1_value.get()) * 1000 pounds = float(e1_value.get()) * 2.20462 ounces = float(e1_value.get()) * 35.274 t1.delete("1.0", END) t1.insert(END,str(round(grams,2)) + ' grams') t2.delete("1.0", END) t2.insert(END,str(round(pounds,2)) + ' pounds') t3.delete("1.0", END) t3.insert(END,str(round(ounces,2)) + ' ounces') except ValueError: pass """ Setting window placement and defining properties of each window """ l1 = Label(window, text='Input kg to convert') l1.grid(row=0, column=0) """ Input Window """ e1_value = StringVar() e1 = Entry(window, textvariable=e1_value) e1.grid(row=0, column=1) """ Button """ b1 = Button(window, text = 'Convert', command=kg_to) b1.grid(row=0, column=2) """ Conversion Windows """ t1 = Text(window, height=1, width=20) t1.grid(row=1, column=0) t2 = Text(window, height=1, width=20) t2.grid(row=1, column=1) t3 = Text(window, height=1, width=20) t3.grid(row=1, column=2) window.mainloop()
77de51fd88642bda186a95dded225cace555e92e
spaceguy01/PythonProjects
/Excelopenpyxl.py
1,269
3.59375
4
""" Working with Excel Files using openpyxl """ import openpyxl """WORKING WITH ALREADY EXISTING EXCEL FILE """ """ Open excel file as workbook in same directory """ worksheet = openpyxl.load_workbook('example.xlsx') """ Getting sheetnames of workbook and set sheets to variable""" print(worksheet.sheetnames) sheet1 = worksheet['Sheet1'] sheet2 = worksheet['Sheet2'] """ Setting Cells as variables in Two ways""" a1 = sheet1['A1'] A1 = sheet1.cell(row=1, column=1) b2 = sheet1['B2'] B2 = sheet1.cell(row=2, column=2) """ Getting Values of Cells """ a1.value A1.value """ Using for loop to get values of cells in B column""" for i in range(1,9): print (i, sheet1.cell(row=i, column=2).value) """------------------------------------------------------""" """ CREATING NEW EXCEL FILE """ workbook = openpyx.Workbook() """ Create new Excel Sheet and set it to a variable """ sheet1 = workbook.create_sheet() """ Set new title to newly created Sheet1 """ sheet1.title = "NewSheet" """ Setting values into Cell in new sheet """ sheet1['A1'].value = "THIS IS NEW VALUE" """ Create New Sheet and Insert it into specific index """ workbook.create_sheet(index=1, title="Another New Sheet") """ Save the Modified Excel File """ workbook.save('filename.xlsx')
4783c951d8caaf9c5c43fb57694cfb8d60d466b7
marcinosypka/learn-python-the-hard-way
/ex30.py
1,691
4.125
4
#this line assigns int value to people variable people = 30 #this line assigns int value to cars variable cars = 30 #this line assigns int value to trucks variable trucks = 30 #this line starts compound statemet, if statemets executes suite below if satement after if is true if cars > people: #this line belongs to suite started by if above, prints a string to terminal print("We should take the cars.") #this line starts elif statement, if statement after elif is true suite below is executed, it has to be put after if compound statement elif cars < people: #this line belongs to suite started by elif, it prints string to terminal print("We should not take the cars.") #this line starts a compound statement, if if statement and all elif statements above are false then else suite is executed else: #this line belongs to else suite, it prints string to terminal print("We can't decide.") #this line starts if statement if trucks > cars: #this line prints string to terminal if if statement is true print("That's too many trucks.") #this line starts elif statement elif trucks < cars: #this line prints string to terminal if elif statement is true print("Maybe we could take the trucks.") #this line starts else statement else: #this line prints string to terminal if all elifs and if above is false print("We still can't decide") #this line starts if statement if people > trucks or not people > cars * 2 : #this line prints string to terminal if if statement above is true print("Alright, let's just take the trucks.") #this line starts else statement else: #this line prints string to terminal if all elifs and if statement above is false print("Fine, let's stay home than.")
94e322bcb05ff775e87bb66b2f5854e9866abfe0
haugstve/plotly-and-dash-with-udemy
/1-02E-ScatterplotExercises/Ex1-Scatterplot.py
978
3.640625
4
####### # Objective: Create a scatterplot of 1000 random data points. # x-axis values should come from a normal distribution using # np.random.randn(1000) # y-axis values should come from a uniform distribution over [0,1) using # np.random.rand(1000) ###### # Perform imports here: import numpy as np import pandas as pd import plotly.offline as pyo import plotly.graph_objs as go x = np.random.randint(1,101,100) y = np.random.randint(1,101,100) # Define a data variable data = [go.Scatter( x=x, y=y, mode='markers', marker={ 'size': '20', 'symbol': 'pentagon', 'color': 'rgb(0,0,0)' } )] # Define the layout layout = go.Layout(title="Test scatter plot", xaxis={'title': 'Some x'}, yaxis={'title': 'another y'}, hovermode ='closest') # Create a fig from data and layout, and plot the fig fig = go.Figure(data=data, layout=layout) pyo.plot(fig, filename='tmp.html')
16a475d3b83ea0a1f8daf415e04210fcedda79a2
PaveLLodiagin/homework
/5.py
1,313
3.640625
4
'''Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. Например: a = 2, b = 3. Результат: 1-й день: 2 2-й день: 2,2 3-й день: 2,42 4-й день: 2,66 5-й день: 2,93 6-й день: 3,22 Ответ: на 6-й день спортсмен достиг результата — не менее 3 км.''' start = int(input('Введите ваш лучший результат: ')) finish = int(input('Введите желаемый результат: ')) i = 1 while start < finish: start = start + (start*0.1) print(f"{start:.2f}") i += 1 print('Через ', i, 'дней вы достигните результата')
e85ae23a40de086dbe652ff142643e4ada28546f
Ccook4Umass/Lab2
/VC_Encrypt.py
721
3.65625
4
#!/usr/bin/env python import string mykey="ECE" data = open("test.txt", "r") input_mes = data.readline() source = string.ascii_uppercase shift = 23 matrix = [ source[(i + shift) % 26] for i in range(len(source)) ] def coder(thistext): ciphertext = [] control = 0 for x,i in enumerate(input_mes.upper()): if i not in source: ciphertext.append(i) continue else: control = 0 if control % len(mykey) == 0 else control result = (source.find(i) + matrix.index(mykey[control])) % 26 ciphertext.append(matrix[result]) control += 1 return ciphertext print("-> Coded text: {0}".format(''.join(coder(input_mes)).lower()))
1b59b6f971ce37b62f3ed7eb6cc5d94ed8b2df44
felcygrace/fy-py
/currency.py
852
4.21875
4
def convert_currency(amount_needed_inr,current_currency_name): current_currency_amount=0 Euro=0.01417 British_Pound=0.0100 Australian_Dollar=0.02140 Canadian_Dollar=0.02027 if current_currency_name=="Euro": current_currency_amount=amount_needed_inr*Euro elif current_currency_name=="British_Pound": current_currency_amount=amount_needed_inr*British_Pound elif current_currency_name=="Australian_Dollar": current_currency_amount=amount_needed_inr*Australian_Dollar elif current_currency_name=="Canadian_Dollar": current_currency_amount=amount_needed_inr*Canadian_Dollar else: print("-1") return current_currency_amount currency_needed=convert_currency(3500,"British_Pound") if(currency_needed!= -1): print(currency_needed ) else: print("Invalid currency name")
1612734eb81f25fe55018dcef2bb15dfe58c33a2
mbaraldi/Coppie
/lista_persone.py
1,671
3.609375
4
from persona import Persona from archiviatore import Archiviatore class ListaPersone(object): """ gestisce una lista di oggetti Persona, caricandoli e salvandoli su file """ def __init__(self): self.lista = [] #lista di persone self.archivio = Archiviatore() self.npersone = 0 def Nuovo(self, nome, cognome): p = Persona(nome, cognome) self.lista.append(p) self.npersone += 1 def Aggiungi(self): print ("Aggiungi nuove persone ('x' per finire)") continua = True while continua: nome = input("Nome: ") if nome == "x" or nome == "": continua = False else: cognome = input("Cognome: ") if cognome == "x" or cognome == "": continua = False else: self.Nuovo(nome, cognome) def Rimuovi(self, indice = 0): if indice > 0: elem = indice else: print ("Rimuovi una persona (da 1 a {0})".format(self.npersone)) elem = int(input("Elimina la persona numero: ")) if elem < 1 or elem > self.npersone: print ("{0} non e' un elemento valido".format(elem)) else: self.lista.pop(elem-1) def Ordina(self): self.lista = sorted(self.lista) def Carica(self, file = "data"): self.lista = self.archivio.Carica(file) self.npersone = len(self.lista) def Salva(self, file = ""): self.archivio.Salva(self.lista, file) def getElemento(self, indice): if indice < 1 or indice > self.npersone: print ("{0} non e' un elemento valido".format(indice)) ret = "" else: ret = self.lista[indice - 1].getNomeCognome() return ret def getListaDaStampare(self): lista = [] lista.append(["Nome", "Cognome"]) for elem in self.lista: lista.append([elem.nome, elem.cognome]) return lista
61b6c8f82b21b8c22200af21229debd4a1a76934
majsylw/Python-3.x-examples
/150321-strings/zad4-cesar.py
1,320
3.65625
4
import string # dla caesar_encode3 def caesar_encode(message, key): res = [] for c in message: if 'A' <= c <= 'Z': idx = ord(c) - ord('A') idx = (idx + key) % 26 res.append(chr(ord('A') + idx)) else: res.append(c) return "".join(res) def caesar_encode2(message, key): def letter(x): if 'A' <= x <= 'Z': idx = ord(x) - ord('A') idx = (idx + key) % 26 return chr(ord('A') + idx) return x return "".join([letter(x) for x in message]) def caesar_encode3(message, key): alphabet = string.ascii_uppercase # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' res = [] for c in message: idx = alphabet.find(c) if idx == -1: res.append(c) continue idx = (idx + key) % len(alphabet) res.append(alphabet[idx]) return "".join(res) def caesar_decode(message, key): return caesar_encode(message, -key) if __name__ == "__main__": print(caesar_encode("THIS IS A VERY, VERY SECRET MESSAGE!", 7)) print(caesar_encode2("THIS IS A VERY, VERY SECRET MESSAGE!", 7)) print(caesar_encode3("THIS IS A VERY, VERY SECRET MESSAGE!", 7)) print(caesar_decode(caesar_encode("THIS IS A VERY, VERY SECRET MESSAGE!", 50), 50))
461002afa84528d9fdc4f77fbfa4b57db41142d2
majsylw/Python-3.x-examples
/170521-lambda-expresions,list-comprehension,classes/excercises.py
1,663
3.859375
4
# lista składana (ang. list comprehension), podobnie wyglądaj set comprehension i tuple comprehension liczby = [1, 2, 3, 4, 5] # jeśli liczba jest parzysta wypełniamy listę 2 potęgami, inaczej 1 nowe_liczby = [] for i in liczby: if i % 2 == 0: nowe_liczby.append(i ** 2) else: nowe_liczby.append(1) print(nowe_liczby) nowe_liczby21 = [i ** 2 for i in liczby] # wypełniamy listę 2 potęgami print(nowe_liczby21) nowe_liczby22 = [i ** 2 for i in liczby if i%2==0 ] # jeśli liczba jest parzysta wypełniamy listę 2 potęgami print(nowe_liczby22) nowe_liczby2 = [i ** 2 if i%2==0 else 1 for i in liczby] # jeśli liczba jest parzysta wypełniamy listę 2 potęgami, inaczej 1 (jak w petli powyżej) print(nowe_liczby2) ################################################################################################################################################### # funkcje a wyrażenia lambda # standardowa definicja funkcji suma def suma(x, y): return x + y print(suma(2, 3)) # wywołanie funkcji suma # zdefiniowanie wyrażenia lambda - jeden argument potega = lambda x: x**2 print(potega(16)) # wywołanie # zdefiniowanie wyrażń lambda - jeden w drugim (wyrażenie lambda generuje drugie) sumator = lambda x: lambda y: x + y print(sumator(2)(3)) # wywołanie # generatory ''' Generatory są w Pythonie mechanizmem leniwej ewaluacji funkcji, która w przeciwnym razie musiałaby zwracać obciążającą pamięć lub kosztowną w obliczaniu listę. ''' print(range(3)) def generuj_calkowite(n): for i in range(n): yield i print(generuj_calkowite) for i in generuj_calkowite(7): print(i)
9310f1a6233e5dde2142749ed9dd41f64af46eba
bohdi2/euler
/202/elegant.py
2,332
4.03125
4
#!/usr/bin/env python3 def gcd(x, y): while y != 0: (x, y) = (y, x % y) return x def isquareroot(n): return int(n ** 0.5) + 1 # Check if n is divisible by a square . def is_divisible_by_square(n): i = 2 while i ** 2 <= n: if n % (i ** 2) == 0: return 1 i += 1 return 0 # Count the number of prime factors of n. def number_of_factors(n): counter = 0 while n > 1: i = 2 while i <= n: if n % i == 0: n /= i counter += 1 break i += 1 return counter # The Mobius function . def mu(n): if n == 1: return 1 # Important to check this first . elif is_divisible_by_square(n): return 0 else: # As n is not divisible by a square , # every power of a prime is equal to one. # Hence , the number of factors is correct . return (-1) ** number_of_factors(n) def find_divisors(n): factors = set() i = 1 limit = isquareroot(n) while i <= limit: if n % i == 0: factors.add(i) factors.add(n//i) i += 1 return factors def phi(n): sum = 0 for d in find_divisors(n): sum += d * mu(n//d) return sum def phi3(n): remainder = n % 3 total = 0 for divisor in find_divisors(n): count = (divisor + remainder) // 3 print(divisor, remainder, count) total += count * mu(n // divisor) return total def terminal(bounces): return (bounces+3)//2 def laser(bounces): terminal_line = terminal(bounces) return phi3(terminal_line) def main(): phi_format = "{0:<12} {1:<12} {2:<12}" print(phi_format.format("n", "phi(n)", "phi3(n)")) for n in [2,3,7]: #3, 4, 5, 11, 25, 64, 100, 1000001]: # print(phi_format.format(n, phi(n), phi3(n))) c = phi3(n) print(c) print() laser_format = "{0:<12} {1:<12} {2:<12}" #print(laser_format.format("bounces", "terminal", "laser(n)")) # for n in range(1, 200): # print(laser_format.format(n, terminal(n), laser(n))) #for n in [11]: #1000001, 12017639147, 715225739*2-3]: # print(laser_format.format(n, terminal(n), laser(n))) # laser(n) if __name__ == "__main__": main()
010249ce07999afdd314a34f02eb8756c5bdbc48
bohdi2/euler
/1/problem1.py
1,709
3.515625
4
#!/usr/bin/env python3 import sys from common.timing import elapsed @elapsed def sum1(limit, d1, d2): sum = 0 for n in range(1, limit): if n % d1 == 0 or n % d2 == 0: sum += n return sum @elapsed def sum2(limit, d1, d2): return sum([n for n in range(1, limit) if n % d1 == 0 or n % d2 == 0]) @elapsed def sum3(limit, d1, d2): return sum(g(limit, d1, d2)) def g(limit, d1, d2): for n in range(1, limit): if n % d1 == 0 or n % d2 == 0: yield n return @elapsed def sum4(n, d1, d2): return d1 * t(n // d1) \ + d2 * t(n // d2) \ - d1 * d2 * t(n // (d1 * d2)) def t(n): return n * (n + 1) // 2 def main(argv): million = 1000000 billion = 1000 * million trillion = 1000 * billion # print("sum_1(million): %d" % sum_1(million, 3, 5)) # print("sum_1(10 million): %d" % sum_1(10 * million, 3, 5)) # print("sum_1(100 million): %d" % sum_1(100 * million, 3, 5)) # print("sum_1(billion): %d" % sum_1(billion, 3, 5)) # print("For loop: %d" % sum_1(limit, 3, 5)) # print("List comp: %d" % sum_2(limit, 3, 5)) # print("Generator: %d" % sum_3(limit, 3, 5)) print("sum_1(million): %d" % sum1(million, 3, 5)) print("sum_1(10 million): %d" % sum1(10 * million, 3, 5)) print("sum_1(100 million): %d" % sum1(100 * million, 3, 5)) print("sum_1(billion): %d" % sum1(billion, 3, 5)) print("-----") print("sum_10(million): %d" % sum10(million, 3, 5)) print("sum_10(billion): %d" % sum10(billion, 3, 5)) print("sum_10(trillion): %d" % sum10(trillion, 3, 5)) if __name__ == "__main__": main(sys.argv)
c5d852ead39ef70ee91f26778f4a7874e38466cf
bohdi2/euler
/208/directions.py
792
4.125
4
#!/usr/bin/env python3 import collections import itertools from math import factorial import sys def choose(n, k): return factorial(n) // (factorial(k) * factorial(n-k)) def all_choices(n, step): return sum([choose(n, k) for k in range(0, n+1, step)]) def main(args): f = factorial expected = {'1' : 2, '2' : 2, '3' : 2, '4' : 2, '5' : 2} print("All permutations of 10: ", 9765625) print("All permutations of pairs: ", 113400) print("All 11s: ", 22680) print("All 12s: ", 42840) length = 10 count = 0 for p in itertools.product("12345", repeat=length): p = "".join(p) c = collections.Counter(p) #print(c) if c == expected: print(p) if __name__ == '__main__': sys.exit(main(sys.argv))
be1046d9aae2f8671503696ad63b836edba0b6ae
adesamthomas/python-challenge_hw
/PyBoll/main.py
1,987
3.90625
4
#PyBoll import os import csv file = 'election_data.csv' with open(file, encoding='utf-8') as csvfile: csvreader = csv.DictReader(csvfile) #declaring variables total_votes = 0 dict_candidates = {} #dictionary for candidate votes winning_vote_count = 0 csv_header = next(csvreader) for row in csvreader: #this simply adds up the number of rows of information #or could us total_votes += 1 if set total_votes = 0 total_votes += 1 #add up all the votes for each candidate candidate_name = row["Candidate"] if candidate_name not in dict_candidates: dict_candidates[candidate_name] = 1 else: dict_candidates[candidate_name] += 1 print("Election Results") print("----------------------------") print("Total Votes: " + str(int(total_votes))) print("----------------------------") #determine the winner. .items --> can loop through all the values and keys for key,value in dict_candidates.items(): #loops through every value print(key + ": " + str(round(value/total_votes*100, 3)) + "% (" + str(value) + ")" ) if value > winning_vote_count: winning_vote_count = value winner_name = key #dictionaries are key value pairs print("----------------------------") print("Winner: " + winner_name) print("----------------------------") #export to text file (\n creates a line break) output_file = open('Pypoll Output.txt', 'w') output_file.write("Election Results \n") output_file.write("---------------------------- \n") output_file.write("Total Votes: " + str(int(total_votes)) + "\n") output_file.write("---------------------------- \n") for key,value in dict_candidates.items(): output_file.write(key + ": " + str(round(value/total_votes*100, 3)) + "% (" + str(value) + ")" + "\n") output_file.write("---------------------------- \n") output_file.write("Winner: " + winner_name + "\n") output_file.write("---------------------------- \n") output_file.close()
6d75c8ac5465accd45c9edb6f486c17d75cc7594
MohamedEmad1998/OCR
/OCR CODE.py
1,537
3.65625
4
# import needed libraries import cv2 as my_cv import pytesseract as my_pt import os # get the image to work on img=my_cv.imread("textbook_image_3.PNG") # i had some problems with tesseract installation # so i used this line as an explicit reference to tesseract path in my PC my_pt.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # do some preprocess to the image to prepare it for the OCR # change the image to grey scale image grey_img=my_cv.cvtColor(img,my_cv.COLOR_BGR2GRAY) # remove any noise from the image no_noise_img=my_cv.medianBlur(grey_img,3) # apply thresholding thr_img=my_cv.threshold(no_noise_img,0,255,my_cv.THRESH_BINARY+my_cv.THRESH_OTSU)[1] # get text from the the image my_config= r'--oem 3 --psm 6' extracted_text=my_pt.image_to_string(img, lang='eng',config=my_config) # create new file and give it a name and write mode access txt_file= open("textbook_image_3.txt", 'w') # write the text taken from the image to the file txt_file.write(extracted_text) txt_file.close()# close the file #count the numbers of characters num_ch=0 num_spaces=extracted_text.count(' ') for i in extracted_text: num_ch=num_ch+1 num=num_ch-num_spaces print("number of characters is ",num) # open the text file and show it on the screen when running the program os.startfile("textbook_image_3.txt") # Resize the image and show it on the screen resized_img = my_cv.resize(img, (0, 0), fx=0.5, fy=0.5) my_cv.imshow("image", resized_img) my_cv.waitKey(0)