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 |
|---|---|---|---|---|---|---|
74017efa8a5b23477f99c4565885cb002dc1f5d0 | shivanimall/ML_KNN | /PA4/perceptrons2.py | 11,414 | 3.53125 | 4 | import numpy as np
import copy
### DEFAULT FILENAMES
TRAINING_NAME = "hw4train.txt"
TEST_NAME = "hw4test.txt"
DICTIONARY_NAME = "hw4dictionary.txt"
class Perceptron:
#make sure everything is in numpy
def __init__(sf):
sf.input_data, sf.input_label = sf.read_data(TRAINING_NAME)
sf.test_data, sf.test_label = sf.read_data(TEST_NAME)
sf.dict = sf.read_data(DICTIONARY_NAME, True)
#shape of input_data == 2000, 891
#initialize to all 0's
sf.weight_mat = np.zeros(sf.input_data.shape[1])
#save weigth count and weights for voted and averaged perceptrons
sf.weight_count = []
sf.all_weight_mat = []
#for averaged perceptron algo
sf.running_avg = np.zeros(sf.weight_mat.shape)
sf.train_err = []
sf.test_err = []
def read_data(sf, filename, isDict=None):
#read test train and label data
print("Loading %s ..." %filename)
filehandle = open(filename, "r")
line = filehandle.readline()
data = []
while line != "":
line = line.split()
data += [line]
line = filehandle.readline()
if(isDict == True):
return data
data = np.array(data)
data = data.astype(float)
print(filename,"loaded : Dim",data.shape)
return data[:,:-1], data[:,-1]
'''
what are we classifying? what are we learning? what do these
test and data points correspond to and labels to?
'''
'''
intuitively and logically think why is it a problem to run all 1 labels
first and run all -1 labels next --> how does this affect the updates
of the weight matrix -- why should you make sure to shuffle the data
randomly before training the perceptron.
'''
def perceptron(sf, data, label, test_data, test_label, weight_mat):
num_passes = 2
#is the hyperplane getting updated every time
#we compute a new weight vector?
#such that the weigth vector is always normla to the
#hyperplane?
#print "data.shape: ", data.shape
#print "label.shape: ", label.shape
print("Running Regular Perceptron!")
for t in range(num_passes):
for i in range(data.shape[0]):
dot_XW = np.dot(data[i], weight_mat)
#print "dot prod: ", dot_XW
#print "sign of dot prod: ", np.sign(dot_XW)
if(label[i]*dot_XW <= 0):
weight_mat = weight_mat + ( label[i]*data[i] )
#print "i label[i]: ", i, ": ", label[i]
#if (i == 0):
#print "weights: ", weight_mat
sf.train_err += [sf.test_perceptron(data, label, weight_mat)]
print("train err after", t+1 ,"pass:", sf.train_err[-1])
sf.test_err += [sf.test_perceptron(test_data, test_label, weight_mat)]
print("test err after", t+1, "pass:", sf.test_err[-1])
def test_perceptron(sf, data, label, weight_mat):
#predict output for normal perceptron
err = 0.0
for i in range(data.shape[0]):
dot_YW = np.dot(data[i], weight_mat)
class_sign = np.sign(dot_YW)
if(class_sign != label[i]):
err += 1
return err/data.shape[0]
def voted_perceptron(sf, data, label, test_data, test_label):
count = 1
num_passes = 3
weight_mat = np.zeros(sf.input_data.shape[1])
print("Running Voted Perceptron!")
for t in range(num_passes):
for i in range(len(data)):
dot_XW = np.dot(data[i], weight_mat)
#print "dot_XW: ", dot_XW
if(label[i]*dot_XW <= 0):
temp_weight_mat = weight_mat + (label[i]*data[i])
#print "i label[i]: ", i, ": ", label[i]
#append for the previous matrix
sf.all_weight_mat.append(copy.copy(weight_mat))
sf.weight_count.append(count)
weight_mat = temp_weight_mat
count = 1
else:
count += 1
#print "sf.all_weight_mat.shape: ", len(sf.all_weight_mat)
#print "sf.weight_count: ", len(sf.weight_count)
#print "sf.weight_count: ", sf.weight_count
#print "sf.all_weight_mat: ", sf.all_weight_mat
sf.train_err += [sf.test_voted_perceptron(data, label)]
print("train err after", t+1, "pass:", sf.train_err[-1])
sf.test_err += [sf.test_voted_perceptron(test_data, test_label)]
print("test err after", t+1, "pass:", sf.test_err[-1])
def test_voted_perceptron(sf, data, label):
sum_sign = 0.0
err = 0.0
for t in range(len(data)):
sum_sign = 0.0
#you can totally vectorize this loop
for i in range(len(sf.all_weight_mat)):
dot_WY = np.dot(sf.all_weight_mat[i],data[t])
sum_sign += sf.weight_count[i]*np.sign(dot_WY)
#final sign or class of test data t
class_t = np.sign(sum_sign)
if(class_t != label[t]):
err += 1
#print "sum_sign: ", sum_sign
return err/data.shape[0]
#think about why would voted and averaged perceptron give you the
#same result?!
def averaged_perceptron(sf, data, label, test_data, test_label, running_avg):
print("Running Averaged Perceptron!")
weight_mat = np.zeros(sf.input_data.shape[1])
count = 1
num_passes = 4
for t in range(num_passes):
for i in range(len(data)):
dot_XW = np.dot(data[i], weight_mat)
if(label[i]*dot_XW <= 0):
temp_weight_mat = weight_mat + (label[i]*data[i])
#append for the previous matrix
running_avg += weight_mat*count
weight_mat = temp_weight_mat
#print "i label[i]: ", i, ": ", label[i]
count = 1
else:
count += 1
sf.train_err += [sf.test_averaged_perceptron(data, label, running_avg)]
print("train err after", t+1, "pass:", sf.train_err[-1])
sf.test_err += [sf.test_averaged_perceptron( test_data, test_label, running_avg)]
print("test err after", t+1, "pass:", sf.test_err[-1])
####### CHANGE THIS TO 3 #############
topK = 3
sf.interpret_averaged_perceptron(topK)
def test_averaged_perceptron(sf, data, label, running_avg):
sum_sign = 0.0
err = 0.0
for t in range(len(data)):
sum_sign = 0.0
#you can totally vectorize this loop
dot_WY = np.dot(running_avg,data[t])
#final sign or class of test data t
class_t = np.sign(dot_WY)
if(class_t != label[t]):
err += 1
#print err
per = err/data.shape[0]
return per
'''
what does it mean for every dim/axis to have a word associated with it?
why would words correspond to certain coordinates?
Three highest coordinates are those with ...strongly and
three lowest coordinates are those with ...strongly why so?
'''
def interpret_averaged_perceptron(sf, topK):
sorted_weights_ind = np.argsort(sf.running_avg)
#print sorted_weights_ind
#3 lowest dimensions
low_dim = []
for x in range(topK):
low_dim += [sorted_weights_ind[x]]
#print low_dim
#3 highest dimensions
high_dim = []
for x in range(topK):
high_dim += [sorted_weights_ind[-1*(x+1)]]
#print high_dim
#3 words that represent positive class strongly
for x in range(len(low_dim)):
print(sf.dict[low_dim[x]][0])
#3 words that represent negative class strongly
for x in range(len(high_dim)):
print(sf.dict[high_dim[x]][0])
def classify_A_VS_B(sf, a, b=None):
if(b != None):
#train
labels_ind_a = np.where(sf.input_label == a)[0]
labels_ind_b = np.where(sf.input_label == b)[0]
#test
labels_ind_a_T = np.where(sf.test_label == a)[0]
labels_ind_b_T = np.where(sf.test_label == b)[0]
if(b == None):
#train
labels_ind_a = np.where(sf.input_label == a)[0]
labels_ind_b = np.where(sf.input_label != a)[0]
#test
labels_ind_a_T = np.where(sf.test_label == a)[0]
labels_ind_b_T = np.where(sf.test_label != b)[0]
#print "labels_inx_1: ", labels_ind_1
#print "labels_idx_2: ", labels_ind_2
data = np.vstack((sf.input_data[labels_ind_a,:],sf.input_data[labels_ind_b,:]))
#print "data[3]: ", data[3]
label_a = sf.input_label[labels_ind_a].reshape(len(labels_ind_a),1)
label_a[:,0] = 1
label_b = sf.input_label[labels_ind_b].reshape(len(labels_ind_b),1)
label_b[:,0] = -1
#print "labels_1[690]: ", label_1
#print "labels_2[690], ", label_2
label = np.vstack((label_a,label_b))
#print "label[3]: ", label[3]
train_data_label = np.hstack((data, label))
np.random.shuffle(train_data_label)
#print "data_label ", data_label
data = train_data_label[:, :-1]
#print "data ", data
label = train_data_label[:, -1]
#print "label ", label
data_test = np.vstack((sf.test_data[labels_ind_a_T,:],sf.test_data[labels_ind_b_T,:]))
label_a = sf.test_label[labels_ind_a_T].reshape(len(labels_ind_a_T),1)
label_a[:,0] = 1
label_b = sf.test_label[labels_ind_b_T].reshape(len(labels_ind_b_T),1)
label_b[:,0] = -1
label_test = np.vstack((label_a,label_b))
return (data, label, data_test, label_test)
def get_data_AvsB(sf, a, b=None):
# a = 1
# b = -1
all_data = np.hstack((sf.input_data, sf.input_label.reshape((sf.input_label.shape[0],1))))
all_test_data = np.hstack((sf.test_data, sf.test_label.reshape((sf.test_label.shape[0],1))))
if b == None:
# b is the rest of labels
for i in range(all_data.shape[0]):
if all_data[i,-1] == a:
all_data[i,-1] = 1
else:
all_data[i,-1] = -1
for i in range(all_test_data.shape[0]):
if all_test_data[i,-1] == a:
all_test_data[i,-1] = 1
else:
all_test_data[i,-1] = -1
else:
# b is a label
rows_not_used = []
for i in range(all_data.shape[0]):
if all_data[i,-1] == a:
all_data[i,-1] = 1
elif all_data[i,-1] == b:
all_data[i,-1] = -1
else:
rows_not_used += [i]
all_data = np.delete(all_data,rows_not_used,0)
rows_not_used = []
for i in range(all_test_data.shape[0]):
if all_test_data[i,-1] == a:
all_test_data[i,-1] = 1
elif all_test_data[i,-1] == b:
all_test_data[i,-1] = -1
else:
rows_not_used += [i]
all_test_data = np.delete(all_test_data, rows_not_used,0)
return (all_data[:,:-1], all_data[:,-1], all_test_data[:,:-1], all_test_data[:,-1])
def run_all_perceptron_algorithms(sf):
####REMEMBER TO RESET VARIABLES######
data, label, data_test, label_test = sf.get_data_AvsB(1, 2)
sf.perceptron(data, label, data_test, label_test, sf.weight_mat)
####REMEMBER TO RESET VARIABLES######
sf.voted_perceptron(data, label, data_test, label_test)
####REMEMBER TO RESET VARIABLES######
sf.averaged_perceptron(data, label, data_test, label_test, sf.running_avg)
def run_one_vs_all(sf):
data1, label1, data_test1, label_test1 = sf.get_data_AvsB(1)
weight_mat_1 = np.zeros(sf.input_data.shape[1])
sf.perceptron(data, label, data_test, label_test, weight_mat_1)
data2, label2, data_test2, label_test2 = sf.get_data_AvsB(2)
weight_mat_2 = np.zeros(sf.input_data.shape[1])
sf.perceptron(data, label, data_test, label_test, weight_mat_2)
data3, label3, data_test3, label_test3 = sf.get_data_AvsB(3)
weight_mat_3 = np.zeros(sf.input_data.shape[1])
sf.perceptron(data, label, data_test, label_test, weight_mat_3)
data4, label4, data_test4, label_test4 = sf.get_data_AvsB(4)
weight_mat_4 = np.zeros(sf.input_data.shape[1])
sf.perceptron(data, label, data_test, label_test, weight_mat_4)
data5, label5, data_test5, label_test5 = sf.get_data_AvsB(5)
weight_mat_5 = np.zeros(sf.input_data.shape[1])
sf.perceptron(data, label, data_test, label_test, weight_mat_5)
data6, label6, data_test6, label_test6 = sf.get_data_AvsB(6)
weight_mat_6 = np.zeros(sf.input_data.shape[1])
sf.perceptron(data, label, data_test, label_test, weight_mat_6)
if __name__ == '__main__':
ptrn = Perceptron()
ptrn.run_all_perceptron_algorithms()
#ptrn.run_one_vs_all() |
0e204d540c440ea27905fba5a1bd7bd1f822018a | meliatiya24/Python_Code | /Asisten/Praktikum Pert 1/kelasa/main.py | 947 | 3.578125 | 4 | class orang:
status = "Sehat"
jumlah = 0
def __init__(self, name, age, gender, tb, bb):
self.nama = name
self.umur = age
self.kelamin = gender
self.tinggibadan = tb
self.beratbadan = bb
self.jumlah +=1
def hasildatari(self):
print(self)
return "Nama pasien {} \n\t Umur Pasien = {} \n\t Kelamin = {} ".format(self.nama,self.umur,self.kelamin)
def cekideal(self):
ideal = self.tinggibadan - 110
if(self.beratbadan < ideal):
print("Anda kurus")
elif(self.beratbadan == ideal ):
print("Anda ideal")
else:
print("Anda Gemuk")
return "Berat badan {}" .format(ideal)
manusia1 = orang("Chinta", 19, "female", 160, 40)
manusia2 = orang("yopy", 18, "female", 150, 60)
print(manusia1.nama)
print(manusia2.hasildatari(),manusia1.status)
print(manusia2.cekideal())
print(manusia2.jumlah)
|
ffdba1403db1bb6d1ee2aa6fe3240c362da507bb | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/1061.py | 1,143 | 4.03125 | 4 | def word_count(phrase):
word_tally = {}
current_word = ''
space = ' '
if '\\n' in phrase:
phrase = phrase.replace('\\n', ' ')
print('No newline phrase:', phrase)
for index in range(len(phrase)):
if phrase[index] == space:
if len(current_word) > 0:
if current_word in word_tally:
word_tally[current_word] += 1
current_word = ''
else:
word_tally[current_word] = 1
current_word = ''
elif (index == len(phrase) -1):
if len(current_word) > 0:
current_word = current_word + phrase[index]
if current_word in word_tally:
word_tally[current_word] += 1
else:
word_tally[current_word] = 1
else:
current_word = current_word + phrase[index]
print(word_tally)
return word_tally
phrase = input('Enter the phrase to be counted: ')
print('Phrase as input:', phrase)
results = word_count(phrase)
print(results)
|
4c8fd88dcc8f5c1c3764c2246492db8431724056 | Ranen98/Python-1 | /牛客网刷题/random函数.py | 775 | 3.796875 | 4 | import random
import string
# 随机整数
print(random.randint(1, 10))
# 随机选取0-100的偶数
print(random.randrange(0, 101, 2))
# 随机浮点数
print(random.random()) # 0-1之间的实数
print(random.uniform(1,10))
# 随机字符
print(random.choice("Ranen is a gentelman!"))
# 多个字符中生成指定数量的随机字符
print(random.sample("Ranen is a gentelman!", 10))
# 从a-zA-Z0-9生成指定数量的随机字符,可以作为验证码
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 6))
print(ran_str)
# 打乱排序
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# 在items上打乱顺序,结果返回none
print(random.shuffle(items))
print(items)
res = random.sample(range(1, 101), 100)
res1 = [i*2 for i in res]
print(res1) |
e5b07156b891a996100bace1bc2531d62afacd8f | Rishabh-Jain21/Python-Basics | /format.py | 415 | 3.65625 | 4 | print("different format pattern")
print(format(13402.4525, '.2f'))
print(format('hello', '.<30'))
print(format('hello', '>30'))
print('hello', format('.', '.<30'), 'Have a nice day')
print(format('hello', '^30'))
print(format('', '-<10'), "Thank you", format('', '->10'))
x = 12
print(format(x, 'b'))
print(format(x, 'x')) # x for hexa
print(format(x, 'o'))
print(format(2**32+x, 'b'))
print(format(2**32+x, 'x'))
|
632866c7d031a21f28320904d0d86f277096d89e | IzabellaPcn/ProjetoBD | /elementos.py | 7,936 | 3.53125 | 4 | """
Universidade Federal de Pernambuco (UFPE) (http://www.ufpe.br)
Centro de Informática (CIn) (http://www.cin.ufpe.br)
Graduando em Sistemas de Informação
IF968 - Programação 1
Autora: Izabella Priscylla da Costa Nascimento (ipcn)
Email: ipcn@cin.ufpe.br
Data: 22-05-2018
Copyright(c) 2018 Izabella Priscylla da Costa Nascimento
"""
from criptografia import criptografar, descriptografar
from log import log, buscarLog
from usuarios import lerUsuario, gravarUsuarioArquivo, buscarNivelUsuario, modificarNivelUsuario, listarUsuarios
def lerElemento():
"""Função para ler os elementos e retorna o dicionário contento o cadastros dos elementos com ISBN, título, autor,
número de chamada, edição,acervo, ano de publicação"""
arq = open("elementos.txt", "r")
lista = []
dicionarioElementos = {}
adicionar = ""
texto = arq.read()
adicionar2 = ""
texto2 = ""
for caractere in texto:
if caractere != " ":
adicionar2 += caractere
else:
texto2 += descriptografar(adicionar2)
adicionar2 = ""
for linha in texto2.split('\n'):
adicionar = ""
for elemento in linha:
if (elemento != ";")and (elemento != "\n"):
adicionar += elemento
else:
lista.append(adicionar)
adicionar = ""
if lista:
lista.append(adicionar)
dicionarioElementos[lista[0]] = (
lista[1], lista[2], lista[3], lista[4], lista[5], lista[6])
lista = []
arq.close()
print(dicionarioElementos)
return(dicionarioElementos)
def gravarElementoArquivo(dicionarioElementos):
"""Função para gravar o dicionario dos elementos no arquivo"""
arq = open("elementos.txt", "w")
string = ""
for x in dicionarioElementos:
string += x + ";" + dicionarioElementos[x][0] + ";" + dicionarioElementos[x][1] + ";" + \
dicionarioElementos[x][2] + ";" + dicionarioElementos[x][3] + ";" + \
dicionarioElementos[x][4] + ";" + dicionarioElementos[x][5] + "\n"
stringNova = ""
for caractere in string:
stringNova += str(criptografar(caractere)) + " "
arq.write(stringNova)
arq.close()
def adicionarElemento(bancoDeDadosElementos, usuario):
"""Função para adicionar livros"""
ISBN = input("\nDigite o ISBN: ")
achou = False
for x in bancoDeDadosElementos:
if ISBN == x:
achou = True
if achou == False:
titulo = input("Digite o título do livro: ")
autor = input("Digite o autor do livro: ")
numeroDeChamada = input("Digite o número de chamada do livro: ")
edicao = input("Digite a edição do livro: ")
acervo = input("Digite o acervo do livro: ")
anoDePublicacao = input("Digite o ano de publicação do livro: ")
print("")
bancoDeDadosElementos[ISBN] = (
titulo, autor, numeroDeChamada, edicao, acervo, anoDePublicacao)
log(usuario, "adicionou_elemento")
print("Livro adicionadao com sucesso.\n")
else:
print("\nISBN já cadastrado.\n")
return bancoDeDadosElementos
def removerElemento(bancoDeDadosElementos, usuario):
"""Função para remover livro"""
print("")
print("Qual livro deseja remover?\n")
listarElemento(bancoDeDadosElementos, 4)
ISBN = input("\nDigite o ISBN: ")
print("")
if ISBN in bancoDeDadosElementos:
bancoDeDadosElementos.pop(ISBN)
log(usuario, "removeu_elemento")
print("Livro removido com sucesso.\n")
else:
print("Livro não cadastrado no sistema.\n")
return bancoDeDadosElementos
def listarElemento(bancoDeDadosElementos, opcaoListar):
if opcaoListar == 1:
for chave in bancoDeDadosElementos.keys():
print("ISBN: ", chave)
elif opcaoListar == 2:
for chave in bancoDeDadosElementos.keys():
print("Título: ", bancoDeDadosElementos[chave][0])
elif opcaoListar == 3:
for chave in bancoDeDadosElementos.keys():
print("Autor: ", bancoDeDadosElementos[chave][1])
else:
for chave in bancoDeDadosElementos.keys():
print("ISBN: ", chave, ", Título: ",
bancoDeDadosElementos[chave][0])
def buscarElemento(bancoDeDadosElementos):
"""Função buscar livro"""
opcao = int(input("\nComo deseja buscar o livro?\n"
"1 - ISBN\n"
"2 - Título\n"
"3 - Autor "))
print("")
if opcao == 1:
listarElemento(bancoDeDadosElementos, 1)
ISBN = input("\nDigite o ISBN: ")
if ISBN in bancoDeDadosElementos:
return ISBN
else:
return False
elif opcao == 2:
listarElemento(bancoDeDadosElementos, 2)
titulo = input("\nDigite o título: ")
for atributo in bancoDeDadosElementos.items():
if atributo[1][0] == titulo:
return atributo[0]
return False
elif opcao == 3:
listarElemento(bancoDeDadosElementos, 3)
autor = input("\nDigite o autor: ")
for atributo in bancoDeDadosElementos.items():
if atributo[1][1] == autor:
return atributo[0]
return False
else:
print("Opção não encontrada, digite novamente.")
buscarElemento(bancoDeDadosElementos)
def atualizarElemento(bancoDeDadosElementos, usuario):
"""Função para atualizar os livros"""
opcao = buscarElemento(bancoDeDadosElementos)
if opcao == False:
print("\nElemento não cadastrado no sistema.\n")
else:
atualizar = int(input("\n------- O que deseja atualizar? ------\n"
"1 - Título\n"
"2 - Autor\n"
"3 - Número de chamada\n"
"4 - Edição\n"
"5 - Acervo\n"
"6 - Ano de Publicação "))
if (atualizar < 1)or(atualizar > 6):
print("\nOpção não encontrada, digite novamente.")
return atualizarElemento(bancoDeDadosElementos, usuario)
elementosDaChave = list(bancoDeDadosElementos[opcao])
elementosDaChave[atualizar-1] = input("\nDigite o novo atributo: ")
print("\nLivro atualizado com sucesso.\n")
bancoDeDadosElementos[opcao] = tuple(elementosDaChave)
log(usuario, "atualizou_elemento")
return bancoDeDadosElementos
def ordenarElementos(bancoDeDadosElementos):
"""Função para ordenar os elementos"""
lista = []
for chave in bancoDeDadosElementos:
lista.append(int(chave))
ordenado = sorted(lista)
arq = open("impressaoelementos.txt", "w")
for x in ordenado:
arq.write("ISBN: " + str(x) + ", Título: " + bancoDeDadosElementos[str(x)][0] + ", Autor: "
+ bancoDeDadosElementos[str(x)][1] + ", Número de chamada: " +
bancoDeDadosElementos[str(x)][2] + ", Edição: "
+ bancoDeDadosElementos[str(x)][3]+", Acervo: " +
bancoDeDadosElementos[str(x)][4]+", Ano de Publicação:"
+ bancoDeDadosElementos[str(x)][5])
arq.write("\n")
arq.close()
def buscarNaTela(bancoDeDadosElementos, usuario):
"""Função para imprimir na tela a busca do elemento"""
ISBN = buscarElemento(bancoDeDadosElementos)
if (ISBN != False):
print("\nISBN: " + ISBN + "\nTítulo: " + bancoDeDadosElementos[ISBN][0] + "\nAutor: " + \
bancoDeDadosElementos[ISBN][1] + "\nNúmero de chamada: " + bancoDeDadosElementos[ISBN][2] + \
"\nEdição: " + bancoDeDadosElementos[ISBN][3] + "\nAcervo: " + bancoDeDadosElementos[ISBN][4] + \
"\nAno de publicação: " + bancoDeDadosElementos[ISBN][5])
print("")
log(usuario, "buscou_elemento")
else:
print("\nLivro não cadastrado no sistema.\n")
|
8e47c6393d76599b4ec2f6b62cfb85418c1441c7 | choi818/data_science_from_scratch | /ch3_visualization/3_histogram.py | 700 | 3.65625 | 4 | from matplotlib import pyplot as plt
from collections import Counter
grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]
decile = lambda grade: grade // 10 * 10
histogram = Counter(decile(grade) for grade in grades)
plt.bar([x for x in histogram.keys()], # move bar to the 4 times left
histogram.values(), # set the height of the bar
8) # width = 8
plt.axis([-5, 105, 0, 5]) # -5 <= x.axis <= 105, 0 <= y.axis <= 5
plt.xticks([10 * i for i in range(11)]) # labels of x.axis = 0, 10, 20, ..., 100
plt.xlabel("Decile")
plt.ylabel("# of Students")
plt.title("Distribution of Exam 1 Grades")
plt.show()
|
dd5a2587a430649a295748ef40d01cdd22634c6b | rschanak/LAtCS | /Lab1/Task2.py | 313 | 4.125 | 4 | """Task 2: Use Python to find the remainder of 2304811 divided by 47 without using the modulo operator %."""
a = 2304811
b = 47
#Use floor division to calculate what isn't the remainder.
floor_division = a // b
floor_multiplication = floor_division * 47
remainder = a - floor_multiplication
print(remainder) |
03aaf28397753604bfe1174c4dbb6f48d6259379 | mrggaebsong/Python_DataStructure | /Recursive_linkedlist.py | 870 | 3.703125 | 4 | class node:
def __init__(self, d, nxt = None):
self.data = d
if nxt is None:
self.next = None
else:
self.next = nxt
def printList(h):
if h is not None:
print(h.data, end = ' ')
printList(h.next)
def createL(h, n):
if n:
p = node(n, h)
p = createL(p, n-1)
return p
else:
return h
h = None
h = createL(h, 5)
print(printList(h))
def createLfromlist(h, i):
global fromList
if i >= 0:
p = node(fromList[i], h)
p = createLfromlist(p, i-1)
return p
else:
return h
fromList = [2,5,4,8,6,7,3,1]
i = len(fromList)-1
print(fromList)
h = None
h = createLfromlist(h, i)
printList(h)
def delete(h, d):
h = h.head
if h.next.data == d:
h.next = h.next.next
delete(h.next,d)
return h
h = delete(h,5)
|
73032033aa3858638aae9ba655e8c01004a8d3cc | siryang/leetcode | /src2/MediaOfTwoSortedArrays/MediaOfTwoSortedArrayst.py | 2,445 | 3.90625 | 4 | '''
There are two sorted arrays A and B of size m and n respectively.
Find the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
'''
class Solution:
# get media of A --> ma
# get count of number in B that smaller than ma
def getNumBiggerThanValue(self, Array, Value):
# lower bounder is better
for i in range(len(Array)):
if Array[i] > Value:
return i + 1
return len(Array)
# return iA, iB
def moveFoward(self, A, B, iA, iB):
# min of A[iA + 1], B[iB]
if iB == len(B):
return iA + 1, iB
elif iA == len(A):
return iB + 1, iA
else
# @return a float
def findMedianSortedArrays(self, A, B):
lenA = len(A)
lenB = len(B)
mid = (lenA + lenB) / 2
if lenA >= lenB:
iA = len(A) / 2
iB = self.getNumBiggerThanValue(B, A[iA])
else:
iB = len(B) / 2
iA = self.getNumBiggerThanValue(A, B[iB])
A.append(0x8ffffffff)
B.append(0x8ffffffff)
while True:
## step
left = iA + iB
#print mid, left, iA, iB, ".."
if left == mid:
return min(A[iA], B[iB])
elif left < mid:
# step forward
if A[iA - 1] > B[iB - 1]:
iB+=1
else:
iA+=1
elif left > mid:
# step backward
if A[iA] > B[iB]:
iA-=1
else:
iB-=1
#print "A:%d, B:%d" %(A[iA], B[iB])
if __name__ == '__main__':
slu = Solution()
print slu.findMedianSortedArrays([1], [2])
print slu.findMedianSortedArrays([1, 12, 15, 26, 38], [2, 13, 17, 30, 45, 50])
print slu.findMedianSortedArrays([1, 12, 15, 26, 38], [2, 13, 17, 30, 45])
print slu.findMedianSortedArrays([1, 2, 5, 6, 8], [13, 17, 30, 45, 50])
print slu.findMedianSortedArrays([1, 2, 5, 6, 8, 9, 10], [13, 17, 30, 45, 50])
print slu.findMedianSortedArrays([1, 2, 5, 6, 8, 9], [13, 17, 30, 45, 50])
print slu.findMedianSortedArrays([1, 2, 5, 6, 8], [11, 13, 17, 30, 45, 50])
print slu.findMedianSortedArrays([1], [2,3,4])
## [1,2,3] --> 2
## [1,2,3,4] --> 3
## [1,2,4,5,5,8] ==> 5
## [1,2,4,5,5,6,8] ==> 5
|
e3609181fd3081de8d3fe99fb477c5a7bf958a8e | faryar48/practice_bradfield | /python-practice/learn_python_the_hard_way/ex01.py | 4,143 | 3.90625 | 4 | # print "Hello World!"
# print "Hello Again"
# print "I will now count my chickens", 30 / 2
# cars = 100
# space_in_cars = 4.0
# print "there are", cars, "cars available."
# print "since there are", cars, "cars available, and", space_in_cars, "spaces in cars, we can take", cars * space_in_cars, "people to burning man"
# print "Hey %s there." % "you"
# my_name = "Faryar"
# my_age = 24
# my_height = 64
# my_weight = 115
# my_eyes = "green"
# my_hair = "brown"
# print "Let's talk about %s." % my_name
# print "She is %d inches tall." % my_height
# print "She weighs %d pounds." % my_weight
# print "She has %s eyes and %s hair." % (my_eyes, my_hair)
# print "If I add my weight, %d, my height, %d, and my age, %d, I get %d." % (my_weight, my_height, my_age, my_weight + my_height + my_age)
# x = "There are %d types of people." % 10
# binary = "binary"
# do_not = "don't"
# y = "those who know %s and those who %s" % (binary, do_not)
# print x
# print y
# print "I said: %r" % x
# print "I also said '%s'" % y
# hilarious = False
# joke_eval = "Isn't that joke so funny?! %r"
# print joke_eval % hilarious
# w = "this is the left side of the "
# e = "string, and this is the right"
# print w + e
# formatter = "%r %r %r %r"
# print formatter % (1, 2, 3, 4)
# print formatter % ("one", "two", "three", "four")
# print formatter % (True, False, False, True)
# print formatter % (formatter, formatter, formatter, formatter)
# print formatter % ("did you know?", "what it feels like?", "when it rains?", "in the snow?")
# months = "Jan\nFeb\nMarch\nApril"
# print "Here are the months: ", months
# print "Here are the months: %s" % months
# print "Here are the months: %r" % months # doesn't work because That's how %r formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging.
# print """
# What is going on here?
# Can i just type as much as I want?
# """
# tabby_cat = "\tI am tabbed in."
# persian_cat = "I am split \non a line"
# backlash_cat = "I'm \\ a \\ cat"
# fat_cat = """
# I'll do a list:
# \t*Chips
# \t*Dips
# \t*Kips\n\t*Lips
# """
# print tabby_cat, persian_cat, backlash_cat, fat_cat
# # When I use a %r format none of the escape sequences work.
# # That's because %r is printing out the raw representation of what you typed, which is going to include the original escape sequences. Use %s instead. Always remember this: %r is for debugging, %s is for displaying.
# print "How old are you?",
# age = raw_input()
# print "What is your name?",
# name = raw_input()
# print "How much do you weigh?",
# weight = raw_input()
# print "My name is %r, I am %r, and I weigh %r pounds." % (name, age, weight)
# print "My name is %s, I am %s, and I weigh %s pounds." % (name, age, weight)
# # How do I get a number from someone so I can do math?
# # That's a little advanced, but try x = int(raw_input()) which gets the number as a string from raw_input() then converts it to an integer using int().
# name = raw_input("What is your name? ")
# age = raw_input("How old are you? " )
# weight = raw_input("How much do you weigh? ")
# print "My name is %s, I am %s, and I weigh %s pounds." % (name, age, weight)
# from sys import argv
# script, first, second, third = argv
# print "The script is called:", script
# print "The first variable is:", first
# print "The second variable is:", second
# print "The third variable is:", third
# make sure to pass this in command like:
# python ex1.py Faryar (or some other user_name)
from sys import argv
script, user_name = argv
prompt = '>=> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s" % user_name
likes = raw_input(prompt)
print "Where do you live %s" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice.
""" % (likes, lives, computer)
|
bc15d7c7aa79db6e6509d8aa492c139f2c9944a3 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/kevin_t/lesson3/ex2_list_lab.py | 2,294 | 4.09375 | 4 | #Create list of fruit and print it
my_list = ['Apples', 'Pears', 'Oranges', 'Peaches']
print (my_list)
#Ask user to add another fruit. Make it title cased and add it to the end. Display the list
my_list.append((input('What fruit would you like to add?' )).title())
print (my_list)
#Ask the user for a number, display the number and the fruit corresponding to the number.
#1 is first basis. Truncate input, check that the number is in range.
while True:
user_num = int(input('Which number in the list would you like to pull? '))
if user_num - 1 in range(len(my_list)):
break
print('The fruit in position {} is {}'.format(user_num, my_list[user_num-1]))
#Add another fruit to the beginning using '+', display the list
my_list = ['Papayas'] + my_list
print (my_list)
#Add another fruit to the beginning using 'insert()', display the list
my_list.insert(0,'Mangos')
print (my_list)
#Display all fruits that begin with "P" using a 'for' loop
for fruit in my_list:
if fruit[0] == 'P':
print (fruit)
print (my_list)
#Remove the last fruit from the list, display the list
del my_list[-1]
print (my_list)
#Ask the user for a fruit to delete, verify the fruit is in the list.
#Delete all occurences of that fruit, display the list
while True:
user_del = input('Which fruit would you like to delete? ')
if user_del.title() in my_list:
break
while user_del in my_list:
my_list.remove((user_del).title())
print (my_list)
#Make a copy of the list, ask user if they like each fruit.
#Check that the answer is 'yes' or 'no', ask again if not.
#If no, delete that fruit from the list. Display the list
copy_my_list = my_list[:]
for fruit in copy_my_list:
while True:
fruit_preference = input('Do you like {}?'.format(fruit.lower()))
if fruit_preference.lower() == 'yes' or fruit_preference.lower() == 'no':
break
if fruit_preference.lower() == 'no':
my_list.remove(fruit)
print (my_list)
#Make a new list with the contents of the original, but reverse the letters in each
my_new_list = my_list[:]
for i,fruit in enumerate(my_new_list):
my_new_list[i] = my_new_list[i][::-1]
print (my_new_list)
#Delete last item of original list. Display both.
my_list.remove(my_list[-1])
print(my_list)
print(my_new_list) |
09bb4cc87ade98ab469fe9e91503b37193a62976 | Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis | /Chapter 3/Algorithm Workbench/4.py | 658 | 4.09375 | 4 | # What will the following program display?
# def main():
# x = 1
# y = 3.4
# print(x, y)
# change_us(x, y)
# print(x, y)
# def change_us(a, b):
# a = 0
# b = 0
# print(a, b)
# main()
# The display should be as follows
# 1 3.4
# 0 0
# 1 3.4
# The reason a and b are not 0 in the final print statement is that the
# change_us(x,y) function only changes a copy of the x and y variables
# This change has not affect on x or y outside of the change_us function
def main():
x = 1
y = 3.4
print(x, y)
change_us(x, y)
print(x, y)
def change_us(a, b):
a = 0
b = 0
print(a, b)
main()
|
cc28dbc4647668ff0547f1a26006446bdf4d0ec0 | Saquib472/Innomatics-Tasks | /Task 8(Stats)/03_Normal_Distribution.py | 659 | 3.875 | 4 | # Task_08 Q_03:
# In a certain plant, the time taken to assemble a car is a random variable, x, having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours. What is the probability that a car can be assembled at this plant in:
# Less than 19.5 hours?
# Between 20 and 22 hours?
import math
def CDF(x, mean, std):
return 1/2*(1+math.erf((x-mean) / std / 2**(1/2)))
mean = 20
std = 2
print("The probability that a car can be assembled in less than 19.5 hours: ",round(CDF(19.5, mean, std), 3))
print("The probability that a car can be assembled in between 20 to 22 hours: ",round(CDF(22, mean, std) - CDF(20, mean, std), 3)) |
eba028339fe9fd42ccff77d68adbcfbbc8cf5bc2 | DeanHe/Practice | /LeetCodePython/NumberOfGoodPaths.py | 2,925 | 3.640625 | 4 | """
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges.
You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.
A good path is a simple path that satisfies the following conditions:
The starting node and the ending node have the same value.
All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).
Return the number of distinct good paths.
Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.
Example 1:
Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]
Output: 6
Explanation: There are 5 good paths consisting of a single node.
There is 1 additional good path: 1 -> 0 -> 2 -> 4.
(The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.)
Note that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0].
Example 2:
Input: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]]
Output: 7
Explanation: There are 5 good paths consisting of a single node.
There are 2 additional good paths: 0 -> 1 and 2 -> 3.
Example 3:
Input: vals = [1], edges = []
Output: 1
Explanation: The tree consists of only one node, so there is one good path.
Constraints:
n == vals.length
1 <= n <= 3 * 10^4
0 <= vals[i] <= 10^5
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges represents a valid tree.
hints:
1 Can you process nodes from smallest to largest value?
2 Try to build the graph from nodes with the smallest value to the largest value.
3 May union find help?
TC: O(N)
SC: O(N)
"""
from collections import Counter
from typing import List
class NumberOfGoodPaths:
def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:
# single nodes
res = n = len(vals)
parent = list(range(n))
edges = sorted([max(vals[a], vals[b]), a, b] for a, b in edges)
cnt = [Counter({vals[i]: 1}) for i in range(n)]
def find_root(x):
root = x
while root != parent[root]:
root = parent[root]
while parent[x] != root:
fa = parent[x]
parent[x] = root
x = fa
return root
for v, a, b in edges:
root_a, root_b = find_root(a), find_root(b)
cnt_a, cnt_b = cnt[root_a][v], cnt[root_b][v]
res += cnt_a * cnt_b
# union
parent[root_b] = root_a
cnt[root_a] = Counter({v: cnt_a + cnt_b})
return res |
00c8f1cfcbc38dcdc2c6e4330b5fb22da40c68dc | Franalvarezfx/mTICP772022 | /Ciclo I/python_elemental.py | 5,773 | 3.84375 | 4 | # Datatypes ------------------------------------------
# Enteros (int)
# 5
# 21
# -54
print(type(42))
# Flotantes (float)
# 554.25
# -54.02
# 547.1
print(type(0.25))
# String (str)
print(type('Hola Mundo'))
print(type("Hola Mundo"))
print(type('''Hola Mundo'''))
print(type("""Hola Mundo"""))
print(type(''))
# Booleanos (bool)
# True -> ...-3, -2, -1, 1, 2, 3...
# False -> 0
print(type(True))
print(type(False))
# Variables ---------------------------------------
nombreClave = 'Almacena datos, colecciones' # Camel Case
nombre_clave = 'Almacena datos, colecciones' # Snake Case
NombreClave = 'Almacena datos, colecciones' # Pascal Case
var1, var2, var3 = 1, 2, 3
print(type(nombreClave))
nombreClave = 25
print(type(nombreClave))
print(nombreClave)
numeroSTR = '25'
print(type(numeroSTR))
numero = int(numeroSTR)
print(type(numero))
print(type(numeroSTR))
numero = float(numeroSTR)
print(type(numero))
print(numero)
print(int(True))
print(int(False))
print(chr(47))
print(ord('/'))
# Colecciones --------------------------------------------
# Lista (list)
lista_vacia = []
print(type(lista_vacia))
mi_lista = [345,456,96,5476,456,36,345.34,3434.346,['ter','ert','ertyg']]
print(mi_lista[0])
print(mi_lista[1])
# print(mi_lista[9]) # Error, indice fuera del rango
print(mi_lista[8])
print(mi_lista[len(mi_lista)-1])
print(mi_lista[8][2])
print(mi_lista[7:58])
print(mi_lista[::-1]) # Invierte el orden de los elementos de la coleccion
print(mi_lista[:-1]) # Omite el ultimo elemento de la coleccion
mi_lista[8][2] = 'P77'
print(mi_lista)
print(dir(mi_lista))
mi_lista.append('Otra cadena')
print(mi_lista)
ultimo_elemento = mi_lista.pop()
print(mi_lista)
print(ultimo_elemento)
mi_lista.pop(7)
print(mi_lista)
mi_lista.insert(0,[23,2354,235,245,4])
print(mi_lista)
print(lista_vacia.__sizeof__())
print(mi_lista.__sizeof__())
# Tuplas (tuple)
tupla_vacia = ()
una_tupla = (345,56,476,54687,65789,768)
otra_tupla = 345,56,476,54687,65789,768
print(type(tupla_vacia), type(una_tupla), type(otra_tupla))
print(dir(tupla_vacia))
print(otra_tupla[0])
# otra_tupla[0] = 234 # No se puede
print(otra_tupla[len(otra_tupla)-1])
print(otra_tupla[1:5])
print((345,5463,465) > (345,674,548))
# Conjuntos (set)
un_set = {234,2345,345,6356,234,456,2345,56,57,34,345,456,3456,45,345}
print(type(un_set))
# print(un_set[0]) # No se puede
print(dir(un_set))
print(len(un_set))
print(un_set)
print(un_set.pop())
print(un_set)
otro_set = {345,363,636,4756,33,453245,246,535746,345,32,34,345}
union = un_set.union(otro_set)
print(union)
interseccion = otro_set.intersection(un_set)
print(interseccion)
diferencia1 = un_set.difference(otro_set)
diferencia2 = otro_set.difference(un_set)
print(diferencia1)
print(diferencia2)
# Diccionarios (dict)
# {key: value}
diccionario_vacio = {}
otro_diccionario = {
'nombre': 'Jhonatan',
'apellido': 'Barrera',
'adicional': ['Risaralda', 'Pereira', {'profesion': 'Ingeniero de Sistemas y Computación',
'universidad': 'Universidad Tecnológica de Pereira'}]
}
print(otro_diccionario['adicional'][2]['profesion'])
print(dir(otro_diccionario))
un_elemento = otro_diccionario['adicional'][2].pop('universidad')
print(un_elemento)
print(otro_diccionario)
print(list(otro_diccionario.keys()), list(otro_diccionario.values()))
print(list(otro_diccionario.items()))
otro_diccionario['Nueva llave'] = 85
print(otro_diccionario)
otro_diccionario['Nueva llave'] = 'Nuevo valor'
print(otro_diccionario)
otro_diccionario.update(nueva_llave = {'codigo': 'FP01', 'nombre': 'Fundamentos de programacion'})
print(otro_diccionario)
# Condicionales ---------------------------------------------
if otro_diccionario['Nueva llave'] == 'Nuevo valor':
print('Son iguales')
# instruccion 2
# instruccion 3
#instruccion 4
if otro_diccionario['Nueva llave'] == 85:
print('Son iguales')
else:
print('No son iguales')
numero1 = [234,345,45,3564]
numero2 = [345,45,634,5]
if numero1[0] == numero2[0]:
print('Son iguales')
elif numero1[0] < numero2[0]:
print(f'{numero1[0]} es menor que {numero2[0]}')
else:
print(f'{numero1[0]} es mayor que {numero2[0]}')
if True:
print('Esto siempre se va a mostrar (Siempre es verdadero)')
if False:
pass
else:
print('Siempre se va ha mostrar (Nunca sera verdadero)')
# Ciclos (for, while)
for item in numero2:
print(item, end=' ')
print()
for i in range(len(numero2)):
print(numero2[i], end=' ')
print()
for key in otro_diccionario:
print(otro_diccionario[key])
for k, v in otro_diccionario.items():
print(k, v)
band = True
contador = 0
while band:
contador = contador + 1
print(contador, end=' ')
if contador == 10:
band = False
# break
print()
i = 0
while i < len(numero2):
if numero1[i] == numero2[i]:
print('Son iguales')
elif numero1[i] < numero2[i]:
print(f'{numero1[i]} es menor que {numero2[i]}')
else:
print(f'{numero1[i]} es mayor que {numero2[i]}')
i = i + 1
for i in range(len(numero2)):
if numero1[i] == numero2[i]:
print('Son iguales')
elif numero1[i] < numero2[i]:
print(f'{numero1[i]} es menor que {numero2[i]}')
else:
print(f'{numero1[i]} es mayor que {numero2[i]}')
print('-------------------------------------------------------')
# Funciones
def comparaNum(num1:int,num2:int)->str:
if num1 == num2:
return 'Son iguales'
elif num1 < num2:
return f'{num1} es menor que {num2}'
else:
return f'{num1} es mayor que {num2}'
print(comparaNum(34,567),'\n')
for i in range(len(numero2)):
print(comparaNum(numero1[i], numero2[i]))
print()
i = 0
while i < len(numero2):
print(comparaNum(numero1[i], numero2[i]))
i = i + 1 |
6f9dee3ebdc20679bc5b1167c9a80dafd1974fb8 | Anshnema/Programming-solutions | /implement_stack_using_queues.py | 1,004 | 4.09375 | 4 | """
Ques. Implement Stack Using queues
T.C. = Push - O(n); Pop - O(1); Top - O(1); empty - O(1)
S.C. = O(n)
1 Queue is used here.
Link - https://leetcode.com/problems/implement-stack-using-queues/
"""
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue1 = list()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.queue1.append(x)
n = len(self.queue1)
while n > 1:
self.queue1.append(self.queue1.pop(0))
n -= 1
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.queue1.pop(0)
def top(self) -> int:
"""
Get the top element.
"""
return self.queue1[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return len(self.queue1) == 0 |
d8477b3811ff77120caa82ed303de6b3551b8322 | YuyaMurata/TeranoPapersAnalize | /paperobj.py | 456 | 3.6875 | 4 | class PaperObj:
def __init__(self, authors, title, info, year):
self.authors = authors
self.title = title
self.info = info
self.year = year
# Mapを作成
def toDictionary(self):
jsonDict = {"author":self.authors, "title":self.title, "info":self.info, "year":self.year}
return jsonDict
def string(self):
return format("%s:%s,%s,%s" %(self.authors, self.title, self.info, self.year)) |
df18d663f06a3689c8904557ff3324d06f90271d | ii0/algorithms-6 | /BFS.py | 751 | 4.03125 | 4 | """
author: buppter
datetime: 2019/8/25 10:09
"""
graph = {
"A": ["B", "C"],
"B": ["A", "C", "D"],
"C": ["A", "B", "D", "E"],
"D": ["B", "C"],
"E": ["C", "F"],
"F": ["E"]
}
def bfs(graph, start):
if not graph or not start:
return [], []
stack = [start]
seen = set()
seen.add(start)
parent = {start: None}
res = []
while stack:
cur = stack.pop(0)
nodes = graph[cur]
for node in nodes:
if node not in seen:
stack.append(node)
seen.add(node)
parent[node] = cur
res.append(cur)
return res, parent
if __name__ == "__main__":
res, parent = bfs(graph, "A")
print(res)
print(parent)
|
3be1d48b4a6358fcb8d72452c2c5007f6cebe3e0 | hugomacielads/Introducao_Python_3 | /list_comprehension/comprehension_v2.py | 270 | 3.546875 | 4 | # [expressão for item in list if condicional ]
dobro_dos_pares = [i * 2 for i in range(10) if i % 2 == 0]
print(dobro_dos_pares)
# Vernão 'Nomal"
dobro_dos_pares = []
for i in range(10):
if i % 2 == 0:
dobro_dos_pares.append(i * 2)
print(dobro_dos_pares)
|
be8cceb335428b029d70f03a16f137e9d60f742b | SACHSTech/livehack-3-daniellen23 | /problem1.py | 723 | 4.125 | 4 |
""""
Name: TournamentTracker.py
Purpose: This program will track the player wins and determine which group a player is placed in.
Author: Nguyen.D
Created: 2021-03-04
"""
#get the player win and losses
player = (input("Enter the wins and losses for your team: "))
# Set the initial total
total=0
# count the number of wins or "w"
for i in range(len(player)):
if player[i] == "w":
total = total + 1
print(player[i])
# condition and print the team
if total == 5 or total == 6:
print ("Your team is in Group 1")
elif total == 3 or total == 4:
print ("Your team is in Group 2")
elif total == 1 or total == 2:
print ("Your team is in Group 3")
else:
print ("Your team is eliminated from the tournament") |
788f57d556dd103a66c8fb52c4423e6492591f3e | estebesov01/it_school_files | /modules/n10.py | 419 | 3.875 | 4 | # Используя функцию randrange() получите
# псевдослучайное четное число в пределах
# от 6 до 12. Также получите число кратное
# пяти в пределах от 5 до 100.
from random import randrange
n = randrange(6,12)
n2 = randrange(5,100)
while True:
if n2 % 5 == 0:
break
n2 = randrange(5,100)
print(n,n2) |
a9b63db7edd8d7bdf25286520c7cee15dbbac506 | Sherlynchance/SherlynChance_ITP2017_Exercises | /3-8. Seeing the World.py | 342 | 3.96875 | 4 | locations = ['himalaya','everest','niagara falls','yellow river','fuji']
print(locations)
print(sorted(locations))
print(locations)
print(sorted(locations, reverse=True))
print(locations)
locations.reverse()
print(locations)
locations.reverse()
print(locations)
locations.sort()
print(locations)
locations.sort(reverse=True)
print(locations)
|
422a2c4928c8fb45a6810ce4238b48e9c07df5b7 | karthik-siru/practice-simple | /array/Search_&_Sort/aggcows.py | 741 | 3.515625 | 4 | def AggCows(self,arr, n, m):
# function to check the possibility of division.
def placeCows(barrier ) :
cows= 1
cord = arr[0]
for i in arr :
if i-cord >= barrier :
cows += 1
cord = i
if cows >= m :
return True
return False
#defining search-space
left, right = 1 , arr[-1] -arr[0]
res = -1
#binary search ..
while left <= right :
mid = (left + right)>>1
#if allocation possible.. check with
# lower limits.
if placeCows(mid) :
res = mid
left = mid +1
else :
right = mid -1
return res
|
b5dfcdea9d24e9560d030950aa97d9621d5e9964 | abansagi/GroupRecommendationThesis | /Experiment Processing/skip_dataset/plot_track_sum.py | 542 | 3.5625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
def plot_track_sum():
"""
Plots the amount of times each track appears in the Spotify Sequential Skip Prediction Challenge dataset.
The datafile is provided in the skip_dataset/data folder and was pre-generated using the full data.
:return:
"""
file_name = "skip_dataset/data/track_sum.csv"
df = pd.read_csv(file_name)
sums = df["sum"].to_list()
sums.sort(reverse=True)
plt.plot(sums)
ax = plt.gca()
ax.set_yscale("log")
plt.show()
|
5ec275245a8892222d60699e9c6ebcbdfbef8935 | Deepak710/created-py | /mimimized.py | 3,614 | 3.703125 | 4 | import datetime as d
from time import ctime
import os
while True:
print("\t\tFile Forensics\n\t\t____ _________\n\n")
root_path = input("Enter the path : ")
while True:
while True:
try:
days = int(input("Enter number of days : "))
today = d.datetime.now()
diff = (today - d.timedelta(days = days)).timestamp()
except ValueError:
print("Invalid number of days (NaN). Please enter a valid number")
continue
except OverflowError:
print("Your input goes way too back in the past. Please enter a lesser value")
continue
else:
break
write_list = list()
for p,s,f in os.walk(root_path):
print("\nCurrently Searching in ", p)
for i in f:
file_name = os.path.join(p, i)
file_time = os.path.getctime(file_name)
if file_time > diff:
ago = today - d.datetime.fromtimestamp(file_time)
if ago.days:
ago = "{0} days".format(ago.days)
else:
ago = "{0} seconds".format(ago.seconds)
file_time = ctime(file_time)
print(i, "\t\twas created on {0} - {1} ago".format(file_time, ago))
temp_list = [file_name, os.path.getsize(file_name), file_time, ctime(os.path.getmtime(file_name)), ctime(os.path.getatime(file_name)), ago]
write_list.append(temp_list)
if len(write_list):
save = input("\nDo you want to save this result in an Excel Workbook? (y/n)")
if save == 'y' or save == 'Y':
import xlwt as x
wb = x.Workbook()
ws = wb.add_sheet("List of Files")
title_list = [["Date of the Exercise : {0}".format(ctime(today.timestamp()))], ["Date {0} days ago : {1}".format(days, ctime(diff))], ["Fully qualified File Name", "File Size", "File Created Time", "Last Modified Time", "Last Accessed Time", "Days passed in between"]]
for i, row in enumerate(title_list):
for j, col in enumerate(row):
ws.write(i, j, col, style = x.easyxf('font:bold on'))
for i, row in enumerate(write_list):
for j, col in enumerate(row):
ws.write(i+3, j, col)
save_path = input("Enter the save directory : ")
while True:
try:
save_name = input("Enter the workbook name (Without extension) : ")
wb.save(os.path.join(save_path, save_name) + ".xls")
except OSError:
print("Can't use special characters while naming files [or] File is currently in use. Please rename your file")
continue
else:
break
else:
print("\nNo files created in {0} during the past {1} days".format(root_path, days))
cont = input("\nDo you want to check for files created within a different period in the same path? (y/n)")
if cont == 'y' or cont == 'Y':
continue
else:
break
cont = input("\nDo you want to check in a different path? (y/n)")
if cont == 'y' or cont == 'Y':
continue
else:
break
|
17d38d17d7cdcec82491064c761e5d1d6d7ffac2 | ItsMeNori/MTA-python | /clock.py | 164 | 3.59375 | 4 | import time as t
start = t.clock()
for i in range (0,1000):
for j in range (0,1000):
n = i * j
end = t.clock()
print(str(end-start) +" seconds") |
6697cf0fcc2b9cb77b9347b6be46bc8247748f77 | corgiTrax/Sparse-Reinforcement-Learning | /old/test.py | 5,482 | 3.5625 | 4 | #! /usr/bin/python
'''experiment file'''
from config import *
import world
import agent
import reinforcement
import modularIRL
class Experiment():
def __init__(self, trial, data_file):
self.data_file = data_file
self.trial = trial
self.mouse = MOUSE
self.draw = DRAW
#generate a Maze
self.testMaze = world.Maze(TESTR, TESTC)
#Predator starts at (0,0)
self.predators = []
for i in range(NUM_PREDATOR):
predator = agent.Predator([0,0], self.testMaze)
self.predators.append(predator)
self.predator_chase = P_CHASE
#Agent starts at middle
self.myAgent = agent.Agent([int(TESTR/2),int(TESTC/2)], self.testMaze)
self.captured = 0 #being captured by predator or not
self.success = False
self.stepCount = 0
self.max_step = MAX_STEP
def run(self):
if self.draw:
self.testMaze.drawSelf(True)
self.myAgent.drawSelf(True)
for predator in self.predators: predator.drawSelf(True)
while (self.stepCount <= self.max_step and (self.captured == 0) and (not self.success)):
#Module class #1: prize, calculate Q values for each of the prize object in the maze
prizeQvalues = reinforcement.calc_Qvalues('prize', self.myAgent.pos, self.testMaze.prizes, self.testMaze)
#Module class #2: obstacle, calculate Q values for each of the obstacle object in the maze
obsQvalues = reinforcement.calc_Qvalues('obstacle', self.myAgent.pos, self.testMaze.obstacles, self.testMaze)
#Module class #3: predator, calculate Q values for each of the predator object in the maze
#predators move first
predatorPos = []
for predator in self.predators:
predator.move(predator.chase(self.myAgent.pos, self.predator_chase))
predatorPos.append(predator.pos)
predatorQvalues = reinforcement.calc_Qvalues('predator', self.myAgent.pos, predatorPos, self.testMaze)
#SumQ
globalQvalue = reinforcement.sumQ(prizeQvalues + obsQvalues + predatorQvalues)
#action = numpy.argmax(globalQvalue)
action = reinforcement.softmax_act(globalQvalue)
#print("prizes: ", testMaze.prizes)
#print("prize Q values: ", prizeQvalues)
#print("Global Q values: ", globalQvalue)i
'''IRL task: data recording'''
if RECORDING:
new_instances = []
#prize instances
for prizePos in self.testMaze.prizes:
xs = reinforcement.calc_dists(self.myAgent.pos, prizePos, self.testMaze)
new_instance = modularIRL.observed_instance(self.trial, self.stepCount, PRIZE, action, xs)
new_instances.append(new_instance)
#obstacle instances
for obsPos in self.testMaze.obstacles:
xs = reinforcement.calc_dists(self.myAgent.pos, obsPos, self.testMaze)
new_instance = modularIRL.observed_instance(self.trial, self.stepCount, OBS, action, xs)
new_instances.append(new_instance)
self.data_file.write(str(self.trial) + ',' + str(self.stepCount))
for instance in new_instances:
self.data_file.write(',')
instance.record(self.data_file)
#print(instance)
self.data_file.write('\n')
del new_instances
'''end IRL part'''
#move one step only when mouse clicks
if self.mouse: self.testMaze.window.getMouse()
#agent takes action
self.myAgent.move(action)
#Compute consequences
for predator in self.predators:
self.captured += (self.myAgent.pos == predator.pos)
self.myAgent.cum_reward += self.testMaze.calc_reward(self.myAgent.pos)
if (self.captured > 0):
#print("Captured by predator!")
self.myAgent.cum_reward -= R_PRED #config
#Visualization
if self.draw:
self.testMaze.drawSelf(False)
self.myAgent.drawSelf(False)
for predator in self.predators:
predator.drawSelf(False)
if len(self.testMaze.prizes) == 0:
#print("Success!")
self.success = True
self.stepCount +=1
#print("StepCount: ", stepCount)
if self.draw: self.testMaze.window.close()
if __name__ == "main":
#Experiment
total_success = 0
data_file = open(RECORD_FILENAME,'w')
data_file.write(str(R_PRIZE) + ',' + str(R_OBS) + ',' + str(GAMMA_PRIZE) + ',' + str(GAMMA_OBS) + ',' + str(ETA) + '\n')
for trial in range(MAX_TRIAL):
print("trial #", trial)
experiment = Experiment(trial, data_file)
experiment.run()
total_success += experiment.success
print("total success: ", total_success)
data_file.close()
#Hold graph window
#raw_input("Press enter to exit")
|
9d74af9fcc08086d1a34b374587d15fd255d00ae | richardadalton/GameBits | /guessing_games/best_score.py | 1,141 | 4 | 4 | from random import randint
best_score = None
best_score_name = None
game_over = False
while not game_over:
number_of_guesses = 1
number = randint(1, 100)
guess = input("I'm thinking of a number from 1 to 100, try to guess it: ")
while guess != number:
if guess < number:
guess = input("Too low, guess again: ")
else:
guess = input("Too high, guess again: ")
number_of_guesses += 1
if number_of_guesses == 1:
print "You got it in 1 guess"
else:
print "You got it in {0} guesses".format(number_of_guesses)
if best_score is None:
best_score = number_of_guesses
best_score_name = raw_input("New best score, enter your name: ")
else:
if number_of_guesses < best_score:
best_score = number_of_guesses
best_score_name = raw_input("New best score, enter your name: ")
print "The best score is {0} by {1}".format(best_score, best_score_name)
play_again = raw_input("Would you like to play again? (Y/N)? ").upper()[:1]
game_over = play_again != 'Y'
|
0a076dc3a49b202dfd11322e6092458018496353 | ZitingShen/Euler-Project | /36. Double-base palindromes.py | 524 | 3.53125 | 4 | import time
start=time.time()
def palindrome(x):
l=len(x)
if l%2==0:
for y in range(l//2):
if x[y]!=x[l-y-1]:
return False
return True
else:
for y in range((l-1)//2):
if x[y]!=x[l-y-1]:
return False
return True
S=0
for x in range(1000000):
sx=str(x)
if palindrome(sx):
sx2=bin(x)[2:]
if palindrome(sx2):
S+=x
elapsed=(time.time()-start)
print ("found %s in %s seconds" % (S,elapsed))
|
f9305aced1fb4892aa48e09d0bec93edf382c5c9 | alexandredct/estudo_python | /eXcript/aula 19 - operadores relacionais.py | 334 | 4.0625 | 4 | """
OPERADORES CONDICIONAIS
1 - OPERADORES DE IGUALDADE
-Igualdade: ==
-Diferente: !=
2- OPERADORES RELACIONAIS
-Maior que: >
-Menor que: <
-Maior ou igual que: >=
-Menor ou igual que: <=
"""
a = (100!=100)
b=('a'=='a')
print(a)#FALSE
print(a)#TRUE
print(a==b)#FALSE
print('a'<'b')#TRUE; Usa a tabela ASCII
print('a'<'a')#FALSE
|
297e376622ac649b007cadb6a5cae340f43b587f | shahlaaminaei/python-learning | /exercise12-v2.py | 175 | 3.8125 | 4 | string = input('enter string: ').lower()
seda="aeiou"
result=[]
[result.append(".") if letter in seda else result.append(letter) for letter in string]
print("".join(result)) |
1c74cafe53a485ea5e702943a7b10657d3e2e699 | purnesh42H/Algorithm-Problems | /Common Coding Problems/DetectingCycleList.py | 263 | 3.59375 | 4 | def has_cycle(head):
if not head:
return 0
nodeDict = {}
current = head
while current.next:
if current.data in nodeDict:
return 1
nodeDict[current.data] = 1
current = current.next
return 0 |
8b4154e5169efa6ec6b37430e41f567a736ddf0f | changethisusername/uzh | /Informatik1/Actual Midterm/scopes.py | 149 | 3.578125 | 4 | str_freq = {}
def func(str_list):
str_freq = {}
for s in str_list:
str_freq[s] = str_freq[s] + 1
return str_freq
print(str_freq) |
52a0fa5e47ae8b94fd6e97cfd61f67b563c7669f | divyaagarwal24/coderspree | /ML/Ayushsingh07_Ayushkumarsingh_2024cse1037_2/Patterns/pattern10.py | 340 | 3.515625 | 4 | a=int(input())
s1=1
s2=int(a/2)
c=-1
for i in range(1,a+1):
for j in range(1,s2+1):
print("",end="\t")
print("*\t",end="\t")
for j in range(1,c):
print("",end="\t")
if (i>1 and i<a):
print("*",end="\t")
print()
if (i<=a/2):
s2-=1
c+=2
else:
s2+=1
c-=2
|
34d689fe31975f919e3656525caf7c30fb72c5d5 | TheAutomationWizard/learnPython | /pythonUdemyCourse/Interview_Questions/Visa__/arrayBased.py | 645 | 3.8125 | 4 | # Function to find sublists with the given sum in a list
def findSublists(A, sum):
for i in range(len(A)):
sum_so_far = 0
# consider all sublists starting from `i` and ending at `j`
for j in range(i, len(A)):
# sum of elements so far
sum_so_far += A[j]
# if the sum so far is equal to the given sum
if sum_so_far == sum:
# print sublist `A[i, j]`
print(A[i:j + 1])
if __name__ == '__main__':
A = [3, 4, -7, 1, 3, 1, -4]
sum = 7
findSublists(A, sum)
print()
findSublists([-3, -4, -7, 1, 2, 9, 12, 4, 14, 0], 14) |
2876168db12b425a71db411cbbf1c6875a967c1a | AlphonseBrandon/100DaysOfPython | /PyPasswordGenerator.py | 883 | 4.03125 | 4 | import random
letters = ['A', 'B', 'C', 'D']
numbers = ['1', '2', '3', '4']
symbols = ['!', '#', '$', '&']
print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password\n"))
nr_numbers = int(input("How many numbers would you like in your password\n"))
nr_symbols = int(input("How many symbols woll you like in your password\n"))
#Eazy level
password_list = []
#nr_letters = 4
for char in range(1, nr_letters + 1):
#range is 4
password_list.append(random.choice(letters))
for char in range(0, nr_symbols + 1):
password_list += random.choice(letters)
for char in range(0, nr_numbers + 1):
password_list += random.choice(numbers)
random.shuffle(password_list)
print(password_list)
password = ""
for char in password_list:
password += char
print(f"Your password is {password}")
#Hard level |
3deffb6d27a18cda2b54a186b2102baad9c4a052 | alvanxp/algorithms | /Hopper/funnywithanagrams.py | 363 | 4 | 4 | def funWithAnagrams(arr):
h = set()
result = []
for word in arr:
arrWord = list(word)
arrWord.sort()
hashcode = "".join(arrWord)
if hashcode not in h:
result.append(word)
h.add(hashcode)
result.sort()
return result
print(funWithAnagrams(['code', 'doce', 'ecod', 'framer', 'frame'])) |
1b58a6785b3ed51161ca1b544361664127313f89 | wbsth/mooc-da | /part04-e06_growing_municipalities/src/growing_municipalities.py | 495 | 3.703125 | 4 | #!/usr/bin/env python3
import pandas as pd
def growing_municipalities(df):
all = df.shape[0]
col = df.columns
filtered = df[df[col[1]] > 0].index
part = (len(filtered) / all)
return(part)
def main():
df = pd.read_csv("src/municipal.tsv", sep = '\t', index_col=0)
data = df[1:312]
percentage = growing_municipalities(data) * 100
print(percentage)
print(f"Proportion of growing municipalities: {percentage:.1f}%")
if __name__ == "__main__":
main()
|
bc62be4516938430cb4c3d788f4ab822fb64f4e7 | DEVBRATDUBEY/python | /HarshitVashisth Python/Chapter 2 – All about strings/2-UserInput.py | 183 | 4.21875 | 4 | # user input
# input function
# input function takes input as a string
name = input("enter your name : ")
age = input("type your age : ")
print("Hello " + name)
print("Hello " + age)
|
e8569b99b9ce024a9b7a033e0cf3b47bc373f09a | Comp-Sci-Principles-2018-19/chapter-2-exercises-justishawkins | /Time.py | 209 | 3.640625 | 4 | time=int(input("what time is it"))
long=int(input("how long do you want your alarm to be for?"))
longmodulo=long%24
alarmt=time+longmodulo
print("I will set off at", alarmt)
#x=5100 % 1400
#y=x+1400
#print(y) |
6f3460244241f0f7103572e80e3a2be883ebf332 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2563/60716/277381.py | 494 | 3.5625 | 4 | num = int(eval(input()))
if num%2==0:
print(num-1)
else:
ans = 3
check = False
while True:
index = 1
while True:
temp = (1-ans**index)//(1-ans)
if temp > num: break
elif temp == num:
check = True
break
else:
index+=1
if check or ans == int(pow(num,0.5)):break
else:
ans+=1
if check:
print(ans)
else:
print(num-1)
|
b50098ad3d6d9df2a2229d0cf2fb0086c527f99b | Boot-Error/Poem-Titler | /synonyms.py | 600 | 3.625 | 4 | import urllib
from bs4 import BeautifulSoup
#Method to get synonyms
def get_synonyms(query):
#Website url to search with
url = 'http://www.thesaurus.com/browse/{}'.format(query)
#opening the website
response = urllib.urlopen(url)
document = BeautifulSoup(response.read())
#Finding out the synonyms
try:
words = document.find('div', {'class' : 'relevancy-list'}).find_all('span', {'class':'text'})
except:
print 'synonyms for word \'{}\' not found'.format(query)
return [word.string for word in words]
if __name__ == '__main__':
query = 'the'
for a in get_synonyms(query):
print a |
7babc8f440ace19cbe59d2d01f4bb086c4eb38ee | arnaudpilato/Wild-Code-School | /France IOI/01 - Fundamentals 1/37 - Bétail.py | 115 | 3.5 | 4 | resultat = 0
for loop in range (20):
nbBetail = int(input())
resultat = resultat + nbBetail
print (resultat)
|
ddcd0ad4f7ffd6f34745fb32429aefabd119f4f7 | bluedawn123/Study | /homework/kyokwaseo/08/8-27.py | 517 | 4.28125 | 4 | import pandas as pd
indexes = ["apple", "orange", "banana", "strberry", "kiwi"]
data1 = [10, 5, 8, 12, 3]
data2 = [30, 25, 12, 10, 8]
series1 = pd.Series(data1, index = indexes)
series2 = pd.Series(data2, index = indexes)
#문제. series1, series2로 dataframe을 생성하여 df에 대입하고 출력하라.
df = pd.DataFrame([series1, series2])
df2 = pd.DataFrame([series1], series2)
df3 = pd.DataFrame([series1])
print("df : ",df)
print(" ")
print("df2 : ",df2)
print(" ")
print("df3 : ", df3)
|
ee0af7df595c55a5493f0b2d9deaf1b8a061d5ca | daniel-reich/ubiquitous-fiesta | /ycaiA3qTXJWyDz6Dq_13.py | 170 | 3.640625 | 4 |
def consonants(word):
return sum(1 for i in word.lower() if i in "bcdfghjklmnpqrstvwxyz")
def vowels(word):
return sum(1 for i in word.lower() if i in "aeiou")
|
35f5694d6638ef63ca974c6822d345c3ab9ee475 | joseraz/data_science_journey | /LeetCode/Easy/plusOne.py | 341 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 2 16:34:13 2020
@author: joera
"""
def plusOne(digits):
L = []
num = ""
for i in digits:
num += str(i)
num = int(num)+1
num = str(num)
for i in num:
L.append(int(i))
return L
digits = [1,2,3]
plusOne(digits)
digits = [1,2,9]
plusOne(digits) |
33b698dce967857413b95cbc04a4903eee5cc9d5 | sylee623/2021-spring-Computer_graphics | /LabAssignment2/1/labassignment2_1.py | 575 | 4.1875 | 4 | import numpy as np
#Create a 1d array M with values ranging from 2 to 26 and print M.
M = np.arange(2,26+1)
print(M) #[ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25]
#Reshape M as a 5x5 matrix and print M.
M = M.reshape(5,5)
print(M)
#Set the value of “inner” elements of the matrix M to 0 and print M.
M[1:4,1:4]=0
print(M)
#Assign M2 to the M and print M.
M = M@M
print(M)
#Let’s call the first row of the matrix M a vector v. Calculate the magnitude of the vector v and print it
v = M[0]
magnitude = np.sqrt(sum(v*v))
print(magnitude)
|
e198c3c8281c240a8e2d2450d54fb4d67cd18146 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/allergies/efa1437869664520a167a26e180db2f6.py | 849 | 3.75 | 4 | __author__ = 'grdunn'
class Allergies(object):
allergens = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes',
'chocolate', 'pollen', 'cats']
def __init__(self, score):
self.list = self.list_allergens(score if score < 256 else score - 256)
def list_allergens(self, score):
"""
the (1 << i) & score is the tricky bit here, 1 << i creates a mask
applying the & operator give us the power of two that's set (if 2**i is set)
otherwise it's 0
:param score:
:rtype : list
"""
allergies = []
for allergen in [i for i in range(0, len(self.allergens)) if ((1 << i) & score)]:
allergies.append(self.allergens[allergen])
return allergies
def is_allergic_to(self, allergen):
return allergen in self.list
|
052292465e487f414331b73d70b4e206d97f5c47 | aisiri26/Bank-Account | /BankAccount.py | 561 | 3.515625 | 4 |
class BankAccount:
def __init__(self, id, name, balance):
self.id = id
self.name = name
self.balance = balance
def has_id(self,target_id):
if target_id == self.id:
return True
def withdraw(self, amount):
if amount > self.balance:
raise RuntimeError('No action: Amount greater than available balance.')
self.balance = self.balance - amount
def deposit(self, amount):
self.balance = self.balance + amount
def get_balance(self):
return self.balance
|
17eb06ef2031f4fdb1432d1f94272dea668ef0d2 | thisgirlscode/python-challenge-1 | /challenge_1.py | 808 | 4.1875 | 4 | def start():
while True:
try:
number = int(input("Enter a integer please: "))
#validate the the input value is valid
if number < 0:
print("Negative integers are not valid, try again")
else:
break
except Exception as e:
print("Exception occurred: {}".format(e))
#validate conditional actions of this exercise
if number%2 > 0:
print("Weird")
elif number%2 == 0:
if number >= 2 and number <= 5:
print("Not weird")
elif number >=6 and number <= 20:
print("Weird")
elif number > 20:
print("Not weird")
else:
input("something is wrong with your number, try again")
if __name__ == "__main__":
start()
|
37c15c49279cb69e827a0cf6256cb20cd2b4d858 | danielgitk/competitive-programming | /camp 01/week 02/max-nesting-depth.py | 471 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 10 18:24:53 2021
@author: daniel
"""
class Solution(object):
def maxDepth(self, s):
"""
:type s: str
:rtype: int
"""
maxi = 0
count = 0
for x in s:
if x == '(':
count += 1
if count >= maxi:
maxi = count
if x == ')':
count -= 1
return maxi
|
1f78daaeddda3ea514db7a4c165b07505b4feb1d | terryfine/LeetCode | /PythonProject/HammingDistance.py | 845 | 3.6875 | 4 | class Solution:
def hammingDistance(self, x, y):
num = 0
n_x = ''.join(bin(x).replace('0b', ''))
n_y = ''.join(bin(y).replace('0b', ''))
if len(n_x) > len(n_y):
for _ in range(len(n_x) - len(n_y)):
n_y = '0' + n_y
else:
for _ in range(len(n_y) - len(n_x)):
n_x = '0' + n_x
print("x: %s" % n_x)
print("y: %s" % n_y)
for i in range(len(n_x)):
if n_x[i: i+1] != n_y[i: i+1]:
num += 1
return num
def hammingDistanceSolution(self, x, y):
num = 0
z = int(x ^ y)
while z != 0:
if z % 2 == 1:
num += 1
z = int(z / 2)
return num
s = Solution()
print(s.hammingDistance(3, 8))
print(s.hammingDistanceSolution(3, 8))
|
9b0182bdd7aa19a16c6cabdcc740c21129d08f47 | messi-1020/School-Work | /Lab 07/Lab07_Q1.py | 643 | 4.21875 | 4 | # Lab 07 - Problem 01
def calc_bmi():
height = float(input("Enter height (in inches):"))
weight = float(input("Enter weight (in pounds):"))
bmi = (703 * weight) / (height*height)
print("Your BMI is:", bmi,"\n")
def hypertension():
systolic_p = float(input("Enter your systolic pressure:"))
diastolic_p = float(input("Enter your diastolic pressure:"))
if systolic_p >= 140 or diastolic_p >=90:
print("You have high blood pressure.")
else:
print("You do not have high blood pressure.")
def main():
print("Health and Fitness Program\n")
calc_bmi()
hypertension()
main()
|
ad337825f8a5fb650272874158865deefe86967a | lixiang2017/leetcode | /problems/0652.0_Find_Duplicate_Subtrees.py | 1,002 | 3.953125 | 4 | '''
Runtime: 56 ms, faster than 60.60% of Python3 online submissions for Find Duplicate Subtrees.
Memory Usage: 24.4 MB, less than 27.68% of Python3 online submissions for Find Duplicate Subtrees.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
def dfs(node: Optional[TreeNode]) -> str:
if not node:
return ''
serial = ''.join([str(node.val), '(', dfs(node.left), ')(', dfs(node.right), ')'])
if (tree := seen.get(serial, None)):
repeat.add(tree)
else:
seen[serial] = node
return serial
seen = dict()
repeat = set()
dfs(root)
return list(repeat)
|
21d950222b5ccfb5d8a9a2eeff143b47bca0901b | Ekta-751/Assignment | /assignment14.py | 1,332 | 4.375 | 4 | #1.rite a Python program to read last n lines of a file.
f=open("test.txt")ds
content=f.readlines()
print(content)
f.close()
n=int(input("enter the cantant of index we want to read at a last"))
while n>0:
print(content[-n])
n=n-1
#2.ite a Python program to count the frequency of words in a file.
words=open("test.txt","r").read().split() #read the words into a list.
print(words)
print(type(words))
uniqWords=sorted(set(words)) #remove duplicate words and sort
print(uniqWords)
print(type(uniqWords))
for word in uniqWords:
print(word.count(word),word)
#3.rite a Python program to copy the contents of a file to another file.
with open('test.txt','r') as f1:
with open('test1.txt','w') as f2:
for line in f1:
f2.write(line)
#4.ite a Python program to combine each line from first file with the corresponding line in second file.
with open('test.txt','r') as f1:
with open('test1.txt','r') as f2:
for line1,line2 in zip(f1,f2):
print(line1+line2)
# 5.ite a Python program to write 10 random numbers into a file. Read the file and then sort the numbers and then store it to another file.
import random
f=open('test2.txt','r+')
for i in range(10):
x=str(random.randint(1,100))
f.write(x+"\n")
l=f.readlines()
print(l)
l.sort()
print(l)
with open('test3.txt','r+')as f2:
for n in l:
f2.write(n)
f.close()
|
6ed4159f11e3987fb23e6d9f3567ab97ad5a5d8e | coldhair/DetectionSystem | /tmp/temp015.py | 390 | 3.953125 | 4 | # 2.13 字符串对齐
text = 'Hello World'
t = format(text, '>20')
print(t)
t = format(text, '<20')
print(t)
t = format(text, '^20')
print(t)
t = format(text, '=>20')
print(t)
t = format(text, '*^20s')
print(t)
# 同时格式化多个字符
t = '{:>20s} {:>20s}'.format('Hello', 'World')
print(t)
# 格式化数字
x = 1.2345
d = format(x, '>10')
print(d)
d = format(x, '^10.2f')
print(d)
|
287098a8a38bc9b82624fa9d655cae30187b18e8 | Diego-18/python-algorithmic-exercises | /1. PROGRAMACION ESTRUCTURADA/CALCULOS/promedio.py | 937 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: UTF8 -*-
################################
# Elaborado por: DIEGO CHAVEZ #
################################
#Algoritmo capaz de calcular el promedio de un estudiante, mostrando si aprobó o reprobó
#Inicio
#Entrada
while lsseguir=="s" or lsseguir=="S":
lsnombre=raw_input("Introduzca el nombre del estudiante ")
lscedula=raw_input("Introduzca el numero de cedula del estudiante ")
lfn1=float(raw_input("Introduzca la nota uno: "))
lfn2=float(raw_input("Introduzca la nota dos: "))
lfn3=float(raw_input("Introduzca la nota tres: "))
lfn4=float(raw_input("Introduzca la nota cuatro: "))
#Proceso
lfprom=(lfn1+lfn2+lfn3+lfn4)/4
if lfprom>=12:
print "El estudiante aprobó"
elif lfprom<12:
print "El estudiante reprobó"
#Salida
print "El promedio es de: ",lfprom
lsseguir=raw_input("Desea seguir?: (S/N) ")
#Fin
raw_input ()
#UPTP S1-T1
|
7abeb40a9669593d5b667366e62e17af305eb775 | mjtribble/priority-inversion-scheduling | /tribble-3.py | 6,655 | 3.890625 | 4 | """
Author: Melody Tribble
Created On: Nov 21, 2017
"""
# This class creates a buffer and it's functionality
import sys
class Buffer:
# create a new buffer object
def __init__(self, number, value):
self.number = number
self.value = value
self.j_list = []
# This is called when printing the object
def __str__(self):
return "Buffer %s <%s>" % (self.number, self.value)
# This adds a job to the end of the buffer
def add_job(self, j):
self.j_list.append(j)
# This class creates and prints a job
class Job:
# This creates and instantiates a new job
def __init__(self, number, priority, arrival_time, run_time):
self.number = number
self.priority = priority
self.arrival_time = arrival_time
self.run_time = run_time
self.completed_time = 0
self.remaining_time = run_time
# This is called when printing a job
def __str__(self):
# T_1 Job
if self.number is 1:
return 'T_%s111T_%s.' % (self.number, self.number)
# T_2 Job
elif self.number is 2:
return 'T_%s%sT_%s.' % (self.number, 'N' * self.completed_time, self.number)
# T_3 Job
else:
return 'T_%s%sT_%s.' % (self.number, '3' * self.completed_time, self.number)
# Start program here
if __name__ == '__main__':
# file to write output to
orig_stdout = sys.stdout
f = open('tribble-3.output.txt', 'w')
sys.stdout = f
# Given list of jobs to run
job_l = [(1, 3), (3, 2), (6, 3), (8, 1), (10, 2), (12, 3), (26, 1)]
# sort job lists by arrival time, the first value in the tuple
job_l = sorted(job_l, key=lambda tup: tup[0])
# list to hold the being processed and run
processes_l = []
# Create Buffers
buffer_1 = Buffer(1, '0')
buffer_2 = Buffer(2, 'N')
# Create Jobs and add them to the appropriate Buffer
for i in job_l:
t = i[1]
arrival_t = i[0]
if t is 1:
job = Job(number=1, priority=3, arrival_time=arrival_t, run_time=3)
buffer_1.add_job(job)
if t is 2:
job = Job(number=2, priority=2, arrival_time=arrival_t, run_time=10)
buffer_2.add_job(job)
if t is 3:
job = Job(number=3, priority=1, arrival_time=arrival_t, run_time=3)
buffer_1.add_job(job)
print("Job created : ", i)
# set buffer lists to a variable
b1 = buffer_1.j_list
b2 = buffer_2.j_list
# starting time is zero
time = 0
# determines which job to run first based on which arrived first,
# removes them from the buffer, sets the system time to their arrival time
# adds them to the process list
if b1[0].arrival_time <= b2[0].arrival_time:
processes_l.append(b1[0])
time = b1[0].arrival_time
b1.remove(b1[0])
else:
processes_l.append(b2[0])
time = b2[0].arrival_time
b2.remove(b2[0])
# runs while there are unfinished jobs.
while processes_l:
# sets current job to the beginning of the buffer
current_job = processes_l[0]
current_job.arrival_time = time
finish_time = current_job.arrival_time + current_job.remaining_time
preempt_job = None
next_job = None
# If current job is T2 and buffer 1 is not empty,
# check buffer 1 for a T1 that could preempt it.
if current_job.number == 2 and b1:
for i in b1:
if i.number == 1 and i.arrival_time < finish_time:
preempt_job = i
b1.remove(i)
break
if b1[0].number == 1 and b1[0].arrival_time == current_job.arrival_time:
preempt_job = b1[0]
b1.remove(b1[0])
# If the current job is T3, and buffer 2 is not empty,
# check buffer 2 for a T2 that could preempt it.
if current_job.number == 3 and b2:
if b2[0].arrival_time < finish_time:
preempt_job = b2[0]
b2.remove(b2[0])
# If there is a job that will interrupt the current job
if preempt_job:
# current job was NOT preempted before it was able to run.
if preempt_job.arrival_time > current_job.arrival_time:
# set the current jobs remaining time
current_job.completed_time = preempt_job.arrival_time - current_job.arrival_time
current_job.remaining_time -= current_job.completed_time
# print the current job
print('time %s, %s' % (time, current_job))
time = preempt_job.arrival_time
# add the next job to the font of the list.
processes_l.insert(0, preempt_job)
# If there is a job that will run
else: # the current job will finish without being preempted
current_job.completed_time = finish_time - current_job.arrival_time
current_job.remaining_time -= current_job.completed_time
print('time %s, %s' % (time, current_job))
time = finish_time
processes_l.remove(current_job)
# the process list is empty, choose next job to run
if not processes_l:
# if both buffers still have jobs to run choose the next job based on arrival time and priority.
if b1 and b2:
# choose buffer 1's job if it arrives first,
# or if there is a tie and buffer 1's job has a higher priority
if b1[0].arrival_time < b2[0].arrival_time \
or (b1[0].arrival_time == b2[0].arrival_time and b1[0].priority > b2[0].priority):
processes_l.append(b1[0])
b1.remove(b1[0])
# else choose the job in buffer 2
else:
processes_l.append(b2[0])
b2.remove(b2[0])
if processes_l[0].arrival_time > time:
time = processes_l[0].arrival_time
# if only buffer 1 has jobs left to run
elif b1:
processes_l.append(b1[0])
b1.remove(b1[0])
if processes_l[0].arrival_time > time:
time = processes_l[0].arrival_time
# if only buffer 2 has jobs left to run
elif b2:
processes_l.append(b2[0])
b2.remove(b2[0])
if processes_l[0].arrival_time > time:
time = processes_l[0].arrival_time
sys.stdout = orig_stdout
f.close()
|
a79e136ef152f7bf9759710507d4d713496665e4 | letrongminh/Python | /Recursions/de_quy_da_tuyen.py | 359 | 3.765625 | 4 | def print_arr(arr):
print(arr)
def print_per(arr, n):
print_arr(arr)
for i in range (0, n):
for j in range (0, n):
if arr[i] < arr[j]:
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
j+=1
i+=1
print(arr)
M=[3, 9, 6]
test2 = print_per(M, len(M))
print(test2)
|
20b614a1df3498ba57a5f418515b3cd3ae4adad5 | ChristofferOliveira/TP_IA | /Scripts/Aspirador.py | 1,854 | 4.03125 | 4 | # Módulo que contém as funções do aspirador de pó
def criar_aspirador(ambiente):
posicionado = 0
while posicionado == 0:
print('Em qual posição o aspirador de pó começará?(Não pode coloca-lo em um móvel)')
y = int(input(print('Posição em Y(linha): ')))
x = int(input(print('Posição em X(Coluna): ')))
if ambiente[y][x] == -1:
print('Aspirador não pode iniciar em um móvel. Tente novamente')
else:
posicionado = 1
# Aspirador primeira posição Y, Segunda X, terceira representa uma lista de destinos para busca A estrela.
aspirador = [0, 0, []]
ambiente[aspirador[0]][aspirador[1]] = 'A'
return aspirador
def aspirar(altura, largura, ambiente):
if ambiente[largura][altura] == 1:
ambiente[largura][altura] = 0
print('Sujeira removida')
else:
print('Posição não contém sujeira')
# Realiza o movimento do aspirador
def andar(aspirador, direcao,ambiente):
# Verificando se há móvel na direção
if ambiente[direcao[0]][direcao[1]] != - 1:
ambiente[aspirador[0]][aspirador[1]] = 0
aspirador[0] = direcao[0]
aspirador[1] = direcao[1]
else:
print('Móvel impedindo movimento, realizando outro movimento')
# Se houver sujeira na posição que se moveu aspira
if ambiente[aspirador[0]][aspirador[1]] == 1:
print('Encontrada sujeira, andando e aspirando')
aspirar(aspirador[0], aspirador[1], ambiente)
# Armazenando o destino para busca A estrela
destino = (aspirador[0], aspirador[1])
aspirador[2].append(destino)
# Aspirador movido
ambiente[aspirador[0]][aspirador[1]] = 'A'
print('Aspirador, movido')
return aspirador
|
6cb749f436e3b29d39d46308bdf60a91ced35cf1 | AnTznimalz/python_prepro | /caesar_v1.py | 724 | 3.84375 | 4 | '''CaesarV1 learn from Mr.Saran Hanthongkam(P'Winner)'''
def caesar():
'''Func. caesar for decoding unknown password'''
num_shift = int(input()) % 26
#% 26 when num_shift > 26 or < -26
#Ex. num_shift = 27
#input = 'a' + (27 % 26 = 1) >>> 'b'
#Ex. num_shift = -27
#input = 'a' + (-27 % 26 = 25) >>> 'z'
text = input()
password = ''
alp = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in text:
if i.isalpha():
if i.islower():
password += alp[(alp.find(i) + num_shift) % 26]
if i.isupper():
password += alp[((alp.find(i) + num_shift) % 26) + 26]
else:
password += i
print(password)
caesar()
|
0504534460fc58b60d141dc654c772d7e718e950 | guoziqingbupt/Lintcode-Answer | /string sort.py | 959 | 3.8125 | 4 | class Solution:
"""
@param str: the string that needs to be sorted
@return: sorted string
"""
def stringSort(self, str):
# key: value = char: count
record = {}
for i in str:
if i not in record:
record[i] = 1
else:
record[i] += 1
# sort the dictionary and put the key into the temp list
temp = []
for i in sorted(record, key=lambda x: record[x], reverse=True):
temp.append(i)
result = ""
curCount = record[temp[0]]
begin, cur = 0, 0
n = len(temp)
while cur < n:
while cur < n and record[temp[cur]] == curCount:
cur += 1
for i in sorted(temp[begin: cur]):
result += i * record[i]
begin = cur
if cur < n:
curCount = record[temp[cur]]
return result
# Write your code here
|
8e853cecfa73db3e87c8346fa0db5131e90e4a81 | dpb246/MachineLearning_Testing | /path-finding/main.py | 1,871 | 3.640625 | 4 | import pygame, sys
from engine import *
from individual import *
from time import sleep
import population
import physics
from food import food
# initialize the pygame module
pygame.init()
#Settings
max_steps = 1000
goal = (900, 600) #(x, y)
screen_size = (1000,720) #(x, y)
spawn_point = [30, 30] #Spawn point for circles
# create a surface on screen
screen = pygame.display.set_mode(screen_size)
engine = Render_Engine(screen, goal, screen_size)
physics = physics.physics(goal, engine)
food = food(*screen_size, goal)
food.upfood()
pop = population.population(spawn_point, food, population_size=300, steps=max_steps)
walls = [[500, 300, 10, 600], [600, 0, 10, 400], [800, 500, 10, 200]] #Walls: format [x, y, x_size, y_size], [400, 0, 10, 300]
gen = 0
frame_num = 0
while True:
# Closes program when red[x] button in corner is pressed
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
pygame.quit()
sys.exit()
if pop.everyone_dead():
#Everyone died reset and advance to next generation
print("Gen:", gen)
engine.frame(pop.get_positions(), walls)
#pop.calc_fitness_scores(goal)
best = pop.best_person(goal)
print(best.fitness)
print(pop.individuals[10].fitness)
if best.win:
print("Took the fastest {} steps".format(best.brain.counter))
pop.selection(goal)
pop.reset()
gen += 1
frame_num = 0
food.upfood()
else:
#Continue moving and updating
engine.frame(pop.get_positions(), walls)
pop.move()
physics.check(pop.individuals, walls)
#if frame_num%10 == 0:
# food.upfood()
pop.update_fitness()
frame_num += 1
|
628e6392054e5256324f4de38c0c913721de6280 | GINK03/project-euler-solvers | /91/euler.py | 601 | 3.75 | 4 |
import math, os, sys, itertools
def is_right_triangle(P, Q):
if P[1] == 0 and Q[0] == 0:
return True
elif P[0] * (Q[0] - P[0]) == P[1] * (P[1] - Q[1]):
return True
elif Q[0] * (P[0] - Q[0]) == Q[1] * (Q[1] - P[1]):
return True
return False
def is_right_lower(P, Q):
return P[0] * Q[1] - P[1] * Q[0] > 0
c = 0
for Q in itertools.product(xrange(0,51), repeat=2):
for P in itertools.product(xrange(0,51), repeat=2):
if is_right_lower(P, Q) and is_right_triangle(P, Q):
c += 1
#print Q1, Q2, P1, P2
pass
print c
|
d597db0147de7fe0237302f2e0bfe7821a72725f | jabinw/tutorial | /src/random_planet.py | 192 | 3.671875 | 4 | import random
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
print("One of the planets in our solar system is {0}".format(random.choice(planets)))
|
00e91de98eb8d37c5608bebd5001f44f1664f587 | justinej/project_euler | /62.py | 1,641 | 3.671875 | 4 | # Find smallest cube where 5 permutations are also cubes
def positions(digits):
all_permutations = []
queue = [[x] for x in xrange(digits)]
while len(queue) > 0:
sub_pos = queue.pop()
if len(sub_pos) == digits:
all_permutations.append(sub_pos)
else:
options = [x for x in range(digits) if x not in sub_pos]
for option in options:
queue.append(sub_pos + [option])
return all_permutations
def permute(x, pos):
x = str(x)
y = ''
for spot in pos:
y = y + x[spot]
return int(y)
def permutations(x, positions):
ans = []
for pos in positions:
ans.append(permute(x, pos))
return list(set(ans))
def ceil(x):
if x == int(x):
return int(x)
else: return int(x)+1
def all_cubes(lower, upper):
ans = []
for i in xrange(lower, upper):
ans.append(i**3)
return ans
def group_cubes(cubes):
ans = {}
for cube in cubes:
sort_cube = int("".join(sorted([char for char in str(cube)])))
if sort_cube in ans: ans[sort_cube].append(cube)
else: ans[sort_cube] = [cube]
return ans
def find_cube(num):
num_digits = 9 # Num digits in cube
flag = True
while flag:
cubes = all_cubes(ceil(10**((num_digits-1)/3.)), ceil(10**(num_digits/3.)))
families = group_cubes(cubes)
print "There are approx {} cubes with {} digits".format(len(cubes), num_digits)
for sort_cube in families:
if len(families[sort_cube]) >= num:
return families[sort_cube]
num_digits += 1
print find_cube(5)
|
241029b22946e456be127c38e2316ca9575f5d34 | wizardcalidad/PythonWonders | /venv/pbil.py | 315 | 3.953125 | 4 | '''
word = "alphabetical"
i =0
for i in range(12):
if i % 3 ==0:
print(word.index, end=' ')
else:
continue
'''
word = "alphabetical"
# for i,j in enumerate(word,1):
# if(i%3==0):
# print(j,end='')
for i,j in enumerate("alphabetical", 1):
if(i%3==0):
print(j,end='') |
eb20e8765a2afbde55695a6f97a3054bf41e838d | 0305Chao/Work_file | /python3/sleven/c4.py | 462 | 3.671875 | 4 |
from enum import Enum
class VIP(Enum):
YELLOW = 1
GREEN = 1
RED = 2
BREAK = 3
class VIP1(Enum):
YELLOW = 1
GREEN = 1
RED = 2
BREAK = 3
A = VIP.GREEN is VIP.GREEN
print(A)
B = VIP.GREEN == VIP1.YELLOW
print(B)
C = VIP.GREEN is VIP1.YELLOW
print(C)
D = VIP.GREEN is VIP.YELLOW
print(D)
for v in VIP:
print(v)
for k in VIP.__members__:
print(k)
for j in VIP.__members__.items():
print(j) |
864d4729252afd5d37ab76b6a7b033c22061269a | maknetaRo/python-algo | /selection-sort/selection2.py | 314 | 4.09375 | 4 | def selection_sort(arr):
for i in range(0, len(arr) - 1):
smallest = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[smallest]:
smallest = j
arr[i], arr[smallest] = arr[smallest], arr[i]
return arr
print(selection_sort([3, 5, 1, 6, 3, 7, 8, 0, 9]))
|
99098f82cc60a57ba1071f5715f3e50812dd63f6 | codermore/PythonEjercicios | /TP32.py | 1,606 | 4.03125 | 4 | """
Gabriel Maso
Programa:
Escribi funciones que dada una cadena de caracteres:
a) Imprima los dos primeros caracteres
b) Imprima los ultimos tres caracteres
c) Imprima dicha cadena cada dos caractere. Ej.:'Recta' deberia imprimir 'rca'
d) Dicha cadena den sentido inverso. Ej.: 'Hola mundo!' debe imprimir '!odnum aloh'
e) Imprima la cadena en un sentido y en sentido inverso. Ej: 'refeljo' imprime reflejoojelfer
"""
def cadena(dato,palabra):
dato2 = dato.lower()
if dato2 == 'a':
for x in range (2):
print (palabra[x], end="")
elif dato2 == 'b':
y = len(palabra)
for x in range (y-3,y):
print (palabra[x], end="")
elif dato2 == 'c':
for x in range(0,len(palabra),2):
print (palabra[x], end="")
elif dato2 == 'd':
x = len(palabra)
while x>0:
print (palabra[x-1], end="")
x = x - 1
elif dato2 == 'e':
x = len(palabra)
print(palabra, end="")
while x>0:
print (palabra[x-1], end="")
x = x - 1
else:
print("la opcion ingresada es incorrecta")
palabra = input("ingrese una palabra: ")
print("""a) Imprima los dos primeros caracteres
b) Imprima los ultimos tres caracteres
c) Imprima dicha cadena cada dos caractere. Ej.:'Recta' deberia imprimir 'rca'
d) Dicha cadena den sentido inverso. Ej.: 'Hola mundo!' debe imprimir '!odnum aloh'
e) Imprima la cadena en un sentido y en sentido inverso. Ej: 'refeljo' imprime reflejoojelfer""")
dato = input("ingrese opcion: ")
cadena(dato,palabra)
|
017cd02a966d86a340bcc3908293b23d3b69e0d0 | ncruz12/TKH_Prework | /assignment_2.py | 103 | 4.21875 | 4 | # Asks for name and prints it out
my_name = input("What is your name?")
print ("My name is " + my_name) |
6a96807c16c0eee9019b4c739d2350bb29d7cfe8 | JT4life/PythonRevisePractice | /MostFrequentValueInList.py | 504 | 3.609375 | 4 | # 7. Find the most frequent value in a list
lst = [1,2,3,3,4]
def lstFr(lst):
return max(set(lst), key=lst.count)
print(lstFr(lst))
test = [1, 2, 3, 9, 2, 7, 3, 5, 9, 9, 9]
print(max(set(test), key = test.count))
# 8. Print the file path of imported modules
import os;
print(os)
print(type(2//4))
n='l'
print(id(n))
def delete_book(book_id):
books = [{'id':0,'title':u'harry'},{'id':1,'title':u'lord'}]
book = [book for book in books if book['id'] == book_id]
books.remove(book[0])
|
e1cc9a39fc4420fb29691c12cd6a86b3232e5a8a | MubarizKhan/Python-CSV-Handling-Email-Delievery-using-smtplib | /Functions to Dynamically Add Data to CSV with Python/file.py | 877 | 3.546875 | 4 | import csv
with open("data.csv","w+") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Title","Description"])
def get_length(file_path):
with open("data.csv","r") as csvfile:
reader = csv.reader(csvfile)
reader_list = list(reader)
return len(reader_list)
def append_data(file_path,name,email):
fieldnames = ['id','name','email']
user_id = get_length(file_path)
with open(file_path,"a") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
writer.writerow(
{
"id": user_id,
"name": name,
"email": email,
})
append_data("data.csv","Shamoon","hello@hgmail.com")
append_data("data.csv","Shamoon","hello@hgmail.com")
append_data("data.csv","Shamoon","hello@hgmail.com")
append_data("data.csv","Shamoon","hello@hgmail.com") |
e34ed0465a5fd22c905826be81eda95e1bba69d4 | Harshad06/Python_programs | /PANDAS/joinsIdenticalData.py | 740 | 4.21875 | 4 |
import pandas as pd
df1 = pd.DataFrame([1,1], columns=['col_A'] )
#print("DataFrame #1: \n", df1)
df2 = pd.DataFrame([1,1,1], columns=['col_A'] )
#print("DataFrame #2: \n", df2)
df3 = pd.merge(df1, df2, on='col_A', how='inner')
print("DataFrame after inner join: \n", df3)
# Output: 2x3 --> 6 times it will be printed. [one-many operation]
# It maybe any type of join ---> inner/outer/right/left
'''
DataFrame after inner join:
col_A
0 1
1 1
2 1
3 1
4 1
5 1
'''
# In case where any df data is "NaN" or "None", then value will be empty column-
# df1 = pd.DataFrame([NaN, NaN], columns=['col_A'] )
'''
DataFrame after inner join:
Empty DataFrame
Columns: [col_A]
Index: []
'''
|
56ee1207d798c519decfaa63652cda29be535aff | emmanuel-okwara/Machine-learning-projects | /Learning_Material_beginners/kaggle_ml_course/Data_handling/cross_validation.py | 4,248 | 3.71875 | 4 | '''# A better way to test your model
#What is cross-validation:
#this is when we run our modeling process on different subsets of the data to get multiple measures to model
#quality
# For example, we could begin by dividing the data into 5 pieces,
# each 20% of the full dataset. In this case,
# we say that we have broken the data into 5 "folds".
#Then, we run one experiment for each fold:
#In Experiment 1, we use the first fold as a validation (or holdout) set and everything else as training data.
#This gives us a measure of model quality based on a 20% holdout set.
#In Experiment 2, we hold out data from the second fold (and use everything except the second fold for training the model).
# The holdout set is then used to get a second estimate of model quality.
#We repeat this process, using every fold once as the holdout set. Putting this together, 100% of the data is used as holdout at some point,
# and we end up with a measure of model quality that is based on all of the rows in the dataset (even if we don't use all rows simultaneously).
'''
'''
When should you use cross-validation?
Cross-validation gives a more accurate measure of model quality,
which is especially important if you are making a lot of modeling decisions
However, it can take longer to run, because it estimates multiple models (one for each fold).
So, given these tradeoffs, when should you use each approach?
For small datasets, where extra computational burden isn't a big deal,
you should run cross-validation.
For larger datasets, a single validation set is sufficient.
Your code will run faster, and you may have enough data that there's little
need to re-use some of it for holdout.
There's no simple threshold for what constitutes a large vs.
small dataset. But if your model takes a couple minutes or less to run, it's probably worth switching to cross-validation.
Alternatively, you can run cross-validation and see if the scores for each experiment seem close.
If each experiment yields the same results, a single validation set is probably sufficient.
'''
'''import pandas as pd
# Read the data
data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv')
# Select subset of predictors
cols_to_use = ['Rooms', 'Distance', 'Landsize', 'BuildingArea', 'YearBuilt']
X = data[cols_to_use]
# Select target
y = data.Price
'''
'''
Then, we define a pipeline that uses an imputer to fill in missing values and a random forest model to make predictions.
While it's possible to do cross-validation without pipelines, it is quite difficult! Using a pipeline will make the code remarkably straightforward.
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
my_pipeline = Pipeline(steps=[('preprocessor', SimpleImputer()),
('model', RandomForestRegressor(n_estimators=50,
random_state=0))
])
'''
'''
We obtain the cross-validation scores with the cross_val_score() function from scikit-learn. We set the number of folds with the cv parameter.
from sklearn.model_selection import cross_val_score
# Multiply by -1 since sklearn calculates *negative* MAE
scores = -1 * cross_val_score(my_pipeline, X, y,
cv=5,
scoring='neg_mean_absolute_error')
print("MAE scores:\n", scores)
MAE scores:
[301628.7893587 303164.4782723 287298.331666 236061.84754543
260383.45111427]
The scoring parameter chooses a measure of model quality to report: in this case, we chose negative mean absolute error (MAE). The docs for scikit-learn show a list of options.
It is a little surprising that we specify negative MAE. Scikit-learn has a convention where all metrics are defined so a high number is better. Using negatives here allows them to be consistent with that convention, though negative MAE is almost unheard of elsewhere.
We typically want a single measure of model quality to compare alternative models. So we take the average across experiments.
'''
|
acc7327186d0d6879cc0b958a323c9ebe794ea12 | yuyangd/python-utils | /data_structure/heapq_example.py | 3,080 | 4.3125 | 4 | # Heap is a priority queue
#
# A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps can be of two types:
# Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.
# Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.
# my understanding of heap
# heap seems to be a list but always being ordered in a way
# push will insert a new element to the list, then re-order
# pop will remove the smallest
# however, if you print out the list, it's not sorted
# Stack vs Heap Pros and Cons
# Stack
# very fast access
# don't have to explicitly de-allocate variables
# space is managed efficiently by CPU, memory will not become fragmented
# local variables only
# limit on stack size (OS-dependent)
# variables cannot be resized
# Heap
# variables can be accessed globally
# no limit on memory size
# (relatively) slower access
# no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
# you must manage memory (you're in charge of allocating and freeing variables)
# variables can be resized using realloc()
# Some Python code to demonstrate
# importing "heapq" to implement heap queue
import heapq
# initializing list
li = [5, 7, 9, 1, 3]
# using heapify to convert list into heap
heapq.heapify(li)
# printing created heap
print("The created heap is : ", end="")
print(list(li))
# using heappush() to push elements into heap
# pushes 4
heapq.heappush(li, 4)
# printing modified heap
print("The modified heap after push is : ", end="")
print(list(li))
# using heappop() to pop smallest element
print("The popped and smallest element is : ", end="")
print(heapq.heappop(li))
# using heappushpop() to push and pop items simultaneously
# pops 2
print("The popped item using heappushpop() is : ", end="")
print(heapq.heappushpop(li, 2))
# using heapreplace() to pop and push items simultaneously
# pops 3
print("The popped item using heapreplace() is : ", end="")
print(heapq.heapreplace(li, 2))
# using nlargest to print 3 largest numbers
# prints 10, 9 and 8
print("The 3 largest numbers in list are : ", end="")
print(heapq.nlargest(3, li))
# using nsmallest to print 3 smallest numbers
# prints 1, 3 and 4
print("The 3 smallest numbers in list are : ", end="")
print(heapq.nsmallest(3, li))
# problem:
# sort every element in the n x n matrix
# solution
# use heapq.merge to merge list into the 1st one
mat = [[10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]]
# move exeything into a list
from heapq import merge
result = mat[0]
for row in mat[1:]: # the rest of rows
result = merge(result, row)
# result became an ordered generator
print(list(result))
# print(heapq.nlargest(3, result))
|
fc7e83ae96833ce7d65963c9d8db86bbf5adfc50 | Ichbini-bot/python-labs | /07_classes_objects_methods/07_12_card_game_simple.py | 1,422 | 4.03125 | 4 | import random
class Card:
globalvar = "test"
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
def __init__(self, suit = 0, rank = 2):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.rank_names[self.rank]} of {self.suit_names[self.suit]}" #of {Card.globalvar} of {self.globalvar}" difference Card.globalvar vs. self.globalvar???
class Deck:
def __init__(self):
self.deck = []
for i in range(4):
for x in range(13):
card = Card(i, x)
self.deck.append(card)
def __str__(self):
res = []
for card in self.deck:
res.append(str(card))
return '\n'.join(res)
def shuffle(self):
print("***\n DECK SHUFFLING\n***")
random.shuffle(self.deck)
def pop_card(self):
return self.deck.pop()
def add_card(self, card):
self.cards.append(card)
class Hand(Deck):
def _init__(self):
self.hand = []
def move_cards(self, hand):
for i in range(6):
hand.add_card(self.pop_card())
deck = Deck()
deck.shuffle()
print(deck)
print("Hand is: ")
print("Hand is: ")
print("Hand is: ")
hand = Hand()
print(hand.move_cards)
'''
deck.pop_card()
print("***\npopping Card\n***")
print(deck)
'''
|
408c7056bf3478deb81faee31791fd686e5e031f | Lynkdev/Python-Projects | /chapter2MPG.py | 333 | 4.03125 | 4 | #Jeff Masterson
#Chapter 2 #2
#Get the miles driven.
miles_driven = float(input('Enter the Miles Driven: '))
#Get the gallons of gas used.
gallons = float(input('Enter the ammount of gallons used: '))
#calculate the profit as 23 percent of total sales.
mpg = miles_driven /gallons
# Display the profit.
print('The MPG is', format(mpg,))
|
ae4d0129f29008ba24250c7b935cd049a7c00fb1 | grupy-sanca/dojos | /013/fat.py | 111 | 3.59375 | 4 | """
Fatorial simples
>>> fat(3)
6
>>> fat(5)
120
"""
def fat(n):
return 1 if n == 1 else n * fat(n - 1)
|
f742000fef7316430be53c63a1f6819fa8206779 | kyasui/python_lab | /main.py | 2,281 | 4 | 4 | """Rock Paper Scissors"""
from random import randint
class Player:
def __init__(self, is_human=False):
self.is_human = is_human
def play(self):
if self.is_human == False:
return randint(0,2)
else:
is_recognized_input = False
while is_recognized_input == False:
play = raw_input('ROCK, PAPER or SCISSORS? ')
play = play.lower()
if play == 'rock':
is_recognized_input = True
return 0
elif play == 'paper':
is_recognized_input = True
return 1
elif play == 'scissors':
is_recognized_input = True
return 2
else:
print('Unrecognized play... Try again...')
class Game:
def __init__(self, player_one, player_two):
self.player_one = player_one
self.player_two = player_two
self.choices = {
0: 'Rock',
1: 'Paper',
2: 'Scissors',
}
def start(self):
winner = False
while winner == False:
player_one_score = self.player_one.play()
player_two_score = self.player_two.play()
if player_one_score != player_two_score:
print 'Player One chose ' + self.choices[player_one_score]
print 'Player Two chose ' + self.choices[player_two_score]
result = self.determine_winner(self.choices[player_one_score], self.choices[player_two_score])
print(result)
winner = True
playagain = raw_input('Play Again? Y/N ').lower()
if (playagain == 'y'):
self.start()
else:
print 'Tie, Go Again.'
def determine_winner(self, player_one_play, player_two_play):
if player_one_play == 'Rock':
if player_two_play == 'Paper':
return 'Player One Loses!'
elif player_two_play == 'Scissors':
return 'Player One Wins!'
elif player_one_play == 'Scissors':
if player_two_play == 'Rock':
return 'Player One Loses!'
elif player_two_play == 'Paper':
return 'Player One Wins!'
elif player_one_play == 'Paper':
if player_two_play == 'Scissors':
return 'Player One Loses!'
elif player_two_play == 'Rock':
return 'Player One Wins!'
if __name__ == '__main__':
game = Game(Player(is_human=True), Player(is_human=False))
game.start() |
fd89af19d3c9aed536f9024b7897197cf330ceaf | N2ITN/Scripts | /File Manipulation Tools/FILE_sort_by_extension.py | 1,321 | 3.703125 | 4 |
#Description:
# This script will look at every file in the main directory folder only.
# It sorts files into sub-folders based on their extension (all excel type files will go into a folder called 'excel')
# It will not delete or overwrite anything, it just moves files in the top level to a folder matching the file's extension
# New folders are created only if needed, and are placed in the same directory
##d = r"C:\Users\zestela53\Desktop\gulf_temp\59\Allfiles"
import os, shutil
def Extensions_to_folders(d):
# Initialize counter
n = 0
# Iterate through files in parent folder
for item in os.listdir(d):
# Check if file
if os.path.isfile(os.path.join(d, item)):
print item
# Get extension
iExt = os.path.splitext(item)[-1][1:]
print iExt
# If excel-type document, lump into "excel" folder
if "xls" in iExt:
iExt = "Excel"
# Create path for original
fullPath = d + "\\" + item
# Create path for extension folder
extDir = d + "\\" + iExt+ "\\"
# Create extension folder if it doesn't exist
if os.access(extDir,os.F_OK) == False:
os.mkdir(extDir)
#Create path for new item location
finalPath = extDir + item
# Move files to new folder
if len(fullPath) >1 :
shutil.move(fullPath,finalPath)
n+=1
print "%s Files were moved." %n
|
df00f265ae7c4fcff5db1506893311405e745077 | WooodHead/Code-practice | /Other/prediciting_weather.py | 321 | 3.515625 | 4 | import requests
from pprint import pprint
city =input("Enter your city: ")
url = "http://api.openweathermap.org/data/2.5/weather?q={}&appid=49ca951308953479f7b479e1f6fd7ea0".format(city)
res = requests.get(url)
data = res.json()
temp=data["main"]["temp"]
temp=temp-273.15
print(f"Temperature: {temp} celcius degrees") |
0e3deca6fbfc807efc0055591c780547f5d55f2f | darcycool/python | /darcycool/0006/important_word.py | 1,207 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# 第 0006 题: 你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
import operator
import os
import re
rootDir = 'diary/'
def count_words(filename, words):
wordDict = dict()
for word in words:
if word.lower() in wordDict:
wordDict[word.lower()] += 1
else:
wordDict[word.lower()] = 1
print('%s word:%s' % (filename, max(wordDict.items(), key=operator.itemgetter(1))[0]))
for top, dirnames, filenames in os.walk(rootDir):
for filename in filenames:
file = open(rootDir + filename, 'r')
str = file.read()
reObj = re.compile('\b?(\w+)\b?')
words = reObj.findall(str)
count_words(filename, words)
from collections import Counter
for top, dirnames, filenames in os.walk(rootDir):
for filename in filenames:
file = open(rootDir + filename, 'r')
str = file.read()
reObj = re.compile('\b?(\w+)\b?')
words = reObj.findall(str)
words = map(lambda w: w.lower(), words)
print(filename, Counter(words).most_common(1))
|
a984ee1a9c98f90c178ef0d56ca0ed8574bdaac2 | sindhumantri/python | /Misc/sumOfNumEqMulOfNum.py | 314 | 3.890625 | 4 | def multiples(arr):
mul = 1
for i in arr:
mul *= i
return mul
def sumOfEleEqualToMultiples(arr):
for i in range(len(arr)+1):
for j in range(1, len(arr)+1):
if sum(arr[i:j]) == multiples(arr[i:j]):
print (arr[i:j])
sumOfEleEqualToMultiples([1,2,3,4,5])
|
2bdf2e11a9c37d3fccc7c1995fe26f30a9fa1e80 | ultimate010/codes_and_notes | /445_cosine-similarity/cosine-similarity.py | 750 | 3.640625 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: ultimate010
@Problem: http://www.lintcode.com/problem/cosine-similarity
@Language: Python
@Datetime: 16-06-19 08:03
'''
class Solution:
"""
@param A: An integer array.
@param B: An integer array.
@return: Cosine similarity.
"""
def cosineSimilarity(self, A, B):
# write your code here
na = len(A)
nb = len(B)
if na == 0 or nb == 0 or na != nb:
return 2.0
a = 0
b = 0
c = 0
for i in range(na):
a += A[i] * B[i]
b += A[i] * A[i]
c += B[i] * B[i]
if b == 0 or c == 0:
return 2.0
return a / ((b ** 0.5) * (c ** 0.5)) |
bdf275c956b49696f85b5b18ecdce27097d25f2f | alreadytaikeune/euler | /problem35.py | 1,488 | 3.640625 | 4 | import sets
import math
import copy
primes = {}
def get_digits(n):
out = []
while n > 0:
out.insert(0, n%10)
n /= 10
return out
def is_prime(n):
global primes
if n in primes:
return primes[n]
if n <= 1:
primes[n] = False
return False
for k in range(2, int(math.sqrt(n))+1):
if n%k == 0:
primes[n] = False
return False
primes[n] = True
return True
def find_permutations(l):
n = len(l)
if n<=1:
return [copy.deepcopy(l)]
b = l.pop()
out = []
perms = find_permutations(l)
for perm in perms:
for k in range(n):
l2 = copy.deepcopy(perm)
l2.insert(k, b)
out.append(l2)
return out
def make_int(l):
n = 0
for i in l:
n*=10
n+=i
return n
def rotate(l, n):
return l[n:] + l[:n]
if __name__ == "__main__":
l = [2]
for k in range(2, 1000000):
# print k
if k in l:
continue
if is_prime(k):
digits = get_digits(k)
if 2 in digits or 4 in digits or 6 in digits or 8 in digits:
continue
f = True
for r in range(len(digits)):
digits = rotate(digits, 1)
i = make_int(digits)
if not is_prime(i):
f = False
break
if f:
l.append(k)
print l
print len(l) |
ea49ed191031b4775984d0e0d2f541996c8a0d79 | juanitotaveras/CS301_Intro_to_Programming | /ex10_9.py | 530 | 4.09375 | 4 | # Compute the standard deviation of values
def deviation(x):
sum = 0
for i in range(len(x)):
sum += ((x[i]) - mean(x)) ** 2
return (sum / (len(x) - 1)) ** 0.5
# Compute the mean of a list of values
def mean(x):
sum = 0
for i in range(len(x)):
sum += (x[i]) # sum = (x[i]) + sum
return sum / len(x)
def main():
nums = input("Enter numbers: ")
x = nums.split()
for i in range(len(x)):
x[i] = float(x[i])
print ("The mean is", mean(x))
print ("The standard deviation is", deviation(x))
main()
|
e6e8c9843b01998278ce1fe70754c19215b90533 | kdef/wikiball | /BuildTree.py | 3,123 | 3.59375 | 4 | import sys, re, os, time
import urllib2
import pprint
baseUrl = 'http://en.wikipedia.org/wiki/'
DEBUG = False
MAX_DEPTH = 10000000
#http://preshing.com/20110924/timing-your-code-using-pythons-with-statement/
class Timer:
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self, *args):
self.end = time.clock()
self.interval = self.end - self.start
#http://interactivepython.org/courselib/static/pythonds/BasicDS/deques.html
class Deque:
def __init__(self):
self.items = []
def __str__(self):
string = ""
for i in self.items:
string = string + i + ","
return string
def isEmpty(self):
return self.items == []
def addFront(self, item):
self.items.append(item)
def addRear(self, item):
self.items.insert(0,item)
def removeFront(self):
return self.items.pop()
def removeRear(self):
return self.items.pop(0)
def size(self):
return len(self.items)
class ParsePage:
def __init__(self,start,end):
self.entries = 0
#clean up user input
start = start.replace(" ","_")
end = end.replace(" ","_")
self.start = end
self.end = start
self.deque = Deque()
self.graph = {'dummy_XXX_JDKD': ['foo','bar']}#insert dummy node
self.createGraph(start)#add first real node
#keep adding elements
while not (self.deque.isEmpty()) and self.entries < MAX_DEPTH:
value = self.deque.removeFront()
if DEBUG:
print("Just removed from deque: " + str(value))
self.createGraph(value)
if DEBUG:
pprint.pprint(self.graph)
for key in self.graph.keys():
print(key)
for link in self.graph[key]:
if(link == end):
print("Can get to end: " + key + "=>" + str(link))
#newNode -> name of thing to add to the dictionary
def createGraph(self,newNode):
if DEBUG:
print(newNode)
if self.graph.has_key(newNode):
return #already processed
self.entries += 1
links = self.getLinks(newNode)
self.graph[newNode] = links
for link in links:
if DEBUG:
print("adding link: " + link)
self.deque.addRear(link)
if DEBUG:
print(self.deque)
def getLinks(self,name):
try:
html = urllib2.urlopen(baseUrl + name).read()
except:
print("UNABLE TO OPEN addr for: " + name)
return []
match = re.findall(re.escape('href="/wiki/')+ '(\w+)\"',html)
links = list(set(match)) #deletes duplicate entries
if match and DEBUG:
print("Length: " + str(len(match)) + "Remove Duplicates: " + str(len(list(set(match)))))
return links
#temp = ParsePage("testPage.html")
with Timer() as t:
temp = ParsePage("Baseball","Portland Trail Blazers")
print'Took %.03f sec.' % t.interval |
62c6968330efdfc8ee271eaf41aad56008d11091 | estraviz/codewars | /7_kyu/Vowel Count/get_count.py | 129 | 3.84375 | 4 | """Vowel Count
"""
VOWELS = 'aeiouAEIOU'
def get_count(inputStr):
return sum(1 for letter in inputStr if letter in VOWELS)
|
f5b32c0448ae13b8338eb61989e48308b87eac84 | nscott1991/Salary | /Budget Trace Table.py | 1,583 | 3.828125 | 4 | # Develop a program that can generate one's
# budget based on their pay.
income = float(input('What did you get paid?\n$'))
savings = income*(0.10)
tithe = income*(0.10)
personalUse = income*(0.10)
bills = income*(0.55)
investments = income*(0.10)
myMoney = income*(0.05)
total = (savings+tithe+personalUse+bills+investments+myMoney)
if income < 2224:
print("\tSavings\tTithe\tP.Use\tBills\tInvsts\tMy $")
print("\t-------\t-------\t-------\t-------\t-------\t-------")
print("\t$%.2f\t$%.2f\t$%.2f\t$%.2f\t$%.2f\t$%.2f" %(savings,tithe,personalUse,bills,investments,myMoney))
elif income > 2224 and income < 5000:
print("\tSavings\t\tTithe\t\tP.Use\t\tBills\t\tInvsts.\t\tMy $")
print("\t--------\t--------\t--------\t--------\t--------\t--------")
print("\t$%.2f\t\t$%.2f\t\t$%.2f\t\t$%.2f\t$%.2f\t\t$%.2f" %(savings,tithe,personalUse,bills,investments,myMoney))
elif income > 5000 and income < 10000:
print("\tSavings\t\tTithe\t\tP.Use\t\tBills\t\tInvsts.\t\tMy $")
print("\t--------\t--------\t--------\t--------\t--------\t--------")
print("\t$%.2f\t\t$%.2f\t\t$%.2f\t$%.2f\t$%.2f\t\t$%.2f" %(savings,tithe,personalUse,bills,investments,myMoney))
elif income > 10000 and income < 250001:
print("\tSavings\t\tTithe\t\tP.Use\t\tBills\t\tInvsts.\t\tMy $")
print("\t--------\t--------\t---------\t---------\t--------\t--------")
print("\t$%.2f\t$%.2f\t$%.2f\t$%.2f\t$%.2f\t$%.2f" %(savings,tithe,personalUse,bills,investments,myMoney))
#if income != total:
# print("Your income doesn't match your total money earned.")
|
b5eb3fab9be2706674b07ef70d4825b76866fd64 | dsterlyagov/algorithms_mipt | /recursion/evklid.py | 358 | 3.703125 | 4 | def gcd(a, b):
if a == b:
return a
elif a > b:
return gcd(a-b, b)
else: # a < b
return gcd(a, b-a)
print(gcd(30, 5))
def gcd_new(a, b):
if b==0:
return a
else:
return gcd_new(b, a%b)
print(gcd_new(33, 3))
def gcd_final(a, b):
return a if b==0 else gcd_final(b, a%b)
print(gcd_final(33,3)) |
856aa6fb1acd99cf395ac50f589841c47b01a1d4 | drumgiovanni/schoolPythonProject | /04/6.py | 507 | 3.9375 | 4 | for i in range(1,2):
print(" ")
for j in range(1,10):
print("{:>7}".format(i * j),end =" ")
if j == 1 :
print("|",end=" ")
for i in range(2,3):
print("\n" + "- " * 4 + "+" + "- " * 33)
for j in range(1,10):
print("{:>7}".format(i * j), end=" ")
if j == 1 :
print("|",end=" ")
for i in range(3,10):
print(" ")
for j in range(1,10):
print("{:>7}".format(i * j),end =" ")
if j == 1 :
print("|",end=" ") |
f7844c99bae38d56e45580e39bb1562edab014fb | ashleyspeigle2/DataStructuresHW | /50.py | 183 | 3.84375 | 4 | for i in range(2,50):
isPrime = True
for j in range(2,i):
if i % j == 0:
isPrime = False
break
if isPrime:
print(i)
|
aa0dda1c88a0ddbd1d827ec03105099ac2fc3d04 | langrenzhang/laowangwork | /work/2py20.py | 2,105 | 4.09375 | 4 | #coding=utf-8
import threading
import time
import urllib
'''
1.全局锁(GIL)是一个很重要的概念。
在任意一个指定的时间,有且只有一个线程在运行 -》 python是线程安全的
线程安全 歧义
2.多线程 复杂度高,不建议使用。(它用在哪里?)
一个程序的复杂度,大部分情况下,只和代码行数有关。
简单 != 简陋
数据库连接池
3.多线程还是有点爽的,比如?
4.io操作用到多线程?必须要lock,acquire release
互斥锁
加锁 acquire
释放锁 release
加锁 一定 释放
死锁
5.rlock 可重入锁
# import threading
# num = 0
# def t():
# global num
# num += 1
# print num
# for i in xrange(0,10):
# d = threading.Thread(target=t)
# d.start()
import time
def a():
print 'a begin'
time.sleep(2)
print 'a end'
def b():
print 'b begin'
time.sleep(2)
print 'b end'
# b_time = time.time()
# a()
# b()
# print time.time() - b_time #代码完成时间
# import threading
# b_time = time.time()
# _a = threading.Thread(target=a)
# _b = threading.Thread(target=b)
# _a.start()
# _b.start()
# _a.join()
# _b.join()
# print time.time() - b_time #代码完成时间
import threading
mlock = threading.RLock()
num = 0
def a():
global num
mlock.acquire() #加锁
num += 1 #你要执行的代码
mlock.release() #释放锁
print num
for i in xrange(0,10):
d = threading.Thread(target=a)
d.start()
习题:
有10个刷卡机,代表建立10个线程,每个刷卡机每次扣除用户一块钱进入总账中,每个刷卡机每天一共被刷100次。账户原有500块。所以当天最后的总账应该为1500
用多线程的方式来解决,提示需要用到这节课的内容
'''
total = 500
mlock = threading.RLock()
def test():
global total
mlock.acquire()
for i in xrange(0,100):
total = total + 1
mlock.release()
t1 = time.time()
st = []
for i in xrange(0,10):
sh = threading.Thread(target=test)
sh.start()
st.append(sh)
print total
for i in st:
i.join()
t2 = time.time()
print t2-t1
|
92cfa43c870369bc94c62ea10b50c1e46bfeb4a3 | nreyes-cl/test_numpy | /NumPy_Tutorial.py | 1,936 | 4.15625 | 4 | import numpy as np
a = np.array([1, 2, 3], dtype=np.int16)
print(a)
b = np.array([[9.0, 8.0, 7.0], [6.0, 5.0, 4.0]])
print(b)
#Get dimensions
print(a.ndim) #1 un vector
print(b.ndim) #2 una matriz
#Get shape
print(a.shape) # es un vector por lo tanto muestra cantidad de columnas en este caso 3
print(b.shape) # es una matriz por lo tanto muestra cantidad de filas y columnas en este caso 2 y 3
#Get type
print(a.dtype) #int32 se puede cambiar
print(b.dtype) #float64
#Get size
print(a.itemsize) #4 bytes
print(b.itemsize) #8 bytes
#Get total size
print(a.size) #3 cantidad total de elementos
print(b.size) #6 cantidad total de elementos
a = np.array([[1, 2, 3, 4, 5,6,7], [8, 9, 10, 11, 12,13,14]])
print(a)
#Get a specific element [row, column]
print(a[1,-2]) #13
print(a[0,6]) #7
#Get a specific row
print(a[1,:]) #[8 9 10 11 12 13 14]
#Get a specific column
print(a[:,1]) #[2 9]
#Get a specific row and column
print(a[0,1:6]) #[2 3 4 5 6]
#3d example
b = np.array([[[1, 2], [3,4]], [[5,6], [7,8]]])
print(b)
#get a specific element in 3d format (work outside in)
print(b[1,1,1]) #8
#replace element in 3d format
b[:,1,:] = [[9,9],[8,8]]
print(b)
#all 0s matrix
print(np.zeros((3,3)))
#all 1s matrix
print(np.ones((3,3)))
#any other number
print(np.full((3,3),5))
#any other number (full_like)
print(np.full_like(a,4))
#random decimal number
print(np.random.random((3,3)))#numeros aleatorios entre 0 y 1
#random interger number
print(np.random.randint(0,10,(3,3)))#entre 0 a 10 y una matriz de 3x3
#the identity matrix
#ambas funcionan de igual manera pero si quiero mantener la diagonal debo ocupar identity, en eye la diagonal puede terminar desviada
print(np.eye(4))
print(np.identity(4))
#repeat number of a matrix
arr= np.array([1,2,3])
r1=np.repeat(arr,3,axis=0)
print(r1)
#reshape matrix
output = np.ones((5,5))
print(output)
z = np.zeros((3,3))
z[1,1] = 9
print(z)
output[1:4,1:4] = z
print(output) |
c75087147c29ccabb186173cc2b237478b47ff7a | wangyuhui12/AID1804 | /python/day17/code/03_attribute.py | 511 | 3.75 | 4 |
# 此示例示意为对象添加属性
class Dog(object):
def kinds(self, kinds):
self.kinds = kinds
def color(self, color):
self.color = color
@property
def obj(self):
print(self.color,'的',self.kinds,sep='')
return self.color
# 创建一个对象
dog1 = Dog()
dog1.kinds = '京巴' # 添加属性kinds
dog1.color = '白色' # 添加属性 color
dog1.color = '黄色'
dog1.obj
dog2 = Dog()
dog2.kinds = '牧羊犬'
dog2.color = '灰色'
print(dog2.obj) |
eefd08dd670f148b0f82c08589cdb91a7720aae2 | TimCargan/Tims-Translator | /bin/test.py | 1,586 | 3.6875 | 4 | import math
import pickle
DATA_PATH = "../data/"
PXYZ = 0.475
PYZ = 0.475
PZ = 0.049
PB = 0.001
#Bigest flaw is that it trigram cant deal with less than 3 words
def calcStringP(pString):
pString = pString.split(" ")
stringProb = []
for word in range(0, len(pString)):
x = getFromAray(pString, word)
y = getFromAray(pString, word + 1)
z = getFromAray(pString, word + 2)
prob = trigramS(x, y, z)
stringProb.append(prob)
print "b({:s}|{:s}) = {:f}".format(z, join([x,y]), prob)
result = "{:f}".format(prob)
return result
def trigramS(x, y, z):
cxyz = numOfAcc(join([x,y,z]), "t")
print "cxyz: {:d}".format(cxyz)
return cxyz
#get element for array or reutrn "" if index is not valid
def getFromAray(aray, index):
if index < 0 :
return "*#es#*"
try:
return aray[index]
except IndexError:
return "*#es#*"
#return the number of accurences in the test data
def numOfAcc(search, type):
acc = 0
search = search
#search the trigram file
try:
return trigrams[search]
except KeyError:
return 0
# return the sum of the logs of a list of numbers
def multiLog(numbers):
total = 0
for num in numbers:
total += math.log(num, 2)
return total
#join an array of words into a string
def join(strings):
r = ""
for word in strings:
r += word + " "
return r.strip()
def load(name):
with open(DATA_PATH + 'obj/' + name + '.pkl', 'r') as f:
return pickle.load(f)
print "PXYZ {:f}".format(PXYZ)
print "PYZ {:f}".format(PYZ)
#load files
print "loading files..."
trigrams = load("trigrams")
print calcStringP("member states were")
|
1c6adbc90096c752219acd49c6fc13e63f6a2abf | CorollaD/class_for_pratice | /Restaruant.py | 993 | 3.671875 | 4 | # -*- coding='utf-8' -*-
class Restaruant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def discribe_restaurant(self):
print('restaurant name is {0}.'.format(self.restaurant_name))
print('restaurant type is {0}.'.format(self.cuisine_type))
def open_restaurant(self):
print('{} opening!'.format(self.restaurant_name))
def read_number_served(self):
print("There has {0} peoples".format(self.number_served))
def set_number_served(self, number):
self.number_served = number
def increment_number_served(self, number1):
self.number_served += number1
if __name__ == '__main__':
restaurant = Restaruant('qiaojiangnan', 'zhongcan')
restaurant.set_number_served('20')
restaurant.read_number_served()
restaurant.increment_number_served('5')
restaurant.read_number_served()
|
28706d0fd3309283974ea018452773ab54b35dcb | tana777/LeetCode | /Array/1329_Sort_the_Matrix_Diagonally.py | 2,280 | 4.15625 | 4 | """
Given a m * n matrix mat of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array.
Example 1:
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100
"""
"""
Time Complexity: O(m*n)
Space Complexity: O(min(m,n))
"""
class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
rows = len(mat)
cols = len(mat[0])
for col in range(cols):
sortedLs = self.sortList(mat, 0, col, rows, cols)
self.updateDiagonal(mat, 0, col, sortedLs)
for row in range(1, rows):
sortedLs = self.sortList(mat, row, 0, rows, cols)
self.updateDiagonal(mat, row, 0, sortedLs)
return mat
def sortList(self, mat, rowX, colY, rows, cols):
res = []
for l in range(min(rows, cols)):
nx = rowX + l*1
ny = colY + l*1
if nx >= 0 and nx < rows and ny >= 0 and ny < cols:
res.append(mat[nx][ny])
return sorted(res)
def updateDiagonal(self, mat, rowX, colY, sortedLs):
for l in range(len(sortedLs)):
mat[rowX + l*1][colY + l*1] = sortedLs[l]
## Approach 2: Use hint
# All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
"""
1. use a dictionary to store diagnoal value with corresponding key = i-j
2. sort the diagnoal list
3. restore the matrix
"""
class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
rows = len(mat)
cols = len(mat[0])
diagnoalDict = {}
for i in range(rows):
for j in range(cols):
if (i-j) in diagnoalDict:
diagnoalDict[i-j].append(mat[i][j])
else:
diagnoalDict[i-j] = [mat[i][j]]
for key in diagnoalDict:
diagnoalDict[key] = sorted(diagnoalDict[key])
for i in range(rows):
for j in range(cols):
mat[i][j] = diagnoalDict[i-j].pop(0)
return mat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.