blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
2f9414e9b90616d6ccbb39d5fd09cdfa23ab5d10
MarcoGlez/Mision-08
/listas.py
3,510
3.65625
4
#Autor: Marco González Elizalde #Mision 08: Listas en Python def sumarAcumulado(listaEnteros): suma = 0 nuevaLista = [] if len(listaEnteros)>0: for k in range(0,len(listaEnteros)): suma += listaEnteros[k] nuevaLista.append(suma) return (nuevaLista) else: return "Error, no hay datos" def recortarLista(listaEnteros): listaRecortada = [] if len(listaEnteros)>2: listaRecortada = listaEnteros for k in range(0,len(listaEnteros)-1,len(listaEnteros)-2): del listaRecortada[k] return listaRecortada else: return listaRecortada def estanOrdenados(lista): #Checar Secuencia en ciclo for (subin if len(lista) > 0: for k in range (len(lista)-1): if lista[k] > lista[k+1]: return False return True else: return "Error, no hay datos" def sonAnagramas(cadenaA,cadenaB): listaA = list(cadenaA.lower()) listaB = list(cadenaB.lower()) for k in listaA: if k in listaB and (len(listaA) == len(listaB)): return True else: return False def hayDuplicados(lista): contador = 0 for k in lista: if lista.count(k) > 1: contador +=1 if contador != 0: return True else: return False def borrarDuplicados(lista): for k in range (len(lista)-1,-1,-1): if lista.count(lista[k]) > 1: del lista[k] else: pass return lista def main(): listaA = [1,2,3,4,5] listaAA = [5] listaAAA = [] listaB = [1,2,3,4,5] listaBB = [1,2] listaBBB = [] listaC = [1,2,3,4,5] listaCC = [1,3,5,2,4] listaCCC = [] cadenaD = "Mono" cadenaDA = "Nomo" cadenaDB = "Noomoo" cadenaDC = "No" listaE = [1,2,3,4,5] listaEE = [1,2,3,1,4,5] listaEEE = [] listaF = [1,2,3,4,1,2,3] listaFF = [3,5,2,1,1,2,3,6,6,5] print(""" Ejercicio 1: La lista""",listaA,"regresa la lista acumulada:",sumarAcumulado(listaA),""" La lista""",listaAA,"regresa la lista acumulada:",sumarAcumulado(listaAA),""" La lista""",listaAAA, "regresa la lista acumulada:", sumarAcumulado(listaAAA), """ Ejercicio 2: Lista original:""",listaB,"regresa la lista:",recortarLista(listaB),""" Lista original:""",listaBB,"regresa la lista:",recortarLista(listaBB),""" Lista original:""",listaBBB,"regresa la lista:",recortarLista(listaBBB),""" Ejercicio 3: ¿Están ordenados los datos en la lista""", listaC,"?",estanOrdenados(listaC),""" ¿Están ordenados los datos en la lista""", listaCC,"?",estanOrdenados(listaCC),""" ¿Están ordenados los datos en la lista""", listaCCC,"?",estanOrdenados(listaCCC),""" Ejercicio 4: ¿Son""",cadenaD,"y",cadenaDA,"anagramas?",sonAnagramas(cadenaD,cadenaDA),""" ¿Son""",cadenaD,"y",cadenaDB,"anagramas?",sonAnagramas(cadenaD,cadenaDB),""" ¿Son""",cadenaD,"y",cadenaDC,"anagramas?",sonAnagramas(cadenaD,cadenaDC),""" Ejercicio 5: ¿Hay duplicados en la lista""",listaE,"?",hayDuplicados(listaE),""" ¿Hay duplicados en la lista""",listaEE,"?",hayDuplicados(listaEE),""" ¿Hay duplicados en la lista""",listaEEE,"?",hayDuplicados(listaEEE),""" Ejercicio 6: Borrando los duplicados en la lista""",listaF,"obtenemos:",borrarDuplicados(listaF),""" Borrando los duplicados en la lista""",listaFF,"obtenemos:",borrarDuplicados(listaFF) ) main()
efcb4dd373f36063c47ea6cc1426b62fb4c970c7
qiyue0421/python3-crawler
/beautifulsoup_usage.py
6,083
3.53125
4
# Beautiful Soup是python的一个HTML或XML解析库,善于提取数据 # 自动将输入文档转换为Unicode编码,输出文档转换为UTF-8编码 # 在解析时依赖解析库,除了支持python标准库中的HTML解析器外,还支持一些第三方解析器(lxml、html5lib) from bs4 import BeautifulSoup import re html = ''' <html> <head> <title>The Dormouse's story</title> </head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three title sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a> <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> ''' string = ''' <div class="panel"> <div class="panel-heading"> <h4>hello</h4> </div> <div class="panel-body"> <ul class="list" id="list-1" name="elements"> <li class="element">Foo</li> <li class="element">Bar</li> <li class="element">Jay</li> </ul> <ul class="list list-small" id="list-2"> <li class="element">Foo</li> <li class="element">Bar</li> <p>link 1</p> </ul> </div> </div> ''' """基本用法 soup = BeautifulSoup(html, 'lxml') # BeautifulSoup对象初始化(自动更正格式),解析器为lxml print(soup.prettify()) # prettify()方法将要解析的字符串以标准的缩进格式输出 print(soup.title.string) # 输出title节点的文本内容 """ """节点选择器""" """选择元素 # 直接调用节点的名称就可以选择节点元素,再调用string属性就可以得到节点内的文本 soup = BeautifulSoup(html, 'lxml') print(soup.title) print(type(soup.title)) print(soup.title.string) print(soup.head) print(soup.p) # 选择第一个匹配到的节点,后面节点会忽略 """ """提取信息 # 使用name属性获取节点的名称 soup = BeautifulSoup(html, 'lxml') print(soup.title.name) # 调用attrs获取所有属性 print(soup.p.attrs) # 返回一个包含属性和属性值的字典 # 获取单独属性 print(soup.p.attrs['name']) # 第一种方式相当于从字典中提取键值 print(soup.p['name']) # 第二种方式直接在节点元素后面加中括号,传入属性名获取,因为是唯一属性,返回单个字符串 print(soup.p['class']) # 因为属性值不唯一,所以返回的是一个列表 # 输出为 # dromouse # dromouse # ['title'] # 获取内容 print(soup.p.string) # 利用string属性获取节点元素包含的文本内容 """ """嵌套选择 soup = BeautifulSoup(html, 'lxml') print(soup.head.title) # 嵌套调用选择节点 print(type(soup.head.title)) # 得到的结果依然是Tag类型 print(soup.head.title.string) """ """关联选择 html1 = ''' <html> <head> <title>The Dormouse's story</title> </head> <body> <p class="story"> Once upon a time there were three title sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1"> <span>Elsie</span> </a> <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a> and they lived at the bottom of a well. </p> ''' # 子节点与孙节点 soup = BeautifulSoup(html1, 'lxml') print(soup.p.contents) # 调用contents属性获取节点元素的直接子节点,返回一个列表,其中每个元素都是p节点的直接子节点(不包含孙子节点) print() print(soup.p.children) # 调用children属性可以得到一样的结果,返回一个生成器 for i, child in enumerate(soup.p.children): print(i) print(child) print(soup.p.descendants) # 递归查询,获取所有子孙节点 for i, child in enumerate(soup.p.descendants): print(i) print(child) # 父节点和祖先节点 print(soup.a.parent) # 获取a节点的父节点 print(soup.p.parents) # 获取所有的祖先节点,返回结果是生成器类型 print() print(list(enumerate(soup.p.parents))) # 兄弟节点 print('next sibling', soup.a.next_sibling) # 下一个兄弟节点 print('prev sibling', soup.a.previous_sibling) # 上一个兄弟节点 print('next siblings', list(enumerate(soup.a.next_siblings))) # 后面的兄弟节点 print('prev siblings', list(enumerate(soup.a.previous_siblings))) # 前面的兄弟节点 """ """方法选择器 # find_all(name, attrs, recursive, text, ***kwargs)——查询所有符合条件的元素 # name参数——节点名查询 soup = BeautifulSoup(string, 'lxml') print(soup.find_all(name='ul')) # 传入name参数,查询所有ul节点,返回一个列表 print(type(soup.find_all(name='ul')[0])) # bs4.element.Tag类型 for ul in soup.find_all(name='ul'): # 进行嵌套查询 print(ul.find_all(name='li')) # 获取内部li节点 for li in ul.find_all(name='li'): # 遍历每个li print(li.string) # 获取文本信息 # attrs参数——属性查询 print(soup.find_all(attrs={'id': 'list-1'})) # 传入的参数为字典类型,返回结果为列表 print(soup.find_all(attrs={'name': 'elements'})) print(soup.find_all(id='list-1')) # 或者直接传入参数 print(soup.find_all(class_='element')) # text参数——匹配节点文本,传入形式可以是字符串或者正则表达式对象 print(soup.find_all(text=re.compile('link'))) # find(name, attrs, recursive, text, ***kwargs)——查询第一个符合条件的元素 soup = BeautifulSoup(string, 'lxml') print(soup.find(name='ul')) print(type(soup.find(name='ul'))) """ """CSS选择器 soup = BeautifulSoup(string, 'lxml') print(soup.select('.panel .panel-heading')) print(soup.select('ul li')) # 选择ul节点下面的所有li节点 print(soup.select('#list-2 .element')) print(type(soup.select('ul')[0])) # 嵌套选择 for ul in soup.select('ul'): print(ul.select('li')) print(ul['id']) # 获取属性 # print(ul.attrs['id']) # 获取文本 for li in soup.select('li'): print('Get text:', li.get_text()) # print('String:', li.string) """
55a06c83c2ea487a9783facd95082c9b68a8d819
bus1029/HackerRank
/Statistics_10days/Day7/Spearman'sRankCorrelationCoefficient.py
698
3.765625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math from copy import deepcopy """ Task Given two n-element data sets, X and Y, calculate the value of Spearman's rank correlation coefficient. Constraints Data set X contains unique values. Data set Y contains unique values. """ n = int(input()) X = list(map(float, input().split())) Y = list(map(float, input().split())) # Ranking X_tmp = sorted(X) Y_tmp = sorted(Y) X_rank, Y_rank = [], [] for x, y in zip(X, Y): X_rank.append(X_tmp.index(x)+1) Y_rank.append(Y_tmp.index(y)+1) r_xy = 1 - ((6 * sum(list((x_r - y_r)**2 for x_r, y_r in zip(X_rank, Y_rank)))) / (n * (n**2 - 1))) print(round(r_xy, 3))
3ad9ad562541180791817f6cb4c7918f4464d4c2
kaurjassi/pythonnew
/csv_file1.py
1,587
3.890625
4
# FOR READ THE CSV FILES # from csv import reader # with open('csv1.csv','r') as f: # csv_reader = reader(f) # for row in csv_reader: # print(row) # from csv import DictReader # with open('csv1.csv' , 'r') as f: # csv_reader = DictReader(f, delimiter = '|') # for row in csv_reader: # print(row) # # FOR WRITE IN CSV FILES # 1. writer function # from csv import writer # with open('csv2.csv' ,'a', newline = '') as f: # csv_writer = writer(f) # TWO METHODS FOR WRITING ROWS # 1. writerow method # csv_writer.writerow(['fname','lname','age']) # csv_writer.writerow(['jassi','kaur',22]) # csv_writer.writerow(['mandeep','singh' , 20]) # csv_writer.writerow(['jasleen','matharu',27]) # 2. writerows method # csv_writer.writerows([['fname','lname','age'],['jassi','kaur',22],['mandeep','singh',20]]) # 2. DictWriter function from csv import DictWriter with open('output3.csv' , 'a' , newline='') as wf: csv_writer = DictWriter(wf , fieldnames = ['fname','lname','age']) csv_writer.writeheader() # HERE ALSO TWO METHODS TO WRITE # csv_writer.writerow({ # 'fname':'jassi', # 'lname':'kaur', # 'age':22 # }) # csv_writer.writerow({ # 'fname':'mandeep', # 'lname':'singh', # 'age':21 }) csv_writer.writerows([ {'fname':'jassi','lname':'kaur','age':22}, {'fname':'mandeep','lname':'singh','age':20} ])
612e3a0d899bc5ab0d1f33f5e44d3a97df20ff3f
TrinUkWoLoz/Python
/none_examples.py
628
4.09375
4
# Example 1 # If value = none is true then print string value = None if value == None: print("Sorry, you don't carry any value") # Example 2 def strangeFunction(n): if (n % 2 == 0): return True print(strangeFunction(2)) print(strangeFunction(1)) # Result: # True # None # Example 3 def sumOfList(lst): sum = 0 for elem in lst: sum += elem return sum print(sumOfList([5, 4, 3])) # Example 4 def strangeListFunction(n): strangeList = [] for i in range(0, n): strangeList.insert(0, i) return strangeList print(strangeListFunction(5)) # Returns [4, 3, 2, 1, 0]
bbdea8e07eefd9807d87d67ed3c53954c589bab9
Sravaniram/Python-Programming
/Code Kata/prime no.py
215
3.609375
4
n=raw_input() r=0 if n.isdigit(): a=int(n) if a==2: print "yes" else: for i in (2,a): if(a%i)==0: r=1 break else: r=0 if(r==0): print "yes" else: print "no" else: print "invalid"
77b644ad3111862cb3ee71e90ed2970fbf68be6d
Liaowag/Practice
/Python/2048.py
3,545
3.65625
4
# 2048游戏初步实现 import random # 初始化游戏矩阵 def init(matrix): random_x = random.sample(range(4), 2) random_y = random.sample(range(4), 2) matrix[random_x[0]][random_y[0]] = 2 matrix[random_x[1]][random_y[1]] = 2 return matrix #打印当前矩阵 def printmatrix(matrix): cutline = '+' + (('-') * 4 + '+') * 4 for i in range(4): print(cutline) for j in range (4): print('|',end='') print('{0:' '>4}'.format(matrix[i][j]), end='') print('|') print(cutline) #移动指令 def move(command, matrix): if command == 'u': for j in range(4): for i in range(3): for x in range(i + 1, 4): if matrix[x][j] != 0 and matrix[i][j] == 0: matrix[i][j] = matrix[x][j] matrix[x][j] = 0 elif matrix[x][j] != 0 and matrix[i][j] == matrix[x][j]: matrix[i][j] *= 2 matrix[x][j] = 0 break elif command == 'd': for j in range(4): for i in range(3, 0, -1): for x in range(i - 1, -1, -1): if matrix[x][j] != 0 and matrix[i][j] == 0: matrix[i][j] = matrix[x][j] matrix[x][j] = 0 elif matrix[x][j] != 0 and matrix[i][j] == matrix[x][j]: matrix[i][j] *= 2 matrix[x][j] = 0 break elif command == 'l': for i in range(4): for j in range(3): for x in range(j + 1, 4): if matrix[i][x] != 0 and matrix[i][j] == 0: matrix[i][j] = matrix[i][x] matrix[i][x] = 0 elif matrix[i][x] != 0 and matrix[i][j] == matrix[i][x]: matrix[i][j] *= 2 matrix[i][x] = 0 break elif command == 'r': for i in range(4): for j in range(3, 0, -1): for x in range(j - 1, -1, -1): if matrix[i][x] != 0 and matrix[i][j] == 0: matrix[i][j] = matrix[i][x] matrix[i][x] = 0 elif matrix[i][x] != 0 and matrix[i][j] == matrix[i][x]: matrix[i][j] *= 2 matrix[i][x] = 0 break return matrix def gameover(matrix): for i in range(4): for j in range(4): if matrix[i][j] == 2048: break print('Congratuation!') return False for i in range(4): for j in range(4): if matrix[i][j] == 0: return False return True def insert(matrix): while gameover(matrix): x = random.randint(0, 3) y = random.randint(0, 3) if matrix[x][y] == 0: matrix[x][y] = 2 return matrix print('Game is over!') return matrix #开始游戏 def Game(): matrix = [[0 for i in range(4)] for j in range(4)] matrix = init(matrix) printmatrix(matrix) while(True): command = input('Please input your next step(u express up, d express down, l express left, r express right): ') matrix = move(command, matrix) matrix = insert(matrix) printmatrix(matrix) if __name__ == '__main__': Game()
36731c74ffcc393c43d03fb26dfbcceab87287a9
carloscuti/bicicletasjeff
/ppy/edad.py
253
3.71875
4
edad = int(input('ingrese edad: ')) if edad < 18: print('eres menor de edad') else: if edad < 60: print('eres adulto') elif edad < 99: print('eres adulto mayor') else: print('no deberas estar vivo')
ab845957f73a26127703248db9c47dab305db319
ecastan960/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
401
4.15625
4
#!/usr/bin/python3 """File that contains a function to find a peak """ def find_peak(list_of_integers): """function that finds a peak in a list of unsorted integers Args: list_of_integers (list): List of unsorted integers Returns: [type]: Integer of at least one peak """ if list_of_integers: list_of_integers.sort() return list_of_integers[-1]
7dacd65f371367f1d94e5d02e204c99a0aa8ae6f
selbovi/python_exercises
/week2/neubivanie.py
132
3.5
4
a = int(input()) b = int(input()) c = int(input()) l = sorted([a, b, c]) l.reverse() while len(l) > 0: print(l.pop(), end=' ')
c5730df425bf3098b226ee58e7d30b5536e3a4ac
MaAlexHr/Practica12
/e4.py
814
3.765625
4
""" Programador Hernandez Rojas Mara Alexandra Practica 12 Grafica Tortugas forma recursiva """ import turtle import argparse def recorrido_recursivo(tortuga, espacio, huella): if huella >0: tortuga.stamp() espacio = espacio + 3 tortuga.forward(espacio) tortuga.right(24) recorrido_recursivo(tortuga, espacio, huella-1) ap = argparse.ArgumentParser() ap.add_argument("--huella",required=True, help="numero de huellas") args = vars(ap.parse_args()) huellas = int(args["huella"]) wn = turtle.Screen() wn.bgcolor("lightgreen") wn.title("Tortuga") tess = turtle.Turtle() tess.shape("turtle") tess.color("blue") tess.penup() recorrido_recursivo(tess, 20, huellas) wn.mainloop() """ Cuando llegue a uno pinta la primera huella Caso recursivo Huellas = 0 Operación Dibujar Tortuga Caso """
2a5f9791db4df22b7809aab99d309ddbbb4dacf8
SushantAcc/tf-fashionMNIST
/DeepFashion.py
6,849
3.78125
4
#!/usr/bin/env python import numpy as np import tensorflow as tf from dataset import fashion_MNIST from util import config from progressbar import ProgressBar def model(batch_x): """ We will define the learned variables, the weights and biases, within the method ``model()`` which also constructs the neural network. The variables named ``hn``, where ``n`` is an integer, hold the learned weight variables. The variables named ``bn``, where ``n`` is an integer, hold the learned bias variables. In particular, the first variable ``h1`` holds the learned weight matrix that converts an input vector of dimension ``n_input + 2*n_input*n_context`` to a vector of dimension ``n_hidden_1``. Similarly, the second variable ``h2`` holds the weight matrix converting an input vector of dimension ``n_hidden_1`` to one of dimension ``n_hidden_2``. The variables ``h3``, ``h5``, and ``h6`` are similar. Likewise, the biases, ``b1``, ``b2``..., hold the biases for the various layers. The model consists of fully connected 2 hidden layers along with input and output layers. """ b1 = tf.get_variable("b1", [config.n_hidden1], initializer = tf.zeros_initializer()) h1 = tf.get_variable("h1", [config.n_input, config.n_hidden1], initializer = tf.contrib.layers.xavier_initializer()) layer1 = tf.nn.relu(tf.add(tf.matmul(batch_x,h1),b1)) b2 = tf.get_variable("b2", [config.n_hidden2], initializer = tf.zeros_initializer()) h2 = tf.get_variable("h2", [config.n_hidden1, config.n_hidden2], initializer = tf.contrib.layers.xavier_initializer()) layer2 = tf.nn.relu(tf.add(tf.matmul(layer1,h2),b2)) b3 = tf.get_variable("b3", [config.n_class], initializer = tf.zeros_initializer()) h3 = tf.get_variable("h3", [config.n_hidden2, config.n_class], initializer = tf.contrib.layers.xavier_initializer()) layer3 = tf.add(tf.matmul(layer2,h3),b3) return layer3 def compute_loss(predicted, actual): """ This routine computes the cross entropy log loss for each of output node/classes. returns mean loss is computed over n_class nodes. """ total_loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits = predicted,labels = actual) avg_loss = tf.reduce_mean(total_loss) return avg_loss def create_optimizer(): """ we will use the Adam method for optimization (http://arxiv.org/abs/1412.6980), because, generally, it requires less fine-tuning. """ optimizer = tf.train.AdamOptimizer(learning_rate=config.learning_rate) return optimizer def one_hot(n_class, Y): """ return one hot encoded labels to train output layers of NN model """ return np.eye(n_class)[Y] def train(X_train, X_val, X_test, y_train, y_val, y_test, verbose = False): """ Trains the network, also evaluates on test data finally. """ # Creating place holders for image data and its labels X = tf.placeholder(tf.float32, [None, 784], name="X") Y = tf.placeholder(tf.float32, [None, 10], name="Y") # Forward pass on the model logits = model(X) # computing sofmax cross entropy loss with logits avg_loss = compute_loss(logits, Y) # create adams' optimizer, compute the gradients and apply gradients (minimize()) optimizer = create_optimizer().minimize(avg_loss) # compute validation loss validation_loss = compute_loss(logits, Y) # evaluating accuracy on various data (train, val, test) set correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(Y,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # initialize all the global variables init = tf.global_variables_initializer() # starting session to actually execute the computation graph with tf.Session() as sess: # all the global varibles holds actual values now sess.run(init) # looping over number of epochs for epoch in range(config.n_epoch): epoch_loss = 0. # calculate number of batches in dataset num_batches = np.round(X_train.shape[0]/config.batch_size).astype(int) # For displaying progresbar pbar = ProgressBar(term_width=80) # looping over batches of dataset for i in pbar(range(num_batches)): # selecting batch data batch_X = X_train[(i*config.batch_size):((i+1)*config.batch_size),:] batch_y = y_train[(i*config.batch_size):((i+1)*config.batch_size),:] # execution of dataflow computational graph of nodes optimizer, avg_loss _, batch_loss = sess.run([optimizer, avg_loss], feed_dict = {X: batch_X, Y:batch_y}) # summed up batch loss for whole epoch epoch_loss += batch_loss # average epoch loss epoch_loss = epoch_loss/num_batches # compute train accuracy train_accuracy = float(accuracy.eval({X: X_train, Y: y_train})) # compute validation loss val_loss = sess.run(validation_loss, feed_dict = {X: X_val ,Y: y_val}) # compute validation accuracy val_accuracy = float(accuracy.eval({X: X_val, Y: y_val})) # display within an epoch (train_loss, train_accuracy, valid_loss, valid accuracy) if verbose: print("epoch:{epoch_num}, train_loss: {train_loss}, train_accuracy: {train_acc}," "val_loss: {valid_loss}, val_accuracy: {val_acc}".format( epoch_num = epoch, train_loss = round(epoch_loss,3), train_acc = round(train_accuracy,2), valid_loss = round(float(val_loss),3), val_acc = round(val_accuracy,2) )) # calculate final accuracy on never seen test data print ("Test Accuracy:", accuracy.eval({X: X_test, Y: y_test})) sess.close() def main(_): # Instantiating the dataset class fashion_mnist = fashion_MNIST.Dataset(data_download_path='../data/fashion', validation_flag=True, verbose=True) # Loading the fashion MNIST data X_train, X_val, X_test, Y_train, Y_val, Y_test = fashion_mnist.load_data() # Showing few exapmle images from dataset in 2D grid fashion_mnist.show_samples_in_grid(w=10,h=10) # One hot encoding of labels for output layer training y_train = one_hot(config.n_class, Y_train) y_val = one_hot(config.n_class, Y_val) y_test = one_hot(config.n_class, Y_test) # Let's train and evaluate the fully connected NN model train(X_train, X_val, X_test, y_train, y_val, y_test, True) if __name__ == '__main__' : tf.app.run(main)
2a34efda9297ad602650b02f1b1db330ed8846ca
mujina93/google-foundations-path
/1longestwordsubsequence/find.py
2,269
4.03125
4
# author - Michele Piccolini (mujina93) # given a string S and a list of word D, find the # word (from D) which is a substring (not a consecutive # subsequence) of S and # which is the longest among the ones that you can # find in S # Solution 1 # greedy find import time # for execution time # data def init(): S = 'abppplee' D = ['able','ale','apple','bale','kangaroo','hallelujahuh'] return S, D def is_subseq(S,word): # return true if word is a subsequence of the string S N = len(S) L = len(word) print("Length is "+str(L)) # loop through the string, one position at a time i = 0 # index on string S j = 0 # index on word's characters while i < N and L - j <= N - i: print("{:d}) {} {:d}) {}".format(j, word[j], i, S[i])) if word[j] == S[i]: # we found a character of word in S! j += 1 # increase j so that you will check following characters in word if j == L: # we found all the characters! (j=0,...,L-1 means that we are still searching for a char) return True i += 1 # increase to go to check the next character in S # we did not find it return False def clean(S,D): # filter out words that are too long N = len(S) fD = list(filter(lambda str: len(str)<=N, D)) print("Filtered: ", fD) # sort the words by lenght, so that you look for the longest before looking for # the shortest. If you find one, you know that that is immediately the longest # subsequence in S. sD = sorted(fD, key=len, reverse=True) print("Sorted: ", sD) return sD def find(S, D): # filter out long words and sort (longest words first) list sD sD = clean(S,D) # select a word for index, word in enumerate(sD): print("CHECK: " + word) if is_subseq(S,word) == True: # found! # since we pre-sorted D, we know that this is the longest one return word # return the longest word # we did not find it return None def run(): S, D = init() res = find(S,D) print("Longest substring is: "+res) if res is not None else print("No word found in the string") # execution start = time.time() run() end = time.time() print("Execution time: {:f}".format(end-start))
65c4b8ad8f44efbfd65017ac1dc5a7e98d668cf2
akvara/CodeWars
/6kyu/Tribonacci_Sequence.py
1,170
3.8125
4
def tribonacci(signature,n): res = signature for x in range(3, n): res.append(res[x - 1] + res[x - 2] + res[x - 3]) return res[:n] # Clever: # while len(signature) < n: # signature.append(sum(signature[-3:])) # # return signature[:n] from KataTestSuite import Test Test = Test() Test.describe("Basic tests") Test.assert_equals(tribonacci([1,1,1],10),[1,1,1,3,5,9,17,31,57,105]) Test.assert_equals(tribonacci([0,0,1],10),[0,0,1,1,2,4,7,13,24,44]) Test.assert_equals(tribonacci([0,1,1],10),[0,1,1,2,4,7,13,24,44,81]) Test.assert_equals(tribonacci([1,0,0],10),[1,0,0,1,1,2,4,7,13,24]) Test.assert_equals(tribonacci([0,0,0],10),[0,0,0,0,0,0,0,0,0,0]) Test.assert_equals(tribonacci([1,2,3],10),[1,2,3,6,11,20,37,68,125,230]) Test.assert_equals(tribonacci([3,2,1],10),[3,2,1,6,9,16,31,56,103,190]) Test.assert_equals(tribonacci([1,1,1],1),[1]) Test.assert_equals(tribonacci([300,200,100],0),[]) Test.assert_equals(tribonacci([0.5,0.5,0.5],30),[0.5,0.5,0.5,1.5,2.5,4.5,8.5,15.5,28.5,52.5,96.5,177.5,326.5,600.5,1104.5,2031.5,3736.5,6872.5,12640.5,23249.5,42762.5,78652.5,144664.5,266079.5,489396.5,900140.5,1655616.5,3045153.5,5600910.5,10301680.5])
2b5ede28abd90e1e4e29fde53619459ae69188a2
mihmax189/Artezio
/test tasks/list comprehension/return every second element of list/main.py
367
4.125
4
#!/usr/bin/env python2 #-*- coding: utf-8 -*- def return_every_second_element(list_args): """ Возвращает каждый второй элемент аргумента-списка """ return [el for i, el in enumerate(list_args, 1) if i % 2 == 0] if __name__ == '__main__': print return_every_second_element([el for el in range(-10,1)])
71c183167a4d3f634930e343a1a11cc76ade48be
kabhari/Project_Euler
/P0019-Counting-Sundays/counting_sundays.py
1,315
4.0625
4
''' Q:You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? ''' ''' final answer: 171 ''' # init constant months = [ 31, # Jan -1, # Feb - this will be filled later depending on the year 31, # Mar 30, # Apr 31, # May 30, # Jun 31, # Jul 31, # Aug 30, # Sep 31, # Oct 30, # Nov 31, # Dec ] def compute_sundays(start, end): sun_sum = 0 remainder = 0 for y in range(start, end + 1): months[1] = 28 + (y % 4 == 0 and y % 400 == 0); for m in range(len(months)): remainder += months[m] % 7 if remainder >= 7: remainder = remainder % 7 if remainder == 6: sun_sum += 1 return sun_sum # compute def compute(): return compute_sundays(1901, 2000) if __name__ == '__main__': print(" " + str(compute()) + " ")
9b977ddf6cfd7bb10bf8fef5c810ce417c3e6059
gerrycfchang/leetcode-python
/medium/merge_interval.py
1,369
3.875
4
class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if len(intervals) == 0: return [] res = [] intervals.sort(key=self.getKey) for i in range(len(intervals)): if len(res) == 0 or res[-1].end < intervals[i].start: res.append(intervals[i]) else: if res[-1].end < intervals[i].end: res[-1].end = intervals[i].end return res def getKey(self, Interval): return Interval.start if __name__ == '__main__': sol = Solution() int2 = Interval(1, 3) int1 = Interval(2, 6) int3 = Interval(8, 10) int4 = Interval(15, 18) num = [] num.append(int1) num.append(int2) num.append(int3) num.append(int4) sol.merge(num) #assert sol.merge(num) == [[1,6],[8,10],[15,18]] int1 = Interval(1, 4) int2 = Interval(0, 4) num = [] num.append(int1) num.append(int2) sol.merge(num) #assert sol.merge(num) == [[0, 4]] int1 = Interval(1, 4) int2 = Interval(2, 3) num = [] num.append(int1) num.append(int2) sol.merge(num) #assert sol.merge(num) == [[1, 4]]
4741b4b604312a87a03b4f7174843a8fbe918276
nimbid/MITx-6.00.1x--Introduction-to-Computer-Science-and-Programming-Using-Python-
/Basic_Recursion/recursive_multiplication.py
278
4.3125
4
def multiply(a,b): product = 0 if b == 1: return a else: return a + multiply(a,b-1) a = int(input("Enter number to multiply: ")) b = int(input("Enter the number with which you want to multiply "+str(a)+": ")) print("Product: "+ str(multiply(a, b)))
eb3fa349eccd891e06058e13381f61f9d376da8c
Team-Tomato/Learn
/Juniors - 1st Year/Subhiksha.B/converting_to_binary.py
193
4.15625
4
def convert_to_binary(d): if d > 1 : convert_to_binary(d // 2) print(d % 2,end = "") dec = int(input("Enter the decimal number to be converted to binary:")) convert_to_binary(dec)
65c67fceec4d1eda02e7cff98eb022a7b00de300
bjeong16/Python
/ExamplePython/HangmanGame/HangManGame.py
1,955
4.15625
4
import string from string import maketrans import random def startGame(question): tries = len(question) * 3 currentstate = list() for x in question: currentstate.append("_") while tries != 0: print("You now have " + str(tries) + " tries left") print(currentstate) option = input("To guess the entire word, press 1 \nTo guess a letter in the word press 2 \nTo give up and see the word press 3 \n") if option == 1: guess = raw_input("Please enter your guess: \n") if guess == question: print("Congratulations, you have saved Hangman") return else: print("That is not the right word. You now have " + str(tries - 1) + "chances left \n") tries -= 1 if option == 2: guess = raw_input("Please enter a character: \n") counter = 0 for letter in question: if guess == letter: currentstate[counter] = letter counter += 1 tries -=1 if option == 3: print(question) print("Hangman Died") return print("Hangman Died") print("The correct answer was: " + question) return if __name__ == '__main__': print("Welcome to HangMan.") text_file = open("Dict.txt", 'r') mysteryWord = text_file.read() mysteryWord = mysteryWord.split() for word in mysteryWord: length = len(word) if length < 5: mysteryWord.remove(word) count = len(mysteryWord) index = random.randint(0, count) question = mysteryWord[index] count = len(question) for x in range(count): print("_ ") print("There are " + str(count) + " letters in the word") print("You get " + str(count*3) + " tries to guess the word") startGame(question)
776c6474c2c2e05f471173783ee0ab0b68e7c681
mixtah/message-board-app
/SQLiteAdapter.py
3,197
3.59375
4
''' Created on 28 Aug 2017 @author: Michael ''' import sqlite3 from datetime import datetime DB_NAME = 'message-board.db' def QUERY(query,params=None): ''' Provides direct access to the SQLite Database. Given a query it will run it and return a result depending on the query. @param query: The SQL query to be run @type query: str @param params: A tuple of parameters to be inserted into the query in order to prevent SQLInjection @return: list of dictionaries, each dictionary containing keys as column names and values as the row value. @rtype: list ''' try: print query.replace('?','%s') % tuple(params) except: print query try: conn = sqlite3.connect(DB_NAME) cur = conn.cursor() #Hint: I would not normally do this, why not? spl = query.split(';') if len(spl)>1: for q in spl: if params: cur.execute(q,params) params = None conn.commit() else: cur.execute(q) conn.commit() else: if params: cur.execute(query,params) else: cur.execute(query) #Check if we were given a select statement #If so we want to return the results, #otherwise we want to return the last row that was updated if query.lstrip().lower().startswith('select'): result = [] for row in cur.fetchall(): cols = [] fixedRow = [] for i in range(len(row)): if isinstance(row[i], datetime): fixedRow.append(row[i].strftime('%Y-%m-%d %H:%M:%S')) else: fixedRow.append(row[i]) for i in cur.description: cols.append(i[0]) result.append(dict(zip(cols,fixedRow))) return result else: cid = cur.lastrowid conn.commit() if not cid: return True return cid except Exception as err: print "Exception: ",err return None finally: #Is run no matter what, even if there is an error. #perfect place to close connections conn.close() def initialize_db(): QUERY('''DROP TABLE IF EXISTS topic''') QUERY('''DROP TABLE IF EXISTS messages''') with open('create-tables.sql', 'r') as script: queries = script.read().split(';') for query in queries: QUERY(query) return True if __name__ == '__main__': initialize_db() print('Insert Data') print(QUERY('''INSERT INTO messages (username,message) VALUES (?,?)''',('myusername','<h3>mymessage</h3>'))) print('Select Data') print(QUERY('''SELECT * FROM messages WHERE username=?''',('myusername',))) print('Deleting Data') print(QUERY('''DELETE FROM messages WHERE username=?''',('myusername',)))
f0dd89d467efc7181fbd27c0e9eb6e2410dcca15
Endiexe/uas
/lematization.py
347
3.6875
4
import nltk from nltk.stem import WordNetLemmatizer wordnet_lemmatizer = WordNetLemmatizer() sentence =input("Type the Sentence : ") sentence_words = nltk.word_tokenize(sentence) print("{0:20}{1:20}".format("Word","Lemma")) for word in sentence_words: print ("{0:20}{1:20}".format(word,wordnet_lemmatizer.lemmatize(word,pos = "v")))
f2fcf67df00a42520b195e69b1e6c5d871a8e8b6
sairaghav619/Python-Assignment-1
/python assignment 3.py
2,271
4.3125
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 27 11:53:07 2021 @author: Sai """ #######1.1 Write a Python Program to implement your own myreduce() function which works exactly ########like Python's built-in function reduce()#### def myreduce(num): num_list=list(range(1,number+1)) sum_of_elements=0 for i in num_list: sum_of_elements+=i return num_list,sum_of_elements #Input number=int(input("Please insert the number :")) output_value=myreduce(number) #Output print("Output:") print("List of First n Natural numbers are:",output_value[0]) print("Sum of List elements are :",output_value[1]) #######1.2 Write a Python program to implement your own myfilter() function which works exactly ########like Python's built-in function filter() number=int(input("Please insert the number: ")) num_list=list(range(1,number+1)) num_even_list=list(filter(lambda x: x%2==0,list(filter(lambda x: x%5==0 ,num_list)))) num_odd_list= list(filter(lambda x: x%2!=0,list(filter(lambda x: x%5==0 ,num_list)))) print("List of numbers:",num_list) print("List of Even number and also which are multiples of 5 are:",num_even_list) print("List of Odd numbers and also which are multiples of 5 are:",num_odd_list) #########Implement List comprehensions to produce the following lists. #####['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz'] word1=list('xyz') word2=[x*n for x in word1 for n in range(1,5) ] print(word2) #####['x', 'y', 'z', 'xx', 'yy', 'zz', 'xxx', 'yyy', 'zzz', 'xxxx', 'yyyy', 'zzzz'] word1=list('xyz') word3=[x*n for n in range(1,5) for x in word1 ] print(word3) ######[[2], [3], [4], [3], [4], [5], [4], [5], [6]] [[2, 3, 4, 5], [3, 4, 5, 6], number=[2,3,4] resultnumber1=[[x+n] for x in number for n in range(0,3)] print(resultnumber1) ########[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]] number2=[2,3,4,5] resultnumber3=[[x+n for n in range(0,4)] for x in number2 ] print(resultnumber3) ####[(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3) number4=[1,2,3] resultnumber5= [(b,a) for a in number4 for b in number4] print(resultnumber5)
d8a0e851785054decbc7c20c5ddcec3f80f492ff
UCSD-ECE140/140A-lab-5
/additional_code/utils_new.py
481
3.703125
4
def euclidean_distance(x1, y1, x2, y2): """Compute euclidean distance between two points.""" def which_start_and_pitstop(pitstop_num, pitstop_coords, start_coords): """Computes the relevant pitstop and startpoint info. Extracts the pitstop coordinates, relevant startpoint number and startpoint coordinates and returns them.""" # Write your code here return my_pitstop_coord, my_start_coord, my_start_num # Feel free to add more utility functions
db37938f85b37da2cde45c4feeeb59bfeb883d1d
okipriyadi/NewSamplePython
/SamplePython/dari_buku_network_programming/Bab2_multiplexing_socket.socket/_01_forking_mixin.py
4,184
4.09375
4
""" You have decided to write an asynchronous Python socket server application. The server will not block in processing a client request. So the server needs a mechanism to deal with each client independently. Python 2.7 version's SocketServer class comes with two utility classes: ForkingMixIn and ThreadingMixIn . The ForkingMixin class will spawn a new process for each client request We can create a ForkingServer class inherited from TCPServer and ForkingMixin . The former parent will enable our ForkingServer class to do all the necessary server operations that we did manually before, such as creating a socket, binding to an address, and listening for incoming connections. Our server also needs to inherit from ForkingMixin to handle clients asynchronously. The ForkingServer class also needs to set up a request handler that dictates how to handle a client request. Here our server will echo back the text string received from the client. Our request handler class ForkingServerRequestHandler is inherited from the BaseRequestHandler provided with the SocketServer library. We can code the client of our echo server, ForkingClient , in an object-oriented fashion. In Python, the constructor method of a class is called __init__() . By convention, it takes a self-argument to attach attributes or properties of that particular class. The ForkingClient echo server will be initialized at __init__() and sends the message to the server at the run() method respectively. In order to test our ForkingServer class, we can launch multiple echo clients and see how the server responds back to the clients An instance of ForkingServer is launched in the main thread, which has been daemonized to run in the background. Now, the two clients have started interacting with the server. """ import os import threading import socket import SocketServer SERVER_HOST = 'localhost' SERVER_PORT = 0 #port 0 akan membuat kernel memilih secara otomatis pada port yang kosong BUF_SIZE = 1024 ECHO_MSG = 'hello echo server' class ForkedClient(): """ A client to test forking server""" def __init__(self, ip, port): # Create a socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to the server self.sock.connect((ip, port)) def run(self): """ Client playing with the server""" current_process_id = os.getpid() print 'PID %s Sending echo message to the server : "%s"' % (current_process_id, ECHO_MSG) # Send the data to server sent_data_length = self.sock.send(ECHO_MSG) print "Sent: %d characters, so far..." %sent_data_length # Display server response response = self.sock.recv(BUF_SIZE) print "PID %s received: %s" % (current_process_id,response[5:]) def shutdown(self): """ Cleanup the client socket """ self.sock.close() class ForkingServerRequestHandler(SocketServer.BaseRequestHandler): def handle(self): # Send the echo back to the client print "handle waiting" data = self.request.recv(BUF_SIZE) current_process_id = os.getpid() response = '%s: %s' % (current_process_id, data) print "Server sending response [current_process_id: data] = [%s]" %response self.request.send(response) return class ForkingServer(SocketServer.ForkingMixIn, SocketServer.TCPServer,): """Nothing to add here, inherited everything necessary from parents""" pass def main(): # Launch the server server = ForkingServer((SERVER_HOST, SERVER_PORT), ForkingServerRequestHandler) ip, port = server.server_address # Retrieve the port number server_thread = threading.Thread(target=server.serve_forever) server_thread.setDaemon(True) # don't hang on exit server_thread.start() print 'Server loop running PID: %s' %os.getpid() # Launch the client(s) client1 = ForkedClient(ip, port) client1.run() client2 = ForkedClient(ip, port) client2.run() # Clean them up server.shutdown() client1.shutdown() client2.shutdown() server.socket.close() if __name__ == '__main__': main()
8692f5c12bf7ff4400c98b7b6eb3e0628368a71b
garladinne/python_codetantra
/string_cut_first_last_characters.py
248
4.28125
4
st=input("Enter a string: ") l=len(st) #if(l<3): # print("The string is:",st) #else: # print("The first & last two characters of the string:",st[0]+st[1]+st[-2]+st[-1]) print("String after removing first and last characters:",st[1:(l-1):1])
45093b9e07c9621e63febad461a523adc41f798d
daniisler/dobble
/server/datenbank.py
3,016
3.875
4
import sqlite3 as sql class DB: def __init__(self, name=None): self.conn = None self.cursor = None if name: self.open(name) def addTable(self,table_name,column_names): try: self.cursor.execute("CREATE TABLE " + table_name + "({})".format(column_names)) except: print("table already exists") def open(self,name): try: self.conn = sql.connect(name); self.cursor = self.conn.cursor() except sql.Error as e: print("Error connecting to database!") def close(self): if self.conn: self.conn.commit() self.cursor.close() self.conn.close() def __exit__(self,exc_type,exc_value,traceback): self.close() def write(self,table,columns,data): query = "INSERT INTO {0} VALUES ({2});".format(table,columns,data) print(query) self.cursor.execute(query) self.conn.commit() def querry(self,sql): self.cursor.execute(sql) return (self.cursor.fetchall()) def print(self,table_name): for row in self.cursor.execute('SELECT * FROM '+ table_name): print(row) def delete(self,table_name): try: self.cursor.execute(f"DROP TABLE {table_name}") except: print("no such table") def update(self,table_name,values,querry): string = f"UPDATE {table_name} SET {values} WHERE {querry} " print(string) self.cursor.execute(string) self.conn.commit() print("updated") # dobble_db = DB() # dobble_db.open("DOBBLE") # # dobble_db.addTable("users","id, ipv4, user_name") # # dobble_db.write("users","id, ipv4, user_name","'5', 'name4', 'figa7'") # print(dobble_db.querry("SELECT * FROM users WHERE id == '5'")) # dobble_db.print("users") # def get(self,table,columns,limit=None): # query = "SELECT {0} from {1};".format(columns,table) # self.cursor.execute(query) # # fetch data # rows = self.cursor.fetchall() # return rows[len(rows)-limit if limit else 0:] # def create_table(self,table_name,column_names): # self.table_name = table_name # cursor = self.c.cursor() # try: # cursor.execute("CREATE TABLE " + table_name + " (" + ", ".join(column_names) + ")") # except: # print("table already exists!") # def print(self): # for row in self.c.execute('SELECT * FROM '+self.table_name): # print(row) # def inser_data(self,table_name,data): # cursor = self.c.cursor() # string = "INSERT INTO "+table_name+" VALUES ("+"?" + ",?"*(len(data)-1)+")" # cursor.execute(string, data) # self.c.commit() # def querry(self,statement,data): # cursor = self.c.cursor() # cursor.execute(statement,data) # return cursor.fetchall()
2a107ace93a7c610bb3fc6b5c28ca261cae605c5
msourav16/mrjobtutorials
/holmes/simple_word_count.py
484
3.515625
4
from mrjob.job import MRJob class MRWordCount(MRJob): def mapper(self, _, line): # yield each word in the line words = line.split() for word in words: yield (word.lower(), 1) def reducer(self, word, counts): # send all (num_occurrences, word) pairs to the same reducer. # num_occurrences is so we can easily use Python's max() function. yield word, sum(counts) if __name__ == '__main__': MRWordCount.run()
0fe5256f6d39aec378e843e83a3a1b669b3121af
chaichai1997/python-algorithm
/link_rotate_k.py
1,025
3.640625
4
# -*- coding: utf-8 -*- # author = "chaichai" from link_find_k import construct_link from link_find_k import print_link """ 将链表向右反转k步 1 2 3 4 5 6 7 翻转3步 7 6 5 1 2 3 4 """ class LNode: def __init__(self): self.data = None self.next = None def rotate_k(head, k): if head.next is None or head is None: return else: fast = head.next slow = head.next i = 0 while i < k and fast is not None: fast = fast.next i += 1 if i < k: return else: while fast.next is not None: slow = slow.next fast = fast.next tmp = slow slow = slow.next tmp.next = None fast.next = head.next head.next = slow if __name__ == '__main__': head = construct_link() print("未旋转链表:", end='') print_link(head) rotate_k(head, 3) print("旋转后:", end='') print_link(head)
8403c433d6c75316eeb8edfe4c9a2317fc67cf35
evanleeturner/tbtools
/build/lib/tbtools/write.py
2,398
3.5
4
'''Writing TxBLEND input/output files''' import pandas as pd import os def gensal(df, out_path, loc_string): ''' Write the TxBLEND boundary salinity concentration input file Parameters ---------- df : dataframe Dataframe of the interpolated salinity values *must have a continuous, bihourly index out_path : string location where the file will be saved plus file name loc_string : string location string to indicate where the salinity data was colleged *e.g. 'OffGalves' Example ------- import tbtools as tbt tbt.write.gensal(data, 'desired/output/path', 'OffGalves') Returns ------- None ''' fout = open(out_path,'w') for i in range(0,len(df),12): fout.write('%3i%3i%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%6i %8s\n' % (df.index[i].month,df.index[i].day, df.salinity[i],df.salinity[i+1], df.salinity[i+2],df.salinity[i+3], df.salinity[i+4],df.salinity[i+5], df.salinity[i+6],df.salinity[i+7], df.salinity[i+8],df.salinity[i+9], df.salinity[i+10],df.salinity[i+11], df.index[i].year,loc_string)) fout.close() def tide(df, out_path): ''' Write the TxBLEND tide input file Parameters ---------- df : dataframe Dataframe of the bihourly tide data *must have a continuous, bihourly index out_path : string location where the file will be saved plus file name Example ------- import tbtools as tbt tbt.write.tide(data, 'desired/output/path') Returns ------- None ''' fout = open(out_path,'w') col = df.columns[0] for i in range(0,len(df),12): fout.write('%3i%3i%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f' '%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%6i %-8s\n' % (df.index[i].month,df.index[i].day, df[col][i],df[col][i+1], df[col][i+2],df[col][i+3], df[col][i+4],df[col][i+5], df[col][i+6],df[col][i+7], df[col][i+8],df[col][i+9], df[col][i+10],df[col][i+11], df.index[i].year,col)) fout.close()
3c2faabd44dad496d9433b44e648399cb6471d94
ChaoMneg/Offer-python3
/数组/Array_duplicate_numbers.py
2,061
3.890625
4
# -*- coding: utf-8 -*- # @Time : 2020/1/31/031 15:54 # @Author : mengchao # @Site : # @File : Array_duplicate_numbers.py # @Software: PyCharm """ 题目: 数组中重复的数字 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 """ class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False # 修改数组 def duplicate(self, numbers, duplication): n = len(numbers) for i in range(n): if numbers[i] != i: tmp = numbers[numbers[i]] if tmp == numbers[i]: duplication[0] = numbers[i] return True else: numbers[numbers[i]] = numbers[i] numbers[i] = tmp return False # 不修改数组,P43 def duplicate_2(self, numbers, duplication): n = len(numbers) start = 1 end = n while end >= start: middle = ((end - start) >> 1) + start count_n = count(numbers, n, start, middle) if start == end: if count_n > 1: return start else: break elif count_n > (middle - start +1): end = middle else: start = middle + 1 return -1 # 计数函数,算法2使用 def count(numbers, len, start, end): count_n = 0 for i in range(len): if numbers[i] >= start and numbers[i] <= end: count_n = count_n + 1 return count_n # 测试用例 [2,3,1,0,2,5,3] S = Solution() duplication = ["a"] numbers = [2,3,1,0,2,5,3] d_result = S.duplicate_2(numbers, duplication) print(d_result)
7975ab24ddfb3cc4212c91dcbe39e3fad0314a30
kjk402/PythonWork
/programmers/level1/3.py
644
3.53125
4
# 완주하지 못한 선수 def solution(party, complet): party.sort() complet.sort() answer = [] for person in party: if person not in complet: answer.append(person) else: complet.pop(0) return answer p =["mislav", "stanko", "vinko","mislav", "ana","marina","vinko"] c = ["stanko", "ana", "mislav", "marina","vinko"] print(solution(p, c)) """ def solution(participant, completion): participant.sort() completion.sort() for i in range(len(completion)): if participant[i] != completion[i]: return participant[i] return participant[i+1] """
7a81e81b7e98677ad28626610905421a9fda7414
AdamZhouSE/pythonHomework
/Code/CodeRecords/2098/60763/281385.py
118
3.578125
4
a = int(input()) s = '' while a > 0: b = a % 26 a = int(a/26) s = chr(ord('a')-1 + b) + s print(s.upper())
d6bee997195cff763adcc9fd9d2880a42fb54e87
penguin1214/CS231n
/assignment2/cs231n/classifiers/cnn.py
15,054
3.53125
4
import numpy as np from cs231n.layers import * from cs231n.fast_layers import * from cs231n.layer_utils import * class ThreeLayerConvNet(object): """ A three-layer convolutional network with the following architecture: conv - relu - 2x2 max pool - affine - relu - affine - softmax The network operates on minibatches of data that have shape (N, C, H, W) consisting of N images, each with height H and width W and with C input channels. """ def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0, dtype=np.float32): """ Initialize a new network. Inputs: - input_dim: Tuple (C, H, W) giving size of input data - num_filters: Number of filters to use in the convolutional layer - filter_size: Size of filters to use in the convolutional layer - hidden_dim: Number of units to use in the fully-connected hidden layer - num_classes: Number of scores to produce from the final affine layer. - weight_scale: Scalar giving standard deviation for random initialization of weights. - reg: Scalar giving L2 regularization strength - dtype: numpy datatype to use for computation. """ self.params = {} self.reg = reg self.dtype = dtype ############################################################################ # TODO: Initialize weights and biases for the three-layer convolutional # # network. Weights should be initialized from a Gaussian with standard # # deviation equal to weight_scale; biases should be initialized to zero. # # All weights and biases should be stored in the dictionary self.params. # # Store weights and biases for the convolutional layer using the keys 'W1' # # and 'b1'; use keys 'W2' and 'b2' for the weights and biases of the # # hidden affine layer, and keys 'W3' and 'b3' for the weights and biases # # of the output affine layer. # ############################################################################ C, H, W = input_dim HC = filter_size # conv filter height WC = filter_size F = num_filters P = (filter_size-1) / 2 # padding SC = 1 conv_h = (H+2*P-HC) / SC + 1 conv_w = (W+2*P-WC) / SC + 1 HP = 2 WP = 2 # pool filter size 2*2 SP = 2 pool_h = 1 + (conv_h - HP) / SP pool_w = 1 + (conv_w - WP) / SP # mind not to use np.random.rand! self.params['W1'] = weight_scale * np.random.randn(F, C, HC, WC) self.params['b1'] = np.zeros(F) # what is the size of fc layer? # the input of affine layer is (N, F, pool_h, pool_w) and should be reshaped into (N,F*pool_h*pool_w) # weights should be (F*pool_h*pool_w, H) self.params['W2'] = weight_scale * np.random.randn(F*pool_h*pool_w, hidden_dim) self.params['b2'] = np.zeros(hidden_dim) self.params['W3'] = weight_scale * np.random.randn(hidden_dim, num_classes) self.params['b3'] = np.zeros(num_classes) ############################################################################ # END OF YOUR CODE # ############################################################################ for k, v in self.params.iteritems(): self.params[k] = v.astype(dtype) def loss(self, X, y=None): """ Evaluate loss and gradient for the three-layer convolutional network. Input / output: Same API as TwoLayerNet in fc_net.py. """ W1, b1 = self.params['W1'], self.params['b1'] W2, b2 = self.params['W2'], self.params['b2'] W3, b3 = self.params['W3'], self.params['b3'] # pass conv_param to the forward pass for the convolutional layer filter_size = W1.shape[2] conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2} # pass pool_param to the forward pass for the max-pooling layer pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2} scores = None ############################################################################ # TODO: Implement the forward pass for the three-layer convolutional net, # # computing the class scores for X and storing them in the scores # # variable. # ############################################################################ SC = conv_param['stride'] PC = conv_param['pad'] HP = pool_param['pool_height'] WP = pool_param['pool_width'] SP = pool_param['stride'] # conv forward with conv_relu_forward_fast out, cache_conv = conv_relu_pool_forward(X, W1, b1, conv_param, pool_param) # fully-connected forward # print X.shape, out.shape # print W2.shape, b2.shape # print out.reshape([out.shape[0], np.prod(out.shape[1:])]).shape # (50, 3, 32, 32)(50, 32, 16, 16) # (8192, 100)(100, ) # (50, 8192) # h1, cache_h1 = affine_relu_forward(out.reshape([out.shape[0], np.prod(out.shape[1:])]), W2, b2) h1, cache_h1 = affine_relu_forward(out, W2, b2) scores, cache_scores = affine_forward(h1, W3, b3) ############################################################################ # END OF YOUR CODE # ############################################################################ if y is None: return scores loss, grads = 0, {} ############################################################################ # TODO: Implement the backward pass for the three-layer convolutional net, # # storing the loss and gradients in the loss and grads variables. Compute # # data loss using softmax, and make sure that grads[k] holds the gradients # # for self.params[k]. Don't forget to add L2 regularization! # ############################################################################ data_loss, dscores = softmax_loss(scores, y) reg_loss = 0.5 * self.reg * np.sum(W1 * W1) + 0.5 * self.reg * np.sum(W2 * W2) + 0.5 * self.reg * np.sum(W3 * W3) loss = data_loss + reg_loss # backprop dh2, dW3, db3 = affine_backward(dscores, cache_scores) dh1, dW2, db2 = affine_relu_backward(dh2, cache_h1) dX, dW1, db1 = conv_relu_pool_backward(dh1, cache_conv) # note to add L2 regularization!!! grads['W1'] = dW1 + self.reg * W1 grads['W2'] = dW2 + self.reg * W2 grads['W3'] = dW3 + self.reg * W3 grads['b1'] = db1 grads['b2'] = db2 grads['b3'] = db3 ############################################################################ # END OF YOUR CODE # ############################################################################ return loss, grads class TwoConvLayerCNN(object): """ A deeper cnn compared to ThreeLayerConvnet. conv - relu - conv - relu - 2x2 max pool - affine - affine - relu -affine - softmax """ def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0, dtype=np.float32): """ Initialize a new network. Inputs: - input_dim: Tuple (C, H, W) giving size of input data - num_filters: Number of filters to use in the convolutional layer - filter_size: Size of filters to use in the convolutional layer - hidden_dim: Number of units to use in the fully-connected hidden layer - num_classes: Number of scores to produce from the final affine layer. - weight_scale: Scalar giving standard deviation for random initialization of weights. - reg: Scalar giving L2 regularization strength - dtype: numpy datatype to use for computation. """ self.params = {} self.mem = {} self.reg = reg self.dtype = dtype # variables C, H, W = input_dim F = num_filters HC = filter_size # conv filter height WC = filter_size SC = 1 P = (filter_size-1) / 2 # the value of padding make sure that the spatial size stays unchanged after convolution conv_h = (H + 2 * P - HC) / SC + 1 conv_w = (W + 2 * P - WC) / SC + 1 HP = 2 WP = 2 # pool filter size 2*2 SP = 2 pool_h = 1 + (conv_h - HP) / SP pool_w = 1 + (conv_w - WP) / SP self.params['W0'] = weight_scale * np.random.randn(F, C, HC, WC) self.params['b0'] = np.zeros(F) self.params['W1'] = weight_scale * np.random.randn(F, F, HC, WC) self.params['b1'] = np.zeros(F) # what is the size of fc layer? # the input of affine layer is (N, F, pool_h, pool_w) and should be reshaped into (N,F*pool_h*pool_w) # weights should be (F*pool_h*pool_w, H) self.params['W2'] = weight_scale * np.random.randn(F * pool_h * pool_w, hidden_dim) self.params['b2'] = np.zeros(hidden_dim) self.params['W3'] = weight_scale * np.random.randn(hidden_dim, num_classes) self.params['b3'] = np.zeros(num_classes) for k, v in self.params.iteritems(): self.params[k] = v.astype(dtype) def loss(self, X, y=None): W0, b0 = self.params['W0'], self.params['b0'] W1, b1 = self.params['W1'], self.params['b1'] W2, b2 = self.params['W2'], self.params['b2'] W3, b3 = self.params['W3'], self.params['b3'] # pass conv_param to the forward pass for the convolutional layer filter_size = W1.shape[2] conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2} # pass pool_param to the forward pass for the max-pooling layer pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2} scores = None # two conv-relu layer scores, cache_conv0 = conv_relu_forward(X, W0, b0, conv_param) scores, cache_conv1 = conv_relu_pool_forward(scores, W1, b1, conv_param, pool_param) h1, cache_h1 = affine_relu_forward(scores, W2, b2) scores, cache_scores = affine_forward(h1, W3, b3) if y is None: return scores loss, grads = 0, {} data_loss, dscores = softmax_loss(scores, y) reg_loss = 0.5 * self.reg * np.sum(W0 * W0) + 0.5 * self.reg * np.sum(W1 * W1) + 0.5 * self.reg * np.sum(W2 * W2) + 0.5 * self.reg * np.sum( W3 * W3) loss = data_loss + reg_loss # backprop dh2, dW3, db3 = affine_backward(dscores, cache_scores) dh1, dW2, db2 = affine_relu_backward(dh2, cache_h1) dc1, dW1, db1 = conv_relu_pool_backward(dh1, cache_conv1) dX, dW0, db0 = conv_relu_backward(dc1, cache_conv0) # note to add L2 regularization!!! grads['W0'] = dW0 + self.reg * W0 grads['W1'] = dW1 + self.reg * W1 grads['W2'] = dW2 + self.reg * W2 grads['W3'] = dW3 + self.reg * W3 grads['b0'] = db0 grads['b1'] = db1 grads['b2'] = db2 grads['b3'] = db3 return loss, grads class ThreeConvLayerCNN(object): """ A deeper cnn compared to ThreeLayerConvnet. conv - relu - conv - relu - conv - relu - 2x2 max pool - affine - affine - relu -affine - softmax """ def __init__(self, input_dim=(3, 32, 32), num_filters=32, filter_size=7, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0, dtype=np.float32): self.params = {} self.mem = {} self.reg = reg self.dtype = dtype # variables C, H, W = input_dim F = num_filters HC = filter_size # conv filter height WC = filter_size SC = 1 P = (filter_size-1) / 2 # the value of padding make sure that the spatial size stays unchanged after convolution conv_h = (H + 2 * P - HC) / SC + 1 conv_w = (W + 2 * P - WC) / SC + 1 HP = 2 WP = 2 # pool filter size 2*2 SP = 2 pool_h = 1 + (conv_h - HP) / SP pool_w = 1 + (conv_w - WP) / SP # conv parameters self.params['W0'] = weight_scale * np.random.randn(F, C, HC, WC) self.params['b0'] = np.zeros(F) self.params['W1'] = weight_scale * np.random.randn(F, F, HC, WC) self.params['b1'] = np.zeros(F) self.params['W2'] = weight_scale * np.random.randn(F, F, HC, WC) self.params['b2'] = np.zeros(F) # fc parameters self.params['W3'] = weight_scale * np.random.randn(F * pool_h * pool_w, hidden_dim) self.params['b3'] = np.zeros(hidden_dim) self.params['W4'] = weight_scale * np.random.randn(hidden_dim, num_classes) self.params['b4'] = np.zeros(num_classes) for k, v in self.params.iteritems(): self.params[k] = v.astype(dtype) def loss(self, X, y=None): W0, b0 = self.params['W0'], self.params['b0'] W1, b1 = self.params['W1'], self.params['b1'] W2, b2 = self.params['W2'], self.params['b2'] W3, b3 = self.params['W3'], self.params['b3'] W4, b4 = self.params['W4'], self.params['b4'] # pass conv_param to the forward pass for the convolutional layer filter_size = W1.shape[2] conv_param = {'stride': 1, 'pad': (filter_size - 1) / 2} # pass pool_param to the forward pass for the max-pooling layer pool_param = {'pool_height': 2, 'pool_width': 2, 'stride': 2} scores = None # two conv-relu layer scores, cache_conv0 = conv_relu_forward(X, W0, b0, conv_param) scores, cache_conv1 = conv_relu_forward(scores, W1, b1, conv_param) scores, cache_conv2 = conv_relu_pool_forward(scores, W2, b2, conv_param, pool_param) h1, cache_h1 = affine_relu_forward(scores, W3, b3) scores, cache_scores = affine_forward(h1, W4, b4) if y is None: return scores loss, grads = 0, {} data_loss, dscores = softmax_loss(scores, y) reg_loss = 0.5 * self.reg * np.sum(W0 * W0) + 0.5 * self.reg * np.sum(W1 * W1) + 0.5 * self.reg * np.sum(W2 * W2) + 0.5 * self.reg * np.sum(W3 * W3) + 0.5 * self.reg * np.sum( W4 * W4) loss = data_loss + reg_loss # backprop dh2, dW4, db4 = affine_backward(dscores, cache_scores) dh1, dW3, db3 = affine_relu_backward(dh2, cache_h1) dc2, dW2, db2 = conv_relu_pool_backward(dh1, cache_conv2) dc1, dW1, db1 = conv_relu_backward(dc2, cache_conv1) dX, dW0, db0 = conv_relu_backward(dc1, cache_conv0) # note to add L2 regularization!!! grads['W0'] = dW0 + self.reg * W0 grads['W1'] = dW1 + self.reg * W1 grads['W2'] = dW2 + self.reg * W2 grads['W3'] = dW3 + self.reg * W3 grads['W4'] = dW4 + self.reg * W4 grads['b0'] = db0 grads['b1'] = db1 grads['b2'] = db2 grads['b3'] = db3 grads['b4'] = db4 return loss, grads pass
29e89a5ff410272b629b2875d7324fd179bbb526
haokai-li/ICS3U-Unit3-02-Python-Guess
/guess.py
536
4.09375
4
#!/usr/bin/env python3 # Created by: Haokai Li # Created on: Sept 2021 # This Program guess a number between 0 - 9 import constant def main(): # This function guess a number between 0 - 9 # input number = int(input("Enter a number between 0 - 9: ")) print("") # process if number == constant.CORRECT: # output print("You guessed correctly!") if number != constant.CORRECT: # output print("You guessed wrong!") print("\nDone") if __name__ == "__main__": main()
3d8873d3ab91f3d7110b2affaaa60e4100ba95d8
MaksGrynk/python-for-qa
/lesson2-2/Level2.py
1,180
4.3125
4
# 3 Write a function that returns dictionary where keys are even numbers between 1 and n and values are keys in square, by default n = 100. dict_res = lambda val: {key:key ** 2 for key in xrange(1, val+1)} print "square dict " , dict_res(10) # ---------------------------------------- # 1 Write program to evaluate (a or not b) and (c or not a) expression for boolean varibles a, b, c showing result for all possible variables combinations. values = (True, False) def boolen(): for a in values: for b in values: for c in values: print ((a or not b) and (c or not a)) boolen() # ------------------------------------------ # 2 Write a function to return the sum of the numbers in the array, returning 0 for an empty array. Since the number 13 is very unlucky, it does not count, and numbers that come immediately after a 13 also do not count. Array could contain strings and boolean values (do not count them too): def val(num): i = 13 for n in num: if not isinstance(n,bool): if isinstance(n,int): if n == i: break mor.append(n) return sum(mor)
690d9e2def1b83585858fdc3dd7851e62efbdaa3
zyj0725/Function
/fun_narci_num.py
548
3.703125
4
''' 算出100~999之间的水仙花数(Narcissistic number) 水仙花数是指百位的3次方 加上 十位的3次方 加上 个位的3次方等于原数的整数 ''' def is_narci_num(n): if (n // 100) ** 3 + ((n % 100) // 10 ) ** 3 + ((n % 10) ** 3) == n: return True return False def count_narci_num(): L = [] for n in range(100,1000): if is_narci_num(n): print(n) L.append(n) return len(L) count_num = count_narci_num() print("100-999的水仙花数为:",count_num,"个")
4ccd406ad7014e7578048084f424dacd39d2692e
kt8506/Leetcode
/784-字母大小写全排列.py
1,812
3.640625
4
from string import ascii_lowercase class Solution(object): def letterCasePermutation(self, S): """ :type S: str :rtype: List[str] """ rs = [S] def flip(ch): if ch in ascii_lowercase: return ch.upper() else: return ch.lower() # one line # return ch.upper() if ch in ascii_lowercase else ch.lower() for i in range(len(S)): if S[i].lower() not in ascii_lowercase: # 说明当前字母是数字 continue else: ans = [] for cur_s in rs: # print(i,cur_s) tmp = cur_s[:i]+flip(cur_s[i])+cur_s[i+1:] ans.append(tmp) rs+=ans # print(rs) # ['1ab2', '1Ab2'] # ['1ab2', '1Ab2', '1aB2', '1AB2'] return rs def letterCasePermutation1(self, S): """ :type S: str :rtype: List[str] """ res = [""] print(len(res)) # 1 for s in S: # print(s) if not s.isalpha(): for i in range(len(res)): # print(i) # 0 1 0 1 2 3 res[i] += s else: for i in range(len(res)): # print(i) # 0 0 1 tmp = res[i] res[i] += s.lower() # print(i, res) res.append(tmp + s.upper()) print(i, res) return res def main(): S = "1ab2" myResult = Solution() # 第一个字符串的排列之一是第二个字符串的子串 print(myResult.letterCasePermutation(S)) if __name__ == '__main__': main()
9850b2d4f1b1216d9f35c62dabdc155323ca98ff
Ybbbbbbbbbbb/LeetCode
/34.searchRange.py
1,447
3.59375
4
class Solution: def searchRange(self, nums, target): left, right = 0, len(nums)-1 res = [-1, -1] if len(nums) == 1: if nums[0] == target: return [0, 0] else: return [-1, -1] else: while left <= right: mid = int((left + right)/2) if nums[mid] == target: if nums[mid-1] < target or mid -1 == -1: res[0] = mid break else: right = mid-1 elif nums[mid] < target: left = mid + 1 else: right = mid -1 left, right = 0, len(nums)-1 while left <= right: mid = int( (left + right) /2) if nums[mid] == target: if mid+1 >= len(nums): res[1] = mid break elif nums[mid+1] > target: res[1] = mid break else: left = mid + 1 elif nums[mid] < target: left = mid + 1 else: right = mid -1 return res if __name__ == "__main__": s = Solution() result = s.searchRange([5,7,7,8,8,10], 8) print(result)
c0177728f66bc0fb795bf3dc1c630da8af8b16dc
phillib/Python-On-Treehouse.com
/Date-and-Time/timezone_converter.py
360
3.96875
4
# Created using Python 3.4.1 import datetime import pytz starter = pytz.utc.localize(datetime.datetime(2015, 10, 21, 23, 29)) def to_timezone(timezone_name): """ This function takes a timezone as a user input and converts the starter time to that timezone """ new_timezone = pytz.timezone(timezone_name) return starter.astimezone(new_timezone)
a6142ff786c4532292b92a8799e7b4eb28a0716b
dmkok/python3
/hw13.py
602
4.125
4
''' Напишите функцию, которая переводит значения показаний температуры из Цельсия в Фаренгейт и наоборот. hw13: функция должны быть максимально удобной в использовании. ''' def convert(d): print(f'{d} градусов(а) Фаренгейта = ', '%.1f' % ((float(d)-32)*5/9), 'гадусов(а) Цельсия') print(f'{d} градусов(а) Цельсия = ', '%.1f' % (float(d)*9/5+32) , 'гадусов(а) Фаренгейта') convert(0.5)
5aeb12ddb227ac5d2049de1ea24a2a1d002f7cc4
baruchoz/oop_blackjack_project
/blackjack.py
1,460
3.875
4
import random class Card: def __init__(self, suit, val): self.suit = suit self.value = val # Method to print out card def show(self): if self.value == 1: val = "Ace" elif self.value == 11: val = "Jack" elif self.value == 12: val = "Queen" elif self.value == 13: val = "King" else: val = self.value print("{} of {}".format(val, self.suit)) class Deck: def __init__(self): self.cards = [] # Empty list to append to self.build() # Method to create a deck # Generate 52 Cards def build(self): # s== suit. v == value for s in ["Spades", "Clubs", "Diamonds", "Hearts"]: # For loop that will loop “suit” through ["Spades", "Clubs", "Diamonds", "Hearts"]. for v in range(1,14): # For loop within the first for loop that will loop through values in range(1,14) self.cards.append(Card(s, v)) # Display all cards in the deck def show(self): for card in self.cards: card.show() # Shuffle the deck def shuffle(self): random.shuffle(self.cards) # Deal a card def deal(self): return self.cards.pop() class Player: def __init__(self): self.hand = [] class User(Player): pass class Dealer(Player): pass class Game: def __init__(self): pass
4ec3238bd488810a0a0c42aac45480b71982d511
dishant470266/hacker_rank
/function.py
1,343
3.984375
4
# def add_two(a,b): # return(a+b) # print(add_two(5,4)) #========================================================= # def add_two(a,b): # return a+b # a = int(input("enter first nummber : ")) # b = int(input("enter second nummber : ")) # total = add_two(a,b) # print(total) #============================================================= # def last_letter(name): # return name[-1] # print(last_letter("disha")) # #==================================================== # def odd_even(num): # if num%2 == 0: # return "even" # return "odd" # #print(odd_even(5)) # num = int(input("enter first number : ")) # result = odd_even(num) # print(result) #==================================================== # def is_even(num): # return num%2 == 0 # print(is_even(5)) #============================================== #ex. 1 # def greater(a,b): # if a > b: # return a # else: # return b # num1 = int(input("enter first nummber : ")) # num2 = int(input("enter second nummber : ")) # bigger = greater(num1,num2) # print(bigger) #=============================================== def greater(a,b,c): if a>b and a>c: return a elif b>a and b>c: return b else: return c print(greater(10,20,30))
4179ce20a80295b1f0eced4a0846d7cd95ddd414
riri31/Machine_Learning_Training_Rabaute
/outliers/outlier_cleaner.py
922
3.90625
4
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ cleaned_data = [] from math import pow as mt import numpy as np residual_error = predictions-net_worths squares=[] squares=pow(residual_error,2) max=np.sort(squares,axis=None)[-9] j=0 for i in predictions: if pow(predictions[j]-net_worths[j],2) <max: item = (ages[j], net_worths[j],residual_error[j]) cleaned_data.append(item) j+=1 print 'Length of cleaned data={}'.format(len(cleaned_data)) ### your code goes here return cleaned_data
c418404602931a2170bef5548da680757fd46cc4
freanymellynusmany/Pratikum-Alproo-3
/Soal.py
1,105
3.65625
4
#Nama : Freany Mellyn Usmany #Universitas Kristen Duta Wacana #Soal bersumber dari https://koding.alza.web.id/latihan-soal-percabangan/ '''Berikut adalah beberapa istilah generasi berdasarkan tahun kelahirannya : Boomer = 1944 - 1964 Generasi X = 1965 - 1979 Generasi Y = 1980 - 1994 Generasi Z = 1995 - 2015 Buat program dimana user diminta untuk menuliskan nama dan tahun kelahirannya, kemudian cetak nama dan generasinya''' #Input nama = input("Masukkan nama Anda") #input nama tahun_lahir = int(input("Masukkan tahun berapa Anda lahir : ")) #input tahun lahir #Proses try: tl = int(tahun_lahir) if tl >=1944 and tl <=1964: print(nama, ", berdasarkan tahun lahir Anda tergolong Boomer") elif tl >=1965 and tl <=1979: print(nama, ", berdasarkan tahun lahir Anda tergolong Generasi X") elif tl >=1980 and tl <=1994: print(nama, ", berdasarkan tahun lahir Anda tergolong Generasi Y") elif tl >=1995 and tl <= 2015: print(nama, ", berdasarkan tahun lahir Anda tergolong Generasi Z") except: print("Tahun lahir Anda di luar range")
b691eda1e54e6b1335f5842eca106c3eeab4f105
AileenXie/leetcode
/141_linked_list_cycle.py
3,036
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/22 5:39 PM # @Author : aileen # @File : 141_linked_list_cycle.py # @Software: PyCharm """ Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node. Example 2: Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node. Example 3: Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. Follow up: Can you solve it using O(1) (i.e. constant) memory? """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def list_to_node(x,pos): head = ListNode(x[0]) p = head back = None for i in range(0,len(x)): p.next = ListNode(x[i]) p = p.next if i == pos: back = p if back is not None: p.next = back return head.next def node_to_list(head): x = [] p = head visited = {} pos = -1 index = 0 while p: if p not in visited.keys(): x.append(p.val) visited.setdefault(p, index) p = p.next else: pos = visited[p] break index += 1 return x, pos class Solution: """ 不破坏原链表 Runtime: 48ms, faster than 64.66%(visited用字典!!,用列表耗时1196 ms, faster than 5.11%) Memory Usage: 15.9 MB, less than 100.00% """ def hasCycle(self, head: ListNode) -> bool: p = head visited = {} while p: if p not in visited: visited.setdefault(p, 0) # 只存key,value无用,为了查找更快 p = p.next else: return True return False """ 巧思:有环,快跑和慢跑终会相遇 Runtime: 48 ms, faster than 64.66% Memory Usage: 15.8 MB, less than 100.00% """ def hasCycle1(self, head: ListNode) -> bool: fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False """ 破坏链表 Runtime: 48 ms, faster than 64.66% Memory Usage: 15.6 MB, less than 100.00% """ def hasCycle2(self, head: ListNode) -> bool: while head: if head.val is None: return True pre = head head = head.next pre.val=None return False if __name__ == "__main__": head = [1, 2] pos = 0 node = list_to_node(head, pos) print(Solution().hasCycle(node))
f31ca60bcf37eaddaf3b8aff53a5d8b7312e1e13
tapa8728/code_2_win
/mirror_replace_2_with_abc.py
382
3.6875
4
def f(n): if n <=0: return "" elif n == 1: return "1" elif n == 2: return "11" elif n == 3: return "abc1abc" elif n == 4: return "abc11abc" elif n%2 == 0: #even return str(n//2) + f(n-2) + str(n//2) elif n%2 != 0: #odd return str(n//2 + 1) + f(n-2) + str(n//2 + 1) print f(1) print f(2) print f(3) print f(4) print f(5) print f(6) print f(7) print f(8)
794790ba4929caec9359aa5cd27a4a947fa22561
jksdou/tkinter-learn
/demo/Menu/context_menu.py
1,819
3.546875
4
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # 弹出菜单, 利用鼠标右击事件触发 from tkinter import Frame, Menu, Tk, Toplevel window = Tk() window.title("右键弹出菜单") def callback(): print("回调") # 创建窗口 def createWindow(): w = Toplevel() w.title("新建窗口") # 绑定右键事件,在窗口的任意位置都可以右键弹出菜单 w.bind("<ButtonPress-2>", popup) menuBar = Menu(window) # 菜单栏 text_menu = Menu(menuBar) # 创建菜单,作为下拉菜单列表 menuBar.add_cascade(label="文本", menu=text_menu, command=callback) # 作为下拉菜单的标题 # 二级菜单 text_menu.add_command(label="复制", command=callback) text_menu.add_command(label="粘贴", command=callback) text_menu.add_command(label="撤销", command=callback) text_menu.add_separator() text_menu.add_command(label="重置", command=callback) text_menu.add_command(label="新建窗口", command=createWindow) # 一级菜单,直接放在菜单栏上,窗口菜单栏上不会生效 menuBar.add_separator() menuBar.add_command(label="重置2", command=callback) # 窗口菜单栏不现实 menuBar.add_command(label="新建窗口2", command=createWindow) # 窗口菜单栏不现实 # 没有置顶menu参数的情况下,在顶部菜单栏是无效的 menuBar.add_cascade(label="顶部菜单栏是无效的") # 禁用某个菜单 menuBar.entryconfigure(2, state='disabled') frame = Frame(window, width=512, height=512) frame.pack() def popup(event): # print(event.x_root + 10, event.y_root + 10) menuBar.post(event.x_root + 1, event.y_root) # frame绑定事件popup frame.bind("<Button-2>", popup) # or # frame.bind("<ButtonPress-2>", popup) # window绑定事件popup,此时的 # window.bind("<ButtonPress-2>", popup) window.mainloop()
162dd799dd9077b9a98aacb078bff36eea1d4283
ravish0007/patterns
/p0005.py
217
3.828125
4
a = ['d', 'C', 'B', 'a'] b = sorted(a, key=lambda x: x.lower()) print(b) """< ['a', 'B', 'C', 'd'] >""" print(a) """< ['d', 'C', 'B', 'a'] >""" a.sort(key=lambda s: s.lower()) print(a) """< ['a', 'B', 'C', 'd'] >"""
f1ecf90c19ae54ff646a3780a87defefac4d7da4
yiliyu1211/BattleShip_SimpleScripts
/player.py
5,253
3.953125
4
import random from ship import Ship from board import Board from position import Position # This is a naive implementation of a Player class that: # 1. Sets up the same board every time (i.e. a static layout) # 2. Fires randomly, without remembering which shots were hits and misses class Player: # Each player has a name. There should be no need to change or delete this! def __init__(self, name): self.__name = name self.results = [] # all position self.hitpos = [] # hit position self.hitonpos = [] def get_name(self): return self.__name def __str__(self): return self.get_name() # get_board should return a Board object containing 5 ships: # 1 aircraft carrier (length = 5) # 1 battleship (length = 4) # 1 cruiser (length = 3) # 1 submarine (length = 3) # 1 destroyer (length = 2) # You can make your own fun names for the ships, but the number and lengths # of the ship will be validated by the framework. Printing the board will # show the first letter of each ship's name. # This implementation returns the first sample layout from this web page: # http://datagenetics.com/blog/december32011/index.html def get_board(self): ships_1 = [Ship('Carrier', Position('J', 2), 5, False), Ship('battleship', Position('E', 5), 4, True), Ship('submarine', Position('B', 2), 3, False), Ship('crusier', Position('D', 8), 3, False), Ship('destroyer', Position('E', 3), 2, True)] ships_2 = [Ship('Carrier', Position('D', 2), 5, False), Ship('battleship', Position('F', 5), 4, True), Ship('submarine', Position('A', 2), 3, False), Ship('crusier', Position('A', 9), 3, True), Ship('destroyer', Position('I', 3), 2, True)] ships_3 = [Ship('Carrier', Position('C', 1), 5, True), Ship('battleship', Position('F', 7), 4, True), Ship('submarine', Position('A', 2), 3, False), Ship('crusier', Position('C', 9), 3, True), Ship('destroyer', Position('H', 4), 2, True)] ships_list = [ships_1, ships_2, ships_3] return Board(ships_list[random.randint(0, 2)]) # random shot def select_random_shot(self): row = chr(64 + random.randint(1, 10)) if row == 'A' or row == 'C' or row == 'E' or row == 'G' or row == 'I': col = random.choice((1, 3, 5, 7, 9)) else: col = random.choice((2, 4, 6, 8, 10)) return Position(row, col) def random_shot(self): shot = self.select_random_shot() shot_pos = (chr(shot.get_row_idx()+65), shot.get_col_idx()+1) while shot_pos in self.hitpos: shot = self.select_random_shot() shot_pos = (chr(shot.get_row_idx()+65), shot.get_col_idx()+1) self.hitpos.append(shot_pos) return shot # target shot def clear_around(self): hit_or_not = self.results[-1] pos = hit_or_not[0] # row = hit_or_not[0].get_row_idx() + 65 # col = hit_or_not[0].get_col_idx() + 1 # shot = Position(row, col) pos_loc = (chr(pos.get_row_idx()+65), pos.get_col_idx()+1) self.hitpos.append(pos_loc) if hit_or_not[1] is True: shot_list = self.target_around(pos) for x in shot_list: if (chr(x.get_row_idx()+65), x.get_col_idx()+1) not in set(self.hitonpos + self.hitpos): self.hitonpos.append((chr(x.get_row_idx()+65), x.get_col_idx()+1)) self.hitpos.append((chr(x.get_row_idx()+65), x.get_col_idx()+1)) # for shot in self.hitonpos: # if shot in self.hitpos: # self.hitonpos.remove(shot) # print(hit_or_not[0]) def target_shot(self): pos = self.hitonpos.pop() return Position(pos[0], pos[1]) def target_around(self, pos): target = [] row = pos.get_row_idx() + 65 col = pos.get_col_idx() + 1 N = Position(chr(row - 1), col) if N.validate() is True: target.append(N) S = Position(chr(row + 1), col) if S.validate() is True: target.append(S) E = Position(chr(row), (col + 1)) if E.validate() is True: target.append(E) W = Position(chr(row), (col - 1)) if W.validate() is True: target.append(W) return target def next_shot(self): # 1st # self.hit() if len(self.results) == 0: # print('-----') return self.random_shot() else: self.clear_around() if len(self.hitonpos) > 0: return self.target_shot() else: # print(self.hitonpos) return self.random_shot() # result is a tuple consisting of: # - the shot location (a Position object) # - whether the shot was a hit (True) or a miss (False) # - whether a ship was sunk (True) or not (False) def post_shot_result(self, result): self.results.append(result)
aeb5387a37f4d61e2d9dbd67fa541a669312856e
praveen2896/python
/Assignment_op.py
428
4.15625
4
f_num=input("enter the number1") print f_num s_num=input("enter the number2") print s_num answer=f_num+s_num answer += f_num print "addition ",answer answer -= f_num print "subtraction ",answer answer *= f_num print "multiplication ",answer answer /= f_num print "division ",answer answer %= f_num print "modolo ",answer answer ^=f_num print "exponent ",answer answer //=f_num print "floor division ",answer
7bb63a2dabb0e72e07cd55a6232f6805af3321d3
claraj/ProgrammingLogic1150Examples
/7_dictionaries/hello_dictionary_loop.py
525
4.5625
5
""" Looping over a dictionary examples """ classes = { 1150: 'Programming Logic', 1425: 'Data Communications', 1310: 'PC Maintenance' } # Looping over a dictionary - by default, loop over keys for class_code in classes: print(class_code) # To loop over the values, use the values() function for class_name in classes.values(): print(class_name) # And to loop over both at once, use the items() function for class_code, class_name in classes.items(): print(f'ITEC {class_code} is {class_name}')
1b30ee3a041a989f0afd3612482706783ebb14ea
ismaelconejeros/100_days_of_python
/Day 83/83_tic_tac_toe/tic_tac_toe_classes.py
5,143
3.765625
4
from turtle import Turtle, Screen WIDTH = 450 HEIGHT = 450 class CircleBlue(Turtle): def __init__(self): super().__init__() self.penup() self.hideturtle() self.shape('circle') self.speed('fastest') self.color('darkblue') self.shapesize(8,8) self.used_squares = [] def stamp_in(self, num): if num == 1: self.goto(-WIDTH*2/3, HEIGHT*2/3) elif num == 2: self.goto(0, HEIGHT*2/3) elif num == 3: self.goto(WIDTH*2/3, HEIGHT*2/3) elif num == 4: self.goto(-WIDTH*2/3, 0) elif num == 5: self.goto(0,0) elif num == 6: self.goto(WIDTH*2/3, 0) elif num == 7: self.goto(-WIDTH*2/3, -HEIGHT*2/3) elif num == 8: self.goto(0, -HEIGHT*2/3) elif num == 9: self.goto(WIDTH*2/3, -HEIGHT*2/3) else: pass self.stamp() def one(self): self.stamp_in(1) self.used_squares.append(1) def two(self): self.stamp_in(2) self.used_squares.append(2) def three(self): self.stamp_in(3) self.used_squares.append(3) def four(self): self.stamp_in(4) self.used_squares.append(4) def five(self): self.stamp_in(5) self.used_squares.append(5) def six(self): self.stamp_in(6) self.used_squares.append(6) def seven(self): self.stamp_in(7) self.used_squares.append(7) def eight(self): self.stamp_in(8) self.used_squares.append(8) def nine(self): self.stamp_in(9) self.used_squares.append(9) class CircleRed(Turtle): def __init__(self): super().__init__() self.penup() self.hideturtle() self.shape('circle') self.speed('fastest') self.color('red') self.shapesize(8,8) self.used_squares = [] def stamp_in(self, num): if num == 1: self.goto(-WIDTH*2/3, HEIGHT*2/3) elif num == 2: self.goto(0, HEIGHT*2/3) elif num == 3: self.goto(WIDTH*2/3, HEIGHT*2/3) elif num == 4: self.goto(-WIDTH*2/3, 0) elif num == 5: self.goto(0,0) elif num == 6: self.goto(WIDTH*2/3, 0) elif num == 7: self.goto(-WIDTH*2/3, -HEIGHT*2/3) elif num == 8: self.goto(0, -HEIGHT*2/3) elif num == 9: self.goto(WIDTH*2/3, -HEIGHT*2/3) else: pass self.stamp() def one(self): self.stamp_in(1) self.used_squares.append(1) def two(self): self.stamp_in(2) self.used_squares.append(2) def three(self): self.stamp_in(3) self.used_squares.append(3) def four(self): self.stamp_in(4) self.used_squares.append(4) def five(self): self.stamp_in(5) self.used_squares.append(5) def six(self): self.stamp_in(6) self.used_squares.append(6) def seven(self): self.stamp_in(7) self.used_squares.append(7) def eight(self): self.stamp_in(8) self.used_squares.append(8) def nine(self): self.stamp_in(9) self.used_squares.append(9) class Board(Turtle): def __init__(self): super().__init__() self.color('darkblue') self.pensize(4) self.speed('fastest') self.hideturtle() self.penup() self.goto(-WIDTH/3,HEIGHT) self.write("1", move=False, align="center", font=("Arial", 20, "bold")) self.pendown() self.goto(-WIDTH/3, -HEIGHT) self.penup() self.goto(WIDTH/3,HEIGHT) self.pendown() self.goto(WIDTH/3, -HEIGHT) self.penup() self.goto(-WIDTH,HEIGHT/3) self.pendown() self.goto(WIDTH, HEIGHT/3) self.penup() self.goto(-WIDTH,-HEIGHT/3) self.pendown() self.goto(WIDTH, -HEIGHT/3) self.penup() self.goto(-WIDTH*2/3, HEIGHT*2/3) self.write("1", move=False, align="center", font=("Arial", 20, "bold")) self.goto(0, HEIGHT*2/3) self.write("2", move=False, align="center", font=("Arial", 20, "bold")) self.goto(WIDTH*2/3, HEIGHT*2/3) self.write("3", move=False, align="center", font=("Arial", 20, "bold")) self.goto(-WIDTH*2/3, 0) self.write("4", move=False, align="center", font=("Arial", 20, "bold")) self.goto(0, 0) self.write("5", move=False, align="center", font=("Arial", 20, "bold")) self.goto(WIDTH*2/3, 0) self.write("6", move=False, align="center", font=("Arial", 20, "bold")) self.goto(-WIDTH*2/3, -HEIGHT*2/3) self.write("7", move=False, align="center", font=("Arial", 20, "bold")) self.goto(0, -HEIGHT*2/3) self.write("8", move=False, align="center", font=("Arial", 20, "bold")) self.goto(WIDTH*2/3, -HEIGHT*2/3) self.write("9", move=False, align="center", font=("Arial", 20, "bold"))
4bed2a27c2e495dc5787ce7899e89a84e90d48a2
dundunmao/lint_leet
/mycode/lintcode/Array/two sum/423 valid-parentheses.py
1,504
3.90625
4
# -*- encoding: utf-8 -*- # 括号是否合理 # 方法一: # 建一个空stack,建个hash={"]":"[", "}":"{", ")":"("}看到出左边的在value,右边的在key里, # 遍历string,遇到左边,就压入stack,如果是右半,就看跟栈顶的配不配对,配对,就把栈顶的pop出去,不配对,就false。 class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] dict = {"]":"[", "}":"{", ")":"("} for char in s: if char in dict.values(): #如果是左半,就压入栈 stack.append(char) elif char in dict.keys(): #如果是右半 if stack == [] or dict[char] != stack.pop():#如果栈空,就false;如果本轮的char对应的左半不是栈pop出来的那个,也false。如果是,就pop并进入下一轮 return False return stack == [] # 方法二: class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ n = len(s) if n == 0: return True if n % 2 != 0: return False while '()' in s or '{}' in s or '[]' in s: s = s.replace('{}', '').replace('()', '').replace('[]', '') if s == '': return True else: return False if __name__ == "__main__": str = '()())()' s = Solution() print s.isValid(str)
fdc8207dce4cc091af124bea6fc5b73273768f0a
codewithgurpreet/completepythoncourse
/Primitive Types/Escape Sequences.py
512
3.78125
4
course = "Python Programming" # What if you want to insert a double quote in your string? # There are two ways: # First one - use single quotes for the string course = 'Python "Programming' # Second one - use \ escape character course = "Python \"Programming" print(course) # Other common escape sequences # \" course = "Python \"Programming" print(course) # \' course = "Python \'Programming" print(course) # \\ course = "Python \\Programming" print(course) # \n course = "Python \nProgramming" print(course)
ce3276d02ac9613191a9a873c9ad23839a544ac5
that-jpg/repositorio_do_desafiador
/l33t/problems/_uri/Salary Increase/main.py
589
3.5
4
#!/usr/bin/env python n = float(input()) if(n <= 400.0): new_n = n * 1.15 delta_n = new_n - n percentage = 15 elif(n <= 800.0): new_n = n * 1.12 delta_n = new_n - n percentage = 12 elif(n <= 1200.0): new_n = n * 1.10 delta_n = new_n - n percentage = 10 elif(n <= 2000.0): new_n = n * 1.07 delta_n = new_n - n percentage = 7 else: new_n = n * 1.04 delta_n = new_n - n percentage = 4 print('Novo salario: {:0.2f}'.format(new_n)) print('Reajuste ganho: {:0.2f}'.format(delta_n)) print('Em percentual: ' + str(percentage) + ' %')
43b2341bc8c2396452b8e54d723d7de1edb8f7d6
seok-jong/Coding_Master
/CodeUp 100/code_up_6011.py
328
3.859375
4
# # 숫자(0~9)와 소수점(.)을 사용해 표현한 수를 실수(real number)라고 한다. # # 변수에 실수값을 저장한 후 # 변수에 저장되어 있는 값을 그대로 출력해보자. # # 예시 # f = input() # f = float(f) # print(f) # 와 같은 형태로 가능하다. # source Code print(float(input()))
85c0b3a93b1fc213e142a900b1dd630b57d8a961
M1-2000-2020/ICTPRG-Python
/Week05-Arrays_and_Lists/Quiz.Q2.py
773
4.40625
4
''' Design a program which will ask the user to enter the date in the form dd/mm/yyyy. Example 23/08/2019 The date will be printed like below: Date: 23 Month : 08 Year: 2019 ''' from itertools import groupby dateToday = input("Please enter the current date in the format dd/mm/yyyy: ") print("The date is: " + dateToday) print("I am now separating the numbers from the date and placing them in an array.") getNumbers = [''.join(j).strip() for sub in dateToday for k, j in groupby(sub, str.isdigit)] print ("The elements put in the array: " + str(getNumbers)) print("The day is: " + getNumbers[0]+getNumbers[1]) print("The month is: " + getNumbers[3]+getNumbers[4]) print("The year is: " + getNumbers[6]+getNumbers[7]+getNumbers[8]+getNumbers[9])
a87b09a7c7feeba588b7320192a4e7bc8b04a51b
chenxu0602/LeetCode
/765.couples-holding-hands.py
2,836
3.578125
4
# # @lc app=leetcode id=765 lang=python3 # # [765] Couples Holding Hands # # https://leetcode.com/problems/couples-holding-hands/description/ # # algorithms # Hard (53.49%) # Likes: 509 # Dislikes: 53 # Total Accepted: 20.8K # Total Submissions: 38.8K # Testcase Example: '[0,2,1,3]' # # # N couples sit in 2N seats arranged in a row and want to hold hands. We want # to know the minimum number of swaps so that every couple is sitting side by # side. A swap consists of choosing any two people, then they stand up and # switch seats. # # The people and seats are represented by an integer from 0 to 2N-1, the # couples are numbered in order, the first couple being (0, 1), the second # couple being (2, 3), and so on with the last couple being (2N-2, 2N-1). # # The couples' initial seating is given by row[i] being the value of the person # who is initially sitting in the i-th seat. # # Example 1: # Input: row = [0, 2, 1, 3] # Output: 1 # Explanation: We only need to swap the second (row[1]) and third (row[2]) # person. # # # Example 2: # Input: row = [3, 2, 0, 1] # Output: 0 # Explanation: All couples are already seated side by side. # # # # Note: # ⁠ # ⁠len(row) is even and in the range of [4, 60]. # ⁠row is guaranteed to be a permutation of 0...len(row)-1. # # # @lc code=start class Solution: def minSwapsCouples(self, row: List[int]) -> int: # Greedy # Time complexity: O(N^2) # Space complexity: O(1) # ans = 0 # for i in range(0, len(row), 2): # x = row[i] # if row[i + 1] == x ^ 1: # continue # ans += 1 # for j in range(i + 1, len(row)): # if row[j] == x ^ 1: # row[i + 1], row[j] = row[j], row[i + 1] # break # return ans # Cyclic Swapping # Time complexity: O(N) # Space complexity: O(N) pairs = {} for i in range(0, len(row), 2): pairs[row[i]] = row[i + 1] pairs[row[i + 1]] = row[i] res = 0 for pos in range(0, len(row), 2): if pairs[pos] != pos + 1: left, right = pairs[pos + 1], pairs[pos] pairs[left], pairs[right] = right, left res += 1 return res # Union Find # N = len(row) # d = [0] * N # def find(a): # if d[a] != a: # d[a] = find(d[a]) # return d[a] # def union(a, b): # d[find(a)] = d[find(b)] # for i in range(0, N, 2): # d[i] = d[i + 1] = i # for i in range(0, N, 2): # union(row[i], row[i + 1]) # return (N // 2) - sum([1 for i in range(0, N, 2) if i == d[i] == d[i + 1]]) # @lc code=end
3f7cbc854fa8a9a3c11dda56f02fa2cc37e7cdd1
Jeetendranani/yaamnotes
/algorithm/007_count_sort.py
512
3.703125
4
""" count_sort(A, B, k): for i in range(k): B[i] = 0 for j in range(len(A)): b[A[j]] += 1 j = 0 for i in range(k): for n in range(B[i]): A[j] = i j += 1 """ def count_sort(nums1, nums2, k): nums2 = [0] * k for i in range(len(nums1)): nums2[nums1[i]] += 1 i = 0 for j in range(k): for n in range(nums2[j]): nums1[i] = j i += 1 nums1 = [1, 2, 3, 3, 2, 1, 5, 6, 0, 1, 4] nums2 = [] count_sort(nums1, nums2, 7) print(nums1)
04750264a11519a001ec51f961f1658f6d8ee470
salamer/My_OJ_practice
/python/power_of_three.py
347
3.734375
4
class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ if n==3: return True res=0 while(n>0): res=n%10+res n=n/10 print res if(res==9): return True else: return False
aebc4118caaf2d65a52822ec86d3b414fa2ccf6b
shiquanz/Python_stu
/_07advanced_oop.py
3,002
3.6875
4
#-*- coding:utf-8 -*- ''' ''' class Student(object): """docstring for Student""" pass s = Student() s.name = 'Joker' # 动态给实例绑定一个属性 print s.name def set_age(self , age): self.age = age from types import MethodType s.set_age = MethodType(set_age , s , Student) #给实例绑定一个方法 s.set_age(25) ##调用实例方法 print s.age ##测试结果 #但给一个实例绑定方法,对另一个实例不起作用 s2 = Student() # s2.set_age(24) 尝试调用方法,报 AttributeError #为了给所有实例都绑定方法,可以给class绑定方法: def set_score(self , score): self.score = score Student.set_score = MethodType(set_score , None , Student) #绑定方法后,实例均可以使用 s.set_score(100) s2.set_score(88) print s.score print s2.score #动态绑定允许我们在程序运行的过程中动态给class加上功能 '''如果想要限制class的属性,只允许对student实例添加name和age属性''' '''python允许定义class的时候,定义一个特殊变量__slots__ , 来限制class能添加的属性''' class Students(object): """docstring for Students""" __slots__ = ('name' , 'age') #用tuple定义允许绑定的属性名称 c = Students() c.name = 'Michael' #动态绑定属性name s.age = 22 # s.score = 89 报错AttributeError ''' 只用__slots__注意: __slots定义的属性仅对当前类起作用,对继承的子类不起作用!! ''' ''' Python 内置的 @property装饰器负责把一个方法变成属性调用 ''' class Studen(object): """docstring for Studen""" @property # @property把一个getter方法变成属性 def score(self): return self._score @score.setter # @score.setter把 setter方法变成属性 def score(self , value): if not isinstance(value , int): raise ValueError('score must be an integer!') if (value<0 or value>100): raise ValueError('score must between 0-100') self._score = value s = Studen() s.score = 60 print s.score #s.score = 99999 ##报错ValueError ## @property广泛应用在类的定义中,可以让调用者写出简短的代码, ## 同时保证对参数进行必要的检查 ''' 多继承 class Dog(Animal , Flying): """docstring for Dog""" pass 通过多继承,一个子类就可以同时获得多个父类的所有功能 ''' ''' Mixin 在设计类的继承关系时,通常,主线都是单一继承下来的, 如果需要“混入”额外的功能,通过多重继承就可以实现, 这种设计通常称之为 Mixin。 Mixin的目的就是给一个类增加多个功能, 这样,在设计类的时候,我们优先考虑通过多重继承选择组合不同的类的功能, 而不是设计多层次的复杂的继承关系。 ''' """ ###### 定制类 __str__ __iter__ __getitem__ __getattr__ __call__ ###### 定制类 """ # type() 函数可以查看一个类型或变量的类型 # __metaclass__ : metaclass 允许你创建类或者修改类,或者:类可以看成是metaclass的"实例"
f29a1e7e0521d0db4f1b28ecf9dc7fcd0ac1eafb
Spartabariallali/Pythonprograms
/pythonSparta/pythonday2.py
1,712
4.375
4
# # data types and operators # # strings and casting # # concatenation # # single quotes vs double quotes # # checking the values as Boolean output(True/False) # x = 10 # y = 11 # print(x == y) #False # print(x > y) #False # print(x < y) #True # print(x != y) #True # age = 18 # print(age < 19) # print( 3 % 9) #modular returns the left over value after division # #Double quotes VS single quotes # print("hello world") #double quotes is best practise # print('hello world') # #single quotations can return error when using apostrophes # #print('bari's class is eng 67') # #double quotes remove the error # print("bari's class is eng 67") # #using \ \ is a method to use apostrophes # print('bari\'s class is eng 67') # #Strings, Indexing, Casting, Slicing and concatenation # greeting = ("hello") # print(greeting) # # indexing # print(len(greeting)) # #concatenation # welcome_user = input("please enter your name: ") # print(welcome_user) # print(greeting + ' ' + welcome_user) # hi = "hello world" # print(len(hi)) # print(hi[-1]) # for i in hi: # print(i) # print(hi[6:11]) # print(hi[-11:-6]) # print(hi[-6:-1]) # #strip removes the space at the end of a string # remove_white_space = "strip removes the space at the end of a string" # print(len(remove_white_space)) # print(len(remove_white_space.strip())) #boolean values within DATA types use_text = "here's SOME text with lots of texts" #count() - counts the substring within the string print(use_text.count("t")) print(use_text.lower()) print(use_text.upper()) print(use_text.capitalize()) print(use_text.title()) #replacing text in the string print(use_text.replace("text","jargon"))
ad6f177450727bcf6bdb4de32bbb394fa1f191d2
Isobel22/Arena
/arena_game.py
7,399
3.53125
4
#Arena - combat turn-based game from sys import exit from dies_roll import die6, die10 from characters import heavy, cat, rogue, giant, amazon, two_orc, random_character, p_heavy, p_cat, p_rogue, p_giant, p_amazon, p_two_orc from weapons import sabre, great_club, sword, rapier, lance from fight_style import standard, aggressive, defensive, strong, furious, parry, after_parry, after_furious class Arena(object): def __init__(self, player_name): self.player_name = player_name def menu(self): """main options""" chosen_menu = '1' while chosen_menu not in ('3'): print "-------------------------------\n A*R*E*N*A !!! \nTurn-based battle game by Misa\n-------------------------------" print "1: PLAY THE GAME\n2: GAME RULES\n3: EXIT:" chosen_menu = raw_input("> ") if chosen_menu == "1": self.play() elif chosen_menu == "2": self.rules() elif chosen_menu == "3": exit(0) def play(self): """basic game scheme""" print "Game started, %s ! \n" % self.player_name print "Now select your character \n" self.player = self.choosing_character() # player chooses his character print "You are playing as %s, the %s, fighting with %s." % (self.player.name, self.player.title, self.player.weapon.name) print "Hitpoints: %s, Base attack: %s, Defense: %s\n" % (self.player.hp, self.player.attack, self.player.defense) print "Now selecting random opponent... \n" raw_input(">") self.opponent = self.random_opponent() # random AI opponent is selected print "Your opponent: %s, the %s, fighting with %s." % (self.opponent.name, self.opponent.title, self.opponent.weapon.name) print "Hitpoints: %s, Base attack: %s, Defense: %s, %s \n" % (self.opponent.hp, self.opponent.attack, self.opponent.defense, self.opponent.description) raw_input("Press any key: ") self.combat() # all combat procedures including game endings def choosing_character(self): """Choosing predefined player character or create custom character""" player_chars = {"1": p_heavy, "2": p_cat, "3": p_rogue, "4": p_giant, "5": p_amazon, "6": p_two_orc} # pre-built characters weapons = {"1": sabre, "2": great_club, "3": sword, "4": rapier, "5": lance} print "Choose your warrior:" for index, character in sorted(player_chars.iteritems()): # prints all pre-built characters print "%s: %s, %s" % (index, character.name, character.title) print "7: Custom character" choose = raw_input("> ") while choose not in player_chars or choose != "7": try: return player_chars[choose] except KeyError: if choose == "7": print "Choose your name:" random_character.name = raw_input("> ") # custom name print "Select weapon:" # custom character weapons for index, weapon in sorted(weapons.iteritems()): print "%s: %s, attack %s, damage: %s" % (index, weapon.name, weapon.attack, weapon.damage_string) player_weapon = None while player_weapon not in weapons: player_weapon = raw_input("> ") try: random_character.weapon = weapons[player_weapon] except KeyError: print "Try again" return random_character else: print "Try again" def random_opponent(self): """randomly choosing an opponent""" opp_chars = {1: heavy, 2: cat, 3: rogue, 4: giant, 5: amazon, 6: two_orc} # pre-built characters opp_roll = die6() return opp_chars[opp_roll] def combat(self): """ Basic scheme of combat, rounds counting, styles history, win/lose conditions, endings""" round = 1 while self.player.hp > 0 and self.opponent.hp > 0: print "-------------------------------\nFighting round %s began!\n-------------------------------" % round self.player.attacking(self.opponent, True) self.opponent.attacking(self.player, False) round += 1 if self.player.hp <= 0 and self.opponent.hp > 0: # LOSE print "-------------------------------\n%s is falling to the ground, heavily wounded.\nYOU LOST THIS MATCH!!!\n------------------------------- " % self.player.name elif self.player.hp > 0 and self.opponent.hp <= 0: # WIN print "-------------------------------\nYour foe %s is falling to the ground, heavily wounded.\nYOU WON THIS MATCH!!!\n------------------------------- " % self.opponent.name elif self.player.hp <= 0 and self.opponent.hp <= 0: # DRAW print "-------------------------------\nYou brutally hit %s in same moment, as %s hit you. You both are falling to the ground, heavily wounded.\nTHIS WAS A DOUBLE KILL!!!\n------------------------------- " % (self.opponent.name, self.opponent.name) raw_input("Press any key:") def rules(self): weapons = [sabre, great_club, sword, rapier, lance] styles = [standard, aggressive, defensive, strong, furious, parry] game_rules = {"1": "BASIC SYSTEM:\nIn this game, you select your character and you fight in arena against selected foe. Both fighters have HitPoints, Attack and Defense stats. First combanatnt with zero or less HP loses the fight and game ends. ", "2": "FIGHTING ROUND:\n\nEach round both opponent try to hit each other.\nWhen the combatant is attacking, he makes random 1d10 roll (1-10). Then he adds his base attack, and his weapon attack bonus and bonus for his style. If total score is higher than opponent Defense score, the opponent is his. Combatant then rolls his damage roll, which depends on his weapon. Result is substracted from opponents HitPoints.", "3": "FIGHTING STYLES:\nAt the beginning of each round, you can choose your fighting style for the round. Each one can alter your stats in some way:", "4": "WEAPONS:\nThere are different weapons in game, each has its own attack and damage modifier. For example Sword has attack bonus 0, and deal damage of 1d6 + 1, e.g. one roll of six-sided dice plus 0, so the range is between 2 - 7." } chosen_rule = None while chosen_rule != "5": print "GAME RULES:\n1: BASIC SYSTEM\n2: FIGHTING ROUND\n3: FIGHTING STYLES\n4: WEAPONS\n5: BACK TO MAIN MENU" chosen_rule = raw_input("> ") try: print game_rules[chosen_rule] if chosen_rule == "3": for style in styles: print "%s: attack %s, defense %s, damage bonus %s. %s" % (style.name, style.attack_bonus, style.defense, style.damage_bonus, style.style_desc) if chosen_rule == "4": for weapon in weapons: print "%s: attack %s, damage: %s" % (weapon.name, weapon.attack, weapon.damage_string) except KeyError: pass my_game = Arena("Misa") my_game.menu()
f66cfd8d786bce9d3aa10732475b15e504fbd790
wwwwodddd/Zukunft
/spoj/THRPWRS.py
223
3.640625
4
while True: n = int(input()) if n == 0: break if n == 1: print('{ }') continue n -= 1 s = '{ ' f = 0 for i in range(64): if n >> i & 1: if f: s += ', ' f = 1 s += str(3 ** i) s += ' }' print(s)
58154bcca5863b1ba47c029c99c28507905e9765
Aasthaengg/IBMdataset
/Python_codes/p03544/s224362737.py
130
3.671875
4
N = int(input()) R = [2, 1] if N < 2: print(R[N]) exit() for i in range(2, N+1): R.append(R[i-1] + R[i-2]) print(R[N])
ec7cc7f43f78519e20f76a46d5f1dc52e3da1f96
anbcodes/MultiplicationPersistence
/MultPersistChecker.py
315
3.703125
4
import sys steps = 0 maxNumber = 0 maxSteps = 0 def check(number): global steps sum = 1 print("step {}: {}".format(steps,number)) if (len(str(number)) <= 1): return number for x in str(number): sum *= int(x) steps += 1 check(sum) check(sys.argv[1]) print("steps:", steps)
4a125d8f906b0472ae9486aabc00f07e6afb6d2a
thalycomp/Python-Exercises
/Arquivos/ex1_arquivos.py
373
4.21875
4
""" Exercício 1: Escreva um programa que leia o arquivo Mbox-short e mostre o con- teúdo deste (linha por linha), completamente em caixa alta. """ try: entrada = input("Arquivo > ") arquivo = open(entrada) except: print("Erro. Arquivo não encontrado. ") exit() for linha in arquivo: linha = linha.rstrip() linha = linha.upper() print(linha)
b28c660ffb4e659afb8f4f7fc1b4eb8e7c5f4271
LarynQi/leetcode
/easy/freqAlphabets.py
651
3.53125
4
# https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/ # https://leetcode.com/submissions/detail/442256001/ # 01/12/2021 17:51 class Solution: def freqAlphabets(self, s: str) -> str: s = s.split("#") result = "" n = len(s) for i in range(n): c = s[i] if i == n - 1 and "#" not in c: for ch in c: result += chr(int(ch) + 96) else: while len(c) >= 3: result += chr(int(c[0]) + 96) c = c[1:] result += chr(int(c[:2]) + 96) return result
2d5b5a7f60a257220b85abdb685668bd65d1d3b1
toticavalcanti/uri_online_judge
/1037.py
511
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 7 15:10:31 2018 @author: toti.cavalcanti """ num = float(input()) intervals = ["[0,25]", "(25,50]", "(50,75]", "(75,100]"] if num < 0 or num > 100: print("Fora de intervalo") elif num >= 0 and num <= 25: print("Intervalo {}".format(intervals[0])) elif num > 25 and num <= 50: print("Intervalo {}".format(intervals[1])) elif num > 50 and num <= 75: print("Intervalo {}".format(intervals[2])) else: print("Intervalo {}".format(intervals[3]))
7c7a97fa75c2da1717c75d222d2002a9046e40aa
venkatatejaswi9/1p
/fact.py
72
3.6875
4
f=int(input()) fact=1 while(f>0): fact=fact*f f=f-1 print(fact)
e6774c9420d4cc303b1ed3be349a62060f0d65be
bfavis2/hackerrank
/algorithms/sorting/find-the-median.py
256
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 25 10:24:18 2020 @author: brianf """ def findMedian(arr): sorted_arr = arr.copy() sorted_arr.sort() median_index = len(sorted_arr) // 2 return sorted_arr[median_index]
caebe76a85186838eb02eb940ff5e9e4f694c6ae
zjw-hunter/CFAB
/Module 8/encapsulation.py
818
3.6875
4
class myBankAccount: def __init__(self): self.__myBalance = 0 def getBalance(self): return(self.__myBalance) def __setBalance(self, newBalance): self.__myBalance = newBalance def deposit(self, amount): self.__setBalance(self.__myBalance + amount) print("New balance: ", self.__myBalance) def withdraw(self, amount): if( amount > self.__myBalance): print("Not enough money!") else: self.__setBalance(self.__myBalance - amount) print("You withdrew: ", amount, "\nBalance remaining: ", self.__myBalance) mba = myBankAccount('Zach') mba.deposit(50) print(mba.getBalance()) mba.withdraw(49) print(mba.getBalance()) mba.withdraw(2) print(mba.getBalance()) # mba.__setBalance(50)
3b6a7f9f92b52480b234f61b6873053dc7f1b200
priyash555/Automation-Bots
/KS/MAIN APP_after/MAIN APP/name_extractor.py
1,237
3.515625
4
import nltk from nameparser.parser import HumanName # TEST CASE text = ['in the car version 2 and Abhinav Anand.', 'hi there John Vogue.','Regards,', 'Gaurav Sharma'] def get_human_names(text): ''' takes a string and returns a list of names present in it. ''' tokens = nltk.tokenize.word_tokenize(text) # tokenize pos = nltk.pos_tag(tokens) sentt = nltk.ne_chunk(pos, binary = False) # chunking person_list = [] person = [] name = "" for subtree in sentt.subtrees(filter=lambda t: t.label() == 'PERSON'): for leaf in subtree.leaves(): person.append(leaf[0]) if len(person) > 1: #avoid grabbing lone surnames for part in person: name += part + ' ' if name[:-1] not in person_list: person_list.append(name[:-1]) name = '' person = [] return (person_list) def crawl_names(lines): ''' takes a list of lines join the lines to form a string and extract the names using the get_human_names function above ''' text = '\n'.join(lines) names = get_human_names(text) return names print(crawl_names(text))
669d8fadb8907040fef118b50c2e34eb3f336ed3
Rozdrigo/python
/potência.py
164
3.703125
4
bas = int(input('Dado a base: ')) exp = int(input('e o expoente: ')) res = 1 for x in range(exp): res *= bas print('o resultado é: {NUM}' .format(NUM = res))
5184d9fa1e4f822b687ecbb4fc26ec44f64f7be8
bayramcicek/language-repo
/p057_more_else.py
1,938
4.3125
4
#!/usr/bin/python3.6 # created by cicek on 14.09.2018 16:45 ''' The else statement is most commonly used along with the if statement, but it can also follow a for or while loop, which gives it a different meaning. With the for or while loop, the code within it is called if the loop finishes normally (when a break statement does not cause an exit from the loop) ''' print("\n-------------------FOR-ELSE--------------------------------------------") for i in range(10): if i == 5: print("5: non break in for") else: print("Unbroken and with-for ELSE3") print("---------------------------------") for i in range(10): if i == 999: print("aaa") # or print, does not matter else: print("Unbroken non-for ELSE1") # Unbroken ELSE1 print("---------------------------------") for i in range(10): if i == 5: print("5: break in for") break else: print("broken ELSE2") print("\n-------------------WHILE-ELSE-------------------------------------------") a = 5 while a < 10: print(a, "in while") a += 1 else: print("else part with while") print("-----------------------") b = 15 while b < 10: print(a, "in while") a += 1 else: print("else part non-while") print("--------------------------") c = 5 while c < 10: print(c, "in while with break") c += 1 break else: print("else part with break") print("\n-------------------TRY-EXCEPT-ELSE--------------------------------------------") # The else statement can also be used with try/except statements. # In this case, the code within it is only executed if no error occurs in the try statement. try: print("try") # try except ZeroDivisionError: print("ZeroDivisionError") else: print("else1") # else1 print("------------------------------") try: print(1/0) print("e") except ZeroDivisionError: print("ZeroDivisionError") # ZeroDivisionError else: print("else2")
a060b33270c6c736e397f22f81ebab6f68b1a4e8
arcae/git_lesson-1
/data/portcsv.py
626
3.671875
4
#using csv module import csv def portfolio_cost(filename): ''' Computes total shares*proce for a CSV file with name,shares,price data' ''' total = 0.0 with open(filename,'r') as f: rows = csv.reader(f) headers = next(rows) #skip first row for headers for rowno, row in enumerate(rows,start=1): try: row[2] = int(row[2]) row[3] = float(row[3]) except ValueError as err: print('Row:',rowno, 'Bad row:',row) print('Row:',rowno, 'Reason:', err) continue #skip to the next row total += row[2]*row[3] return total total = portfolio_cost('Mydata1.csv') print('Total cost:', total)
b2c0af11c6e9ff22c8fc310f86409635bc0d850f
tygamvrelis/CSC411-Project2
/Code/part4.py
11,486
3.53125
4
## part4.py # In this file, helper functions are defined for training the simple neural # network in part 2 using vanilla gradient descent, and plotting learning # curves. from pylab import * import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook import time from scipy.misc import imread from scipy.misc import imresize import matplotlib.image as mpimg from scipy.ndimage import filters import urllib from numpy import random import cPickle import os from scipy.io import loadmat import re import part2 as p2 import part3 as p3 def makeTrainingMatrices(): ''' makeTrainingMatrices returns 2 matrices: X -- the training matrix whose columns correspond to images Y -- the label matrix whose i-th column corresponds to the i-th target output Also returned is a list of tuples (digit, start index). This way, one can easily reference the images for each digit from within X and Y. ''' M = loadmat("../Data/mnist_all.mat") # Load MNIST dataset numExamples = sum([len(M[k]) for k in M.keys() if "train" in k]) # Pre-allocate space for matrices X = np.empty((28 * 28 + 1, numExamples)) # 28 * 28 + 1 = num_pixels + bias Y = np.empty((10, numExamples)) # 10 is the number of output classes indices = list() i = 0 for k in M.keys(): if("train" in k): # print(k) # Notice that digit 0,...,9 are not grabbed in order numImages = M[k].shape[0] # Number of images for the current digit digitNum = int(re.findall('\d', k)[0]) # The current digit indices.append((digitNum, i)) # Track the starting index for this # digit in the columns of X M[k] = np.true_divide(M[k], 255.0) # Normalize images M[k] = np.vstack((np.ones((1, numImages)), M[k].T)) # Stack 1s ontop X[:, i:i + numImages] = M[k].copy() # Put images in X matrix # Make the label for this set of images label = np.zeros((10, 1)) label[digitNum] = 1 Y[:, i:i + numImages] = label i += numImages return (X, Y, indices) def makeTestMatrices(): ''' makeTestMatrices returns 2 matrices: X -- the test matrix whose columns correspond to images Y -- the label matrix whose i-th column corresponds to the i-th target output Also returned is a list of tuples (digit, start index). This way, one can easily reference the images for each digit from within X and Y. ''' M = loadmat("../Data/mnist_all.mat") # Load MNIST dataset numExamples = sum([len(M[k]) for k in M.keys() if "test" in k]) # Pre-allocate space for matrices X = np.empty((28 * 28 + 1, numExamples)) # 28 * 28 + 1 = num_pixels + bias Y = np.empty((10, numExamples)) # 10 is the number of output classes indices = list() i = 0 for k in M.keys(): if("test" in k): # print(k) numImages = M[k].shape[0] # Number of images for the current digit digitNum = int(re.findall('\d', k)[0]) # The current digit indices.append((digitNum, i)) # Track the starting index for this # digit in the columns of X M[k] = np.true_divide(M[k], 255.0) # Normalize images M[k] = np.vstack((np.ones((1, numImages)), M[k].T)) # Stack 1s ontop X[:, i:i + numImages] = M[k].copy() # Put images in X matrix # Make the label for this set of images label = np.zeros((10, 1)) label[digitNum] = 1 Y[:, i:i + numImages] = label i += numImages return (X, Y, indices) def part4_gradient_descent(X, Y, init_W, alpha, eps, max_iter): ''' part4_gradient_descent finds a local minimum of the hyperplane defined by the hypothesis dot(W.T, X). The algorithm terminates when successive values of W differ by less than eps (convergence), or when the number of iterations exceeds max_iter. Arguments: X -- input data for X (the data to be used to make predictions) Y -- input data for X (the actual/target data) init_W -- the initial guess for the local minimum (starting point) alpha -- the learning rate; proportional to the step size eps -- used to determine when the algorithm has converged on a solution max_iter -- the maximum number of times the algorithm will loop before terminating ''' Whistory = list() iter = 0 previous_W = 0 current_W = init_W.copy() firstPass = True history = list() # Do-while... while(firstPass or (np.linalg.norm(current_W - previous_W) > eps and iter < max_iter)): firstPass = False previous_W = current_W.copy() # Update the previous W value # Update W current_W = current_W - alpha * p3.negLogLossGrad(X, Y, current_W) if(iter % (max_iter // 100) == 0): # Print updates every so often and save cost into history list cost = p3.NLL(p2.SimpleNetwork(current_W, X), Y) history.append((iter, cost)) Whistory.append(current_W) print("Iter: ", iter, " | Cost: ", cost) iter += 1 return(Whistory, history) def part4_split_sets(X, Y, train_size, val_size, indices): ''' part4_split_sets allocates the data in X and Y into a training set and a validation set. It returns the X and Y matrices corresponding to their respective sets in a tuple of 4 matricies. Arguments: X -- matrix of training examples whose columns correspond to images from which predictions are to be made Y -- matrix of labels whose i-th column corresponds to the actual/target output for the i-th column in X train_size -- The desired number of images in the training set. val_size -- The desired number of images in the validation set. indices -- a list containing the starting indexes for the various digits ''' # Prepare data numDigits = len(indices) #10 trainX = np.zeros(shape=(X.shape[0], train_size * numDigits)) trainY = np.zeros(shape=(Y.shape[0], train_size * numDigits)) valX = np.zeros(shape=(X.shape[0], val_size * numDigits)) valY = np.zeros(shape=(Y.shape[0], val_size * numDigits)) for j in range(numDigits): offset = [k[1] for k in indices if k[0] == j][0] for i in range(train_size + val_size): if i < train_size: trainX[:, i + j * train_size] = X[:, i + offset] # data to predict upon (images) trainY[:, i + j * train_size] = Y[:, i + offset] # target/actual values (labels) else: valX[:, i - train_size + j * val_size] = X[:, i + offset] # data to predict upon (images) valY[:, i - train_size + j * val_size] = Y[:, i + offset] # target/actual values (labels) j += 1 return (trainX, trainY, valX, valY) def part4_classify(X, Y, W): ''' part4_classify returns the average cost and percentage of correct classifications for the hypothesis np.dot(W.T, x), using the learned weights W and testing the images in the input set against the labels. Arguments: X -- the input image matrix from which predictions are to be made Y -- the label matrix which the predictions will be compared to W -- the learned parameters that will be used to make predictions ''' output = list() #numDigits = len(Yindices) # 10 P = p2.SimpleNetwork(W, X) # Make predictions for ALL inputs correct = [0.0]*10 cost = [0.0]*10 size = [0]*10 total_samples = int(X.shape[1]) #Find out how many samples there are to classify. for i in range(total_samples): highest = np.argmax(P[:, i]) #Find the prediction from the network label = np.argmax(Y[:, i]) #Find the label of the given input if highest == label: correct[label] += 1 size[label] += 1 cost[label] += p3.NLL(P[:, i], Y[:, i]) for j in range(10): output.append((j, cost[j]/size[j], correct[j]/size[j])) return output def part4_plotLearningCurves(XTrain, YTrain, XVal, YVal, Whistory, history, imagePath, part): ''' part4_plotLearningCurves plots the learning curves associated with training a neural network. Arguments: history -- a list of pairs of numbers (num_iterations, cost), where cost is the average cost associated with training the neural network using num_examples training examples. ''' correctTrain = [] correctVal = [] costTrain = [] costVal = [] for i in range(100): outputList = part4_classify(XTrain, YTrain, Whistory[i]) correctTrain.append(sum([a[2] for a in outputList])/len(outputList)) costTrain.append(sum([a[1] for a in outputList])) outputList = part4_classify(XVal, YVal, Whistory[i]) costVal.append(sum([a[1] for a in outputList])) correctVal.append(sum([a[2] for a in outputList]) / len(outputList)) num_iter = [i[0] for i in history] #cost = [i[1] for i in history] plt.figure(plt.gcf().number + 1) plt.plot(num_iter, costTrain) plt.ylabel('Cost') plt.xlabel('Iterations') plt.title('Training Set Cost Learning Curve') plt.savefig(imagePath + part + "training_set_cost" + ".jpeg") plt.show() plt.figure(plt.gcf().number + 1) plt.plot(num_iter, correctTrain) plt.ylabel('Accuracy') plt.xlabel('Iterations') plt.title('Training Set Accuracy Learning Curve') plt.savefig(imagePath + part + "training_set_acc" + ".jpeg") plt.show() plt.figure(plt.gcf().number + 1) plt.plot(num_iter, costVal) plt.ylabel('Cost') plt.xlabel('Iterations') plt.title('Validation Set Cost Learning Curve') plt.savefig(imagePath + part + "valid_set_cost" + ".jpeg") plt.show() plt.figure(plt.gcf().number + 1) plt.plot(num_iter, correctVal) plt.ylabel('Accuracy') plt.xlabel('Iterations') plt.title('Validation Set Accuracy Learning Curve') plt.savefig(imagePath + part + "valid_set_acc" + ".jpeg") plt.show() def part4_plotWeights(W, indices, imagePath, str_part): ''' part4_plotWeights produces visualizations of the learned parameters in the weight matrix W. Arguments: W -- the weight matrix to be visualized indices -- a list containing the starting indexes for the various digits imagePath -- a string giving the location to which images should be saved str_part -- a string indicating the project part ''' nums = [k[0] for k in indices] for n in nums: plt.figure(plt.gcf().number + 1) plt.yscale('linear') plt.title("(Part 4) " + str(n)) plt.imshow(W[1:,n].reshape((28,28)), interpolation = 'gaussian', cmap = plt.cm.coolwarm) plt.colorbar(orientation='vertical') plt.show() plt.savefig(imagePath + str_part + str(n) + ".jpg")
a5f20be446de1b2b6c737a360426cff48ac1d454
Cassie07/19FallSemesterHW
/algo2/mss_linear.py
1,014
3.875
4
def find_max_subarray(arr, start, end): """Returns (l, r, m) such that arr[l:r] is the maximum subarray in A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x < end.""" max_ending_at_i = tmp_max = arr[start] max_left_at_i = tmp_max_left = start # max_right_at_i is always i + 1 tmp_max_right = start + 1 for i in range(start + 1, end): if max_ending_at_i > 0: max_ending_at_i += arr[i] else: max_ending_at_i = arr[i] max_left_at_i = i if max_ending_at_i > tmp_max: tmp_max = max_ending_at_i tmp_max_left = max_left_at_i tmp_max_right = i + 1 return tmp_max_left, tmp_max_right, tmp_max arr = input('Enter the list of numbers: ') arr = arr.split() arr = [float(x) for x in arr] start, end, maximum = find_max_subarray(arr, 0, len(arr)) print('The maximum subarray starts at index {}, ends at index {}' ' and has sum {}.'.format(start, end - 1, maximum))
f3d04a00d351454520b77d7b86f208b897fdb7d5
mrudula-pb/Python_Code
/Udacity/LeetCode/roblox.py
2,709
4.125
4
""" Imagine we have an image. We'll represent this image as a simple 2D array where every pixel is a 1 or a 0. The image you get is known to have a single rectangle of 0s on a background of 1s. Write a function that takes in the image and returns one of the following representations of the rectangle of 0's: top-left coordinate and bottom-right coordinate OR top-left coordinate, width, and height. image1 = [ [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1], [1, 1, 1, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1], ] Sample output variations (only one is necessary): findRectangle(image1) => x: 3, y: 2, width: 3, height: 2 2,3 3,5 -- row,column of the top-left and bottom-right corners """ # top_left_row = row # top_left_column = column # column += 1 # while image1[row][column] == 0: # column += 1 # column 6 # bottom_right_row = row # bottom_right_column = column # return (top_left_row, top_left_column, bottom_right_row, bottom_right_column) def return_2dImage(image1): global bottom_right_row, bottom_right_column def top_left_row_column(): global top_left_row, top_left_column img_length = len(image1) for row in range(img_length): for column in range(img_length): while image1[row][column] == 0: top_left_row = row top_left_column = column row += 1 print(top_left_row, top_left_column) if image1[row][column] != 0: column += 1 else: row += 1 continue # def find_bottom_right_row_column(top_left_row, top_left_column, image1): # # global bottom_right_row, bottom_right_column # length = len(image1) # while image1[top_left_row][top_left_column] != 1: # top_left_row += 1 # if # top_left_column += 1 # top_left_row -= 1 # continue # # for top_left_row in range(length): # for top_left_column in range(length): # if image1[top_left_row][top_left_column] == 0: # top_left_row += 1 # continue # elif image1[top_left_row][top_left_column] != 0: # top_left_column += 1 # continue # continue image1 = [ [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1], [1, 1, 1, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1], ] top_left_row, top_left_column = top_left_row_column(image1) # find_bottom_right_row_column(top_left_row, top_left_column, image1) print(top_left_row, top_left_column) #print(bottom_right_row, bottom_right_column)
bada9366316fc85e3c332e58fafc2a6870c40b88
OnestoneW/UZH
/week6/exercise_1.py
1,664
4.1875
4
import scipy.stats as sp import numpy as np import pylab as plb ''' Question 1: The expected values for the standard deviation and the expected value are the sums of all variables. So the expected value of the new (gaussian) distribution is the sum of all expected values. Same with the std. deviation. ''' def generate_arrays(how_many, size_of_array): '''Generates a number of arrays with exponentional distributed numbers. returns a list of arrays''' arrays = [] for i in range(how_many): arrays.append(sp.expon.rvs(loc=0, scale=1, size=size_of_array)) return arrays if __name__ == "__main__": test = generate_arrays(1000, 100) sum_of_numbers = sum(test) mean_of_sum = np.mean(sum_of_numbers) mean_calculated = 0 for arr in test: mean_calculated += np.mean(arr) deviation_calculated = 0 for arr in test: deviation_calculated += np.sqrt(np.mean(arr**2)-np.mean(arr)**2) deviation_observed = np.sqrt(np.mean(sum_of_numbers**2)-np.mean(sum_of_numbers)**2) print("Calculated mean value:", mean_calculated) print("Observed mean value:", mean_of_sum) print("Calculated std deviation:", deviation_calculated) print("Observed std devaition:", deviation_observed) #normalize the gaussian: x = np.linspace(min(sum_of_numbers), max(sum_of_numbers), len(sum_of_numbers)) gaussian = sp.norm.pdf(x, loc=mean_calculated, scale=deviation_observed ) plb.figure() plb.hist(sum_of_numbers, bins=x, normed=True) plb.xlabel("summed up distribution") plb.ylabel("propability") plb.plot(x, gaussian, 'r') plb.show()
03ffe2cd988e09542624505d80f4d67220d55258
Arash67/cardiovascular
/simvascular-python-scripts/path_distance.py
2,586
3.546875
4
#!/usr/bin/env python """ This script is used to compute the distance between two control points on a path created by the SimVascular 'SV Path Planning' module. A Path name corresponds to a data node under the SimVascular 'SV Data Manager' 'Paths' node. Example: SimVascular DemoProject >>> aorta_dist = PathDistance('aorta') [PathDistance] Repository name: aortaRepo [PathDistance] Add aortaRepo to the repository. [PathDistance] Number of control points: 27 >>> aorta_dist.dist(1,6) [PathDistance] Distance between control points 1 6 : 11.3838 >>> """ from sv import * import vtk import math class PathDistance(object): """ This class is used to calculate distances between path control points. """ def __init__(self, path_name): """ Initialize the PathDistance object Args: path_name (string): The name of a SimVascular Path data node. """ self.path_name = path_name self.repo_path_name = path_name + 'Repo' print('[PathDistance] Repository name: {0:s}'.format(self.repo_path_name)) # Add the Path to the Repository. if int(Repository.Exists(self.repo_path_name)): print('[PathDistance] {0:s} is already in the repository.'.format(self.repo_path_name)) else: GUI.ExportPathToRepos(self.path_name, self.repo_path_name) print('[PathDistance] Add {0:s} to the repository.'.format(self.repo_path_name)) self.path = Path.pyPath() self.path.GetObject(self.repo_path_name) # Get the path's control points. self.control_points = self.path.GetControlPts() self.num_control_points = len(self.control_points) print('[PathDistance] Number of control points: {0:3d}'.format(self.num_control_points)) def dist(self, id1, id2): """ Calculate the distance between two control points. This function calculates the distance between two control point IDs id1 and id2 by summing the distance between adjacent control points. Args: id1 (int): The start ID. id2 (int): The end ID. """ dist = 0.0 for id in range(id1, id2+1): p1 = self.control_points[id]; p2 = self.control_points[id+1]; dist_squared = vtk.vtkMath.Distance2BetweenPoints(p1,p2) dist += math.sqrt(dist_squared) #_for id in range(id1, id2+1) print('[PathDistance] Distance between control points {0:d} {1:d} : {2:g}'.format(id1, id2, dist)) return dist
35b780edb1543cf08893a2a8db1c92a8bfa4489a
robertdevenyi/frequency_analysis_code_breaker
/freq_analysis_code_breaker.py
9,321
3.875
4
import re import string, random # break ceaser cipher with sequency analysis original_sentence = input(">>: ") # the lowercase version of the original sentence original_sentence_lowercase = original_sentence.lower() # decryption takes place with lowercase characters most_common_words_file = "1-1000.txt" #Note: usa.txt is the shortest textfile available without Welsh, Scottish, etc. accents, containing only american english words and special abbreviations all_words_file = "US.txt" def remove_non_letters(sentence): STR = string.ascii_letters + " " for chr in sentence: if chr not in STR: sentence = sentence.replace(chr, "") else: pass return sentence.strip() def encrypt(sentence, ascii_lower): charlist = [] for char in sentence: if char not in charlist and char in ascii_lower: charlist.append(char) else: pass random_sample = random.sample(ascii_lower, k=len(charlist)) for i in charlist: sentence = sentence.replace(i, random_sample[charlist.index(i)].upper()) return sentence.lower() #this function checks if a word's structure matches another word's structure such as: 'the' and 'abc' or 'qwr', etc.: this function will be used for finding the right words for substitution def word_identity(word): id = [] w_id = "" # part 1 for char in word: if char not in w_id: w_id += char else: pass id.append(len(w_id)) # part 2 enumerate_results = [] for result in enumerate(list(word)): enumerate_results.append(result) for char in w_id: container = [] for r in enumerate_results: if char in r: container.append(r[0]) else: pass id.append(container) return id # 'the', id = [3, [0], [1], [2]], which means: 3 different characters, at indices 0,1,2 def match(word, match): if len(match) == len(word): if word_identity(match) == word_identity(word): return True else: return False else: return False # update the sentence by substitution def update_sentence(target, match, sentence): for char in sentence: if char != char.upper() and char in match: sentence = sentence.replace(char, target[match.index(char)].upper()) return sentence def generate_pattern(target): # generate the pattern from the target by using the re module final_target = "" for chr in target: if chr != chr.upper(): final_target += '[a-z]' else: final_target += chr.lower() return final_target # Find matching words in the sentence for the target by using: re.match() and word_identity checker function def match_sample_target(pattern, sample, target): if re.match(pattern, sample) and word_identity(target) == word_identity(sample): return True else: return False # could be done by set(ls) as well def remove_duplicates(ls): for i in ls: if ls.count(i) > 1: ls.remove(i) else: continue return ls # we need an algorithm to choose which word is most likely to be predicted the best, with most uppercase characters def choosing_algorithm(sentence): potential_words = [] for word in sentence.split(" "): if word == word.upper(): pass continue else: for char in word: if char == char.upper(): potential_words.append(word) else: pass potential_words = list(set(potential_words)) # make the correct order counter_list = [] for word in potential_words: n = 0 for char in word: if char == char.upper(): n += 1 else: pass continue counter_list.append(n) if counter_list != [] and potential_words != []: upper_maximum = max(counter_list) next_word = potential_words[counter_list.index(upper_maximum)] return next_word else: return None # we need a function to find all words in textfile that match a certain pattern def find_matches_in_wordlist(textfile, pattern, target): all_matches = [] for word in open(textfile, "r").readlines(): word = word.replace("\n", "").lower() if match_sample_target(pattern, word, target): # we need pattern and target for checking word identity match all_matches.append(word) # instead of return word --> which would give the first and only one word else: pass continue return all_matches # we are supposed to create a loop, but before: initialize the whole processes by finding the most common word that matches any word from the sentence def prepare(target, sentence, all_words_file): # generate the pattern for the word pattern = generate_pattern(target) # find the matching words in sentence matching_words = [] for word in sentence.split(" "): if match_sample_target(pattern, word, target): matching_words.append(word) else: continue # omit duplications matching_words = remove_duplicates(matching_words) updated_list = [] # update the sentence by subtituting the characters of the target word to the matching word, then to the whole sentence for word in matching_words: updated_sentence = update_sentence(target, word, sentence) updated_list.append(updated_sentence) # choose the next word to find matches '''next_word = choosing_algorithm(updated_sentence) # generate pattern again pattern2 = generate_pattern(next_word) # Note: next_word and pattern2 are both needed for checking word identity in match_sample_target() function matching_words_2 = find_matches_in_wordlist(all_words_file, pattern2, next_word) # in this case all possible words updated_sentence = update_sentence(matching_words_2[0], next_word, updated_sentence)''' return updated_list #if the checker function is valid(True) def complete(sentence): next_word = choosing_algorithm(sentence) if next_word is not None: next_pattern = generate_pattern(next_word) matching_words = find_matches_in_wordlist(all_words_file, next_pattern, next_word) # from this point the tree should be continued sentence_list = [] for i in matching_words: sentence_list.append(update_sentence(i, next_word, sentence)) return sentence_list else: return None #if checker function is False, then next_word(choosing_algorithm) returns None, thus a new word should be found def got_stuck(sentence): all_matches = None WORD = None #the sentence contains only words that have only capital letters or only lowercase letters for word in sentence.split(" "): if word == word.lower(): WORD = word all_matches = find_matches_in_wordlist(all_words_file, generate_pattern(word), word) break for match_ in all_matches: if any([i.upper() in sentence for i in match_]): all_matches.remove(match_) else: pass #this part removes all characters that have been used as a replacer before sentence_list = [] # list with all matches done if all_matches != None: for i in all_matches: sentence_list.append(update_sentence(i, WORD, sentence)) return sentence_list else: print("Sentence failed.") return None #in this case the program fails to find a meaningful word to update and leaves the word unassigned #valid = True: update sentence, valid = False: no words with both capital and lowercase, thus use got_stuck function def checker(sentence): valid = False for word in sentence.split(" "): if re.search(r"[^A-Z]", word) and re.search(r"[^a-z]", word): #it means that the word contains not only uppercase and not only lowercase letters: thus it contains both valid = True break else: pass return valid def recursion(sentence): if checker(sentence) == True: completed = complete(sentence) for i in completed: if i.upper() != i: recursion(i) else: print(i) #sentence is done else: #False completed = got_stuck(sentence) for i in completed: if i.upper() != i: recursion(i) else: print(i) #sentence is done original_sentence_lowercase = remove_non_letters(original_sentence_lowercase) print("Original sentence:", original_sentence_lowercase) encrypted_sentence = encrypt(original_sentence_lowercase, string.ascii_lowercase) print("Encrypted sentence:", encrypted_sentence) for target in open(most_common_words_file, "r"): print("${0}$".format(target.rstrip())) try: target = target.rstrip() prepared_sentences = prepare(target, encrypted_sentence, all_words_file) for sentence in prepared_sentences: recursion(sentence) except IndexError: pass #dr.
9d44b8c8d95f00eaff2f8b8fc631f92082f7e3f9
PARKINHYO/Algorithm
/python algorithm interview/14장 트리/이진 트리의 최대 깊이.py
795
3.734375
4
from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: if root is None: return 0 queue = deque([root]) depth = 0 while queue: depth += 1 for _ in range(len(queue)): cur_root = queue.popleft() if cur_root.left: queue.append(cur_root.left) if cur_root.right: queue.append(cur_root.right) return depth a = TreeNode(3) a.left = TreeNode(9) b = a.right = TreeNode(20) b.left = TreeNode(15) b.right = TreeNode(7) print(Solution().maxDepth(a))
ad6fa4dd86406b0773681dabba0929553d0f2b87
nicolas-git-hub/python-sololearn
/7_Object_Oriented_Programming/classes.py
2,270
4.34375
4
# We have previously loked at two paradigms of programming: # # - imperative: using statements, loops, and functions as subroutines # - functional: using pure functions, higher-order functions, and recursion. # # Another very popular paradigm is object-oriented programming (OOP). # # Objects are created using classes, which are actually the focal of OOP. # The class describes what the object will be, but is separate from the object itself. # In other words, a class can be described as an object's blueprint, description, or definition. # # You can use the same class as a blueprint for creating multiple different objects. # # # Classes are created using the keyword 'class' and an indented block, which contains # class methods (which are functions). # # Below is an example of a simple class and its objects. class Cat: def __init__(self, color, legs): self.color = color self.legs = legs felix = Cat('ginger', 4) rover = Cat('dog-coloured', 4) stumpy = Cat('brown', 3) # This code defines a class named 'Cat' which has two attributes: 'color' and 'legs'. # # Then the class is used to create 3 separate objects of that clas. # # ============================================================================== # # The __init__ method is the most important method in a class. # This is called when an instance (object) fo the class is created, using the class name as a function. # # All methods must have 'self' as their first parameter, although it isn't explicitly passed, # Python adds the 'self'argument to the list for you; you do not need to include it when you # call the methods. # # Within a method definition, 'self' refers to the instance calling the method. # # Instances of a class have 'attributes', which are pieces of data associated with them. # in this example, 'Cat' instances have attributes 'color' and 'legs'. # These can be accessed by putting a dot, and the attribute name after an instance. # # In an '__init__' method, self.attribute can therefore be used to set the initial value # of an instance'a attribute. # # Example: print(felix.color) # # In the example above, the '__init__' method takes two arguments and assigns them to the # object's attributes. The '__init__' method is called the class constructor.
035080c5806cfa29ef56156c0af3ee23459bbc27
PrashantWalunj999/Artificial-Intelligence-and-Neural-Network-AINN-
/Artificial IntelligenceLab/Assignment1/ML_1.py
2,099
3.875
4
from collections import defaultdict,deque cityCode = [] graph = [] #Graph: LINKED CITIES vTable = [] #VISITED TABLES prev = [] #LINK TO PREVIOUS NODE (BACKTACK NODE TO DISPLAY SHORTEST PATH) adjList = defaultdict(list) q = deque() #Generate: CITY CODE print 'City List: ', print 'Enter Cities in order: A B C D.....' while len(cityCode) < 3: print 'Enter Cities for GRAPH: ', city = raw_input().upper() cityCode = map(str,city.split()) if len(cityCode) < 3: print 'Atlease 3 Cities must be entered.\n\n' #LINK CITIES print 'LINK Cities: (True/False)' for i in range(len(cityCode)): for j in range(len(cityCode)): if i < j: print '{0} - {1}: '.format(cityCode[i],cityCode[j]), lCheck = raw_input().capitalize() if lCheck == 'True': graph.append([i,j]) for edge in graph: adjList[edge[0]].append(edge[1]) adjList[edge[1]].append(edge[0]) for edge in range(10): #Initialize Visited Table[vTable] and prev vTable.append(False) prev.append(-1) #Calculate: SHORTEST PATH s = cityCode.index(raw_input('Enter Source: ').upper()) q.append(s) vTable[s] = True while q: u = q.popleft() for i in adjList[u]: if vTable[i] == False: q.append(i) vTable[i] = True prev[i] = u #Display: PATH COST & PATH count = 0 itr = [] v = cityCode.index(raw_input('Enter Destination: ').upper()) while prev[v] != -1: itr.append(v) v = prev[v] count += 1 print 'Path: {0}'.format(cityCode[s]), for value in reversed(itr): print ' ---> ',cityCode[value], print '\nPath Cost: ',count ############################ SAMPLE - OUTPUT ######################## ''' City List: Enter Cities in order: A B C D..... Enter Cities for GRAPH: pune mumbai patna delhi LINK Cities: (True/False) PUNE - MUMBAI: true PUNE - PATNA: false PUNE - DELHI: false MUMBAI - PATNA: false MUMBAI - DELHI: true PATNA - DELHI: true Enter Source: pune Enter Destination: patna Path: PUNE ---> MUMBAI ---> DELHI ---> PATNA Path Cost: 3 '''
39eaa941b3ea6384c56876c9530d92ab46aa713f
hjlarry/practise-py
/fluent_py/coroutines/coroaverage2.py
565
3.53125
4
import collections Result = collections.namedtuple("Result", "count average") def average(): total = 0 count = 0 average = None while True: recv = yield average if recv is None: break total += recv count += 1 average = total / count return Result(count, average) avg_cor = average() next(avg_cor) print(avg_cor.send(100)) print(avg_cor.send(50)) print(avg_cor.send(10)) # print(avg_cor.send(None)) try: avg_cor.send(None) except StopIteration as e: result = e.value print(result)
edc08a6175768257f62249844a41c490f252573b
Knadsen/Himen
/is105/lab/lab2test.py
424
3.9375
4
def inches_to_meters(inches, feet): a = float(inches * 0.0254) b = float(feet * 0.3048) return a + b def meters_to_feet(meters): feet = meters * 3.2808399 inches = (feet * 12) % 12 return int(feet), inches test = inches_to_meters(2, 53) test2 = inches_to_meters (84, 53) test3 = meters_to_feet(1.82) test4 = meters_to_feet(2.01) test5 = meters_to_feet(1.45) print test print test2 print test3, test4, test5
e5ced8a2c07e20caea06c69f126553daf4dc3d83
peterpod/python_algorithms
/15112/hw5.py
17,006
3.609375
4
#hw5.py # Peter Podniesinski + ppodnies + H """ Reasioning About Code f1(s):f1("afkpu") basically what this function does is iterates j the length of the ascii lowercase letters and if j% len(s) == 0 or j%5 == 0 you add one to i. To solve this problem you must check when this is true. So it occurs when j is 0,5,10,1,20. Therefore, since s[i] must equal string.ascii_lowercase[j] "afkpu" is the answer since they mirror the appropriate index's. f2(a):f2([6,8,5,7]) This is because, #sorted(a)=[5,6,7,8] #b[3]=0 since b[3]=b*i or b*0 when i=0 also b[2]=5(because its the minimum) #b[1]=7 b[0]==18 therefore a[0]=6 since its b[0]*=3 #then a[2]==5 since its the min(a) . then the last 2 integers #are easy since a[1]>a[3] so a[1] must=8 and the other =7 f3(x,y): #x=36, y=8. This is because you must #satisfy the boolean constraints being y==1<<(x/10) #first. This is a bitwise operator that does a left shift. #the values above satisfy this because 1 left shift 3 will make #1000 since this converted from binary to decimal is 8. #the next case is satisfied by 8<<3 which is 1000 plus 3 more 0's #this equals 1000000= 64. Thus 64+36=100 f4(s): f4("ABCDDAD") #this means that the count for index 0,1,2,3 should be #2,1,1,3 respectively because of the assertion statement which says that ord(t[i])-ord("A")==s.count[i] so for i=0, ord(C)-ord(A)=2 so s.count must =2 # also, every third element should equal s[5:2:-1] ' Therefore, my solution works because the first index is repeated twice and s[0]==s[5]. while second/third only appears once. Now D is the s[3] as well as s[4] and s[6] f5(y):y=23 #basically in this problem you must solely focus on the #return statement within the while loop because 2*y can never equal -y # therefore you loop through the while tracing what the code will do for each #x value. basically you must find an x value with only 2 factors 1 and itself #so the first prime under 28 which is 23. So x==23==y f6(n): answer= 8766 I got to this solution by first realizing when r will attain a value of 6 since inside that conditional is when the value of m will change. Then I figured out certain numbers that would help multiply r to 6. It is not possible to multiply straight to 6 since 5 is in the middle so the largest possible value for ord(c)-ord("5") is 5. Therefore, you would have to get to 6 by multiplying by 2 or 3 first and then again vica versa. The next step is to find a value that results in r=6 so I found out 78 will work because 7 is 2 from 5 and 8 is 3 from 5 so you get r*=2, r*=3. However, The loop iterates all the way to 10,000 so we need to find the largest possible value that can generate r=6. This will be 8766 since it cannot be > 9000 since this will automatically disqualify it because 6 has no factor of 5. f7(n,k,x): f7(6,2,2) because len(s)==6 since the tab acts as one index and a backslash deletes the character after it . k=2 because the index of the tab is 2 x=2 because s.find returns 1 if the string finds the character and -1 if it doesnt so 1=-1+2 f8(fmt): f8("%+dabc%0.1f") because %+d adds the first integer specified in that location including the correct sign and %0.1f substitutes the float in rounded to 0.1 decimal f9(s): f9("degjn") because (ord(s[i]) MUST== (i + ord(s[i-1])))and i increments by 1 each time. Therefore the difference between letters increases by 1 each time so you get degjn which has a respective difference of 1,2,3,4 f10(s,t): #t[2] has to be number #since its the str of an int #len(t) has to be less than 10 since t[2] is one index place holder not 2 or more #len(s)=5 because s[1:len(s)] has to be equivelant to t[4:0] which has a length of 4 #f4(f4("23456", "76543")) will suffice as there is a variety of answers because t[2] had #to equal 5 since 5==str(len(t)) and then basically s and t are reversed so that #s[1]has to equal t[4] Answer:("23456", "76543") f11(a):f11([1,"1",2,"3",4,"7",8,"15"]) To get to this answer first I understood exactly what both the assertions were asking. First a[i] must always be > than s. So for example a possible a[0] could be 1 since 1>0 . Then it says that str(s)== a[i+1]. Therefore not only must they be equivilant but in the array. the a[i+1] element must always be a string. There for the first two element could be [1,"1"] Then you must basically repeat these steps with a[i] > s so next possibility is 2 since 2>1 and s=s+2 now so s=3 therefore a[i+1] ="3" and so on. f12(a): #b is sorted and its basically the list of range(len(a)) .For example #range(4) is [0,1,2,3]. and so on. i is the index in a where b[1] occurs #then it basically says b[1],b[3],b[5] equal a[i],a[i+1],a[i+2] respectively # all this function requires then is for the values at those index's to be #equivelant therefore values at a[0],a[2],a[4] are not as important #a possible soultion is as follows #f12([0,1,3,5,2,4]), b would equal[0,1,2,3,4,5] TRUE OR FALSE a.True b.False c.False d.False e.True f.False g.True h.False i.False j.True Very Short Answers a.height bars: at this point (half way) you should have 4 lists each of which are sorted from smallest to largest. The last step is to combine the two. (1,3) (4,8) (2,3) (7,9) b. def f(s,t): if(s==t): return True else: return False c.1 billion elements should take 8 miliseconds d. fa(n):O(n**2) fb(n):O(n) fc(n):O(n**3) fd(n):O(nlogn) e. Short circuit evalutaion is the boolean process that can occur when you have boolean comparisons seperated by an and. So for example if(x) and (y): this means that if x is false then the python will not even evaluate y because by the defenition of an and, if one is false it cannot be true. """ ###################################################################### # Place your non-graphics solutions here! ###################################################################### def sumOfDigits(n): sum=0 while n>0: digit=n%10 sum+=digit n=n/10 return sum def isHarshadNumber(n): #tests if n is a harshad number if(n<10): return False elif n%sumOfDigits(n)==0: return True #print isHarshadNumber(10) def nthHarshadNumber(n): #returns nthHarshad number=1 count=-1 while count <=n: if(count==n): return number elif(isHarshadNumber(number)==True): count+=1 if(count==n): return number number+=1 #print nthHarshadNumber(0) def rangeHarshad(n): #this function will create an upperbound #for nearestHarshadNumber, which is the next #harshadNumber >n if(isHarshadNumber(n)): #if n is already a harshadNumber i increment it by 1 #so that the while loop will execute properly upperRange=n+1 else: upperRange=n i=0 while nthHarshadNumber(i)!=upperRange: if(nthHarshadNumber(i)>upperRange): return nthHarshadNumber(i) i+=1 #print rangeHarshad(12) def nearestHarshadNumber(n): i=0 nearestHarshad=nthHarshadNumber(0) #variable to keep track of #nearestHarshad so far while i<=rangeHarshad(n):#rangeHarshad(n) is an upperbound if(isHarshadNumber(i)): #i is a harshadNumber if(abs(n-i))<abs(n-nearestHarshad): #tests if the difference is < the prior difference nearestHarshad=i i+=1 return nearestHarshad #print nearestHarshadNumber(16) def alternatingSum(a): total=0 for i in range(len(a)): if(i%2==0):#if index is even add the element in the list total+=a[i] else:#odd index subtracts the elements total-=a[i] return total #print alternatingSum([5,3,8,4]) def nameCountList(list): #helper function to organize the parameter of mostCommonName to #return the frequencies of each name nameCountList=[] nameCount=0 if(len(list)==0): return None for i in range(len(list)): mostCommonName=list[i] for j in range(len(list)): if(mostCommonName==list[j]): nameCount+=1 #create a list compiled of the count of each name in the original list nameCountList+=[nameCount] nameCount=0 return nameCountList #print nameCountList(["Jane","Aaron","Cindy","Aaron","Jane"]) import copy def mostCommonName(list): if(len(list)==0): return None elif(len(list)==1): return list[0] countList=nameCountList(list) biggestSoFar=0 finalList=[] for index in range(len(countList)): if(countList[index]>biggestSoFar): #records the index of the largest element biggestSoFar=countList[index] finalList.append(list[index]) elif(countList[index]==biggestSoFar): finalList.append(list[index]) #when there are more then one common name a=[] for i in range(len(finalList)): for j in range(len(finalList)): if(finalList[i]==finalList[j]): if(a.count(finalList[i])==0): a.append(finalList[i]) b=sorted(a) print len(b) if(len(b)>1): return b else: return b[0] print mostCommonName(["aaron","jane","aaron"]) def reverse(a): #destructive function that reverses list but returns None for index in range(len(a)/2): #len(a)/2 because you only need to switch numbers up to middle index a[index],a[len(a)-index-1]=a[len(a)-index-1],a[index] #adds numbers to the front from the back of a #uses tuples to perform switch operation #print reverse([2,1,0]) def vectorSum(a,b): assert(len(a)==len(b)) #makes sure length of vectors is the same vectorSum=[] for index in range(len(a)): sum=a[index]+b[index] #add the sum to Vector Sum vectorSum+=[sum] return vectorSum #print vectorSum([2,4],[20,10]) def isSorted(a): if(len(a)<=1): #length <=1 is always sorted return True for index in range(1,len(a)): if(a[index]==a[index-1]): pass elif(a[0]>a[1]): if(a[index]<a[index-1]): pass else: return False elif(a[0]<a[1]): if(a[index]>a[index-1]): pass else: return False return True print isSorted([1,1,2,1]) import copy def duplicates(a): a=sorted(a)#sorts list with O(nlogn) duplicates=[] if(len(a)<=1): return [] for i in range(1,len(a)): if(a[i]==a[i-1]):#if two adjacent elements are equal they are duplicates duplicates+=[a[i]] c=copy.copy(duplicates) for i in range(1,len(duplicates)):#remove duplicates in list duplicates if(duplicates[i]==duplicates[i-1]): c.remove(duplicates[i]) if(len(c)==0): return [] return c #print duplicates([1, 3, 5, 7, 9, 5, 3, 5, 3,7,7]) def dotProduct(a,b): dotProduct=0 if(len(a)>len(b)): #if lengths are not equal use smaller length length=len(b) else: length=len(a) for index in range(length): product=a[index]*b[index] dotProduct+=product return dotProduct #print dotProduct([1,2,3],[4,5,6]) def isRotation(a1,a2): if(len(a1)!=len(a2)): return False for i in xrange(len(a1)): #use an offset value to demonstrate shift offset=-i count=0 for j in xrange(len(a1)): print if(a1[j+offset]==a2[j]): rotation=True count+=1 if count==len(a1): #if count adds up to total length then offset is correct #and the two arrays are rotations return True return False #print isRotation( [3,2,4,5,6], [4,5,6,2,3]) def subsetSum(a): return 42 ###################################################################### ##### ignore_rest: The autograder will ignore all code below here #### ###################################################################### ###################################################################### # Place your (optional) additional tests here ###################################################################### def runMoreStudentTests(): print "Running additional tests..." def testAlternatingSum(): print "testing.. " , assert(alternatingSum([5,3,8,4])==6) assert(alternatingSum([5,1,2,4])==2) assert(alternatingSum([0,3,8,4])==1) assert(alternatingSum([5,7,8,9])==-3) print "passed alternatingSum " def testMostCommonName(): print "testing.. ", assert(mostCommonName(["Jane", "Aaron", "Jane", "Cindy", "Aaron"])==["Aaron","Jane"]) assert(mostCommonName(["Aaron", "Jane", "Cindy", "Aaron"])==["Aaron"]) print "passed..mostCommonName " def testReverse(): print "testing.. reverse", assert(reverse([5,3,8,4])==None) assert(reverse([5,1,2,4])==None) assert(reverse([0,3,8,4])==None) print "passed.. reverse" def testVectorSum(): print "testing.. VectorSum", assert(vectorSum([2,4],[20,10])==[22,14]) assert(vectorSum([0,2],[30,20])==[30,22]) assert(vectorSum([8,12],[2,11])==[10,23]) print "passed.. VectorSum" def testIsSorted(): print "testing.. isSorted", assert(isSorted([10,2,3,9])==False) assert(isSorted([1,2,3,9])==True) assert(isSorted([10,0,3,2])==False) assert(isSorted([0,2,3,24])==True) print "passed.. isSorted" def testDuplicates(): print "testing.. Duplicates", assert(duplicates([1, 3, 5, 7,7]) ==[7]) assert(duplicates([1, 3,3, 5, 7,7]) ==[3,7]) assert(duplicates([1, 3, 5, 7]) ==[]) assert(duplicates([1, 3, 5, 7,7,8,8]) ==[7,8]) print "passed.. Duplicates" def testDotProduct(): print "testing.. DotProduct", assert(dotProduct([1,2,3],[4,5,6])==32) assert(dotProduct([1,2,1],[4,5,6])==20) print "passed.. DotProduct" def testIsRotation(): print "testing.. isRotation ", assert(isRotation( [2,3,4,5,6], [4,5,6,2,3])==True) assert(isRotation( [3,2,4,5,6], [4,5,6,2,3])==False) assert(isRotation( [1,2,3,4], [2,3,4,1])==True) assert(isRotation( [0,1,2,3], [0,2,1,3])==False) assert(isRotation( [6,5,4,3,2,1], [4,3,2,1,6,5])==True) print "passed.. isRotation" def SubsetSum(): print "testing.. " print "passed.. " ################################################################### # Place your graphics solutions here! ###################################################################### from Tkinter import * #import math ###################################################################### # Drivers: do not modify this code ##################################################################### """def onButton(canvas, drawFn): canvas.data.drawFn = drawFn redrawAll(canvas) def redrawAll(canvas): canvas.delete(ALL) canvas.create_rectangle(0,0,canvas.data.width,canvas.data.height,fill="cyan") drawFn = canvas.data.drawFn if (drawFn): drawFn(canvas, 0, 0, 800, 800) canvas.create_text(canvas.data.width/2,20, text=drawFn.__name__, fill="black", font="Arial 24 bold") def graphicsMain(): root = Tk() canvas = Canvas(root, width=750, height=500) class Struct: pass canvas.data = Struct() canvas.data.width = 750 canvas.data.height = 500 buttonFrame = Frame(root) canvas.data.drawFns = [] canvas.data.drawFn = canvas.data.drawFns[0] for i in xrange(len(canvas.data.drawFns)): drawFn = canvas.data.drawFns[i] b = Button(buttonFrame, text=drawFn.__name__, command=lambda drawFn=drawFn:onButton(canvas, drawFn)) b.grid(row=0,column=i) canvas.pack() buttonFrame.pack() redrawAll(canvas) root.mainloop()""" ###################################################################### # Main: you may modify this to run just the parts you want to test ###################################################################### def main(): # include following line to autograde when you run this file runMoreStudentTests() testAlternatingSum() testReverse() testVectorSum() testIsSorted() testDuplicates() testDotProduct() testIsRotation() #testMostCommonName() #graphicsMain() if __name__ == "__main__": main()
a95cc504c5cdc6b087c366a0bbef1c71488c09fd
ShangruZhong/leetcode
/Tree/101.py
906
3.96875
4
""" 101. Symmetric Tree Similar to '100. Same Tree' @author: Shangru @date: 2016/02/05 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root == None: return True else: return self.isSym(root.left, root.right) def isSym(self, leftchild, rightchild): if leftchild == None and rightchild == None: return True if leftchild == None or rightchild == None: return False return leftchild.val == rightchild.val \ and self.isSym(leftchild.left, rightchild.right) \ and self.isSym(leftchild.right, rightchild.left)
228303258e496d46950864b0b4a4cca4dc0aa615
JamesMylan/bom
/main.py
2,422
3.5
4
import pygame, random pygame.init() #initialise variables screenheight = 400 screenwidth = 400 screen = pygame.display.set_mode((screenheight,screenwidth)) x=50 y=50 width=50 height=25 vel=5 score=0 run = True bombdropping = False listt = [] clock = pygame.time.Clock() plane = pygame.Rect(x,y,width,height) sprite = pygame.image.load("images/plane.png") building = pygame.Rect(50,300,50,300) bomb = pygame.Rect(x,y,width/2,height/2) fontyes = pygame.font.SysFont("None",30) gameovertext = fontyes.render("Game Over",True,(0,0,0)) wintext = fontyes.render(("WIN"),True,(0,0,0)) #create buildings in list for i in range(8): listt.append(pygame.Rect(building.x*i,random.randrange(150,375),building.width,building.height)) def gameover(): global run while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False screen.fill((177, 226, 252)) #put text in the middle of the display screen.blit(gameovertext,(screenwidth/2 -gameovertext.get_rect().width/2,screenheight/2-gameovertext.get_rect().height/2)) pygame.display.update() while run: #stop game if x button pressed for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_SPACE] and not bombdropping: bombdropping = True #places bomb under the middle of the plane bomb = pygame.Rect(plane.centerx-(width/2/2),plane.centery+(height/2),25,25) plane.left += vel if plane.left >= screenwidth: plane.left = -50 plane.y += 25 if bombdropping: bomb.y += 5 for v in listt: if v.colliderect(bomb): bombdropping = False listt.remove(v) score+=100 bomb = pygame.Rect(screenwidth,screenheight,25,25) #sky blue colour screen.fill((177, 226, 252)) if bomb.y > 400: bombdropping = False if not bombdropping: #move bomb offscreen bomb = pygame.Rect(500,500,25,25) if plane.collidelist(listt) != -1: gameover() if score == 800: screen.blit(wintext,(screenwidth/2 -wintext.get_rect().width/2,screenheight/2-wintext.get_rect().height/2)) #antialiased text scorefont = fontyes.render(("SCORE: "+str(score)),True,(0,0,0)) screen.blit(scorefont,(0,0)) screen.blit(sprite,(plane.x,plane.y)) pygame.draw.ellipse(screen,"grey",bomb) for v in listt: pygame.draw.rect(screen,"black",v) pygame.display.update() clock.tick(30)
2a79eb904a2a0a8cb7d2955697bc5134002f6315
pranithmacha/PythonExamples
/count_letters.py
269
3.96875
4
def count_characters(word,character): index = 0 count = 0 while index < len(word): print word[index] if word[index] == character: count += 1 index += 1 print 'count of %s\'s in %s is %d'%(character,word,count) count_characters('macha','a')
bec11fb3c434ff82b2d241463eaf0ae6aa7a414e
Bazarovinc/GeekBrains.Algoritms_on_Python
/Lesson_3/3.4.py
828
4.4375
4
"""4. Определить, какое число в массиве встречается чаще всего.""" import random """Использую фукнции написанные ранее. Надеюсь это не запрещено""" def make_and_print_arr(size): arr = [random.randint(-size / 2, size / 2) for _ in range(size)] # Задал разброс поменьше, чтобы были повторяющиеся print(f"Массив: {arr}") return arr size = int(input("Введите размер массива:")) arr = make_and_print_arr(size) d = {} for i in arr: if i in d: d[i] += 1 else: d[i] = 1 max_n = 0 max_n_i = 0 for k, v in d.items(): if v > max_n: max_n = v max_n_i = k print(f"Больше всего {max_n_i}: {max_n}")
1115647214b62b2792fe67affca87cffb2ce9633
kevinelong/network_python
/smarter_loops.py
1,024
3.84375
4
# Lists # OLD WAYS data = ["eat", "sleep", "repeat"] index = 0 for item in data: print(index, item) index += 1 data = ["A", "B", "C"] line = 1 for item in data: print(line, item) line += 1 # SMART WAYS - ENUMERATE data = ["eat", "sleep", "repeat"] for index, item in enumerate(data): print(index, item) data = ["A", "B", "C"] for line, item in enumerate(data, 1): print(line, item) # Dictionaries data = { "111": "Apple", "222": "Orange", "333": "Pear" } # OLD WAY for fruit_key in data: fruit = data[fruit_key] print(fruit_key, fruit) # SMART WAY - .ITEMS() for fruit_key, fruit in data.items(): print(fruit_key, fruit) # # forge = { # [1, 1, 1]: {"wood": 3} # } # wanos = { # "key0": { # "os": "", # "disk": "", # "hash": "" # }, # "key1": { # "os": "", # "disk": "", # "hash": "" # } # } # filename = wanos.wanos.get(key) # # disk = wanos.wandisk.get(key) # # hash_value = wanos.md5_hash.get(key)
d1edddce032c71b5aeb7d93dea9d08a9e421f1e8
jaleson/Python
/myrun.py
164
3.6875
4
import itertools houses = [1,2,3] orders = list(itertools.permutations(houses)) print orders for (red,blue,green) in orders: print red, blue, green
d9dbd9d28b72d3e4c4fc63875df50600c7dfb001
xiaochus/LeetCode
/questions/17.py
769
4.0625
4
"""17. Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. """ class Solution: def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] from functools import reduce maps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} return reduce(lambda p, n: [x + y for x in p for y in maps[n]], digits, [''])
d85dc602ddfbad869bb6da510f6aa84dbf58fbfd
trojrobert/algorithm_and_data_structure
/algorithms/recursion/fibonacci.py
420
4.25
4
def find_fibonacci_recursive(number): if (number < 2): return number return find_fibonacci_recursive(number -1) + find_fibonacci_recursive(number - 2) def find_fibonacci_iterative(number): arr = [ 0, 1] for i in range(2, number + 11): arr.append(arr[i-1] + arr[1-2]) return arr[number] if __name__ == "__main__": print(find_fibonacci_iterative(10))
6596735ca38a4cbf6d2606419284722b59a94d22
SnehaThakkallapally/Assignment2
/seventh_program.py
129
3.5
4
x = [1,2,3,4] l = [1,2,3,4,"a"] z = all(isinstance(i,int)for i in x ) print(z) z = all(isinstance(i,int)for i in l ) print(z)
fb6ead327bb7324561122a51260b647f1014de94
rivalTj7/Primera_Tarea_Python
/Nested Lists .py
776
3.671875
4
#16 Nested Lists l = [] second_lowest_names = [] scores = set() for i in range(int(input())): name = ['Harry','Berry','Tina','Akriti','Harsh'] score = [37.21,37.21,37.2,41] l.append([name, score]) #Crear una matriz scores.add(score) second_lowest = sorted(scores)[1] for name, score in l: if score == second_lowest: second_lowest_names.append(name) for name in sorted(second_lowest_names): print(name, end='\n') #def bubleSort(lista): # for pasanum in range(len(lista)-1,0,-1): # for i in range(pasanum): # if lista[i] > lista[i+1]: # temp = lista [i] # lista[i] = lista[i+1] # lista[i+1] = temp #lista = [7,-8,10,5] #bubleSort(lista) #print(lista)'''
f1aa8f589ccedcff1b0412126a9f8eeb5c2d3dee
padmacho/default
/www/python/Series.py
567
3.890625
4
import pandas as pd # Create series of students with their ids using lists se = pd.Series(data=['Alex', 'Nelly', 'Mike'], index=[100, 101, 102]) print(se) # Create a series from students dict se = pd.Series(data={100: 'Alex', 101: 'Nelly', 102: 'Mike'}) print(se) # Access date using index # Access first element with index se[100] # Slicing # Retrieve all elements se[:] # Retrieve first element se[0:1] # Change Alex to Alexander se[100] = 'Alexander' print(se[100]) # delete an element form series del se[100] print(se[:]) # delete the whole series del se