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 |
|---|---|---|---|---|---|---|
3cd20b58976bc79894edbf142b71aebf1b0c8db1 | tamannasharma95/pyhton_basics20 | /lucky_num.py | 747 | 3.875 | 4 | #Initiate a dictionary
numbers={
0:'Your daya will be awesome',
1:'You will get an opprtunity today,dont miss it',
2:'Day is full of perils',
3:'You will get a lottery today',
4:'Dont go out today,its risky for you',
5:'This day will bring something best for you',
6:'You will meet your bf today',
7:'You will have a horrible fight today',
8:'You will get married soon',
9:'You are about to become Data Scientist',
10:'You are born to rule the world'
}
GREETINGS='Please enter a number: '
Lucky_Prid= int(input(GREETINGS))
print(Lucky_Prid)
print(type(Lucky_Prid))
print('Your lucky prediction for today is: ' + numbers.get(Lucky_Prid,'Sorry wrong option selected'))
print('Thank you for visiting us') |
466e09563347f532340d0cdc5770cf848102ab4c | gerh1992/shogi | /clases/piezas.py | 13,673 | 3.625 | 4 | class Pieza():
def __init__(self, jugador):
self.jugador = jugador
class Rey(Pieza):
simbolo = "K"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "K ^" if jugador.color == "blancas" else "K v"
def __repr__(self):
return "el rey"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif (checkear_fila(i_0, i_1) and abs(j_0 - j_1) == 1) or (checkear_columna(j_0, j_1) and abs(i_0 - i_1) == 1):
return True
elif abs(i_0 - i_1) == 1 and abs(j_0 - j_1) == 1:
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
class Torre(Pieza):
simbolo = "R"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "R ^" if jugador.color == "blancas" else "R v"
def __repr__(self):
return "la torre"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif (checkear_columna(j_0, j_1) and not checkear_fila(i_0, i_1)) or (not checkear_columna(j_0, j_1) and checkear_fila(i_0, i_1)):
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
def promover(self):
return Torre_promocionada(self.jugador)
class Torre_promocionada(Pieza):
simbolo = "+R"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "+R^" if jugador.color == "blancas" else "+Rv"
def __repr__(self):
return "la torre promocionada"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif (checkear_columna(j_0, j_1) and not checkear_fila(i_0, i_1)) or (not checkear_columna(j_0, j_1) and checkear_fila(i_0, i_1)):
return True
elif abs(i_0 - i_1) == 1 and abs(j_0 - j_1) == 1:
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
def involucionar(self, jugador):
return Torre(jugador)
class Alfil(Pieza):
simbolo = "B"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "B ^" if jugador.color == "blancas" else "B v"
def __repr__(self):
return "el alfil"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif checkear_diag1(i_0, j_0, i_1, j_1) or checkear_diag2(i_0, j_0, i_1, j_1,):
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
def promover(self):
return Alfil_promocionado(self.jugador)
class Alfil_promocionado(Pieza):
simbolo = "+B"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "+B^" if jugador.color == "blancas" else "+Bv"
def __repr__(self):
return "el alfil promocionado"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif checkear_diag1(i_0, j_0, i_1, j_1) or checkear_diag2(i_0, j_0, i_1, j_1, ):
return True
elif (checkear_fila(i_0, i_1) and abs(j_0 - j_1) == 1) or (checkear_columna(j_0, j_1) and abs(i_0 - i_1) == 1):
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
def involucionar(self, jugador):
return Alfil(jugador)
class General_dorado(Pieza):
simbolo = "G"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "G ^" if jugador.color == "blancas" else "G v"
def __repr__(self):
return "el general dorado"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif (abs(i_0 - i_1) == 1 and j_0 == j_1) or (abs(j_0 - j_1) == 1 and i_0 == i_1):
return True
elif turno_blancas(jugador):
if i_0 - i_1 == 1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if i_0 - i_1 == -1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
class General_plateado(Pieza):
simbolo = "S"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "S ^" if jugador.color == "blancas" else "S v"
def __repr__(self):
return "el general plateado"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif abs(i_0 - i_1) == 1 and abs(j_0 - j_1) == 1:
return True
elif turno_blancas(jugador):
if i_0 - i_1 == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if i_0 - i_1 == -1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
def promover(self):
return General_plateado_promocionado(self.jugador)
class General_plateado_promocionado(Pieza):
simbolo = "+S"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "+S^" if jugador.color == "blancas" else "+Sv"
def __repr__(self):
return "el general plateado promocionado"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif (abs(i_0 - i_1) == 1 and j_0 == j_1) or (abs(j_0 - j_1) == 1 and i_0 == i_1):
return True
elif turno_blancas(jugador):
if i_0 - i_1 == 1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if i_0 - i_1 == -1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
def involucionar(self, jugador):
return General_plateado(jugador)
class Caballo(Pieza):
simbolo = "N"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "N ^" if jugador.color == "blancas" else "N v"
def __repr__(self):
return "el caballo"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif turno_blancas(jugador):
if i_0 - i_1 == 2 and abs(j_0 - j_1) == 1:
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if i_0 - i_1 == -2 and abs(j_0 - j_1) == 1:
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
def promover(self):
return Caballo_promocionado(self.jugador)
class Caballo_promocionado(Pieza):
simbolo = "+N"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "+N^" if jugador.color == "blancas" else "+Nv"
def __repr__(self):
return "el caballo promocionado"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif (abs(i_0 - i_1) == 1 and j_0 == j_1) or (abs(j_0 - j_1) == 1 and i_0 == i_1):
return True
elif turno_blancas(jugador):
if i_0 - i_1 == 1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if i_0 - i_1 == -1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
def involucionar(self, jugador):
return Caballo(jugador)
class Lancero(Pieza):
simbolo = "L"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "L ^" if jugador.color == "blancas" else "L v"
def __repr__(self):
return "el lancero"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif turno_blancas(jugador):
if checkear_columna(j_0, j_1) and i_0 > i_1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if checkear_columna(j_0, j_1) and i_0 < i_1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
def promover(self):
return Lancero_promocionado(self.jugador)
class Lancero_promocionado(Pieza):
simbolo = "+L"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "+L^" if jugador.color == "blancas" else "+Lv"
def __repr__(self):
return "el lancero promocionado"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif (abs(i_0 - i_1) == 1 and j_0 == j_1) or (abs(j_0 - j_1) == 1 and i_0 == i_1):
return True
elif turno_blancas(jugador):
if i_0 - i_1 == 1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if i_0 - i_1 == -1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
def involucionar(self, jugador):
return Lancero(jugador)
class Peon(Pieza):
simbolo = "P"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "P ^" if jugador.color == "blancas" else "P v"
def __repr__(self):
return "el peon"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif turno_blancas(jugador):
if i_0 == (i_1 + 1) and j_0 == j_1:
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if i_0 == (i_1 - 1) and j_0 == j_1:
return True
else:
if mensaje: mensaje_movimiento_invalido(self)
return False
return False
def promover(self):
return Peon_promocionado(self.jugador)
class Peon_promocionado(Pieza):
simbolo = "+P"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "+P^" if jugador.color == "blancas" else "+Pv"
def __repr__(self):
return "el peon promocionado"
def checkear_movimiento(self, i_0, j_0, i_1, j_1, jugador, mensaje):
if self.jugador != jugador:
if mensaje: mensaje_pieza_rival(self)
return False
elif (abs(i_0 - i_1) == 1 and j_0 == j_1) or (abs(j_0 - j_1) == 1 and i_0 == i_1):
return True
elif turno_blancas(jugador):
if i_0 - i_1 == 1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
elif not turno_blancas(jugador):
if i_0 - i_1 == -1 and abs(j_0 - j_1) == 1:
return True
if mensaje: mensaje_movimiento_invalido(self)
return False
def involucionar(self, jugador):
return Peon(jugador)
def mensaje_pieza_rival(pieza):
print(mensaje_invalido() + "Ese es " + str(pieza) + " de su rival")
def mensaje_movimiento_invalido(pieza):
print(mensaje_invalido() + str(pieza) + " no puede realizar ese movimiento")
def mensaje_invalido():
return "Movimiento invalido!"
def checkear_columna(j_0, j_1):
return j_0 == j_1
def checkear_fila(i_0, i_1):
return i_0 == i_1
def checkear_diag1(i_0, j_0, i_1, j_1):
return abs(i_0 - j_0) == abs(i_1 - j_1)
def checkear_diag2(i_0, j_0, i_1, j_1):
return i_0 + j_0 == i_1 + j_1
def turno_blancas(jugador):
return jugador.color == "blancas" |
d69f2baf0f740e490252e601077d5b9d90cd6732 | realmichaelzyy/Machine-Learning-Project-Python | /Perceptron.py | 10,445 | 3.953125 | 4 | #--------------------------------------------------
# UCLA CS 260 - Machine Learning Algorithm
# Yao-Jen Chang, 2015 @UCLA
# Email: autekwing@ucla.edu
#
# Function about perceptron algorithm and MLP(sequential)
# normalization method for data points
#--------------------------------------------------
import numpy as np
#---------------- single layer perceptron ----------------------------
# Three node N0(bias node), N1, N2
# the bias node input is always -1
# the parameter is a list represent as follow:
# parameter[0]: number of iteration
# parameter[1]: learning rate
# parameter[2]: value for activation function
# parameter[3]: if there's a bias node
# parameter[4]: if use kernel function to increase dimension
def perceptron(train, trainLab, test, parameter):
import random
# no bias, activatio: -1
# has bias, activation: 0
# parameter = [10000, 0.3, 0] # number of iteration, learning rate, activation function
nIter = parameter[0]
learnRate = parameter[1]
activation = parameter[2]
bias = parameter[3]
useKernel = parameter[4]
# make 2 dimension feature into 6 dimentsion, and hope they will be linear seperable
if len(train[0]) == 2 and useKernel:
train = kernel(train)
test = kernel(test)
numInput = len(train)
numFea = len(train[0])
numNode = numFea # number of node is the number of features
if bias:
numNode += 1 # add one more bias node
weights = []
randomWight = 0.05
for i in range(numNode):
weights.append(random.random() * randomWight - (randomWight/2)) # -0.05 ~ 0.05
# print weights
for n in range(nIter):
# if n % 20 == 0:
# print weights
for j in range(numInput): # every input of training data
tra = train[j]
result = 0
for i in range(numFea): # from [0] to [numFea -1]
result = result + tra[i] * weights[i]
if bias: # bias node with always -1 input
result = result -1 * weights[numFea] # the last weight
# if the neuron fired
# print str(result) + ' ' + str(tra) + ' ' + str(trainLab[j])
if result < activation:
predClass = 0
else:
predClass = 1
# the result is correct
if (predClass == 0 and trainLab[j] == 0) or (predClass == 1 and trainLab[j] == 1):
continue
else: # update weights
for i in range(numFea):
weights[i] = weights[i] - learnRate * (predClass - trainLab[j]) * tra[i]
if bias:
weights[numFea] = weights[numFea] - learnRate * (predClass - trainLab[j]) * (-1)
# for test data
result = 0
for i in range(numFea): # from [0] to [numFea -1]
result = result + test[i] * weights[i]
if bias: # bias node with always -1 input
result = result -1 * weights[numFea] # the last weight
# if the neuron fired
# print str(result) + ' ' + str(tra) + ' ' + str(trainLab[j])
if result < activation:
ans = 0
else:
ans = 1
# print weights
return ans
#------------------------- multi-layer perceptron -------------------------
# the parameter is a list represent as follow:
# parameter[0]: number of iteration
# parameter[1]: learning rate
# parameter[2]: value for activation function
# parameter[3]: if there's a bias node
# parameter[4]: if use kernel function to increase dimension
# parameter[5]: beta value
# parameter[6]: Different types of output neurons, which has 'linear', 'logistic', and 'softmax'
# parameter[7]: number of node in hidden layer
def MLP(train, trainLab, test, parameter):
import random
from numpy import sqrt
# no bias, activatio: -1
# has bias, activation: 0
# parameter = [10000, 0.3, 0] # number of iteration, learning rate, activation function
nIter = parameter[0]
learnRate = parameter[1]
activation = parameter[2]
bias = parameter[3]
useKernel = parameter[4]
beta = parameter[5]
outtype = parameter[6] # Different types of output neurons
numHid = parameter[7] # number of node in hidden layer
# make 2 dimension feature into 6 dimentsion, and hope they will be linear seperable
if len(train[0]) == 2 and useKernel:
train = kernel(train)
test = kernel(test)
numInput = len(train)
numFea = len(train[0])
numNode = numFea # number of node is the number of features
weights1 = [] # weights for input layer
weights2 = [] # weights for hidden layer
randomWight = 1/sqrt(numHid) * 2
if bias:
randomWight = 1/sqrt(numHid + 1) * 2
for i in range(numHid):
weights2.append(random.random() * randomWight - (randomWight/2))
if bias:
numNode += 1 # add one more bias node
weights2.append(random.random() * randomWight - (randomWight/2)) # bias node in hidden layer
# every node(include bias) in input layer will have a weight for every node in hidden layer
randomWight = 1/sqrt(numNode) * 2
for i in range(numNode):
tmp = []
for j in range(numHid):
tmp.append(random.random() * randomWight - (randomWight/2)) # -0.05 ~ 0.05
weights1.append(tmp)
# print weights1, weights2
change = range(numInput)
# ==================== Training =====================
for n in range(nIter): # number of iteration
np.random.shuffle(change) # random the order of training data set
# print weights1
for k in change:# every input vector of training data
tra = train[k]
# ------- Forwards phase in input layer -------
hiddenInput = []
for j in range(numHid): # number of node j in hidden layer
result = 0
for i in range(numFea): # from [0] to [numFea -1]
result = result + tra[i] * weights1[i][j]
if bias: # input layer bias node with always -1 input
result = result -1.0 * weights1[numFea][j] # the last weight for input bias node
result = 1.0/(1.0 + np.exp(-beta * result)) # the input result will be input of hidden layer
hiddenInput.append(result)
# ------- Forwards phase in hidden layer -------
OutputResult = 0
for i in range(numHid): # from [0] to [numFea -1]
OutputResult = OutputResult + hiddenInput[i] * weights2[i]
if bias: # hidden layer bias node with always -1 input
OutputResult = OutputResult -1.0 * weights2[numHid] # the last weight
if outtype == 'linear':
OutputResult = OutputResult
elif outtype == 'logistic':
OutputResult = 1.0/(1.0 + np.exp(-beta * OutputResult))
else:
print 'error type'
# print hiddenInput, OutputResult
ans = 1 # it remain be 1 if OutputResult >= activation
if OutputResult < activation:
ans = 0
# print ans, trainLab[k]
# ------- Backward phase in computing error at output -------
if outtype == 'linear':
outputError = (OutputResult - trainLab[k])/numInput
elif outtype == 'logistic':
outputError = (OutputResult - trainLab[k]) * OutputResult * (1 - OutputResult) # only one output node
else:
print 'error type'
# ------- Backward phase in computing error in hidden layer -------
hiddenError = []
for i in range(numHid):
tmp = hiddenInput[i] * (1 - hiddenInput[i]) * weights2[i] * outputError
hiddenError.append(tmp)
# ------- Backward phase in updating output layer weights-------
for i in range(numHid):
weights2[i] = weights2[i] - learnRate * outputError * hiddenInput[i]
if bias:
weights2[numHid] = weights2[i] - learnRate * outputError * (-1)
# ------- Backward phase in updating hidden layer weights-------
for j in range(numHid):
for i in range(numFea):
weights1[i][j] = weights1[i][j] - learnRate * hiddenError[j] * tra[i]
if bias:
weights1[numFea][j] = weights1[numFea][j] - learnRate * hiddenError[j] * (-1)
# print outputError, hiddenError
# ==================== run the MLP for the test data ===================
# ------- Forwards phase in input layer -------
hiddenInput = []
for j in range(numHid): # number of node j in hidden layer
result = 0
for i in range(numFea): # from [0] to [numFea -1]
result = result + test[i] * weights1[i][j]
if bias: # bias node with always -1 input
result = result -1.0 * weights1[numFea][j] # the last weight for input bias node
result = 1.0/(1.0 + np.exp(-beta * result)) # the input result will be input of hidden layer
hiddenInput.append(result)
# ------- Forwards phase in hidden layer -------
OutputResult = 0
for i in range(numHid): # from [0] to [numFea -1]
OutputResult = OutputResult + hiddenInput[i] * weights2[i]
if bias: # bias node with always -1 input
OutputResult = OutputResult -1.0 * weights2[numHid] # the last weight
if outtype == 'linear':
OutputResult = OutputResult
elif outtype == 'logistic':
OutputResult = 1.0/(1.0 + np.exp(-beta * OutputResult))
else:
print 'error type'
# print hiddenInput, OutputResult
ans = 1 # it remain be 1 if OutputResult >= activation
if OutputResult < activation:
ans = 0
return ans # it remain be 1 if OutputResult >= activation
# nomalize data into 0~1 range
# Max = [110, 170]
# Min = [50, 80]
# 50~110, 80~170
def normalize(data, interval = 1, dim = 0):
import copy
normalData = copy.deepcopy(data)
if type(normalData[0]) != type([]):
normalData = [normalData]
dimension = len(normalData[0]) # number of features
if dim != 0:
dimension = dim
size = len(normalData)
Max = [102, 163, 102, 163, 102, 163]
Min = [60, 92, 60, 92, 60, 92]
# Max = [102, 163, 9, 16]
# Min = [60, 92, 0, 0]
# This part can run to determine the Max and Min list when training different data set
# for i in range(dimension): # for different features
# tmpMax = 0
# tmpMin = 1000
# for j in range(size): # how many element in list (normalData)
# tmpMax = max(normalData[j][i], tmpMax)
# tmpMin = min(normalData[j][i], tmpMin)
# tmpMax += 1 # to make new normalized data won't be 1
# tmpMin -= 1 # to make new normalized data won't be 0
# Max.append(tmpMax)
# Min.append(tmpMin)
for point in normalData: # how many element in list (normalData)
for i in range(dimension): # how many feature for each data element
if interval == 1:
point[i] = (point[i] - Min[i])/(Max[i] - Min[i])
else:
point[i] = ( 2 *(point[i] - Min[i])/(Max[i] - Min[i])) - 1
if len(normalData) == 1: #only one list of element
return normalData[0]
return normalData
# only use for 2 dimenstion data
def kernel(data):
import copy
from math import sqrt
extraData = []
if type(data[0]) != type([]):
return [1, sqrt(2) * data[0], sqrt(2) * data[1], data[0] ** 2, data[1] ** 2, sqrt(2)*data[0]*data[1]]
for point in data:
tmp = [1, sqrt(2) * point[0], sqrt(2) * point[1], point[0] ** 2, point[1] ** 2, sqrt(2)*point[0]*point[1]]
extraData.append(tmp)
return extraData
|
e27ca977beace4ddad46cc8f2d1165b9a3f157d0 | Venkat445-driod/Python-Assignment-3 | /prob9.py | 231 | 3.75 | 4 | skillsanta_Dict ={"name": "Sachin", "age": 22, "salary": 60000, "city": "New Delhi"}
print("Before changing:",skillsanta_Dict)
x=skillsanta_Dict.pop("city")
skillsanta_Dict["location"]=x
print("after changing:",skillsanta_Dict) |
836bfc3c1aa4d031737a19e27d750eba8f235365 | zongxinwu92/leetcode | /LargestRectangleInHistogram.py | 455 | 4.28125 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given n non-negative integers representing the histogram s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given heights = [2,1,5,6,2,3],
return 10.
"
'''
|
f973a746225af86be88c32e25ed4f8f305aff139 | linlin-SMU/202011_learn-python | /maizi/04/04-02 列表内的元素修改和删除.py | 629 | 3.859375 | 4 | # index():返回列表里指定元素的下标
name_list = ['damao', 'dagou', 'xioamao', 'xiaogou',11,22,33,44]
if 'damao' in name_list:
index = name_list.index('damao')
print(index)
else:
print('数据不存在')
# 列表的修改
name_list[name_list.index('xiaomao')] = 'henxiaomao' #修改的方法:找到索引值,根据元素下标修改
# 列表的删除
name_list.remove('damao') remove-配合数值使用
name_list.pop(5) pop-配合下标使用
name_list.clear() clear-清空所有数据,为空列表
# del 为彻底清除
num = 13
del num
del name_list[0]
del name_list
|
74eca2ff42c9eda86e35be5cc6aa001c6a6b0764 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/vnklae001/question4.py | 1,175 | 4.0625 | 4 | # Assignment 6 - Question 4
# A program that takes a list of marks and outputs them in histogram representation according to categories
# Written by: Laene van Niekerk
# VNKLAE001
marks = input("Enter a space-separated list of marks:\n")
string_list = marks.split(" ") # Creates a list of numbers represented as strings
num_list = []
for i in string_list: # Converts the string entered by the user into a list of numbers
x = eval(i)
num_list.append(x)
categories = ["1","2+","2-","3","F"]
cat_1 = 0
cat_2_plus = 0
cat_2_minus = 0
cat_3 = 0
cat_F = 0
for i in num_list: # Counts the number of marks that fall into the categories
if i >= 75:
cat_1 = cat_1 + 1
elif 70 <= i < 75:
cat_2_plus = cat_2_plus + 1
elif 60 <= i < 70:
cat_2_minus = cat_2_minus + 1
elif 50 <= i < 60:
cat_3 = cat_3 + 1
else:
cat_F = cat_F + 1
counts = [cat_1, cat_2_plus, cat_2_minus, cat_3, cat_F]
pos = 0
for i in categories:
tally = counts[pos]
tally = "X"*tally
tally = str(tally)
tally = "|" + tally
form = "{:<2}{:>0}".format(i, tally)
print(form)
pos = pos + 1
|
2a99e4dfeb5a77c0027ee7fc14fe35def59187a6 | kaush4l/Euler | /20/7kk.py | 384 | 3.671875 | 4 | # 10001st prime
import math
def isPrime(n):
if n < 4:
return True
bool = True
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
bool = False
return bool
def nthPrime(n):
num = 3
while n - 2 > 0:
num += 2
if isPrime(num):
n -= 1
return num
print(nthPrime(10001))
|
5a345a955c375b6a75eb5d8c76e7327ee97fca7b | marcbichon/tome-rater | /TomeRater.py | 16,897 | 4.09375 | 4 | import re
class User(object):
"""Keep track of Tome Rater users.
Attributes:
name (str): The name of the user.
email (str): The email of the user.
books (dict): Books read by a user, keys are Books, values are
ratings (int).
"""
def __init__(self, name, email):
"""Constructor of User class.
Args:
name (str): The name of the user.
email (str): The email of the user.
"""
self.name = name
self.email = email
self.books = {}
def get_email(self):
"""Return the user's email."""
return self.email
def change_email(self, address):
"""Update the user's email."""
self.email = address
print("{user_name}'s email has been successfully updated!".format(
user_name=self.name))
def __repr__(self):
return "Name: {name}\nEmail: {email}\nBooks read: {number_of_books}\n".format(
name=self.name, email=self.email, number_of_books=len(self.books))
def __eq__(self, other_user):
if self.name == other_user.name and self.email == other_user.email:
return True
else:
return False
def read_book(self, book, rating=None):
"""Add a book to the user's books list.
Args:
book (Book): The book read by the user.
rating (int, optional): The rating given by the user to this book.
Defaults to None.
Returns:
None
"""
self.books[book] = rating
def get_average_rating(self):
"""Calculate the average of all ratings from the user and return it.
Note
This method does not use len() to calculate the number of ratings
as we want to exclude ratings equal to None.
"""
sum_of_ratings = 0
number_of_ratings = 0
for rating in self.books.values():
if rating != None:
number_of_ratings += 1
sum_of_ratings += rating
return sum_of_ratings / number_of_ratings
class Book(object):
"""Keep track of Tome Rater catalog and manage the books ratings.
Attributes:
title (string): The title of the book.
isbn (string): The ISBN of the book.
ratings (list): A list of all book's ratings.
"""
def __init__(self, title, isbn):
"""Constructor of Book class.
Args:
title (str): The title of the book.
isbn (int): The ISBN of the book.
"""
self.title = title
self.isbn = isbn
self.ratings = []
def get_title(self):
"""Return the book's title."""
return self.title
def get_isbn(self):
"""Return the book's ISBN."""
return self.isbn
def _set_isbn(self, new_isbn):
"""Update ISBN of a given book.
Note:
This method has been set private in order to ensure unique ISBNs
and prevent hash issues in the TomeRater.books dict. It is called
only by the 'set_isbn' method in the TomeRater class.
Args:
new_isbn (int): The new ISBN that will replace the previous
attribute value.
Returns:
None
"""
self.isbn = new_isbn
print("The ISBN of {book_title} has been successfully updated!".format(
book_title=self.title))
def add_rating(self, rating):
"""Add a rating to the book object.
Note:
The rating should be included between 0 and 4. Otherwise it will
print an error statement and the rating will not be added.
Args:
rating (int): The rating to be added.
Returns:
None
"""
if rating >= 0 and rating <= 4:
self.ratings.append(rating)
else:
print("Invalid Rating")
def __eq__(self, other_book):
if self.title == other_book.title and self.isbn == other_book.isbn:
return True
else:
return False
def get_average_rating(self):
"""Calculate the average of all the book's ratings and return it."""
sum_of_ratings = 0
for rating in self.ratings:
sum_of_ratings += rating
return sum_of_ratings / len(self.ratings)
def __hash__(self):
return hash((self.title, self.isbn))
def __repr__(self):
return "{title}".format(title=self.title)
class Fiction(Book):
"""Keep track of Tome Rater catalog's novels.
This class inherits from the Book class. The main difference comes from
the author attribute that is not existing in the Book class.
Attributes:
title (str): The title of the novel.
author (str): The author of the novel.
isbn (int): The ISBN of the novel.
"""
def __init__(self, title, author, isbn):
"""Constructor of Fiction class.
Note:
It uses the constructor of the Book class then declares the author
attribute.
Args:
title (str): The title of the book.
author (str): The author of the novel.
isbn (int): The ISBN of the book.
"""
super().__init__(title, isbn)
self.author = author
def get_author(self):
"""Return the novel's author."""
return self.author
def __repr__(self):
return "{title} by {author}".format(title=self.title, author=self.author)
class NonFiction(Book):
"""Keep track of Tome Rater catalog's non fictions.
This class inherits from the Book class. The main difference comes from
the subject and level attributes that are not existing in the Book class.
Attributes:
title (str): The title of the book.
subject (str): The subject of the book.
level (str): The difficulty level of the book.
isbn (int): The ISBN of the novel.
"""
def __init__(self, title, subject, level, isbn):
"""Constructor of NonFiction class.
Note:
It uses the constructor of the Book class then declares the subject
and level attributes.
Args:
title (str): The title of the book.
subject (str): The subject of the book.
level (str): The difficulty level of the book.
isbn (int): The ISBN of the book.
"""
super().__init__(title, isbn)
self.subject = subject
self.level = level
def get_subject(self):
"""Return the book's subject."""
return self.subject
def get_level(self):
"""Return the book's level."""
return self.level
def __repr__(self):
return "{title}, a {level} manual on {subject}".format(title=self.title,
level=self.level, subject=self.subject)
class TomeRater(object):
"""Manage a books catalog and the corresponding ratings given by users.
This class allows to create new books or new users, manages the ratings
given by users and gives some interesting analytics.
Attributes:
users (dict): Keys are emails (str), values are users (User).
books (dict): Keys are books (Book), values are read counts (int).
"""
def __init__(self):
"""Constructor of TomeRater class."""
self.users = {}
self.books = {}
def __eq__(self, other_tome_rater):
if self.users == other_tome_rater.users and self.books == other_tome_rater.books:
return True
else:
return False
def create_book(self, title, isbn):
"""Create a book, add it to the catalog and return it.
Note:
ISBNs should be unic in the catalog. This method first checks if
the argument isbn is already used by another book from the catalog
and prints an error if that is the case.
Args:
title (str): The title of the book.
isbn (int): The ISBN of the book.
Returns:
The new Book object if the ISBN was available, None otherwise.
"""
if self.isbn_available(isbn):
new_book = Book(title, isbn)
self.books[new_book] = 0
return new_book
else:
print("This ISBN is already used by another book!")
def create_novel(self, title, author, isbn):
"""Create a novel, add it to the catalog and return it.
Note:
ISBNs should be unic in the catalog. This method first checks if
the argument isbn is already used by another book from the catalog
and prints an error if that is the case.
Args:
title (str): The title of the novel.
author (str): The author of the novel.
isbn (int): The ISBN of the novel.
Returns:
The new Fiction object if the ISBN was available, None otherwise.
"""
if self.isbn_available(isbn):
new_fiction = Fiction(title, author, isbn)
self.books[new_fiction] = 0
return new_fiction
else:
print("This ISBN is already used by another book!")
def create_non_fiction(self, title, subject, level, isbn):
"""Create a non fiction book, add it to the catalog and return it.
Note:
ISBNs should be unic in the catalog. This method first checks if
the argument isbn is already used by another book from the catalog
and prints an error if that is the case.
Args:
title (str): The title of the book.
subject (str): The subject of the book.
level (str): The difficulty level of the book.
isbn (int): The ISBN of the novel.
Returns:
The new NonFiction object if the ISBN was available, None otherwise.
"""
if self.isbn_available(isbn):
new_non_fiction = NonFiction(title, subject, level, isbn)
self.books[new_non_fiction] = 0
return new_non_fiction
else:
print("This ISBN is already used by another book!")
def isbn_available(self, isbn):
"""Check if the ISBN is available in the catalog.
Args:
isbn (str): The ISBN to be checked for availability.
Returns:
True if no book from the catalog uses this ISBN, False otherwise.
"""
isbn_is_available = True
for book in self.books:
if book.get_isbn() == isbn:
isbn_is_available = False
break
return isbn_is_available
def set_isbn(self, book, new_isbn):
"""Update ISBN of a given book.
Notes:
Prevents the hash issues that occur if set_isbn() was called
directly from the Book object. It uses the Book._set_isbn
private method.
ISBNs should be unic in the catalog. This method first checks if
the argument new_isbn is already used by another book from the
catalog and prints an error if that is the case.
Args:
book (Book): The book whose ISBN should be updated.
new_isbn (int): The new ISBN that will replace the previous
attribute value.
Returns:
None
"""
if self.isbn_available(new_isbn):
read_count = self.books.pop(book)
book._set_isbn(new_isbn)
self.books[book] = read_count
else:
print("This ISBN is already used by another book!")
def add_book_to_user(self, book, email, rating=None):
"""Add a new book to the list of books read by an user.
Notes:
It first checks if a user with the given email exist. Otherwise, it
prints an error message.
This method uses the User.read_books method to add the book to the
list of read books. Additionnaly, the book is either added to the
catalog if not already there, or its read count is incremented to
reflect this new reading.
Args:
book (Book): The book read by the user.
email (str): The email of the user.
rating (int, optional): The rating from the user on this book.
Defaults to None.
Returns:
None
"""
if email in self.users:
user = self.users.get(email)
user.read_book(book, rating)
if rating != None:
book.add_rating(rating)
if book in self.books:
self.books[book] += 1
else:
self.books[book] = 1
else:
print("No user with email {email}!".format(email=email))
def add_user(self, name, email, user_books=None):
"""Add a new user to the list of readers.
Notes:
It first checks if the given email is valid and that no reader with
the given email already exist. Otherwise, it prints an error message
in both cases.
If a lits of books already read by this user is provided, they are
added using the add_book_to_user method.
Args:
name (str): The name of the user.
email (str): The email of the user.
user_books (list, optional): The list of books already read by the
user. Defaults to None.
Returns:
None
"""
if not re.match(r"[^@ ]+@[^@ ]+\.[^@]+", email):
print("This is not a valid email!")
elif email in self.users:
print("A user with this email already exists!")
else:
new_user = User(name, email)
self.users[email] = new_user
if user_books != None:
for book in user_books:
self.add_book_to_user(book, email)
def print_catalog(self):
"""Print all books from the catalog in a clear way."""
print("\n-- Catalog --\n")
for book in self.books:
print("- {book}".format(book=book))
def print_users(self):
"""Print all readers in a clear way."""
print("\n-- Users --\n")
for user in self.users.values():
print(user)
def most_read_book(self):
"""Search for the most read book and return it."""
most_read_book = None
most_read_value = 0
for book, read_count in self.books.items():
if read_count > most_read_value:
most_read_book = book
most_read_value = read_count
return most_read_book
def highest_rated_book(self):
"""Search for the highest rated book and return it."""
highest_rated_book = None
highest_average_rating = 0
for book in self.books:
rating = book.get_average_rating()
if rating > highest_average_rating:
highest_rated_book = book
highest_average_rating = rating
return highest_rated_book
def most_positive_user(self):
"""Search for the most positive user and return it."""
most_positive_user = None
highest_average_rating = 0
for user in self.users.values():
rating = user.get_average_rating()
if rating > highest_average_rating:
most_positive_user = user
highest_average_rating = rating
return most_positive_user
def get_n_most_read_books(self, n):
"""Search for the n most read books and return a ranking of these books.
Args:
n (int): The number of books to include in the ranking.
Returns:
A clear string representation of the ranking.
"""
sorted_books = sorted(self.books, key=self.books.__getitem__, reverse=True)
ranking = ""
for i, book in enumerate(sorted_books[:n]):
ranking += "{rank} - {book}\n".format(rank=i+1, book=book)
return ranking
def get_n_most_prolific_readers(self, n):
"""Search for the n most prolific readers and return a ranking of these
readers.
Args:
n (int): The number of readers to include in the ranking.
Returns:
A clear string representation of the ranking.
"""
readers = []
for user in self.users.values():
for i, reader in enumerate(readers):
if len(user.books) > len(reader.books):
readers.insert(i, user)
break
if user not in readers:
readers.append(user)
ranking = ""
for i, reader in enumerate(readers[:n]):
ranking += "{rank} -\n{reader}\n".format(rank=i+1, reader=reader)
return ranking
|
f22ff3c3aa6db710ed4d01d323062dae6c34f21a | SachaReus/basictrack_2021_1a | /how_to_think/chapter_3/set_3/exercise_3_4_4_1.py | 246 | 4.125 | 4 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# count how many odd numbers in the list
count_odd_numbers = 0
for number in numbers:
if number % 2 == 1:
count_odd_numbers += 1
print("The list contains", count_odd_numbers, "odd numbers")
|
47050beefd6b5487807ab069989e18e94d0407b8 | southpawgeek/perlweeklychallenge-club | /challenge-141/sgreen/python/ch-1.py | 573 | 3.96875 | 4 | #!/usr/bin/env python
def divisors(number):
# One only has one divisor
if number == 1:
return 1
# All other numbers have 1 and itself as divisors
divisors = 2
# Find other divisors
for i in range(2, int(number/2)+1):
if number % i == 0:
divisors += 1
return divisors
def main():
number = 1
solutions = []
while (len(solutions) < 10):
if divisors(number) == 8:
solutions.append(number)
number += 1
print(*solutions, sep=', ')
if __name__ == '__main__':
main()
|
454a03dd1df0ed3aa6b9ab9ea841334da9dccd46 | WotIzLove/University-labs | /PythonTutor/Тьютор 6/Задача 9.py | 131 | 3.625 | 4 | x = int(input())
i = 0
max_x = 0
while x != 0:
if x > max_x:
max_x = x
i += 1
x = int(input())
print(i - 1) |
69d97fbe5830fa04bada7d0f0967759997063fd2 | wonjongah/DataStructure_CodingTest | /practice/같은 문자쌍.py | 218 | 3.71875 | 4 | def is_same(string1, string2):
s1 = list(string1)
s2 = list(string2)
if sorted(s1) == sorted(s2):
return True
else:
return False
print(is_same("yes", "sey"))
print(is_same("uy", "ui")) |
880701bd568d9f28f3deafcc866b6e320b77d0f9 | NidhinAnisham/PythonAssignments | /pes-python-assignments-2x-master/55.py | 171 | 3.875 | 4 | pound = float(input("Enter pounds to convert: "))
assert(pound>0), "Negative pound!!"
kg = pound*0.453592
print "It is ",kg
assert(kg<101), "Weight is above 100 kg!"
|
295ebf279f034ccf7bc1807bb4f2ec488231bd31 | Naman-Garg-06/Python_personal | /binarySearchTree.py | 906 | 4.03125 | 4 | class node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def addToTree(self,data):
new_node = node(data)
while True:
if new_node.data <= self.data:
if self.left == None:
self.left = new_node
break
else:
self = self.left
else:
if self.right == None:
self.right = new_node
break
else:
self = self.right
def printTree(self):
if (self.left)!=None:
self.left.printTree()
print(self.data,end = ' ')
if self.right:
self.right.printTree()
root = node(12)
root.addToTree(6)
root.addToTree(14)
root.addToTree(3)
root.addToTree(7)
root.addToTree(13)
root.printTree()
print() |
d55f9f2beca4d5a390cc9adea052c8236e0f7162 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/1-200/000048/000048_algo2.py | 2,047 | 3.78125 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
# 通过观察可以发现,替换的规律是这样的:
## (旧的)第 i 行会变成(新的)第 n-1-i 列;(旧的)第 j 列会变成(新的)第 j 行。
# 比如例子里那个四阶矩阵:
## 第0行会变成第3列;第1行会变成第2列;依次类推。。。
## 第3列会变成第3行;第2列会变成第2行;依次类推。。。
## 所以原来第 i 行第 j 列的元素,会跑到新的第 j 行第 n-1-i 列处。
"""
# 这次不打算用取巧的办法,而是就靠硬代码一轮轮交换。
## 基本思想就是:每次把最外面一圈旋转交换就行。以一个4*4矩阵最外圈为例,为了完成这个矩阵最外圈的
## 旋转交换,需要做三轮,每轮涉及4个数字。比如 5--11--16--15--5。
## 当要交换的圈的宽度为0和1时,直接返回。
"""
def rotate_one_level(width, startInd):
if width == 1 or width == 0:
return
for i in range(width - 1):
x = startInd
y = startInd + i
matrix[x][y], matrix[y][length-1-x], matrix[length-1-x][length-1-y], matrix[length-1-y][x] = matrix[length-1-y][x], matrix[x][y], matrix[y][length-1-x], matrix[length-1-x][length-1-y]
wid = length = len(matrix)
startInd = 0
while wid >= 0:
rotate_one_level(wid, startInd)
wid -= 2
startInd += 1
"""
https://leetcode-cn.com/submissions/detail/133140241/
21 / 21 个通过测试用例
状态:通过
执行用时: 12 ms
内存消耗: 13 MB
执行用时:12 ms, 在所有 Python 提交中击败了94.06%的用户
内存消耗:13 MB, 在所有 Python 提交中击败了43.62%的用户
"""
|
9567f40c4ddfe60645d687054b48ec0dcbed2de0 | mmkvdev/leetcode | /August/Week5/Day3/deleteNodeBST.py | 1,267 | 3.890625 | 4 | # 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 deleteNode(self, root: TreeNode, key: int) -> TreeNode:
# print(root,key)
if root == None:
return root
if key < root.val:
root.left = self.deleteNode(root.left,key)
elif key > root.val:
root.right = self.deleteNode(root.right,key)
else:
if root.left == None and root.right == None:
root = None
elif root.left == None and root.right != None:
root = root.right
elif root.left != None and root.right == None:
root = root.left
else:
minVal = self.findMinNode(root.right)
root.val = minVal.val
root.right = self.deleteNode(root.right, root.val)
return root
def findMinNode(self, root: TreeNode) -> TreeNode:
current = root
while(current.left is not None):
current = current.left
return current
|
f25eec1ea8ced9055b89adf65c8aa6153bf8ee3c | djohn833/code-snippets | /python/binary_search.py | 754 | 3.765625 | 4 | #!/usr/bin/env python
import re
from regex_helpers import escape_for_charset
def binary_search_with_compare(c):
low, high = 0x20, 0x7e
while low < high:
guess = (low + high + 1) // 2
if chr(guess) <= c:
low = guess
else:
high = guess - 1
print(low, high, guess)
return chr(low)
def binary_search_with_regex(c):
low, high = 0x20, 0x7e
while low < high:
guess = (low + high + 1) // 2
# Iff guess <= c, then c matches [guess-high]
if re.fullmatch('[' + escape_for_charset(chr(guess)) + '-' + escape_for_charset(chr(high)) + ']', c):
low = guess
else:
high = guess - 1
print(low, high, guess)
return chr(low)
|
fa2e787aa42d79e5907057848889bcf90803b30c | HarikaDevineni29/HareHoundChase | /hareHoundChase.py | 2,383 | 3.75 | 4 | import turtle
from tkinter import *
def SetHarePos(x,y):
hare.up()
hare.setpos(x,y)
hare.down()
GetHoundPos()
def SetHoundPos(x,y):
hound.up()
hound.setpos(x,y)
hound.down()
Chase()
def GetHarePos():
messagebox.showinfo("Hare Position","Click on the screen to set hare position")
win.onclick(SetHarePos)
def GetHoundPos():
messagebox.showinfo("Hound Position","Click on the screen to set hound position")
win.onclick(SetHoundPos)
def validchase(hare_y,hound_y):
hare_x = round(hare.xcor(),0)
hound_x = round(hound.xcor(),0)
if hare_x > (WIN_SIZE[0]/2):
if hare_vel > hound_vel:
return -3
elif hare_vel < hound_vel: #and hare_y == hound_y:
return -2
elif hare_y == hound_y:
if hare_x == hound_x:
return -1
elif hare_vel == hound_vel:
return -4
return 1
def Chase():
hare_y = round(hare.ycor(),0)
hound_y = round(hound.ycor(),0)
valid = 1
while valid == 1:
hound_y = round(hound.ycor(),0)
valid = validchase(hare_y,hound_y)
win_size = win.screensize()
if hare.xcor() or hound.xcor() == win_size[0]:
win.screensize((win_size[0] + 25),win_size[1])
hound.seth(hound.towards(hare))
hound.forward(hound_vel)
hare.forward(hare_vel)
if valid == -1:
p = hound.pos()
hare.write(str(p),font = ("Arial",20,"normal"))
messagebox.showinfo("Chase Ends","Hound caught the hare")
elif valid == -4:
messagebox.showinfo("Chase Ends","Never ending...both at same pace!!")
elif valid == -2:
messagebox.showinfo("Chase Ends","Hare and Hound meet at point")
elif valid == -3:
messagebox.showinfo("Chase Ends","Hare is too fast!Hare Wins!!")
win = turtle.Screen()
win.bgcolor("green")
WIN_SIZE = (2000,2000)
win.setup(WIN_SIZE[0],WIN_SIZE[1])
hare = turtle.Turtle()
hound = turtle.Turtle()
hare.shape("triangle")
hound.shape("circle")
hare.pensize(5)
hound.pensize(5)
hare.pencolor("yellow")
hare.fillcolor("yellow")
hare_vel = simpledialog.askinteger("input","Enter hare velocity")
hound_vel = simpledialog.askinteger("input","Enter hound velocity")
while hare_vel > 10:
hare_vel /= 10
while hound_vel > 10:
hound_vel /= 10
hare.speed(hare_vel)
hound.speed(hound_vel)
GetHarePos()
turtle.done()
|
003a36ee609e56d9f603f81383e29b8ef178ebd9 | ChrisTimperley/EvoAnalyser.py | /src/representation/storage.py | 582 | 3.765625 | 4 | # A dictionary is used to store registered representations.
__representations = {}
# Registers a provided representation using a given name.
def register(name, cls):
print "- registering representation: %s" % (name)
if __representations.has_key(name):
print "Warning: representation already defined (%s)" % (name)
__representations[name] = cls
# Retrives a representation with a given name.
def retrieve(name):
if not __representations.has_key(name):
raise Exception("Failed to find representation: %s" % (name))
return __representations[name]
|
dfa25481b959b9b68f263b89790629ff27bd796e | lub4ik/- | /Сколько раз встречается слово.py | 254 | 3.984375 | 4 | userString=input("Введите ваш текст: ").lower()
word = input("Введите слово: ").lower()
userString.count(word)
x=userString.count(word)
print("Слово встречается в тексте столько раз: ", x)
|
b860048764de3d452000ae0a4c2943fbf0e0a606 | M1c17/ICS_and_Programming_Using_Python | /Week2_Simple_Programs/Lecture_2/V-Float-Fraction-convert dec-to-bin-3py.py | 941 | 4.0625 | 4 | '''
Write code to convert any number to its binary form
and print out the summary
'''
num = 19
str_num = str(num)
is_decimal = '.' in str_num
is_negative = num < 0
if is_negative:
num = abs(num)
if is_decimal:
decimal_num = num - int(num)
decimal_summary = '.'
while True:
decimal_num = decimal_num * 2
str_num = str(decimal_num)
decimal_summary = decimal_summary + str_num[0]
if decimal_num > 1:
decimal_num = decimal_num - 1
if decimal_num == 1:
break # Break the moment number becomes whole number 1
if len(decimal_summary) == 12: # Break after max of 11 decimal digits.
break
num = int(num)
summary = ''
if num == 0:
summary = '0'
while num > 0:
summary = str(num%2) + summary
num = num//2
if is_decimal:
summary = summary + decimal_summary
if is_negative:
summary = '-' + summary
print(summary) |
2ee4613a9874f1332ff22430d699ab57abf1ef85 | zfyazyzlh/hello-python | /python作业/Week2作业.py | 2,828 | 3.6875 | 4 | 1编写程序,完成下列题目(1分)
题目内容:
身体质量指数(Body Mass Index,BMI)是根据人的体重和身高计算得出的一个数字,BMI对大多数人来说,是相当可靠的身体肥胖指标,
其计算公式为:BMI=Weight/High²,其中体重单位为公斤,身高单位为米。编写程序,提示用户输入体重和身高的数字,输出BMI。
输入格式:
输入两行数字,第一行为体重(公斤),第二行为身高(米)
输出格式:
相应的BMI值,保留两位小数。注:可以使用 format 函数设置保留的小数位数,使用 help(format) 查看 format 函数的使用方法。
输入样例:
80
1.75
输出样例:
26.12
时间限制:500ms内存限制:32000kb
#----------------------------------------------------
Weight = float(raw_input('输入体重(kg) :'))
High = float(raw_input('输入身高(m) :'))
BMI=Weight/High**2
print '{:.2f}'.format(BMI)
#format 用法http://www.cnblogs.com/dplearning/p/5702008.html
#----------------------------------------------------------
题目内容:
接收用户输入的一个秒数(非负整数),折合成小时、分钟和秒输出。
输入格式:
一个非负整数
输出格式:
将小时、分钟、秒输出到一行,中间使用空格分隔。
输入样例:
70000
输出样例:
19 26 40
# 时间转换为输出 参考https://stackoverflow.com/questions/775049/python-time-seconds-to-hms
时间限制:500ms内存限制:32000kb
intime=int(raw_input('输入秒数(s) :'))
outtime=str(datetime.timedelta(seconds=intime))
# 时间转换为输出 参考https://stackoverflow.com/questions/775049/python-time-seconds-to-hms
#结果为19:26:40
#输出格式为http://www.jb51.net/article/62518.htm 但是不成功
这里使用time 模块 不用上面的datetime模块
import time
intime=int(raw_input('输入秒数(s) :'))
print time.strftime("%H %M %S", time.gmtime(intime))
运行结束 跟题目完全一致
over
你可以在此直接在线输入程序代码。
3编写程序,完成下列题目(2分)
题目内容:
对于三角形,三边长分别为a, b, c,给定a和b之间的夹角C,则有:c²=a²+b²-2*a*b*cos(C)。编写程序,使得输入三角形的边a, b, c,可求得夹角C(角度值)。
输入格式:
三条边a、b、c的长度值,每个值占一行。
输出格式:
夹角C的值,保留1位小数。
c²=a²+b²-2*a*b*cos(C)
(a²+b²-c²)/(2*a*b)=cos(C)
输入样例:
3
4
5
输出样例:
90.0
时间限制:500ms内存限制:32000kb
import math
a=int(raw_input('输入a :'))
b=int(raw_input('输入b :'))
c=int(raw_input('输入c :'))
cosc=(a**2+b**2-c**2)/(2*a*b)
#题目中cosC=1
#求出弧长转化为角度orz
#http://www.jb51.net/article/66175.htm
print float(math.acos(cosc)/math.pi)*180
|
c717cd70ad8a15e670ee405f504ba7a3ba505e4c | Hansyaung/Coding-Interviews-Questions-And-Solutions-python- | /用两个栈实现队列.py | 1,085 | 4 | 4 | '''
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
'''
# -*- coding:utf-8 -*-
# 队列为 先进先出
class stack: # 定义栈结构
def __init__(self):
self.stack = []
def isempty(self):
if len(self.stack) > 0:
return False
else:
return True
def push(self, node):
# write code here
self.stack.append(node)
def pop(self):
ret = self.stack[-1]
self.stack = self.stack[:-1]
return ret # 先进后出
class Solution:
def __init__(self):
self.stack_main = stack()
self.stack_order = stack()
def push(self, node):
# write code here
self.stack_main.push(node)
def pop(self):
if self.stack_order.isempty():
if self.stack_main.isempty():
return None
else:
while not self.stack_main.isempty():
self.stack_order.push(self.stack_main.pop())
return self.stack_order.pop()
|
cc56d9e8b83fe6cfab42e7ac8222c00aba45857f | jvslinger/Year9Design01PythonJVS | /Personal/passtest2.py | 513 | 3.578125 | 4 | def chosen_pokemon():
while True:
for trial in range(3):
print "Please enter your password."
fav_type = raw_input()
if "davey" in fav_type:
print "Password Correct."
else:
print "Sorry, password Incorrect."
continue
else:
sys.exit(10)
return
chosen_pokemon()
#check count then at beginning
#if count = 0 then kill
#set count 3
#then do -1 count and read count at end |
6f27d4b7cb0189ef211c748494e56ba787a55880 | jordanmiracle/learnpython3thehardway | /ex44b.py | 540 | 3.875 | 4 | class Parent(object):
def override(self):
print("PARENT override()")
def player(self, health, armor, damage):
self.health = health
self.armor = armor
self.damage = damage
print (f" health is {health}. Armor is {armor}, and damage is {damage}.")
class Child(Parent):
def override(self):
print("CHILD override()")
super(Child, self).player(70, 200, 80)
dad = Parent()
son = Child()
dad.override()
son.override()
dad.player(100, 150, 50)
son.player(70, 200, 80) |
ad1659931f4ea1b3b28c8193cae8012982b05b73 | Smily-Pirate/LeetCode | /climbingStairs_LeetCode.py | 163 | 3.65625 | 4 | def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
def countWays(s):
return fib(s + 1)
s = 5
print("Number of ways = ", countWays(s)) |
27a273fb34712034aa223523747fc739aef6b3bc | Luolingwei/LeetCode | /Tree/Q100_Same Tree.py | 905 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# Solution 1 recursive 40 ms
# def isSameTree(self, p,q):
# if p and q:
# return (p.val == q.val) and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
# elif not p and not q:
# return True
# else:
# return False
# Solution 2 iterative 36 ms
def isSameTree(self, p,q):
stack=[(p,q)]
while stack:
l,r=stack.pop()
if l and r:
if l.val!=r.val: return False
stack.append((l.left,r.left))
stack.append((l.right,r.right))
elif not l and not r:
continue
else:
return False
return True |
d8ee9a30e47926473bf0ed84ab78e7ba4ee76ae6 | piazentin/programming-challenges | /hacker-rank/implementation/bon_appetit.py | 372 | 3.734375 | 4 | # https://www.hackerrank.com/challenges/bon-appetit
def bon_appetit(k, prices, charged):
change = charged - (sum(prices) - prices[k])//2
if change == 0:
return 'Bon Appetit'
else:
return change
n, k = [int(i) for i in input().split()]
prices = [int(i) for i in input().split()]
charged = int(input())
print(bon_appetit(k, prices, charged))
|
9d16b2b151a30b3a18130ca0e6e927a47e0e4398 | standrewscollege2018/2021-year-11-classwork-NekoBrewer | /Try and Except.py | 286 | 4.125 | 4 | # Example of try and except
keep_asking = True
while keep_asking == True:
try:
number = int(input("please enter number "))
print("You chose", number)
print("**** All done****")
keep_asking = False
except:
print("That's not an integer!")
|
6e96ffcaa7d19ea1d250aca4ef490cf303e1d3ab | fontes99/EP_DSoft | /Parte_1.py | 5,006 | 3.765625 | 4 | import json
from firebase import firebase
firebase = firebase.FirebaseApplication('https://memoria-5bd26.firebaseio.com/memoria-5bd26', None)
result = firebase.get('https://memoria-5bd26.firebaseio.com/memoria-5bd26', None)
estoque = result
negativo = []
with open ('memoria.txt','r') as arquivo:
conteudo = arquivo.read()
estoque = json.loads(conteudo)
i = 0
while i == 0:
print('')
print('Controle de estoque')
print('0 - sair')
print('1 - adicionar item')
print('2 - remover item')
print('3 - alterar item')
print('4 - imprimir estoque')
escolha = input('Faa sua escolha: ')
# Escolha numero 1, adicionar item nao existente ************ FEITO *******
if escolha == '1':
produto = input('Nome do produto: ')
nome = produto.lower()
if nome not in estoque:
a = True
while a:
Qinicial = float(input('Quantidade inicial: '))
if Qinicial < 0:
print('A quantidade inicial no pode ser negativa.')
else:
a = False
b = True
while b:
rs = float(input('Valor unitrio do produto: '))
if rs < 0:
print('O valor do produto no pode ser negativo.')
else:
b = False
estoque[nome] = {'quantidade' : Qinicial, 'valor' : rs}
else:
print('Produto ja cadastrado')
with open ('memoria.txt','w') as arquivo:
conteudo = json.dumps(estoque, sort_keys=True, indent=4)
arquivo.write(conteudo)
# Escolha numero 2, remover item **************************** FEITO *******
elif escolha == '2':
produto = input('Nome do produto: ')
nome = produto.lower()
if nome not in estoque:
print('Elemento no encontrado')
else:
del estoque[nome]
print('Elemento Removido')
with open ('memoria.txt','w') as arquivo:
conteudo = json.dumps(estoque, sort_keys=True, indent=4)
arquivo.write(conteudo)
# Escolha numero 3, alterar item **************************** FEITO *******
elif escolha == '3':
produto = input('Nome do produto: ')
nome = produto.lower()
if nome in estoque:
resposta = int(input('Alterar Quantidade ou Valor unitario? (1 ou 2): '))
if resposta == 1:
quan = float(input('Alterao na Quantidade: '))
resultado = estoque[nome]['quantidade'] + quan
estoque[nome]['quantidade'] = resultado
print('Novo estoque de {0} : {1}'.format(nome, estoque[nome]['quantidade']))
elif resposta == 2:
quan = float(input('Alterao no Valor: '))
resultado = estoque[nome]['valor'] + quan
estoque[nome]['valor'] = resultado
print('Novo valor de {0} : {1}'.format(nome, estoque[nome]['valor']))
else:
print('Elemento no encontrado')
with open ('memoria.txt','w') as arquivo:
conteudo = json.dumps(estoque, sort_keys=True, indent=4)
arquivo.write(conteudo)
# Escolha numero 4, printar estoque ************************* FEITO *******
elif escolha == '4':
soma = 0
print('')
print('Estoques:')
for k in estoque:
if estoque[k]['quantidade'] >= 0:
print(' -{0} : {1}'.format(k, estoque[k]['quantidade']))
for k in estoque:
if estoque[k]['quantidade'] < 0:
negativo.append(nome)
print('')
print('Estoques negativos:')
for j in negativo:
print(' -{0} : {1} '.format(j, estoque[j]['quantidade']))
for l in estoque:
soma += estoque[l]['valor'] * estoque[l]['quantidade']
print('')
print('Valor monetario: R${0}'.format(soma))
# Escolha numero 0, Interromper programa ******************** FEITO *******
elif escolha == '0':
i = 1
else:
print('Escolha invlida')
with open ('memoria.txt','w') as arquivo:
conteudo = json.dumps(estoque, sort_keys=True, indent=4)
arquivo.write(conteudo)
print('At mais')
firebase.put('https://memoria-5bd26.firebaseio.com/', 'memoria-5bd26', estoque) |
11f2f42c4b63e985a550daa67c27cdc78e3e6a79 | JIghtuse/python-playground | /crash_course/testing/names.py | 425 | 3.828125 | 4 | from name_function import get_formatted_name
QUIT_VALUE = 'q'
print(f"Enter '{QUIT_VALUE}' at any time to quit.")
while True:
first = input("\nPlease give me a first name: ")
if first == QUIT_VALUE:
break
last = input("Please give me a last name: ")
if last == QUIT_VALUE:
break
formatted_name = get_formatted_name(first, last)
print(f"\tNeatly formatted name: {formatted_name}.")
|
e1d7d1f817fab53e379f476b706f12a1f95c32c1 | Crepkey/AskMate | /data_manager.py | 3,426 | 3.53125 | 4 | import csv
import os
import time
ANSWERS_HEADER = ['id', 'submission_time', 'vote_number', 'question_id', 'message', 'image']
QUESTIONS_HEADER = ['id', 'submission_time', 'view_number', 'vote_number', 'title', 'message', 'image']
ANSWER_FILE_PATH = 'sample_data/answer.csv'
QUESTION_FILE_PATH = 'sample_data/question.csv'
def read_from_csv(file=QUESTION_FILE_PATH, id=None):
list_of_data = []
with open(file) as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
data = dict(row)
if id is not None and row['id'] == id:
return data
list_of_data.append(data)
return list_of_data
def write_to_csv(message, file=QUESTION_FILE_PATH, is_new=True):
old_message = read_from_csv(file)
if file == QUESTION_FILE_PATH:
header = QUESTIONS_HEADER
else:
header = ANSWERS_HEADER
with open(file, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=header)
writer.writeheader()
for row in old_message:
if not is_new:
if message['id'] == row['id']:
row = message
writer.writerow(row)
if is_new:
writer.writerow(message)
def generate_id(file=QUESTION_FILE_PATH):
"""
Generates an ID based on CSV file data
:param file(str): contains the file path
:return: the new ID in a string
"""
list_of_messages = read_from_csv(file)
if len(list_of_messages) == 0:
new_id = '1'
return new_id
max_id = 0
for row in list_of_messages:
if int(row['id']) > max_id:
max_id = int(row['id'])
new_id = str(max_id + 1)
return new_id
def collect_data(recieved_data, header=QUESTIONS_HEADER):
if header == QUESTIONS_HEADER:
file = QUESTION_FILE_PATH
else:
file = ANSWER_FILE_PATH
message = {key: "" for key in header}
for key in recieved_data: #TODO more specific code
message[key] = recieved_data[key]
message['id'] = generate_id(file)
message['submission_time'] = time.time()
return message
def get_time():
"""
This function returns a UNIX timestamp
:return: {string}
"""
return time.time()
def overwrite_old_csv(new_data, file=QUESTION_FILE_PATH):
"""Can be used to overwrite the whole csv with the new data,
for example when you want to delete a row from the csv.
Args:
new_data(list of dictionaries): contains the new data
file(str): name of file to overwrite
"""
if file == QUESTION_FILE_PATH:
header = QUESTIONS_HEADER
else:
header = ANSWERS_HEADER
with open(file, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=header)
writer.writeheader()
for row in new_data:
writer.writerow(row)
def find_answer_id(question_id, file=ANSWER_FILE_PATH):
"""Finds the IDs of the answers which belong to the given question
Args:
question_id(str): ID of the given question
file(str): name of file which contains the answers
Returns:
list of strings: containing the IDs of answers"""
# REFACTORED by Frici
answer_reader = read_from_csv(file)
answer_ids = [row['id'] for row in answer_reader if row['question_id'] == question_id]
return answer_ids
|
64d3091684ced3b42adaf7c9eba3b4fe06256c76 | NikeSmitt/geekbrains_algorithms_main | /hw_4/task_2.py | 5,047 | 3.625 | 4 | import timeit
import cProfile
import matplotlib.pyplot as plt
# Написать два алгоритма нахождения i-го по счету простого числа.
# Без использования решета Эрастофена
def is_prime(value):
if value < 2:
return False
dev = 2
while dev <= value ** 0.5:
if value % dev == 0:
return False
dev += 1
return True
def without_eratosfen(n):
if n > 0:
count = 0
candidate = 1
while count < n:
candidate += 1
if is_prime(candidate):
count += 1
return candidate
# С использованием решета Эратосфена
def with_eratosfen(n):
INC = 100
primes = [True] * INC
primes[0] = primes[1] = False
# основной счетчик простых чисел
count = 0
idx = 0
last_prime = 0
while count < n:
add = 0
# очередная стартовая позиция
while not primes[idx]:
idx += 1
add = idx
last_prime = idx
count += 1
# флаг для отслеживания необходимости расширять массив
need_to_extend = True
# исключаем все кратные idx
while idx + add < len(primes):
idx += add
primes[idx] = False
need_to_extend = False
# если расширили, то просеивание необходимо повторять
if need_to_extend:
primes.extend([True] * INC)
idx = 0
count = 0
continue
idx = add + 1
return last_prime
def test_tasks(func):
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
for i, value in enumerate(primes):
assert func(i + 1) == value, f'{func.__name__} Test failed on {i + 1} number - {value}'
else:
print(f'{func.__name__}: Tests OK')
test_tasks(without_eratosfen)
test_tasks(with_eratosfen)
# print(timeit.timeit('without_eratosfen(10)', number=100, globals=globals())) # 0.0016512520000000058
# print(timeit.timeit('without_eratosfen(50)', number=100, globals=globals())) # 0.017440287
# print(timeit.timeit('without_eratosfen(250)', number=100, globals=globals())) # 0.17905873300000003
# print(timeit.timeit('without_eratosfen(1250)', number=100, globals=globals())) # 1.8562198520000002
#
# cProfile.run('without_eratosfen(1250)')
"""
10180 function calls in 0.019 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.019 0.019 <string>:1(<module>)
10176 0.017 0.000 0.017 0.000 task_2.py:10(is_prime)
1 0.002 0.002 0.019 0.019 task_2.py:21(without_eratosfen)
1 0.000 0.000 0.019 0.019 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
"""
# print(timeit.timeit('with_eratosfen(10)', number=100, globals=globals())) # 0.005089158000000003
# print(timeit.timeit('with_eratosfen(50)', number=100, globals=globals())) # 0.094234776
# print(timeit.timeit('with_eratosfen(250)', number=100, globals=globals())) # 0.79423713
# print(timeit.timeit('with_eratosfen(1250)', number=100, globals=globals())) # 7.648597774000001
#
# cProfile.run('with_eratosfen(1250)')
"""
460088 function calls in 0.147 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.147 0.147 <string>:1(<module>)
1 0.110 0.110 0.147 0.147 task_2.py:34(with_eratosfen)
1 0.000 0.000 0.147 0.147 {built-in method builtins.exec}
460068 0.036 0.000 0.036 0.000 {built-in method builtins.len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
16 0.000 0.000 0.000 0.000 {method 'extend' of 'list' objects}
"""
"""
C решетом результы значительно хуже, чем вариант без него. Все упирается в необходимость постоянно расширять
основной массив и производить просеивание заного. Оба варианта можно оптимизировать. С решетом - можно применять сразу
большие массивы при значительном искомом номере простого числа. Определить эксперементально
В варианте без решета - оптимизировать проверку на простое число (проверять только до sqrt(n))
График - https://drive.google.com/file/d/1LKMHnGT0OiRafVFPfXZAgD-3kMfATrl_/view?usp=sharing
"""
|
90818b96d8f25ed6722dc8f49387e74f5703bded | forzen-fish/python-notes | /6高级函数/2装饰器参数.py | 792 | 3.828125 | 4 | """
多个装饰器
def zhuangshiqi1(hanshu):
print("zhuangshi1_ing")
def inner1():
print("inner1函数")
hanshu
return inner1
def zhuangshiqi2(hanshu):
print("zhuangshi2_ing")
def inner2():
print("inner2函数")
hanshu
return inner2
@zhuangshiqi1
@zhuangshiqi2
def aaa():
print("aaa")
aaa()
注意:不要出现test,不然会有蜜汁bug
"""
"""
装饰器装饰有参函数
方法1(不能通用,装饰器几个参数,函数几个参数):
def zhuanshiqi(f):
def inner(a,b):
f(a,b)
return inner
@zhuanshiqi
def aa(a,b):
print(a)
print(b)
aa(1,44)
方法2使用不定长参数:
def zhuanshiqi(f):
def inner(*arg,**kwargs):
f(*arg,**kwargs)
return inner
#下面省略
"""
|
0077c45f1d00caba876d5b741e4c909e0ab214c2 | pasu-t/myPython | /python_modules/unittest/test_circles.py | 840 | 3.90625 | 4 | import unittest
from circles import circle_area
from math import pi
class TestCircleArea(unittest.TestCase):
"""docstring for TestCircleArea"""
def test_area(self):
#when radius > 0
self.assertAlmostEqual(circle_area(1), pi)
self.assertAlmostEqual(circle_area(2.1), pi*(2.1**2))
self.assertAlmostEqual(circle_area(0), 0)
def test_values(self):
#Make sure value errors are raised when necessary
self.assertRaises(ValueError, circle_area, -2)
def test_types(self):
#Make sure type errors are raised when necessary
self.assertRaises(TypeError, circle_area, "abcd")
self.assertRaises(TypeError, circle_area, 3+4j)
self.assertRaises(TypeError, circle_area, True)
#run the commandto verify: python -m unittest test_circles or python -m unittest |
35469de03cca4255afa3c1ffb46c0be384dd40b4 | sumitAggarwal416/gradeModule | /gradeModule.py | 3,558 | 3.53125 | 4 | '''
I, Sumit Aggarwal, student number:0007893607, certify that all code submitted is my own code, that I have not copied it
from any other source. I also certify that I have not allowed any one else to copy my code.
'''
lab_wt= int(input("Enter the weight of labs in the course: "))
labs= int(input("Enter the number of labs in your course: "))
assignment_wt= int(input("Enter the weight of assignments in your course: "))
assignments=int(input("Number of assignments in your course? "))
exam_wt= int(input("What is the weight of the exams in your course? "))
exams= int(input("Number of exams in your course? "))
#x is the number of grades entered by the user
def exam_avg():
x=1
total=0
while x<=exams:
grade=float(input("Enter your grade in exam {}/{} ".format(x,exams)))
if grade==-1:
x-=1
break
else:
total+=grade
#avg= total/x
if exams==1:
break
elif exams>1:
x+=1
else:
break
exam_wt_each= exam_wt/exams
global exam_total
exam_total= x*exam_wt_each
global exam_earned
exam_earned= total*exam_wt_each
global your_score1
your_score1= (total*exam_wt_each)/100
global total_score3
total_score3=x*exam_wt_each
def assignment_avg():
x=1
total=0
while x<=assignments:
grade=float(input("Enter your grade in assignment #{}/{} ".format(x,assignments)))
if grade==-1:
x-=1
break
else:
total+=grade
#avg= total/x
if assignments==1:
break
elif assignments>1:
x+=1
else:
break
assignment_wt_each= assignment_wt/assignments
global assignment_total
assignment_total= x*assignment_wt_each
global assignment_earned
assignment_earned= total*assignment_wt_each
global your_score2
your_score2= (total*assignment_wt_each)/100
global total_score2
total_score2=x*assignment_wt_each
def lab_avg():
x=1
total=0
while x<=labs:
grade=float(input("Enter your grade in lab {}/{} ".format(x,labs)))
if grade==-1:
x-=1
break
else:
total+=grade
#avg= total/x
if labs==1:
break
elif labs>1:
x+=1
else:
break
lab_wt_each= lab_wt/labs
global lab_total
lab_total= x*lab_wt_each
global lab_earned
lab_earned= total*lab_wt_each
global your_score3
your_score3=(total*lab_wt_each)/100
global total_score1
total_score1=x*lab_wt_each
lab_avg()
assignment_avg()
exam_avg()
total_score=round(your_score1+your_score2+your_score3,1)
score=round(total_score1+total_score2+total_score3,1)
average = round((lab_earned + assignment_earned + exam_earned)/(lab_total + assignment_total + exam_total),1)
#print(average)
if average>=90:
message="Letter grade A"
elif average>=75 and average<90:
message="Letter grade B"
elif average>=60 and average<75:
message="Letter grade C"
elif average>=50 and average<60:
message="Letter grade D"
else:
message="Letter grade F"
print("You got "+ str(total_score) + " out of " + str(score) + " and your average is " + str(average) + " " + message)
|
62e8038bfc3b28d6c43cdf8255ac0e36b9c25019 | okaaryanata/Arkademy | /soal3.py | 230 | 3.703125 | 4 | def count_vowels(data):
lowerString = data.lower()
vowels = ['a','i','u','e','o']
counter = 0
for x in lowerString:
if x in vowels:
counter += 1
return counter
print(count_vowels('RobErT')) |
08c2a06792f5b78cbb7733042ed3b3753789c51b | aydentownsley/AirBnB_clone | /tests/test_models/test_amenity.py | 1,034 | 3.65625 | 4 | #!/usr/bin/python3
""" Testing Amenity Module """
import unittest
from models.base_model import BaseModel
from models.amenity import Amenity
from datetime import datetime
class TestAmenity(unittest.TestCase):
""" testing output from User class """
def test_attrs(self):
""" test attrs of Amenity when created """
amenity = Amenity()
self.assertEqual(amenity.name, "")
self.assertEqual(Amenity.name, "")
self.assertIn("id", amenity.__dict__)
self.assertIn("created_at", amenity.to_dict())
self.assertIn("updated_at", amenity.to_dict())
def test_set_attrs(self):
""" test the attrs of Amenity when set """
amenity2 = Amenity()
amenity2.name = "Beach Access"
self.assertEqual(amenity2.name, "Beach Access")
def test_inheritance(self):
""" test the inheritance of Amenity from BaseModel """
amenity3 = Amenity()
self.assertIsInstance(amenity3, BaseModel)
self.assertIsInstance(amenity3, Amenity)
|
6cccf7841afa7e8fc28465e4251bf108b54da7d7 | syedaali/python | /exercises/28_class.py | 328 | 4.15625 | 4 | __author__ = 'syedaali'
'''
Define a class named Circle which can be constructed by a radius.
The Circle class has a method which can compute the area.
'''
class Circle(object):
def __init__(self, n):
self.n = n
def radius(self):
return self.n * self.n
aCircle = Circle(5)
print aCircle.radius()
|
a801369bee18aca9961334812c2a9f912ee63226 | dvelez1402/dvelez1402.github.io | /my-website/images/FINAL PROJECT !!.py | 3,358 | 3.796875 | 4 | import time
#This is a comment
def trench():
print("We've been here the whole time. You were asleep. Time to wake up. ")
time.sleep(3)
print (' ______ _______ _ ')
print (' | ____| |__ __| | | ')
print (' | |__ ___ ___ __ _ _ __ ___ | |_ __ ___ _ __ ___| |__ ')
print (' | __| / __|/ __/ _ | _ \ / _ \ | | __/ _ \ _ \ / __| _ \ ')
print (' | |____\__ \ (_| (_| | |_) | __/ | | | | __/ | | | (__| | | |')
print (' |______|___/\___\__,_| .__/ \___| |_|_| \___|_| |_|\___|_| |_|')
print (' | | ')
print (' |_| ')
time.sleep(2)
print('Huh ? Where am I ? WHY AM I WET ?')
time.sleep(2)
choice=raw_input('Tyler wakes up confused. Should he get up ? (Y/IDK)')
if choice == 'Y':
print('He wanders in the large trench')
if choice == 'IDK':
choice=raw_input('OH YEAH ? IM GETTING UP ANYWAYS. I DON\'T WANT TO DIE. Shall we continue ? (Y/N)')
time.sleep(1)
print('Welp...time to investigate!')
time.sleep(3)
choice=raw_input('Tyler looks up. BaNDItoS ? Do you continue walking ? (Y/N)')
while choice != 'Y' and choice !='N':
choice=raw_input('Invalid Answer. Try again(Y/N)')
if choice == 'N':
choice=raw_input('You suddenly trip on rocks and crack your head open.')
time.sleep(1)
print('Oh no ! Looks like you have died from excessive blood loss !')
time.sleep(1) ('You have failed to escape trench.')
return
else: #you chose Y
print ('You continue to walk. In the distance you see a bishop.' )
time.sleep(1)
print ('He charges at you. Your first impulse is to shut your eyes.')
time.sleep(2)
print ('A few seconds pass. Nothing happens. Do you open your eyes ? (Y)')
if choice == 'y':
print('The bishop is a few feet away from you. He orders to follow him. You have no choice.')
time.sleep(2)
print ('You begin to follow him and stop when out of the corner of your eye you see yellow flower petals falling from the sky.')
time.sleep(3)
choice=raw_input('BANDITOS !! They startle the horse and bishop. nOW IS YOUR CHANCE TO ESCAPE. DO YOU TAKE IT AND RUN ? (Y/N)')
if choice == 'Y':
print('You sprint away from the Bishop but he goes right after you')
time.sleep(2)
print('You keep running as fast as you can but soon, you run out of breath and trip in the rocky creek.')
time.sleep(1)
print('You don\'t have the strength to get up and you pass out')
time.sleep(2)
print('What will happen next ??? Will Tyler escape or will Bishop Nico lock him up? Was he able to escape trench? Stay tuned because we\'ll win but not everyone will get out...')
return
elif choice == 'N':
choice=raw_input ('The bishop takes you and locks you away with no way for the banditos to find you.')
print('WaRnINg. Failed Perimeter Escape. You are now trapped in Trench')
return |
ecd1c3a183c738f4429f7c8f24227562df902300 | Mamba-ZJP/School | /Network/Client.py | 762 | 3.5 | 4 | from socket import *
import base64
serverAddr = input("Server address:") # server ip 192.168.8.108
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverAddr, serverPort))
def encrypt(plaintext): # 加密明文
encryptedText = base64.b64encode(plaintext.encode("utf-8")) # 先将字符串转为 2 进制 (utf-8:一种二进制编码格式)
return encryptedText
def decrypt(ciphertext):
decryptedText = base64.b64decode(ciphertext).decode("utf-8")
return decryptedText
while 1:
sentence = input("Client input : ")
clientSocket.send( encrypt(sentence) ) # why encode()
response = decrypt( clientSocket.recv(1024) )
print ('Server answer: ', response)
clientSocket.close()
|
7795650a2a6a3a5b487368c2f2f4d9099677115c | marydCodes/jetbrains_coffeemachine | /methods_practice.py | 2,994 | 3.875 | 4 | class Person:
def __init__(self, name):
self.name = name
# create the method greet here
def greet(self):
print(f"Hello, I am {self.name}!")
# first = str(input())
# me = Person(first)
# me.greet()
############################################################
import math as m
class Hexagon:
def __init__(self, side_length):
self.side_length = side_length
# create get_area here
def get_area(self):
return round(((3 * m.sqrt(3) * (self.side_length ** 2)) / 2), 3)
############################################################
class Point:
# constructor
def __init__(self, x, y):
self.x = x
self.y = y
def dist(self, point):
x_sq = (self.x - point.x) ** 2
y_sq = (self.y - point.y) ** 2
return m.sqrt(x_sq + y_sq)
# p1 = Point(1.5, 1)
# p2 = Point(1.5, 2)
# print(p1.dist(p2))
############################################################
# our class Ship
class Ship:
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
self.cargo = 0
# the old sail method that you need to rewrite
def sail(self, dest):
return f"The {self.name} has sailed for {dest}!"
# black_pearl = Ship("Black Pearl", 800)
# going_where = str(input())
# print(black_pearl.sail(going_where))
############################################################
class Lightbulb:
def __init__(self):
self.state = "off"
def change_state(self):
if self.state == "off":
print("Turning the light on")
self.state = "on"
elif self.state == "on":
print("Turning the light off")
self.state = "off"
# test_light = Lightbulb()
# print("Start: ", test_light.state)
# test_light.change_state()
# print("changed once: ", test_light.state)
# test_light.change_state()
# print("changed twice: ", test_light.state)
############################################################
class PiggyBank:
def __init__(self, dollars, cents):
self.dollars = dollars
self.cents = cents
def add_money(self, deposit_dollars, deposit_cents):
self.dollars += deposit_dollars
# mark up deposit_cents
if self.cents + deposit_cents > 99:
self.dollars += (self.cents + deposit_cents) // 100
self.cents = (self.cents + deposit_cents) % 100
else:
self.cents += deposit_cents
# bank = PiggyBank(1, 1)
# print(bank.dollars)
# print(bank.cents)
# bank.add_money(500, 500)
# print(bank.dollars, bank.cents)
############################################################
class Stack:
def __init__(self):
self.stack = []
def push(self, el):
self.stack.append(el)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
############################################################ |
32ed7176e90417b266a4b71ae8af93b325f115f1 | AsthaNegi/FaultyCalculator | /FaultyCalculator.py | 1,682 | 4.0625 | 4 | #Faulty calculator by Astha Negi
while(1):
print("Enter the operation you want to perform:")
print("Enter 1 for addition:")
print("Enter 2 for sub:")
print("Enter 3 for mul:")
print("Enter 4 for div:")
a = int(input())
if a < 1:
print("invalid choice!\nTry again")
exit()
if a > 4:
print("invalid choice!\nTry again")
exit()
print("Enter first number:")
b = int(input())
print("Enter second number:")
c = int(input())
if a == 1:
if b == 33:
if c == 11:
print("the addition is:", 66)
else:
print("the addition is:", b + c)
else:
print("the addition is:", b + c)
elif a == 2:
if b == 33:
if c == 11:
print("the sub is:", 55)
else:
print("the sub is:", b - c)
else:
print("the sub is:", b - c)
elif a == 3:
if b == 33:
if c == 11:
print("the multiplication is:", 44)
else:
print("the multiplication is:", b * c)
else:
print("the multiplication is:", b * c)
elif a == 4:
if b == 33:
if c == 11:
print("division is:", 22)
else:
print("division is:", b / c)
else:
print("division is:", b / c)
print("Do you want to continue?")
print("Enter y for yes n for no")
d = input()
if d == "y":
continue
elif d=="n":
exit()
else:
print("invalid choice")
|
21c5f1020b9babbb33d41e51e61c1689d4e194b1 | hobbyelektroniker/Micropython-Grundlagen | /006_Mengentypen - Tuple/Code/tuples.py | 1,515 | 4.3125 | 4 | # Ein Tuple mit vorgegebenen Werten erzeugen
tup1 = ("Hallo",3,1.25,"Welt",2,3,4,5)
print(tup1)
print()
# Leeres Tuple erzeugen
tup2 = tuple() # macht nicht viel Sinn !!!
print(tup2)
print()
# Aus anderen Collections erzeugen
set1 = {"Hallo",3,1.25,"Welt"}
tup2 = ("Hallo",3,"Jahr 2020",5)
tup1 = tuple(set1)
print(tup1)
tup3 = tup2
print(tup3)
tup3 = tup1 + tup3
print(tup3)
print()
# Mit Hilfe eines Generators erzeugen
tup1 = tuple(range(1,5))
print(tup1)
print()
# Abfragen, ob ein Element vorhanden ist
tup1 = (3,"Hallo",3,"Hallo","Welt",2,4,5)
print("Hallo" in tup1)
print("Hello" in tup1)
print()
# Alle Elemente auflisten
for x in tup1:
print(x)
print()
# Anzahl Elemente im Tuple
print(len(tup1))
print()
# Einzelnes Element auslesen
print(tup1[3])
print()
# Wieviele Male kommt ein Wert vor
print(tup1.count("Hallo"))
print()
# Welcher Index hat das erste Vorkommen eines Wertes
print(tup1.index("Hallo")) # Der Wert muss existieren!!!
print()
# Das erste und das letzte Element
tup1 = (3,"Hallo",3,"Hallo","Welt",2,4,5)
print(tup1)
print(tup1[0])
print(tup1[-1])
print()
# Der Anfang und das Ende
tup1 = (3,"Hallo",3,"Hallo","Welt",2,4,5)
print(tup1)
print(tup1[:3]) # Element 0 bis 2
print(tup1[4:]) # Element 4 bis Ende
print()
# Ein Bereich aus der Mitte
tup1 = (3,"Hallo",3,"Hallo","Welt",2,4,5)
print(tup1)
print(tup1[2:5]) # Element 2 bis 4
print(tup1[-3:-1]) # Drittletztes Element bis zweitletztes Element
# Tuple vollständig löschen
del tup1
# print(tup1) gibt Fehler
|
fdb6344fd385f7b94b7125beda2fa3eb6c1afc07 | kiccho1101/atcoder | /atc001/b.py | 783 | 3.5 | 4 | class UnionFind:
def __init__(self, n: int):
self.par = list(range(n + 1))
def find(self, x: int):
if self.par[x] == x:
return x
self.par[x] = self.find(self.par[x])
return self.par[x]
def same(self, x: int, y: int):
return self.find(x) == self.find(y)
def union(self, x: int, y: int):
x = self.find(x)
y = self.find(y)
if x == y:
return
if x < y:
x, y = y, x
self.par[x] = y
N, Q = map(int, input().split())
qs = [list(map(int, input().split())) for _ in range(Q)]
uf = UnionFind(N)
for p, a, b in qs:
if p == 0:
uf.union(a, b)
if p == 1:
if uf.same(a, b):
print("Yes")
else:
print("No")
|
6e22ad88e072fcf2463c7fb6fd8201b5720245a1 | imrahul22/placementProgram | /Factorial of a number.py | 164 | 4.09375 | 4 | #Factorial of a number
def fact(n):
while n==0:
return 1
while n!=0:
return n*fact(n-1)
n=int(input("Enter the number"))
print(fact(n))
|
2c762fcbfbc7919f218256247f57719d5ab595fc | ju-c-lopes/Univesp_Algoritmos_I | /Semana 6/exercicio5.3.py | 789 | 4.15625 | 4 | """
Problema Prático 5.3
Escreva a função aritmética(), que aceita uma lista de inteiros como entrada e retorna
True se eles formarem uma sequência aritmética. (Uma sequência de inteiros é uma sequência
aritmética se a diferença entre os itens consecutivos da lista for sempre a mesma.)
# >>> aritmética([3, 6, 9, 12, 15])
True
# >>> aritmética([3, 6, 9, 11, 14])
False
# >>> aritmética([3])
True
"""
def aritmetica(lista):
"""
Verifica a sequência numérica dos elementos da lista
"""
for i in range(0, len(lista) - 1):
dif = lista[1] - lista[0]
dif_now = lista[i + 1] - lista[i]
if dif_now == dif:
ver = True
else:
ver = False
if not ver:
return False
return True
|
ef5ddcff852d5192148da2cb328b108317dddcea | KevinChen1994/leetcode-algorithm | /offer/13.py | 2,029 | 3.71875 | 4 | # !usr/bin/env python
# -*- coding:utf-8 _*-
# author:chenmeng
# datetime:2020/8/17 22:27
'''
solution: 使用dfs或者bfs都可以,机器人按照当前坐标,只能移动一个格,所以不能遍历所有的位置来判断是否符合要求,
当机器人遇到一个不符合要求的位置的时候,那后边的位置肯定也是不符合要求的。
这道题的难点在于如何求位数和,其实可以使用一个比较笨的方法:
def sum(x):
s = 0
while x != 0:
s = x % 10
x = x // 10
return s
但是由于机器人每次只移动一个格,所以位数和是有一定的规律的:
数位和增量公式: 设 x 的数位和为 s_x,x+1 的数位和为 s_{x+1}
1 当 (x+1)%10=0时,s_{x+1}=s_x-8,例如:19,20 的数位和分别为 10, 2;
2 当 (x+1)%10!=0时,s_{x+1}=s_x+1,例如:1, 2的数位和分别为 1, 2。
'''
class Solution:
def movingCount_1(self, m: int, n: int, k: int) -> int:
# i,j是当前索引,si,sj是位数和
def dfs(i, j, si, sj):
if i >= m or j >= n or si + sj > k or (i, j) in visited:
return 0
visited.add((i, j))
return 1 + dfs(i + 1, j, si + 1 if (i + 1) % 10 else si - 8, sj) + dfs(i, j + 1, si,
sj + 1 if (j + 1) % 10 else sj - 8)
visited = set()
return dfs(0, 0, 0, 0)
def movingCount_2(self, m, n, k):
queue, visited = [(0, 0, 0, 0)], set()
while queue:
i, j, si, sj = queue.pop(0)
if i >= m or j >= n or k < si + sj or (i, j) in visited:
continue
visited.add((i, j))
queue.append((i + 1, j, si + 1 if (i + 1) % 10 else si - 8, sj))
queue.append((i, j + 1, si, sj + 1 if (j + 1) % 10 else sj - 8))
return len(visited)
if __name__ == '__main__':
solution = Solution()
m = 3
n = 2
k = 17
print(solution.movingCount_2(m, n, k))
|
9f9ef79152fa834d7c41af8e62fbb2f6a7b580e0 | frankye1000/LeetCode | /python/Sum of Even Numbers After Queries.py | 1,649 | 4.0625 | 4 | """We have an array A of integers, and an array queries of queries.
For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].
Then, the answer to the i-th query is the sum of the even values of A.
(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)
Return the answer to all queries. Your answer array should have answer[i] as the answer to the i-th query.
Example 1:
Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation:
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4."""
A = [1]
queries = [[4, 0]]
S = sum([i for i in A if i % 2 == 0])
for query in queries:
adds = query[0]
index = query[1]
#兩個都奇數
if A[index] % 2 != 0 and adds % 2 != 0:
S += A[index] + adds
#兩個都偶數
elif A[index] % 2 == 0 and adds % 2 == 0:
S += adds
#偶數 奇數
elif A[index] % 2 == 0 and adds % 2 != 0:
S -= A[index]
#奇數 偶數
A[index] = A[index] + adds
print(S)
# Time Limit Exceeded
# re = []
# for query in queries:
# adds = query[0]
# index = query[1]
# A[index] = A[index] + adds
#
# even = [i for i in A if i % 2 == 0]
#
# re.append(sum(even))
# print(re) |
f96004cd9d52de306c789f6b6264c7c1bb51f4cd | Knln/online-coding-judge | /leetcode/539-minimum-time-difference.py | 862 | 3.5 | 4 | from typing import List
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
floats = [int(x[0:2]) * int(60) + int(x[3:]) for x in timePoints]
sorted_floats = sorted(floats)
minimum = 1440
day = 1440
if len(sorted_floats) == 2:
return min(day+sorted_floats[0]-sorted_floats[1], sorted_floats[1]-sorted_floats[0])
for i in range(len(sorted_floats)):
if i == len(sorted_floats)-1:
minimum = min(day+sorted_floats[0]-sorted_floats[i], minimum)
else:
minimum = min(sorted_floats[i+1]-sorted_floats[i], minimum)
return minimum
solution = Solution()
print(solution.findMinDifference(timePoints=["23:59","00:00"]))
print(solution.findMinDifference(timePoints=["00:00","23:59","00:00"])) |
8320d9e5bcd7803ebb2c4fe510f965000c205ced | fervorArd/Hackerrank-Solutions-in-Python- | /46_word-order.py | 273 | 3.609375 | 4 | num = int(input())
words = []
for i in range(num):
words.append(input())
count = {}
for i in words:
count.setdefault(i,0)
count[i] = count[i]+1
sorted_list = list(count.items()).sort()
print(len(count))
for i in count.values():
print(i,end=' ')
|
3bdc4e6299592f1578d7ac5260ad2f91822b09e4 | code-killerr/python_practise | /python practise/20.模块.py | 744 | 3.546875 | 4 | #此时为一个模块,放在调用程序的文件夹下即可调用,Py文件名为模块名,可以Import导入模块调用其中函数
def hello():
#外层调用该函数使用文件名.hello()即可
print('helo world')
#from 模块名 import 函数名可以直接导入函数,再加as可以重命名
#模块测试
def test():
print(hello())
import urllib
def translation():
url = r'https://fanyi.baidu.com/'
data = {}
data['aldtype']=r'16047#en/zh/hello%20world!'
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.urlopen(url,data)
txt = req.read().decode('utf-8')
print(txt+' '+str(req.getcode()))
if __name__ == '__main__':
translation() |
71e859579159cc5a30a60b6f56c81cffc63c8f57 | ChAoss0910/python-programming | /Scrabbler/Program.py | 5,000 | 4.1875 | 4 | from manage import manage
#save all of the points values in a dictionary
pointValues = {"a": 1, "b": 3, "c": 3, "d": 2, "e": 1, "f": 4, "g": 2, "h": 4, "i": 1, "j": 8, "k": 5, "l": 1,
"m": 3, "n": 1, "o": 1, "p": 3, "q": 10, "r": 1, "s": 1, "t": 1, "u": 1, "v": 4, "w": 4, "x": 8,
"y": 4, "z": 10}
def menu(): # display a menu
print("1) Display points table and frequency table of 26 English letters")
print("2) Display all two letter words")
print("3) Show all 3 letters words containing a given tile")
print("4) Verify your word in the dictionary")
print("5) Show words that start with a \"Q\" but are not followed by a \"u\"")
print("6) Show all the letters containing \"X\" or \"Z\" and a given tile")
print("7) show all words that begin with given one or more letters.")
print("8) show all words that end with given one or more letters.")
print("9) Exit")
def main():
dictlist = []
f1 = manage("words.txt",dictlist) # create an object of manage class (read file and save its every line into a list)
print("Welcome to use Scrabble Helper.")
while True:
print()
menu()
choice = str(input("Please select your option:"))
while choice != "1" and choice != "2" and choice != "3" and choice != "4" and choice != "5" and choice != "6" and choice != "7" and choice != "8" and choice != "9":
print("Invalid selection!") #Error checking
choice = int(input("Please select your option again:"))
if choice == "1":
f1.printTable()
if choice == "2":
twoletterlist = f1.twoLetters() #use twoLetters function
pointslist = []
i = 0
for item in twoletterlist:
pointslist.append(f1.pointValue(item, pointValues))
# print every word followed with its point value
while i < len(twoletterlist) - 1:
print(twoletterlist[i] + " (points values:" + str(pointslist[i]) + ")")
i += 1
if choice == "3":
letter = input("please enter the letter for the words:")
threeletterlist = f1.inputLetter(letter.lower()) #use inputLetter function
pointslist = []
i = 0
for item in threeletterlist:
pointslist.append(f1.pointValue(item, pointValues))
# print every word followed with its point value
while i < len(threeletterlist) - 1:
print(threeletterlist[i] + " (points values:" + str(pointslist[i]) + ")")
i += 1
if choice == "4":
word = input("please enter the word you want to check:")
if f1.verifyExist(word.lower()):
print("It exists within the Scrabble dictionary.\n")
else:
print("It doesn't exists within the Scrabble dictionary.\n")
if choice == "5":
qlist = f1.Qstart() #use Qstart function
pointslist = []
i = 0
for item in qlist:
pointslist.append(f1.pointValue(item,pointValues))
# print every word followed with its point value
while i < len(qlist) - 1:
print(qlist[i] + " (points values:" + str(pointslist[i]) + ")")
i += 1
elif choice == "6":
checkletter = input("Please enter a letter:")
xorzlist = f1.containXZ(checkletter.lower()) #use contain function
pointslist = []
i = 0
for item in xorzlist:
pointslist.append(f1.pointValue(item, pointValues))
# print every word followed with its point value
while i < len(xorzlist) - 1:
print(xorzlist[i] + " (points values:" + str(pointslist[i]) + ")")
i += 1
if choice == "7":
tiles = input("Please enter a set of tiles:")
beginList = f1.begin(tiles.lower()) # use begin function
pointslist = []
i = 0
for item in beginList:
pointslist.append(f1.pointValue(item, pointValues))
# print every word followed with its point value
while i < len(beginList) - 1:
print(beginList[i] + " (points values:" + str(pointslist[i]) + ")")
i+=1
if choice == "8":
tiles = input("Please enter a set of tiles:")
endList = f1.end(tiles.lower()) # use end function
pointslist = []
i = 0
for item in endList:
pointslist.append(f1.pointValue(item, pointValues))
# print every word followed with its point value
while i < len(endList) - 1:
print(endList[i] + " (points values:" + str(pointslist[i]) + ")")
i+=1
if choice == "9":
print("Goodbye.")
break #Exit
main() |
d323f659521b4f869aebad8247dd52d6c695bff6 | abeaumont/competitive-programming | /atcoder/abc053/c.py | 146 | 3.5625 | 4 | #!/usr/bin/env python3
# https://abc053.contest.atcoder.jp/tasks/arc068_a
x = int(input())
print(x // 11 * 2 + int(x % 11 > 6) + int(x % 11 > 0))
|
0ded5130c5f1448adbf4bc452a8b2f24ce6d39a6 | soham0511/Python-Programs | /PYTHON PROGRAMS/function.py | 546 | 3.796875 | 4 | # def percent(marks):
# sum=0
# for i in marks:
# sum+=i
# return sum/len(marks)
# marks1=[12,56,78,99,100]
# marks2=[14,56,89,99,55]
# percentage1=percent(marks1)
# percentage2=percent(marks2)
# print(percentage1)
# print(percentage2)
# def greet(name="Stranger"):
# print("Good Day "+name)
# greet()#default argument used
# greet("Soham")
# greet("Vivek")
def fact(n):
if(n==1 or n==0):
return 1
else:
return n*fact(n-1)
print(fact(int(input("Enter the number ")))) |
1a3778d2a59178bc0a362d526f3dd2f7748bcfb9 | gaowanting/learnPython | /useful functions/map.py | 563 | 4.40625 | 4 | # 首先map() 是一个函数,会根据提供的函数对指定序列做映射。
# map(function, iterable, ...) --> 返回一个迭代器
# function:定义一个函数,即映射关系
# iterable:一个或多个序列
tuple1 = (1,2)
tuple2 = (3,4)
l1 = map(lambda x:x^2,tuple1)
l2 = map(lambda x,y:x+y ,tuple1,tuple2)
l3 = map(float, tuple1)
'''
注意这里不能print map 因为map返回的就是一个迭代器
<map object at 0x0000022A482686D0>
所以一定要变为list,tuple 或者其他
'''
print(list(l1))
print(list(l2))
print(tuple(l3))
|
0459b31b47c922a8d81a4391a2f851c59d491551 | diskpart123/xianmingyu | /python程序语言设计/E4.09/E4.09.py | 324 | 3.96875 | 4 | weight1, price1 = eval(input("Enter weight and price for package 1:"))
weight2, price2 = eval(input("Enter weight and price for package 2:"))
perprice1 = price1 / weight1
perprice2 = price2 / weight2
if perprice1 < perprice2:
print("Package 1 has the better price.")
else:
print("Package 2 has the better price.")
|
f0b683bb89719dede743c47f890fe81d7d5c8e8c | gkmjack/number-theory-gadgets | /code/quadratic_residue.py | 2,175 | 3.65625 | 4 | from modular import mod;
from random import randint;
from modular import multiplicative_inverse;
import primality; # No splat import
def jacobi_symbol(n, a):
"""Compute the Jacobi symbol (a/n) where n is an odd number."""
if (n%2 == 0):
raise Exception("Invalid Jacobi symbol.");
# Check that n is indeed odd.
a %= n;
if (a == 0 or a == 1):
return a;
if (a == 2):
if (n%8==1 or n%8==7):
return 1;
if (n%8==3 or n%8==5):
return -1;
if (a%2 == 0):
return jacobi_symbol(n, 2) * jacobi_symbol(n, a>>1);
if (n%4 == 3 and a%4 == 3):
return -jacobi_symbol(a, n);
else:
return jacobi_symbol(a, n);
def legendre_symbol(p, a):
"""Compute the Legendre symbol (a/p) where p is an odd prime."""
if (p == 1) or (p%2 == 0) or (primality.miller_rabin_test(p) == 0):
raise Exception("Invalid Legendre symbol");
# Check that p is indeed an odd prime
result = mod(p, a, (p-1)>>1);
if result == (p-1):
result = -1;
return result;
def random_residue(p, is_residue = True):
while True:
a = randint(1, p-1);
if is_residue and legendre_symbol(p, a) == 1:
return a;
if (not is_residue) and legendre_symbol(p, a) == -1:
return a;
def sqrt_mod_p(p, a):
"""Give all x, such that x**2=a (mod p), where p is odd prime."""
if legendre_symbol(p, a) == -1:
return [];
if legendre_symbol(p, a) == 0:
return [0];
# if legendre_symbol(p, a) == 1:
s = 0;
while (p-1) % 2**(s+1) == 0:
s += 1;
t = (p-1) >> s; # Finding the biggest 's' such that (2**s) divides p
n = random_residue(p, False); # Find a quadratic non-residue 'n'
b = mod(p, n, t); # Find b = n**t (mod p)
a_inverse = multiplicative_inverse(p, a);
x = mod(p, a, (t+1)>>1);
for k in range(1, s):
c = mod(p, a_inverse*x**2, 1<<(s-k-1));
if (c == 1):
j = 0;
elif (c == p-1):
j = 1;
else:
raise Exception("Unexpected error.");
x = x*mod(p, b, j<<(k-1));
x %= p;
return [x, p-x];
|
6899e47b4378cacd28912bced5eab55c67dc71fd | matthew-meech/ICS3U-Unit3-05-Python-Month | /month.py | 1,101 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Mr. Matthew Meech
# Created on: Sep 2021
# month namer
def main():
# input
integer = int(input("Enter number a the number of a month:"))
print("")
# if ... then ... elseif
if integer == 1:
print("your month is Jan")
elif integer == 2:
print("your month is Feb")
elif integer == 3:
print("your month is Mar")
elif integer == 4:
print("your month is Apr")
elif integer == 5:
print("your month is May")
elif integer == 6:
print("your month is Jun")
elif integer == 7:
print("your month is Jul")
elif integer == 8:
print("your month is Aug")
elif integer == 9:
print("your month is Sep")
elif integer == 10:
print("your month is Oct")
elif integer == 11:
print("your month is Nov")
elif integer == 12:
print("your month is Dec")
elif integer > 12:
print("not a month number ")
elif integer < 1:
print("not a month number ")
print("\nDone.")
if __name__ == "__main__":
main()
|
e7008e58b21fa471257d492bc2beccb16262c44a | SaturdaysAI/Projects | /Zaragoza/AnalisisEncuestaEmpresas-main/scripts/terminal.py | 10,102 | 3.671875 | 4 | """
Procesamiento de instrucciones.
No se puede grabar o reproducir un fichero que se esté grabando o reproduciendo. Para este control empleamos listaArchivos[]
"""
import re
import os
def esEntero(s):
"""
Devuelve True si la cadena s representa un entero positivo o negaiivo
Parameters
----------
s : string
Returns
-------
Boolean
"""
# Empleo esEntero() en cuenta de isdigit() porque isdigit() no detecta enteros negativos.
reg_exp = "[-+]?\d+$"
return re.match(reg_exp, s) is not None
def es_flotante(variable):
try:
float(variable)
return True
except:
return False
anchoPantalla = 100
altoPantalla = 40
def imprimeLineasConMarco(s, ancho=0, margen=4) :
espacios = margen*" "
lt = s.split('\n')
if ancho == 0:
ancho = 5 + max( [len(l) for l in lt] )
if ancho+5 > anchoPantalla:
ancho = anchoPantalla-5
for l in lt:
if l == "<LINEA>":
print(" +" + (ancho)*"-" + "+")
else :
while len(l) > ancho-2*margen:
print(" |" + espacios + l[:ancho-2*margen] + espacios + "|")
l = l[(ancho+4) :]
print(" |" + espacios + l + (ancho-len(l)-2*margen)*" " + espacios + "|")
def confirma() :
"""
Pide confirmación al usuario.
Returns
-------
bool:
Si responde 's' (sí) o 'y' (yes), devuelve True,
si reponde 'n' (no) devuelve False, y el otro caso repite el bucle.
"""
contador = 0
while True :
contador += 1
resp = input("Confirmar [S/N]: ")
if resp == "S" or resp == "s" or resp == "Y" or resp == "y" :
return True
if resp == "N" or resp == "n" or contador > 6:
return False
def borrarPantalla(): #Definimos la función estableciendo el nombre que queramos
print("\033[2J\033[1;1f")
if os.name == "posix":
os.system ("clear")
elif os.name == "ce" or os.name == "nt" or os.name == "dos":
os.system ("cls")
def preprocesamiento(s) :
"""
Separa una instrucción en sus parámetros en una lista. Los parámetros deben estar separados por espacios, comas o puntos y comas.
Los parámetros se devuelven en una lista.
Si un parámetro representa un entero, en la lista estará como entero.
Se pueden indicar rangos de valores entre dos números. La lista contendrá todos esos números. Ejemplos:
"N 1,..,5,7,15,..,11" --> ['N', 1, 2, 3, 4, 5, 7, 15, 14, 13, 12, 11]
"N 0,-1,..,-5,PEPE" --> ['N', 0, -1, -2, -3, -4, -5, 'PEPE']
Ejemplo de utilización: ejemploProcesainstruccion(s)
Parameters
----------
s : string a preprocesar
Returns
-------
l : list
"""
# 1º Hacemos que los argumentos se separen por espacios, comas y puntos y comas.
l = re.split(';|,| ', s)
# 2º eliminamos posibles argumentos vacíos.
n = l.count('')
for i in range(n):
l.remove('')
# 3º Si un argumento es una cadena que representa un entero, lo cambia por el entero representado.
for i, v in enumerate(l):
if esEntero(v):
l[i] = int(v)
# 4º Tratamiento de rangos, que se definen como .. entre dos números, dejando espacios o comas entre los números y '..'
ips = l.count('..')
while ips > 0:
ips = l.index('..')
if type(l[ips-1]) == int and ips < len(l)-1 and type(l[ips+1]) == int:
ini = l[ips-1]
fin = l[ips+1]
l.pop(ips)
if ini == fin:
l.pop(ips)
elif ini < fin - 1:
for v in range(ini+1, fin):
l.insert(ips, v)
ips += 1
elif ini > fin + 1:
for v in range(ini-1, fin, -1):
l.insert(ips, v)
ips += 1
else:
l.pop(ips)
ips = l.count('..')
return l
def nuevoArchivo(nombreArchivo):
"""
Cuando se ejecuta graba <nombre archivo>
Inicializa el archivo y le pone una cabecera. Si existiera anteriormente, lo borrará.
Parameters
----------
nombreArchivo : string
Returns
-------
booleand: True o False si tiene éxito o no
"""
global listaInstrucciones
global listaArchivosReproduccion
global listaArchivosGrabacion
if listaArchivosReproduccion.count(nombreArchivo) > 0 or listaArchivosGrabacion.count(nombreArchivo) > 0:
print("ERROR: se intenta grabar un archivo que está en ejecución o grabándose. Recursividad no permitida.")
return False
else :
with open(nombreArchivo, 'w') as f:
f.writelines("Fichero instrucciones.\n")
f.close()
listaArchivosGrabacion.append(nombreArchivo)
return True
def escribeLineaArchivo(nombreArchivo, linea) :
if os.path.isfile(nombreArchivo) :
with open(nombreArchivo, 'a') as f:
f.writelines(linea+"\n")
f.close()
else :
nuevoArchivo(nombreArchivo)
escribeLineaArchivo(nombreArchivo, linea)
def procesaArchivo(nombreArchivo) :
global listaInstrucciones
global listaArchivosReproduccion
global listaArchivosGrabacion
r = False
if os.path.isfile(nombreArchivo):
if listaArchivosReproduccion.count(nombreArchivo) == 0 and listaArchivosGrabacion.count(nombreArchivo) == 0:
with open(nombreArchivo, 'r') as f:
l = f.readlines()
for ind, lin in enumerate(l):
if lin[-1:] == '\n':
l[ind] = lin[:-1]
if l[0].find("Fichero instrucciones.") == -1:
print("ERROR. El fichero", nombreArchivo, "no es un fichero de instrucciones.")
else :
l.pop(0) # quitamos primera línea
listaArchivosReproduccion.append(nombreArchivo)
l.append(listaInstrucciones)
listaInstrucciones = l
r = True
f.close()
else:
print("ERROR: se intenta ejecutar un archivo que está en ejecución o grabándose. Recursividad no permitida.")
else:
print("Error, se intenta ejecutar archivo", nombreArchivo, "pero no se ha encontrado.")
return r
listaInstrucciones = []
listaArchivosReproduccion = []
listaArchivosGrabacion = []
def entradaInstuccion(n, promt) :
global listaInstrucciones
global listaArchivosReproduccion
global listaArchivosGrabacion
instruccion = ''
print()
while instruccion == '':
if len(listaInstrucciones) > 0:
instruccion = listaInstrucciones.pop(0)
l = preprocesamiento(instruccion)
if instruccion[0:1] != '#':
print(promt(n, listaArchivosGrabacion, listaArchivosReproduccion) + instruccion)
if len(listaInstrucciones) == 0 :
listaArchivosReproduccion.pop()
elif type(listaInstrucciones[0]) == list:
listaInstrucciones = listaInstrucciones[len(listaInstrucciones)-1]
listaArchivosReproduccion.pop()
if len(l) == 2 and type(l[0]) == str and (l[0].lower() == "graba" or l[0].lower() == "reproduce"):
procesaArchivo(l[1])
instruccion = ''
else :
instruccion = input(promt(n, listaArchivosGrabacion, listaArchivosReproduccion))
l = preprocesamiento(instruccion)
if len(l) == 2 and type(l[0]) == str and type(l[1]) == str and str(l[0]).lower() + " " + str(l[1]).lower() == "fin graba" and len(listaArchivosGrabacion) > 0:
listaArchivosGrabacion.pop()
instruccion = ''
else:
if len(listaArchivosGrabacion) > 0:
escribeLineaArchivo(listaArchivosGrabacion[len(listaArchivosGrabacion)-1], instruccion)
if len(l) == 1 and type(l[0]) == str and l[0].lower() == "cls" :
borrarPantalla()
instruccion = ''
elif len(l) == 2 and type(l[0]) == str and type(l[1]) == str and l[0].lower() == "graba" :
nuevoArchivo(l[1])
instruccion = ''
elif len(l) == 2 and type(l[0]) == str and type(l[1]) == str and l[0].lower() == "reproduce" :
procesaArchivo(l[1])
instruccion = ''
if instruccion[0:1] == '#':
print("\x1b[1;32m" + instruccion)
instruccion = ''
elif len(l) == 1 and type(l[0]) == str and l[0].lower() == "cls" :
borrarPantalla()
instruccion = ''
elif len(l) == 1 and type(l[0]) == str and (l[0] == 'q' or l[0] == 'Q' or l[0].lower() == 'quit' or l[0].lower() == 'exit'):
print("\n\nSALIMOS DE EJECUCIÓN DE PROGRAMA")
import sys
sys.exit()
print("\x1b[1;37m") # Color blanco
return instruccion
def terminal(parse, promt):
comando = ""
n = 0
while comando.lower() != 'q':
comando = entradaInstuccion(n, promt)
parse(comando)
n += 1
def promtEjemplo(n, listaArchivosGrabacion, listaArchivosReproduccion) :
r = "Instrucción"
if len(listaArchivosGrabacion) > 0:
r += '[:> '+ listaArchivosGrabacion[len(listaArchivosGrabacion)-1] + ']'
if len(listaArchivosReproduccion) > 0:
r += '[' + listaArchivosReproduccion[len(listaArchivosReproduccion)-1] + ':>]'
r += " <" + str(n) + ">: "
# El return devuelve cadena que pone colores. Ver https://python-para-impacientes.blogspot.com/2016/09/dar-color-las-salidas-en-la-consola.html
return "\x1b[1;33m" + r + "\x1b[1;34m"
def ejemploProcesainstruccion(s):
"""
Un modelo de procesamiento.
"""
l = preprocesamiento(s)
print("PROCESAR INSTRUCCIÓN CON ARGUMENTOS:", l)
if __name__ == "__main__":
terminal(ejemploProcesainstruccion, promtEjemplo)
|
dc4ef71d108b7d0b5f122cd2c3c01708edf4845b | jemisonf/closest_pair_of_points | /brute_force.py | 1,398 | 3.796875 | 4 | from lib import read_inputs, write_outputs
import math
import sys
def calculate_distance(first_point, second_point):
distance = math.sqrt(math.fabs(
(first_point[1] - second_point[1])**2 +
(first_point[0] - second_point[0])**2))
return distance
def find_closest_pairs(pairs):
closest_distance = sys.maxsize
closest_pairs = list()
for idx1, pair1 in enumerate(pairs):
if (idx1 < len(pairs)):
for idx2, pair2 in enumerate(pairs[idx1 + 1:]):
cur_distance = calculate_distance(pair1, pair2)
if (cur_distance < closest_distance):
closest_pairs = list([tuple([pair1, pair2])])
closest_distance = cur_distance
elif (cur_distance == closest_distance):
closest_pairs.append([pair1, pair2])
return (closest_distance, closest_pairs)
def main():
try:
input_file = sys.argv[1]
output_file = sys.argv[2]
except:
print("Error parsing arguments--need to call with \
'python3 ./brute_force.py $INPUT_FILE $OUTPUT_FILE'")
exit()
pairs = read_inputs(input_file)
closest_distance, closest_pairs = find_closest_pairs(pairs)
write_outputs(output_file, closest_distance, closest_pairs)
if (__name__ == "__main__"):
main()
|
449591e1f1fcca76d0f2b3c172ff516638280d87 | cKompella/python-basics | /src/classes.py | 2,405 | 3.84375 | 4 | #Part1: Creating Menu, Franchise and Business classes
class Menu:
def __init__(self, name, items, start_time, end_time):
self.name = name
self.items = items
self.start_time = start_time
self.end_time = end_time
def __repr__(self):
return "{name} available from {start} to {end}".format(name=self.name, start = self.start_time, end=self.end_time)
def calculate_bill(self, purchased_items):
total=0
for itemName in purchased_items:
total+=self.items[itemName]
return total
class Franchise:
def __init__(self, address, menus):
self.address = address
self.menus = menus
def __repr__(self):
return "This franchise is located at "+self.address
def available_menus(self, time):
list = []
for menu in self.menus:
if time>=menu.start_time and time<=menu.end_time:
list.append(menu)
return list
class Business:
def __init__(self, name, franchises):
self.name = name
self.franchises = franchises
#Part2: Creating menu objects
brunch = Menu("Brunch", {
'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50, 'espresso': 3.00, 'tea': 1.00, 'mimosa': 10.50, 'orange juice': 3.50
}, 1100, 1600)
early_bird = Menu("Early_Bird", {
'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza with quattro formaggi': 9.00, 'duck ragu': 17.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 1.50, 'espresso': 3.00,
}, 1500, 1800)
dinner = Menu("Dinner", {
'crostini with eggplant caponata': 13.00, 'ceaser salad': 16.00, 'pizza with quattro formaggi': 11.00, 'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00,
}, 1700, 2300)
kids = Menu("Kids Menu", {
'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00
}, 1100, 2100)
arepas_menu = {
'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa': 7.50
}
#Part2: Creating franchise objects
flagship_store = Franchise("1232 West End Road", [brunch, early_bird, dinner, kids])
new_installment = Franchise("12 East Mulberry Sreet", [brunch, early_bird, dinner, kids])
arepas_place = Franchise("189 Fitzgerald Avenue", arepas_menu)
#Part3: Creating business objects
basta_business = Business("Basta Fazoolin' with my Heart", [flagship_store, new_installment])
my_business = Business("Take a' Arepa!", [arepas_place]) |
c2f03ff9fb40ccfa997e756da0b43e65a04b888a | ZYZhang2016/think--Python | /chapter15/Exercise15.2.py | 629 | 3.828125 | 4 | #coding:utf-8
class Point(object):
'''一个二维的点
'''
class Rectangle(object):
'''定义一个矩形的点和长宽
attribute:height,width,corner
'''
def move_corner(box,dx,dy):
'''移动矩形boxde1corner
:param box: Recyangle()对象
:param dx: x轴方向移动距离
:param dy: y轴方向移动距离
:return: 返回移动后的矩形
'''
box.corner.x += dx
box.corner.y += dy
return box
def main():
box = Rectangle()
box.corner = Point()
box.corner.x,box.corner.y = 3,7
box.height,box.height = 10,20
move_corner(box,36,75)
print(box.corner.x,box.corner.y)
if __name__=='__main__':
main() |
760019f5052bbf63342a8834e016633f1b22217d | scottberke/algorithms | /algorithms/search/linear_search/linear_search.py | 209 | 3.78125 | 4 | def search(arr, target):
# Grab index and value
for index, val in enumerate(arr):
# If we find our target
if val == target:
# Return index
return index
# Otherwise, return False
return False
|
ec311ce99cb0e65dd7dd207b78665c62ae779dc4 | hughwin/hughpython | /tld.py | 2,242 | 4.3125 | 4 | # This program will hopefully show that I understand tuples, lists and dictionaries.
while True:
user = ""
print """
Welcome to this program. If will hopefully demonstrate that Hugh fully
understands tuples, lists and dictionaries as well as how they can be manipulated.
Hugh will also demonstrate his competence with if, elif and else statements.
Let's continue.
1 - Tuples
2 - Lists
3 - Dictionary
0 - Quit
"""
user += (raw_input("Make your selection, 1 - 3\n:"))
if user == "1":
print "Starting the tuple module... \n\n"
family = ("Hugh", "Jeremy", "Louise", "Amana", "John")
print "So your family contains:"
print family
raw_input("\nPress any key to continue")
q1 = raw_input("Would you like to take a slice? y/n \n>")
if q1 == "y":
begin = int(raw_input("Where would you like your slice to begin? 0 - 4"))
finish = int(raw_input("Where would you like your slice to finish? 0 -4"))
print "Taking slice"
print (family[begin:finish])
raw_input("Press enter to go back to the main menu")
continue
elif q1 == "n":
continue
if user == "2":
list = []
list2 = ["a", "b", "c"]
list.append(raw_input("Please input three of your favourite things seperated by commas"))
for item in list2:
print item
raw_input("Press any key to continue")
q2 = ""
q2 += raw_input("Are you sure those are your favourite things? y/n")
if q2 == "y":
print "Okay then"
continue
raw_input()
if q2 == "n":
change = int(raw_input("Which one would you like to replace?"))
replacement = raw_input("What would you like to replace it with?")
list2[change] = replacement
print list2
if user == "3":
dick = {"Pen": "Something to write with", "Pencil": "Something to write with"}
print dick
raw_input()
print "Wanna see the definition again?"
defi = raw_input("Wanna get a definition? \nEnter a word to define:")
print dick[defi]
raw_input("...")
elif user == "0":
quit()
else:
print "I'm sorry, that is not a valid selection."
("\nPress any key to return")
continue
# import pickle letters=['A','B','C']
#Writing the letters list into the file.
#fh = open("list.pkl", 'wb')
#pickle.dump(letters, fh)
#fh.close()
|
aaf46b4583c50bb4c2cb90571fb4c6f9c6216f2c | kickscar/deep-learning-practices | /03.linear-algebra-basics/01/ex12.py | 597 | 3.984375 | 4 | # coding: utf-8
# 전치행렬(transpose matrix)
"""
1. 어떤 행렬의 행과 열을 바꿔 생성한 행렬이다.
2. 축에 대한 변경이지 요소의 변경이 아니다.
"""
import numpy as np
# a = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)
print('=====================')
a1 = a.T
print(a1)
print(a1.shape)
print('=====================')
a2 = np.transpose(a)
print(a2)
print(a2.shape)
print('=====================')
a3 = np.swapaxes(a, 0, 1)
print(a3)
print(a3.shape)
print('=====================') |
c89252a91f0ed7a40c844b5fc51f9b118415f809 | dpfeifer-dotcom/BroTalk | /openfile.py | 344 | 3.59375 | 4 | from tkinter import filedialog
import tkinter as tk
import os
def openfile():
"""
:return: file helye, file neve
"""
root = tk.Tk()
root.attributes("-topmost", True)
root.withdraw()
file_path = filedialog.askopenfilename(initialdir="/", title="Select A File", )
return file_path, os.path.basename(file_path)
|
5005be8f88be9e32e73f6d6f3f850c32f2e55ab8 | Shantanu0901/sadchatbot | /main.py | 19,127 | 3.5625 | 4 | import wikipediaapi
wiki_wiki = wikipediaapi.Wikipedia('en')
import urllib.request
import sys
import time
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from keras.models import load_model
model = load_model('chatbot_model.h5')
import json
import random
import tkinter
from tkinter import *
# Function and List Definitions
answer_A = ["A", "a", "A.", "a."]
answer_B = ["B", "b", "B.", "b."]
answer_C = ["C", "c", "C.", "c."]
yes = ["Y", "y", "Yes", "yes", "YES"]
no = ["N", "n", "No", "no", "NO"]
# Return Name
def returnname():
print("What's your name? (Enter your name only)(If want to exit the room enter 'exit', if want some help enter 'help')")
global name
name = input(">>> ")
if name == "exit":
print("Goodbye!")
sys.exit()
elif name == "help":
instructions()
elif name == "return":
mainmenu()
else:
print("Wow! Cool name,", name, "!")
# Instructions
def instructions():
#Prints instructions on how to operate the chatbot.
print(
"I am a robot with a wide feature set!\nFirst off, I returned your name at the beginning of the program!\nFurthermore, I can:"
)
print(
"- Find Information about something you want to learn"
)
print("- Just simple CHAT")
print("- Play an Interactive Story")
print(
'Operating me is very simple, from the main menu, type the number that corresponds to the action.\nThen, you can follow the on-screen prompts to tell me what to do.\n If you want to return to the main menu from any action, all you have to say is {"return"} at any time.\nAfter you finish your action, I will automatically prompt you to return to the main menu as well.\nIf you want me to stop running, then just type "exit" from anywhere in the program.\n Don\'t worry if you can\'t memorize all of this.\n Just type "help" if you can\'t remember, and I will give you these instructions again.'
)
# Main Menu
def main_menu_validate(x):
#Input validation for mainmenu() function
if x == "1":
wikichat()
elif x == "2":
chatterbot()
elif x == "3":
intro()
elif x == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif x == "help":
instructions()
time.sleep(1)
mainmenu()
elif x == "return":
mainmenu()
else:
return False
# Main Function
def mainmenu():
#Asks the user what they want to do and redirects accordingly
print(
"\nWhat do you want to do? Type the number that corresponds to the action."
)
time.sleep(1)
print(
"\n\n[1] --> Find Information about something you want to learn"
)
print("[2] --> Retrieve the current weather")
print("[3] --> Play an Interactive story mode")
x = input(">>> Input Your Choice, My Friend --> ")
main_menu_result = main_menu_validate(x)
if main_menu_result == False:
while main_menu_result == False:
print("My Friend, Please enter a valid input")
x = input(">>> here --> ")
main_menu_result = main_menu_validate(x)
#Chatbot code
def chatterbot():
intents = json.loads(open('intents.json').read())
words = pickle.load(open('words.pkl','rb'))
classes = pickle.load(open('classes.pkl','rb'))
def clean_up_sentence(sentence):
sentence_words = nltk.word_tokenize(sentence)
sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
return sentence_words
# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence
def bow(sentence, words, show_details=True):
# tokenize the pattern
sentence_words = clean_up_sentence(sentence)
# bag of words - matrix of N words, vocabulary matrix
bag = [0]*len(words)
for s in sentence_words:
for i,w in enumerate(words):
if w == s:
# assign 1 if current word is in the vocabulary position
bag[i] = 1
if show_details:
print ("found in bag: %s" % w)
return(np.array(bag))
def predict_class(sentence, model):
# filter out predictions below a threshold
p = bow(sentence, words,show_details=False)
res = model.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
# sort by strength of probability
results.sort(key=lambda x: x[1], reverse=True)
return_list = []
for r in results:
return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
return return_list
def getResponse(ints, intents_json):
tag = ints[0]['intent']
list_of_intents = intents_json['intents']
for i in list_of_intents:
if(i['tag']== tag):
result = random.choice(i['responses'])
break
return result
def chatbot_response(msg):
ints = predict_class(msg, model)
res = getResponse(ints, intents)
return res
def send():
msg = EntryBox.get("1.0",'end-1c').strip()
EntryBox.delete("0.0",END)
if msg != '':
ChatLog.config(state=NORMAL)
ChatLog.insert(END, "You: " + msg + '\n\n')
ChatLog.config(foreground="#442265", font=("Verdana", 12 ))
res = chatbot_response(msg)
ChatLog.insert(END, "Bot: " + res + '\n\n')
ChatLog.config(state=DISABLED)
ChatLog.yview(END)
base = Tk()
base.title("Hello")
base.geometry("400x500")
base.resizable(width=FALSE, height=FALSE)
#Create Chat window
ChatLog = Text(base, bd=0, bg="white", height="8", width="50", font="Arial",)
ChatLog.config(state=DISABLED)
#Bind scrollbar to Chat window
scrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set
#Create Button to send message
SendButton = Button(base, font=("Verdana",12,'bold'), text="Send", width="12", height=5,
bd=0, bg="#32de97", activebackground="#3c9d9b",fg='#ffffff',
command= send )
#Create the box to enter message
EntryBox = Text(base, bd=0, bg="white",width="29", height="5", font="Arial")
#EntryBox.bind("<Return>", send)
#Place all components on the screen
scrollbar.place(x=376,y=6, height=386)
ChatLog.place(x=6,y=6, height=386, width=370)
EntryBox.place(x=128, y=401, height=90, width=265)
SendButton.place(x=6, y=401, height=90)
base.mainloop()
# Return to Main Menu
#Returns to the mainmenu() function from the wikichat() function
def wiki_return():
print("Do you want to return to the main menu?")
x = input(">>> ")
if x == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif x == "help":
instructions()
elif x == "return":
mainmenu()
elif x in yes:
mainmenu()
elif x in no:
wikichat()
else:
print("Please enter a valid input (yes or no):")
x = input(">>> ")
wiki_validation_result = wiki_return(x)
#Returns to the mainmenu() function from the weatherchat() function
#Returns to the mainmenu() function from the intro() function
def story_return():
print("Do you want to return to the main menu?")
x = input(">>> ")
if x == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif x == "help":
instructions()
elif x == "return":
mainmenu()
elif x in yes:
mainmenu()
elif x in no:
intro()
else:
print("PLease enter a valid input (yes or no)")
x = input(">>> ")
story_validation_result = story_return(x)
# Retrieve Summary of Wikipedia Article
def wiki_article_validate(articlename):
#Validates the input for the wikichat() function
page_py = wiki_wiki.page(articlename)
if page_py.exists() == True:
print("Here you go,", name, ":")
print("Page - Title: %s" % page_py.title)
print("Page - Summary: %s" % page_py.summary)
else:
return False
return page_py
# Main Function
def wikichat():
#Prompts the user to enter the name of a Wikipedia article to retrieve the summary of said article.
print("What do you want to learn about?")
x = input(">>> ")
if x == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif x == "help":
instructions()
elif x == "return":
mainmenu()
else:
wiki_validation_result = wiki_article_validate(x)
if wiki_validation_result == False:
while wiki_validation_result == False:
print("Please enter a valid input, My Friend:")
x = input(">>> ")
wiki_validation_result = wiki_article_validate(x)
wiki_return()
#Retrieve Local Weather
# Interactive Story
# -- Grabbing Objects --
flower = 0
# -- Cutting down on Duplication --
required = ("\nUse only A, B, or C\n")
# Story Functions
def intro():
#Prompts the user to choose whether the character is a boy or a girl.
print("Would you like to be start?")
print("yes or no")
choice = input(">>> ")
if choice == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif choice == "help":
instructions()
elif choice == "return":
mainmenu()
else:
if choice in yes:
boystory()
return True
elif choice in no:
mainmenu()
else:
print("Please enter a valid input:")
story_return()
# The Male Version for the Story
def boystory_validate(choice):
#Validates the input for the boystory() function
if choice == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif choice == "help":
instructions()
elif choice == "return":
mainmenu()
elif choice in answer_A:
option_rockb()
elif choice in answer_B:
print("\nWelp, that was quick.", "\n\n", name, "died.")
story_return()
elif choice in answer_C:
option_runb()
else:
print(required)
return False
def boystory():
#Introduction to the male interactive story.
print(
name,
", you are on a vacation with all your friends. You are alone right now because you wanted to take a midnight stroll. THUNK! Something hits you, on the head. Your eyes close and you slumps down. Head spinning and fighting the pain on the head, you manage to wake up. You are in a big dark cave. There are bones all over the place. Now, you are trying to find the exit. Atlast you see a light shining from somewhere. You are now following the light until you reaches this dark room. You hears a groan behind you. Slowly turning, you see a big green ogre with a club. You are scared to death.",
name, ", What will you will do?")
time.sleep(1)
print("A. will grab a nearby rock and throw it at the ogre\n B. will lie down and wait to be mauled\nC. will run")
choice = input(">>> ")
boystory_validation_result = boystory_validate(choice)
if boystory_validation_result == False:
while boystory_validation_result == False:
choice = input(">>> ")
boystory_validation_result = boystory_validate(choice)
# Options for the Male Interactive Story.
def option_rockb_validate(choice):
if choice == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif choice == "help":
instructions()
elif choice == "return":
mainmenu()
elif choice in answer_A:
option_runb()
elif choice in answer_B:
print(
"\n You decided to throw another rock, as if the first rock thrown did much damage. The rock flew well over the ogre's head. You missed.\n\n You are died.")
story_return()
else:
print("Use only A or B.")
return False
def option_rockb():
print(
"\nThe ogre is stunned, but regains control. He begins running towards",
name, ", again. What will you do?")
time.sleep(1)
print("A. will run\nB. will throw another rock")
choice = input(">>> ")
option_rockb_validation_result = option_rockb_validate(choice)
if option_rockb_validation_result == False:
while option_rockb_validation_result == False:
choice = input(">>> ")
option_rockb_validation_result = option_rockb_validate(choice)
def option_runb_validate(choice):
if choice == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif choice == "help":
instructions()
elif choice == "return":
mainmenu()
elif choice in answer_A:
print("Your are easily spotted.\n\nYou are died.")
story_return()
elif choice in answer_B:
print("\nYou are no match for an ogre.\n\nYou are died.")
story_return()
elif choice in answer_C:
option_run2b()
else:
print(required)
return False
def option_runb():
print(
"\nYou run as quickly as possible, but the ogre's speed is too great.",
name, ", What will you will do?")
time.sleep(1)
print("A. will hide behind a boulder\nB. will fight\nC. will run")
choice = input(">>> ")
option_runb_validate_result = option_runb_validate(choice)
if option_runb_validate_result == False:
while option_runb_validate_result == False:
choice = input(">>> ")
option_runb_validate_result = option_runb_validate(choice)
def option_run2b_validate(choice):
if choice == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif choice == "help":
instructions()
elif choice == "return":
mainmenu()
elif choice in answer_A:
print(
"\nYou take the left trusting the arrow. You ends up in a dead end. You look behind to run, but the ogre is there waiting for you. You realizes that the arrow is a trap. The ogre grabs his club and kills him.\n\nYou are died.")
story_return()
elif choice in answer_B:
option_rightb()
else:
print("Use only A or B")
return False
def option_run2b():
print(
"\nYou run as fast as you can. You endup in a fork. Now, you can either take a left or a right. You noticed a battered sign with burnt edges. It is point towards the left. You can hear the ogre coming behind you and you has to make a decision fast. Does you choose left or right?")
time.sleep(1)
print("A. Left\nB. Right")
choice = input('>>> ')
option_run2b_validation_result = option_run2b_validate(choice)
if option_run2b_validation_result == False:
while option_run2b_validation_result == False:
choice = input(">>> ")
option_run2b_validation_result = option_run2b_validate(choice)
def option_rightb_validate(choice):
if choice == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif choice == "help":
instructions()
elif choice == "return":
mainmenu()
elif choice in answer_A:
print(
"\n You jump off the cliff into the mud. It is a soft landing. You try to get out but you can't, and you slowly starts sinking into the mud. Realizing that it sinking mud, you screams until you sinks fully\n\nYou are died.")
story_return()
elif choice in answer_B:
option_townb()
elif choice in answer_C:
print(
"\nyou take the left into the Cave Entrance. No clue why you would go back into the cave, but you does. You comes back to the fork."
)
option_run2b()
else:
print(required)
return False
def option_rightb():
print(
"\nYour own instincts tell you that the arrow is a trap so you takes a right. You run as fast as you can. You come to a cliff. When you looks down from the cliff you see a pool of mud. You look to your right and there are steps leading toward a town. On your left is another entrance into the cave. What will",
name, ", you do?")
time.sleep(1)
print("A. you will jump off the cliff into the pool of mud\nB. you run towards the Town\nC. you take the entrance back into the cave")
choice = input('>>> ')
option_rightb_validation_result = option_rightb_validate(choice)
if option_rightb_validation_result == False:
while option_rightb_validation_result == False:
choice = input(">>> ")
option_rightb_validation_result = option_rightb_validate(choice)
def option_townb_validate(choice):
if choice == "exit":
print("Thank you! Goodbye!")
sys.exit()
elif choice == "help":
instructions()
elif choice == "return":
mainmenu()
if choice in yes:
flower = 1
elif choice not in yes:
flower = 0
print(
"\nyou hear its heavy footsteps and gets ready for the impending ogre. What will you do?")
time.sleep(1)
if flower > 0:
print(
"\nYou quickly held out the purple flower, somehow hoping it will stop the ogre. It does! The ogre was looking for love.",
"\n\nThis got weird, but you survived!")
story_return()
elif choice in no: # If the user didn't grab the flower
print("\nMaybe you should have picked up the flower."
"\n\nYou are died.")
story_return()
else:
print("Please enter a valid input:")
return False
def option_townb():
print(
"\nWhile frantically running towards the town, you notice a rusted sword lying in the mud. you reache down to grab it, but misses. You try to calm your heavy breathing as you hide behind a boulder, waiting for the ogre to come charging around the corner. You notice a purple flower near your foot. Will you pick it up? Y/N")
choice = input(">>> ")
option_townb_validation_result = option_townb_validate(choice)
if option_townb_validation_result == False:
while option_townb_validation_result == False:
choice = input(">>> ")
option_townb_validation_result = option_townb_validate(choice)
# Main Code
print(
"Hello, my name is Python SADChatbot!\nConsider me as your friend or the helpful tool."
)
time.sleep(1)
returnname()
instructions()
print("Now, let's get started!")
mainmenu()
|
f738b917fd7f6dd8d362ef2c5e0b9e1199b0289b | itmproject/PythonProject | /Project 4/Project 4/Project_4.py | 2,671 | 4.0625 | 4 | ##Project 4
##Nhan Nguyen
##Program that subtracts a withdrawl from a Checking Account.
import datetime
from Banking import BankingAccount
s = BankingAccount()
def validMenu(self): ##Validate input of User
while True:
try:
inputMenu = int(input(self))
if inputMenu > 5: ##Error if input menu greater than 5
raise ValueError
elif inputMenu < 1: ##Error if input menu less than 1
raise ValueError
except ValueError:
print("ERROR: Wrong menu selection. Please enter a integer number from 1 to 5 to try again..\n")
continue
else:
return inputMenu
break
def validDepos(self): ##Validate deposite amountof User
while True:
try:
inputMenu = int(input(self))
if inputMenu < 1: ##Error if input menu greater than 5
raise ValueError
except ValueError:
print("Negative Entries Are Not Allowed. Please try again\n")
continue
else:
return inputMenu
break
def one(): ##Show Account Balance
print("Menu 1 has been selected")
print(40* "_","\n")
s.display()
s.interest()
print(40* "_")
def two(): ##Get amount of withdrawn from user
print("Menu 2 has been selected")
print(40* "_","\n")
s.withdraw()
s.display()
s.interest()
print(40* "_")
def three(): ##Get amount of deposit from user
print("Menu 3 has been selected")
print(40* "_","\n")
s.deposit()
s.display()
s.interest()
print(40* "_")
def four(): ##Show Interest Accrued
print("Menu 4 has been selected")
print(40* "_","\n")
s.display()
s.interest()
print(40* "_")
def five(): #exit program
print("Menu 5 has been selected")
print("program terminated!!!")
return ""
def transaction():
current_time = datetime.datetime.now()
f = open("transaction.txt", "w+")
L = ["Date", 10*" ", "Deposite",10*" ", "Withdrawn" ,10*" ","Balance",10*" ", "Interest Accrued \n"]
f.writelines(L)
f.close()
def function(num): ##switch function to select Menu
switcher = {
1: one,
2: two,
3: three,
4: four,
5: five
}
#Get the function from switcher
func = switcher.get(num, lambda: "Invalid Number: please enter number from 1 to 5")
return func()
def main():
loop = True
transaction()
while loop:
s.menu()
menu = validMenu("Enter your choice from 1 to 5: ")
print("")
function(menu)
if menu == 5:
loop = False
main()
|
cb81ba0af3b04365297bbe546face2475e2a235b | Leskos/ev3 | /simpleTimer_V2.py | 3,714 | 3.9375 | 4 | #!/usr/bin/env python3
from ev3dev.ev3 import *
from time import sleep
# Improved version of simpleTimer.py that is more suitable for
# performing the experiment. The timer is primed when a weight
# is placed on the start sensor, and only started upon release
#
# This is for recreating Galileo's leaning tower of Pisa experiment
# at Brighton's Self Managed Learning College
# Initialise input and output objects
lcd = Screen()
startButton = TouchSensor('in1')
stopButton = TouchSensor('in2')
resetButton = TouchSensor('in3')
# Check we have all sensors connected
assert startButton.connected, "Connect a touch sensor to sensor port 1"
assert stopButton.connected, "Connect a touch sensor to sensor port 2"
assert resetButton.connected, "Connect a touch sensor to sensor port 3"
# Initialise our python timer variables
timerReady = False
timerRunning = False
timeElapsed = 0.0
timeStarted = 0.0
displayText = "Time Elapsed : "
while True: # Loop forever
if resetButton.value() > 0: # If the reset button is pressed down
timeElapsed = 0 # Set timeElapsed to 0
timerReady = False # Set timerReady to False
timerRunning = False # Set timerRunning to False
if timerReady: # If the timer is ready
if startButton.value() == 0: # If the start button is released...
if not timerRunning: # ...and we are not already running the timer
timerRunning = True # Set timerRunning to true
timeStarted = time.clock() # Set timeStarted to the current system time
if stopButton.value() > 0: # If the stop button is pressed down...
if timerRunning: # ...and we are already running the timer
timerRunning = False # Set timerRunning to False
timerReady = False # Set timerReady to False
if timerRunning: # If we are running the timer
timeElapsed = time.clock() - timeStarted # Update the timeElapsed
if timeElapsed > 0: # If we have a recorded time
displayText = "Time Elapsed : %.3f" % timeElapsed # Display it to 3 decimal places
else: # Otherwise we are in a primed state
displayText = "Release to Start" # So display the "Release to Start" message
else: # Otherwise the timer is not ready
if timeElapsed == 0: # If we have no recorded time
displayText = "Press to Prime" # Display "Press to Prime"
if startButton.value() > 0: # If the start button is pressed down...
if not timerReady: # ...and we are not already ready
timerReady = True; # Set us to be ready
lcd.clear() # Clear the lcd screen
lcd.draw.rectangle((0,0,177,40), fill='black' ) # Draw a black rectangle as a background
lcd.draw.text((28,13),displayText, fill='white' ) # Draw our displayText in white on top
lcd.update() # Draw this all to the screen
|
9a6a6d0a1aff374b132bbef82dac50b60741e9db | KosuriLab/MFASS | /scripts/splicemod_src/src/entropy.py | 4,192 | 3.703125 | 4 | '''
A set of functions that computes the entropy, either shannon or kolmogorov, of
a string. The kolmogorov complexity is an approximation using zlip and shannon
was taken off of activestate and modified to use variable wordsizes.
@author: dbgoodman
'''
## {{{ http://code.activestate.com/recipes/577476/ (r1)
# Shannon Entropy of a string
# = minimum average number of bits per symbol
# required for encoding the string
#
# So the theoretical limit for data compression:
# Shannon Entropy of the string * string length
# FB - 201011291
import math
import sys
import zlib
import warnings
import random
import itertools
def shannon(st, wordsize=1):
#st = 'aabcddddefffg' # input string
# Shannon entropy for this would be 1 bit/symbol
#st = '00010101011110'
#print 'Input string:'
#print st
#print
wordsize = int(wordsize)
#print 'Word size:'
#print wordsize
#print
if wordsize == 1:
stList = list(st)
else:
stList = \
[st[i:i+wordsize] for i in range(0, len(st), wordsize)]
alphabet = list(set(stList)) # list of symbols in the string
#print 'Alphabet of symbols in the string:'
#print alphabet
#print
# calculate the frequency of each symbol in the string
freqList = []
for symbol in alphabet:
ctr = 0
for sym in stList:
if sym == symbol:
ctr += 1
freqList.append(float(ctr) / len(stList))
#print 'Frequencies of alphabet symbols:'
#print freqList
#print
# Shannon entropy
ent = 0.0
for freq in freqList:
ent = ent + freq * math.log(freq, 2)
ent = -ent
return ent
#print 'Shannon entropy:'
#print ent
#print 'Minimum number of bits required to encode each symbol:'
#print int(math.ceil(ent))
## end of http://code.activestate.com/recipes/577476/ }}}
def kolmogorov(st):
'''
use zlib.compress to approximate the kolmogorov score. the difference be-
-tween the compressed and original is 8 bytes, so we subtract that from the
compressed length. this approximation isn't valid for strings less than 5.
As it approaches 1, it means the string is incompressible (high entropy. As
it approaches 0, it means the string has very low entropy.
'''
if len(st) < 5:
warnings.warn('''Kolmogorov approximation is not valid for strings
smaller than len 5''')
l = float(len(st))
compr = zlib.compress(st)
c = float(len(compr)-8)
return c/l
def test_kolmogorov(seq_size= 10, seqs= 100, k='['+'0.25, '*4+']'):
k = eval(k)
k = map(int, k)
seq_size = int(seq_size)
seqs = int(seqs)
sample_space = ''.join(map(lambda a: a[0]*a[1], zip('ACGT',k)))
rand_sum = 0
repeat_sum = 0
for i in range(seqs):
rand_seq = ''.join([random.choice('AGTC')
for x in range(seq_size)])
rand_kol = kolmogorov(rand_seq)
#print 'Rand:\t{0}\t{1}'.format(rand_seq, rand_kol)
rand_sum = rand_sum + rand_kol
repeat_seq = ''.join([random.choice(sample_space)
for x in range(seq_size)])
repeat_kol = kolmogorov(repeat_seq[0:seq_size])
#print 'Rep:\t{0}\t{1}'.format(repeat_seq[0:seq_size], repeat_kol)
repeat_sum = repeat_sum + repeat_kol
rand_sum = rand_sum / seqs
repeat_sum = repeat_sum / seqs
#print 'avg kolmogorov entropy of random sequences: %f' % rand_sum
#print 'avg kolmogorov entropy of repeat sequences: %f' % repeat_sum
return (rand_sum,repeat_sum)
def test_kolmogorov_xy(start,end,step,k):
x = range(*map(int,[start,end,step]))
for length in x:
rand_sum,repeat_sum = test_kolmogorov(length,1000,k)
print '\t'.join(map(str,[length, rand_sum, repeat_sum]))
if __name__ == "__main__":
if sys.argv[1] in locals():
out = eval(sys.argv[1]+'(*sys.argv[2:])')
print out
else:
raise(ValueError('no function called %s' %sys.argv[1]))
|
f5ebc18d7b0b08a33a3555379a9b3ad585015392 | zlatnizmaj/Advanced_Algorithm | /Moj practice MIT 60001/Lecture codes/Dictionary02_python.py | 232 | 4.09375 | 4 | grades = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }
for s in grades: # print all keys of dictionary 'grades'
print("key '{}' have value: {}".format(s, grades[s]))
L = grades.values()
print(len(L))
print(grades.keys())
print(L)
|
75bfe42e7a0272b30380583d2849bab1757fc08e | fguedez1311/POO_Tecnologico | /producto.py | 727 | 3.6875 | 4 | class Producto:
def __init__(self,referencia,nombre,pvp,descripcion):
self.referencia=referencia
self.nombre=nombre
self.pvp=pvp
self.descripcion=descripcion
def __str__(self):
return """
Referencia \t {}
Nombre \t\t {}
pvp \t\t {}
Descripcion \t {} """.format(self.referencia,self.nombre,self.pvp,self.descripcion)
class Adorno(Producto):
pass
class Alimento(Producto):
productor=""
distribuidor=""
def __str__(self):
return super().__str() +"""
Productor \t {}
Distribuidor \t {}
""".format(self.productor,self.distribuidor)
al=Alimento(2034,"Botella de aceite de oliva",5,"250ml")
al.productor="La aceitera"
al.distribuidor="Distribuciones S.A"
print(al) |
4560fbd345e37e98f20a4cb55a2906a42913ea43 | adilsonfuta/Scripty-Python | /E1.py | 260 | 3.703125 | 4 | #n=int(input('Diga o valor'))
#print('O quadrado {}'.format(n**2))
#print('O Antecessor {} Sucessor {}'.format(n+1,n-1))
dist=int(input('Diga o valor Distancia'))
comb=int(input('Diga o valor Combustivel'))
print('O consumo Medio {}'.format(dist/comb))
|
873c9b4b813be1d6edece116d6abc9a4fe11ab0d | andrew10per/TFRRS-Web-Scraper | /Athlete.py | 632 | 4.0625 | 4 | '''
A Class that defines an athlete
Athlete holds a name string ( which can also include Class)
Athlete holds an array of events, and an array of times.
These array's should be passed in mathcing
Therefore if events[0] is a 5000, then times[0] should be a 5000 time.
Written by Andrew Perreault
Canisius College Computer Science Student
'''
class Athlete:
def __init__(self, name, events, times):
self.name = name
self.prs = {events[i]: times[i] for i in range(len(events))}
def printAthlete(self):
print(self.name)
#prints out event, and time to go with it.
print(self.prs)
|
6362b19e9c0e9edc3f5c4f5534d884ab6023c0fa | rsmbyk/computer-network | /socket-programming/tcp/code/tcp_client.py | 676 | 3.5625 | 4 | import socket
def main ():
buffer = 32
host = input ("Server IP: ")
port = 3000
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.connect ((host, port))
print ("Connected to", host, "on port", str (port))
print ("Format: [$number] [$operator] [$number]. Send 'exit' to stop program on client and server.\n")
while True:
msg = input ("Send : ")
sock.send (msg.encode ())
if msg.lower () == "exit":
break
response = sock.recv (buffer).decode ()
print ("Response:", response, "\n")
sock.close ()
print ("Program terminated.")
if __name__ == "__main__":
main ()
|
291478ae3d11ea71d3ab02a8a03bbb743e6b1846 | AkshayK25/File_handling | /Combination_file.py | 391 | 3.75 | 4 | with open('abc.txt') as fl1, open('test.txt') as fl2:
for line1, line2 in zip(fl1, fl2):
# line1 from abc.txt, line2 from test.txt
print(line1+line2)
print("\r")
def read_integers(filename):
with open(filename) as f:
numbers = [int(x) for x in f]
return numbers
print(read_integers("integer.txt"))
x = read_integers("integer.txt")
x.sort()
print(x) |
3d61f38ef21161da61f808360ab2b5e800e40609 | jaydenlsf/Python-Exercise | /qa-community-exercise/class.py | 396 | 3.53125 | 4 | class Students:
def __init__(self, name="student", age="student", class_name="student"):
self.name = name
self.age = age
self.class_name = class_name
def get_avg_score(self, *test_scores):
return sum(test_scores) / len(test_scores)
student_1 = Students("Jayden", 24, "DevOps")
print(student_1.name)
print(student_1.get_avg_score(20, 30, 20, 50, 60))
|
f0af6d805e3a63a126f699ec2aaae20e079eec94 | Kyle628/data-structures-python | /test_b_search_tree.py | 357 | 3.609375 | 4 | from binary_search_tree import tree_node
from binary_search_tree import binary_search_tree
my_node = tree_node('k', 'kyle')
'''my_node.right = tree_node('m', 'matias')
my_node.left = tree_node('g', 'giorgi')'''
my_tree = binary_search_tree()
my_tree.put("k", "kyle")
my_tree.put('g', 'giorgi')
my_tree.put('m', 'matias')
print my_tree.root.left.value
|
3ee118e8521e67959f087750172220ceafb48d6e | MathiasDarr/Algorithms | /python-algorithms/strings/palindrome/validPalindrome.py | 591 | 3.6875 | 4 | class Solution:
def validPalindrome(self,s):
def isPalindrome(left, right):
while left<right:
if s[left] != s[right]:
return False
left +=1
right -=1
return True
left =0
right = len(s) -1
while left<right:
if s[left] != s[right]:
return True if isPalindrome(left, right-1) or isPalindrome(left+1, right) else False
left+=1
right -=1
return True
solution = Solution()
solution.validPalindrome("abbca")
|
1ac77dbdcfd12e3438e2ba89ef48d6b79fc3d113 | li-black/bird | /players.py | 675 | 3.75 | 4 | players=['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
my_foods=['pizza','falafel','carrot cake']
firend_foods=my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite food are:")
print(firend_foods)
my_foods=['pizza','falafel','carrot cake']
firend_foods=my_foods[:]
my_foods.append('cannoli')
firend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite food are:")
print(firend_foods)
|
7297ca60e51b68cc074a4743296604bdb02325db | SouradeepSaha/DMOJ | /CCC/Huffman Encoding.py | 279 | 3.5 | 4 | k = int(input())
store = {}
for i in range(k):
k, v = input().split()
store[v] = k
text = input()
start, ans = 0, ''
for stop in range(1, len(text)+1):
word = text[start:stop]
if word in store.keys():
ans += store[word]
start = stop
print(ans)
|
16ed81e8e55511429afefbaff25bcc9e4a17f668 | st3fan/aoc | /2015/py/day12.py | 864 | 3.703125 | 4 | #!/usr/bin/env python3
import json
def sum_int_values1(o):
match o:
case int(i):
return i
case dict(d):
return sum(sum_int_values1(o) for o in d.values())
case list(l):
return sum(sum_int_values1(o) for o in l)
case _:
return 0
def sum_int_values2(o):
match o:
case int(i):
return i
case dict(d):
if "red" in d.values():
return 0
return sum(sum_int_values2(o) for o in d.values())
case list(l):
return sum(sum_int_values2(o) for o in l)
case _:
return 0
def main():
input = json.load(open("day12.input"))
print("Part one:", sum_int_values1(input))
print("Part two:", sum_int_values2(input))
if __name__ == "__main__":
main()
|
4b5d6d2f95bc9b0c0226e2c41aeda2e12c113984 | Munnu/interactivepython | /datastructures/trees/hb-tree-lecture/trees.py | 1,583 | 4.15625 | 4 | class Node(object):
""" Node in a tree. """
def __init__(self, data, children=None):
# children holds a list of Node types
children = children or [] # empty list if children is None
assert isinstance(children, list), \
"children must be a list!"
self.data = data
self.children = children
def __repr__(self):
""" reader-friendly representation. """
return "<Node %s>" % self.data
def find_dft(self, data):
""" Return node object with this data.
Start here. Return None if not found.
DFT (Depth-first Traversal) implementation
also uses the concept of a stack
"""
to_visit = [self]
while to_visit:
node = to_visit.pop() # small differences
if node.data == data:
return node
to_visit.extend(node.children)
def find_bft(self,data):
""" Return node object with this data.
BFT (Breadth-first Traversal) implementation
also uses the concept of a queue
"""
to_visit = [self]
while to_visit:
node = to_visit.pop(0) # small differences
if node.data == data:
return node
to_visit.extend(node.children)
# example of implementation
sharon = Node("Sharon")
sharon.children.append(Node("Angie"))
sharon.children.append(Node("Stefan"))
sharon.children
# another way to do this would be something like this
# sharon = Node("sharon", [ Node("Angie"), Node("Stefan")])
|
d624ec60efc2d65cd77987a28e2c3ab237882c4c | RayRuizheLi/onlineShoppingApplication | /product.py | 593 | 3.5625 | 4 | class Product:
# name: string, price: double, amount: int
def __init__(self, name, price, amount):
self.__name = name
self.__price = price
self.__amount = amount
def getName(self):
return self.__name
def getPrice(self):
return self.__price
def getAmount(self):
return self.__amount
# name: string
def setName(self, name):
self.__name = name
# price: double
def setPrice(self, price):
self.__price = price
# amount: int
def setAmount(self, amount):
self.__amount = amount |
2c218a8e2f07808e03d6a5cb1fe81c9ecb934a64 | timmy61109/Introduction-to-Programming-Using-Python | /own_practice/two_seven.py | 529 | 3.828125 | 4 | """
程式設計練習題 2.2-2.10 2.7 找出年數.
請撰寫一程式,提示使用者輸入分鐘數(例如十億),接著顯示相對應的年數與天數。假設一年365天。以下是
範例輸出樣本:
```
Enter a number of minutes:1000000000
1000000000 minutes is approximately 1902 years and 1000000000 days
```
"""
import ast
minutes = ast.literal_eval(input("Enter a number of minutes:"))
days = minutes // 1440
years = days // 365
print(minutes, "minutes is approximately", years, "years and", days, "days")
|
ba1dd5606a1c4c1425135f1b38bf9315f4811607 | rishavh/UW_python_class_demo.code | /chapter_17/a_Point_class_str_and_init_exercise_17_3.py | 501 | 4.21875 | 4 | #! /usr/bin/env python
#
# Exercise 17-3 Write a str method for the Point class. Create a Point object
# and print it.
#
class Point( object ):
"""A class which represents a point on a plane"""
def __init__ ( self, x, y ) :
"""A constructor for a point"""
self.x = x
self.y = y
def __str__ ( self ) :
"""Output a string representation of a Point object"""
return "["+str(self.x)+","+str(self.y)+"]"
p = Point(60,40)
s = str(p)
print s
print p
|
158bbc37a84fce5d498def8662466ba668d33999 | penroselearning/pystart_code_samples | /15 Combining Dictionaries with Lists - Vacation Favorites V1.py | 305 | 3.96875 | 4 | vacations = {'Vienna' : [2010,'Austria','Schönbrunn Palace', 'Apple Strudel']}
print(f'{"City":10} {"Year of Visit":13} {"Country":15} {"Favorite Spot":25} {"Favorite Food":25}')
print('-'*80)
for city,info in vacations.items():
print(f'{city:10} {info[0]:13} {info[1]:15} {info[2]:25} {info[3]:25}') |
b2e9e3ded41d7ee5fbcae4c13e05591cebfd4da9 | Grey-EightyPercent/Python-Learning | /ex15.py | 1,633 | 4.53125 | 5 | # Read files
# Using argv to read filename from users
#从sys module导入argv功能
from sys import argv
#利用argvuoqu用户输入它想要打开的文件名
script, filename = argv
# !!! Function: open (). Exp.: open(filename, mode ='r')
# mode = 'r' : open for reading
# mode = 'w' : open for writing, truncating the file first
# mode = 'x' : create a new file and open it for writing
# mode = 'a' : open for writing, appending to the end of the file if it exists
# mode = 'b' : binary Mode
# mode = 't' : text mode (default)
# mode = '+' : open a disk file for updating (reading and writing)
# Intact: open(filename, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
# 打开文件名为filename的文件,并把他赋值给txt变量
txt = open(filename)
#打印打开的文件名,并在字符串中插入变量
print(f"Here is your file {filename}:")
# 利用.read命令来读取变量txt的字符串
print(txt.read())
txt.close()
print(txt.read())
# Using input () to read filename
print("Type the filename again:")
#使用input 函数来让用户输入它想要打开的文件的名字,并把它赋值给变量
file_again = input(">")
#使用open 函数打开文件,赋值给变量
txt_again = open(file_again)
#读取txt_again的字符串内容,并打印
print(txt_again.read())
txt_again.close()
# Notes
# Step1: Using import argv or input() to understand which file the user want to open
# Steo2: Using open () to list the content of the file to a variable
# Step3: Using .read to read and display the content.
|
a5d9bc0017d97a2d530016b13ad68378f799d292 | leidyAguiar/exercicios-python-faculdade-modulo-1 | /2 lista_estrutura_de_decisao/exerc_018.py | 1,646 | 3.9375 | 4 | """
18. Faça um programa que receba o código correspondente ao cargo de um funcionário e seu salário atual e mostre o cargo, o valor do aumento e seu novo salário.
Os cargos estão na tabela a seguir.
CÓDIGO | CARGO | PERCENTUAL
1 | Escriturário | 50%
2 | Secretário | 35%
3 | Caixa | 20%
4 | Gerente | 10%
5 | Diretor | Não tem aumento
"""
cargo = float(input('Informe o seu código correspondente ao cargo: '))
salario = float(input('Informe seu salário atual: '))
if cargo == 1:
print('O seu cargo é o de Escriturário')
aumento = salario * 50 / 100
print('O valor do aumento é de:',aumento)
novo_sal = salario + aumento
print('O seu novo salário é:', novo_sal)
elif cargo == 2:
print('O seu cargo é o de Secretário')
aumento = salario * 35 / 100
print('O valor do aumento é de:', aumento)
novo_sal = salario + aumento
print('O seu novo salário é:', novo_sal)
elif cargo == 3:
print('O seu cargo é o de Caixa')
aumento = salario * 20 / 100
print('O valor do aumento é de:', aumento)
novo_sal = salario + aumento
print('O seu novo salário é:', novo_sal)
elif cargo == 4:
print('O seu cargo é o de Gerente')
aumento = salario * 10 / 100
print('O valor do aumento é de:', aumento)
novo_sal = salario + aumento
print('O seu novo salário é:', novo_sal)
elif cargo == 5:
print('O seu cargo é o de Diretor')
aumento = salario * 0 / 100
print('O valor do aumento é de:', aumento)
novo_sal = salario + aumento
print('O seu novo salário é:', novo_sal) |
88747b706b8cfabf220402899543fb2a972520fa | ibrahim2204/main | /main.py | 63 | 3.5625 | 4 | print("Hello World")
a=input("type the value of a: ")
print(a)
|
6729b75c316587702a74279e93ea92f83b11a570 | qram9/c_ast | /c_ast/hir/FloatLiteral.py | 1,853 | 3.671875 | 4 | from hir.Literal import Literal
class InvalidTypeFloatLiteralError(Exception):
def __init__(self, value):
self.value = value
def __repr__(self):
return 'Invalid type: (%s) for integer literal, expected: (%s)' % (value, str(type(int)))
class FloatLiteral(Literal):
"""Represents a Float literal lexical token.
Subclasses Literal type. Sets the given character
value to a __slots__ entry 'value'."""
__slots__ = ['value']
def __init__(self, value):
"""Initializes a Ansi C Float Literal object. Tests
if given character is of type python <float>. Sets the
__slots__.value parameter"""
if not isinstance(value, float):
raise InvalidTypeFloatLiteralError(str(type(value)))
self.initialize()
Literal.__init__(self)
self.value = value
def __repr__(self):
return str(self.value)
__str__ = __repr__
def items(self):
"""Returns items dict when called from hir.etstate.
Adds __slots__ entry "value" to items dict.
Recurses into base classes and collects items from hir.here too."""
items = {}
items['value'] = self.value
for k in FloatLiteral.__bases__:
if hasattr(k, 'items'):
supitems = k.items(self)
for k, v in list(supitems.items()):
items[k] = v
return dict(items)
def __getstate__(self):
"""Returns current state for 'pickling' or 'copy'.
Adds __slots__ entry "value" to items dict."""
return dict(self.items())
def __setstate__(self, statedict):
"""Blindly sets state from hir. given statedict"""
for k, v in list(statedict.items()):
setattr(self, k, v)
def FloatLiteralTest():
l = FloatLiteral(1.25)
return l
if __name__ == '__main__':
print(FloatLiteralTest())
|
6fee6347689b3cec842e9cdca4c3ffb197df97aa | tanyastropheus/holbertonschool-higher_level_programming | /0x05-python-exceptions/0-safe_print_list.py | 315 | 3.875 | 4 | #!/usr/bin/python3
def safe_print_list(my_list=[], x=0):
count = 0
try:
for i in my_list[0:x]: # slicing the list
print("{}".format(i), end="")
count = count + 1
print()
except IndexError:
pass # code after pass will still get executed
return count
|
cd5748d4289d285d7a9196c5ffa1480954cb27ea | oscarDelgadillo/AT05_API_Test_Python_Behave | /FrancoAldunate/Practice1.py | 2,339 | 4.28125 | 4 | #Excercises from slides
print(type(1))
print(type("Test"))
print(type(0.2))
Message = "String test"
print(type(Message))
n = 1000
print(type(n))
pi = 3.1416
print(type(pi))
some_variable_really_long_is_accepted = "Any_value"
print(some_variable_really_long_is_accepted)
some123_variable = 1
print(some123_variable)
help("keywords")
#Practice Arithmetic's operators
#Create a new python script to :
# -Assign values to variables with long names and combining letters with numbers
print("Practice 1: Arithmetic's operators")
print("1. Assign values to variables with long names and combining letters with numbers")
result_of_concatenation_of_2_strings = "String1" + "String2"
print("Variable: result_of_concatenation_of_2_strings = ", result_of_concatenation_of_2_strings)
result_of_multiply_2_numbers_2_times = (7*77) * (7*77)
print("Variable: result_of_multiply_2_numbers_2_times = ", result_of_multiply_2_numbers_2_times)
result_of_22222_to_the_1000_power = 22222**1000
print("Variable: result_of_22222_to_the_1000_power = ", result_of_22222_to_the_1000_power)
print()
# -Perform arithmetic operations using all operators
print("2. Perform arithmetic operations using all operators")
#Addition
def add(a,b):
print(f"Addition of: a = {a} + b = {b}")
return "Result = ",a + b
print(add(7,14))
#Substraction
def sub(a,b):
print(f"Substraction of: a = {a} - b = {b}")
return "Result = ",a - b
print(sub(77,144))
#Multiplication
def multiply(a,b):
print(f"Multiplication of: a = {a} x b = {b}")
return "Result = ",a * b
print(multiply(7,-14))
#Quotient
def div(a,b):
print(f"Quotient of: a = {a} / b = {b}")
return "Result = ",a / b
print(div(7.55,14.99))
#Quotient with floor division
def div(a,b):
print(f"Quotient with floor division of: a = {a} // b = {b}")
return "Result = ",a // b
print(div(80,7))
#Modulus
def mod(a,b):
print(f"a = {a} modulus b = {b}")
return "Result = ",a % b
print(mod(100,3))
#Exponent or Power: where a is base and b is the power
def pow(a,b):
print(f"Base a = {a}, to Power b = {b}")
return "Result = ",a ** b
print(pow(77,777))
#Combination of operators
def percentageof(percentage_input,total):
print(f"Percentage = {percentage_input}, Total = {total}")
return "Result = ",total * percentage_input / 100
print(percentageof(7,5777)) |
dcca07f8763ec798aa5289f392f38005f3a060df | vangaru/labs | /DM labs/lab1/test.py | 500 | 3.78125 | 4 | def partition(collection):
if len(collection) == 1:
yield [ collection ]
return
first = collection[0]
for smaller in partition(collection[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
yield smaller[:n] + [[ first ] + subset] + smaller[n+1:]
# put `first` in its own subset
yield [[ first ]] + smaller
something = [1, 6, 5, 7]
for n in partition(something):
print(n)
|
f6119266d63e9d4aba162224f96ab9b97c07dc9b | maciekgajewski/the-snake-and-the-turtle | /examples/tdemo_geometry/tdemo_illusion_2.py | 805 | 4 | 4 | """ turtle-example-suite:
tdemo_illusion_2.py
A simple drawing suitable as a beginner's
programming example.
Diagonals moving away from the center create
an illusion of depth, which makes the parallel
horizontal lines seem to bend in the center.
Inspired by NetLogo's model of optical
illusions.
"""
from qturtle import *
tracer(False)
ht()
speed(0)
pensize(2)
lt(90)
for i in range(30):
pu()
bk(500)
pd()
fd(1000)
pu()
bk(500)
lt(6)
dot(60)
pensize(16)
fd(53)
rt(90)
bk(400)
pd()
fd(800)
pu()
bk(400)
lt(90)
bk(106)
rt(90)
bk(400)
pd()
fd(800)
pu()
bk(400)
lt(90)
fd(330)
pencolor("red")
write("Are the thick lines parallel?",
align="center",
font=("Courier",24,"bold"))
tracer(True)
print("DONE!")
mainloop()
|
fc499018a1d30890237b5b8aa2f8cef6dcee475b | MaxPoon/EEE-Club-Python-Workshop | /syntax/1_beginning_with_python/4_input.py | 176 | 3.890625 | 4 | x = input("enter an integer: ")
# x = x + 1
# this will cause an error
x = int(x)
x = x + 1
print(x,'\n')
x = input("enter a float number")
print(x)
x = float(x)
print(x+1) |
e7cd2eff9cfdfb5de86ecaca7bd7cc9e541dd1c8 | sinoop/100DaysOfCode | /day019/turtle_race.py | 1,929 | 4 | 4 | import json
import random
from turtle import Turtle, Screen
TURTLE_HEIGHT = 40
TURTLE_WIDTH = 40
class TurtleObject:
def __init__(self, color, name, start_x, start_y, max_x):
self.turtle = Turtle()
self.turtle.penup()
self.turtle.color(color)
self.turtle_name = name
self.turtle.setx(start_x)
self.turtle.sety(start_y)
self.turtle.shape("turtle")
self.max_x = max_x
def move_forward(self):
self.turtle.forward(random.randint(0, 20))
if self.turtle.xcor() + TURTLE_WIDTH >= self.max_x:
return False
return True
# number_of_turtles = input()
s = Screen()
num_turtles_entered = s.numinput(
title="NUM",
prompt="Enter Number of Turtles in race : ",
default=2
)
num_turtles = 2 if num_turtles_entered is None else int(num_turtles_entered)
s.setup(width=400, height=(num_turtles * TURTLE_HEIGHT * 2) + (2 * TURTLE_HEIGHT))
MIN_X = (-1 * s.window_width() / 2) + TURTLE_WIDTH
MIN_Y = (-1 * s.window_height() / 2) + TURTLE_HEIGHT
MAX_X = s.window_width() / 2
start_x = MIN_X
start_y = MIN_Y
with open("colors.json", "r") as f:
json_colors = json.load(f)
is_race_on = False
turtle_list = []
random_list = random.sample(range(0, len(json_colors)), len(json_colors))
for i in range(1, num_turtles):
random_color = json_colors[str(random_list[i])]
turtle_list.append(TurtleObject(color=random_color["hex"],
name=random_color["name"],
start_x=start_x,
start_y=start_y,
max_x=MAX_X)
)
start_y += (TURTLE_HEIGHT * 2)
is_race_on = True
random_turtle = None
while is_race_on:
random_turtle = random.choice(turtle_list)
is_race_on = random_turtle.move_forward()
print(f"{random_turtle.turtle_name} won")
s.exitonclick()
|
648e6d836e3992fcb0a2c7898888bb517cdb2155 | tychonievich/cs1110s2017 | /markdown/files/001/2017-02-17-fundamental_truthiness.py | 412 | 4.03125 | 4 | if 'cheese':
print('yum')
else:
print('I want cheese')
# All things have truthiness
# nothing is false
print(bool(1), bool(-12), bool(0), bool('hi'), bool(''))
def working_age2(age):
if 14 <= age < 70:
return 'True'
else:
return 'False'
age = int(input('How old are you? '))
if working_age2(age):
print("why aren't you at work?")
else:
print('enjoy loafing at home')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.