blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
f288de052e519ef807d5d1746be8ab6521a3a94a
erick-guerra/python-oop-learning
/Python Beyond the Basics - Object-Oriented Programming - Working Files/Chapter 5/3_attr_encps.py
716
3.765625
4
# Example of breaking encapsulation class MyClass(object): pass x = MyClass() print(x) x.one = 1 # here's the break x.two = 2 # and here x.word = "String'o text!" # here 2 print(x.one) class GetSet(object): def __init__(self, value): self.attrval = value @property def var(self): print("Getting a value") return self.attrval @var.setter def var(self, value): print("Setting a value") self.attrval = value @var.deleter def var(self): print("Deleting var attribute") self.attrval = None me = GetSet(5) print("The value after first init of inst is {}".format(me.var)) me.var = 1000 print("Value added, now is {}".format(me.var)) del me.var print("Value removed, now is {}".format(me.var))
676d403aa4a5ec9a9e5fd811c0c3e621945a3f9c
AANICK007/STEPPING_IN_PYTHON_WORLD
/programme_24.py
241
4.09375
4
# Python script to print first 10 odd numbers x = 0 while ( x <= 9 ) : print ( 2*x + 1 ) ; x += 1 ; # Python script to print first 10 even numbers x = 0 while ( x <= 9 ) : print ( 2*x ) ; x += 1 ;
f1281609ae4f3fd410f54ce240b71a435f830db7
AANICK007/STEPPING_IN_PYTHON_WORLD
/programme_1.py
427
4.03125
4
# This is a programme to show that variables are dynamically typed in python x = 5 ; print ( type ( x ) ) ; x = 5.456 ; print ( type ( x ) ) ; x = " hello " ; print ( type ( x ) ) ; # To print value of x x = 234 ; print ( x ) ; # To print Id of variable x= 3 ; print ( id ( x ) ) ; # memory allocation in python is basede on reference concept y = x ; print ( id ( y ) ) ; y = 2 ; print ( id ( y ) ) ; print ( id ( x ) ) ;
d0c28518a33bf41c9945d97690e3891eeba277ad
AANICK007/STEPPING_IN_PYTHON_WORLD
/programme_8.py
413
4.53125
5
# This is a programme to study bitwise operators in python x =5 & 6 ; # this is and operator between bit numbers of 5 and 6 print ( x ) ; x = 5 | 6 ; print ( x ) ; # this is or operator between bit numbers of 5 and 6 x = ~ 5 ; print ( x ) ; # this is not operator x = 5 ^ 6 ; print ( x ) ; # this is xor operator between bit numbers of 5 and 6 x = 99 >> 2 ; print ( x ) ; x = 5 << 3 ; print ( x ) ;
2721fbbb1574a93cfb9418a971135cf308254a8d
RobertoCalvi29/INF8225_TP1
/TP1/side_functions.py
2,323
3.546875
4
import numpy as np def softmax(x: np.ndarray) -> np.array: """ :param x: Takes in the training data wich is a vector of 1XL :return: Returns normalized probability distribution consisting of probabilities proportional to the exponentials of the input numbers. Vector of size """ e_x = np.exp(x - max(x)) return e_x / e_x.sum(0) def get_accuracy(X: np.ndarray, y: np.ndarray, W: np.ndarray) -> int: """ Definition of accuracy: proportion of nb_examples for witch the model produces the correct output. :param X: Matrice of inputs :param y: Matrice of outputs :param W: matrcie of Weight :return: """ good_guess = 0 bad_guess = 0 for img, correct in zip(X, y): y_pred = softmax(W.dot(img)) pred = np.argmax(y_pred) if (correct[pred] == 1): good_guess += 1 else: bad_guess += 1 # print('#good = {}'.format(good_guess)) # print('#bad = {}'.format(bad_guess)) # print("................") return good_guess / (bad_guess + good_guess) * 100 def get_grads(y: np.ndarray, y_pred: np.ndarray, X: np.ndarray) -> int: """ Inner product :param y: :param y_pred: softmax de x is a matrix :param X: :return: """ delta = y - y_pred return np.outer(delta, X) def get_loss(y: np.ndarray, y_pred: np.ndarray) -> int: """ :param y: Is a vector of dimension 1XK :param y_pred: Is a vector of dimension 1XK :return: The loss witch is an int """ return -np.dot(y, np.log(y_pred)) def update_moment(m, v, grad, beta_1, beta_2): m = beta_1 * m + (1 - beta_1) * grad v = beta_2 * v + (1 - beta_2) * grad ** 2 return m, v def compute_bias(m, v, t, beta_1, beta_2): hat_m = m / (1 - beta_1 ** t) hat_v = v / (1 - beta_2 ** t) return hat_m, hat_v def generate_minibatchs(X_train: np.array, y_train, minibatch_size: int) -> [range, np.array, np.array, int]: batches = range(0, X_train.shape[0], minibatch_size) nb_of_batch = X_train.shape[0] // minibatch_size nb_examples = X_train.shape[0] // nb_of_batch X_train = [X_train[i:i + minibatch_size, :] for i in batches] y_train = [y_train[i:i + minibatch_size, :] for i in batches] return batches, X_train, y_train, nb_examples
49d248849cbac1bcdd8329c0b6018fe7eae068d4
marvjaramillo/ulima-intro210-clases
/s037-nota01/p01.py
438
3.734375
4
def main(): codigo = int(input("Ingrese codigo de moneda: ")) monto = int(input("Ingrese monto: ")) res = None if(codigo == 1): res = 3.64 * monto elif(codigo == 2): res = 4.42 * monto elif(codigo == 3): res = 0.57 * monto if(res != None): print("Monto equivalente en soles:", res) else: print("Codigo de moneda invalido") if __name__ == "__main__": main()
0a2c9b55958fe6ad14e3d79923f56c3861ae22b9
marvjaramillo/ulima-intro210-clases
/s052-guia07/p03.py
272
4
4
#Leer 10 valores enteros n = 10 #Definimos una lista en blanco lista = [] for i in range(n): valor = int(input("Ingrese numero: ")) #Almacenar en una lista lista.append(valor) print(lista) #Revertir la lista lista.reverse() #Mostrar elementos print(lista)
208c592758bf6544f9cbeacae5d301552e39ac16
marvjaramillo/ulima-intro210-clases
/s032-guia03/p16.py
346
3.78125
4
def main(): A = int(input("Ingrese el valor de A: ")) B = int(input("Ingrese el valor de B: ")) C = int(input("Ingrese el valor de C: ")) S = 0 if(A / B > 30): S = (A / C) * B ** 3 else: for i in range(2, 31, 2): S = S + i ** 2 print("Valor de S:", S) if __name__ == "__main__": main()
7e8d7097f1648905c8b229d1ec854e4afd1e0cf3
marvjaramillo/ulima-intro210-clases
/s034-guia04/p01.py
401
3.75
4
def mayor(a, b): if(a > b): return a else: return b def mayor3(a, b, c): mayor_ab = mayor(a, b) res = mayor(mayor_ab, c) n = 30 if n % 2 != 0 and n % 3 != 0 and n % 5 != 0: print("z") return res def main(): n1 = 127 n2 = 156 n3 = 77 res = mayor3(n1, n2, n3) print("El mayor es: ", res) if __name__ == "__main__": main()
5a1e59a9c6fb569a22357aeabb61952d112f9e98
marvjaramillo/ulima-intro210-clases
/s021-selectivas/selectiva.py
713
4.28125
4
''' Implemente un programa que lea la calificacion de un alumno y su cantidad de participaciones. Si la cantidad de participaciones es mayor que 10, entonces recibe un punto de bonificacion. Su programa debe mostrar en pantalla la nota final ''' def main(): nota = int(input("Ingrese nota: ")) participaciones = int(input("Ingrese participaciones: ")) #Si la cantidad de participaciones es mayor que 10 if(participaciones > 10): #Incremento la nota en 1 print("Felicidades, tiene un punto de bonificacion") nota = nota + 1 else: print("Lamentablemente no tiene bonificacion") print("Nota final:", nota) if __name__ == "__main__": main()
dc956d22d43c40b4d3ae37c48dd48fe77a72db0e
marvjaramillo/ulima-intro210-clases
/s022-guia02/p01.py
359
3.859375
4
def main(): monto = float(input("Ingrese monto gastado: ")) if(monto < 0): print("Valor del monto es incorrecto") elif(monto <= 100): print("Pago con dinero en efectivo") elif(monto < 300): print("Pago con tarjeta de debito") else: print("Pago con tarjeta de credito") if __name__ == "__main__": main()
9c5b7a1bd84930d40ddc9d7b3f43fb5f201c77ce
marvjaramillo/ulima-intro210-clases
/s073-guia10/ordenamiento.py
750
3.796875
4
def burbuja(lista): for i in range(len(lista) - 1): for j in range(len(lista) - 1 - i): if(lista[j] > lista[j + 1]): #lista[j], lista[j + 1] = lista[j + 1], lista[j] aux = lista[j + 1] lista[j + 1] = lista[j] lista[j] = aux def quicksort(lista): if(len(lista) <= 1): return lista else: pivot = lista[0] menores = [] mayores = [] for i in range(1, len(lista)): if(lista[i] > pivot): mayores.append(lista[i]) else: menores.append(lista[i]) mayores = quicksort(mayores) menores = quicksort(menores) return menores + [pivot] + mayores
69b77563ddc8412aae3112b23ad7acba907e1c36
marvjaramillo/ulima-intro210-clases
/s022-guia02/p10.py
530
3.890625
4
tiempo_h = int(input("Ingrese cantidad de horas de estacionamiento: ")) tiempo_min = int(input("Ingrese cantidad de minutos de estacionamiento: ")) #Si se estaciono menos de una hora >> no se paga estacionamiento if(tiempo_h == 0): print("No tiene que pagar estacionamiento") else: #Si hay minutos (fraccion de hora) >> paga la hora completa if(tiempo_min > 0): tiempo_h = tiempo_h + 1 #Pagar por las horas de estacionamiento monto = 2.5 * tiempo_h print("El monto por estacionamiento es:", monto)
ea6afdaa2f4ba4e97c3f4db0a4cec3926107bde0
marvjaramillo/ulima-intro210-clases
/s073-guia10/p03.py
529
4.09375
4
import ordenamiento as ord def leer_pesos(): continuar = True lista = [] suma = 0 while(continuar == True): peso = int(input("Ingrese peso: ")) if(peso <= 0): continuar = False else: lista.append(peso) suma = suma + peso lista.append(suma // len(lista)) return lista if __name__ == "__main__": lista = leer_pesos() lista_ordenada = ord.quicksort(lista) print("Lista original: ", lista) print("Lista ordenada: ", lista_ordenada)
2a5f44807795975b2d7d392a2295811399606980
marvjaramillo/ulima-intro210-clases
/s036-guia05/p06.1.py
711
4.375
4
''' Estrategia: 1) Leemos el valor como cadena (con el punto decimal) 2) LLamamos a una funcion para quitar el punto decimal 3) aplicamos la funcion que maneja enteros para hallar la suma de digitos ''' import p06 def convertir(numero): res = "" #Convertimos a cadena para procesarlo numero = str(numero) for caracter in numero: if(caracter != "."): res = res + caracter #Convertimos la respuesta a entero return int(res) def main(): n = 49.89343 print("Numero original:", n) n = convertir(n) print("Numero convertido:", n) suma_cifras = p06.suma_cifras(n) print("Suma de cifras:", suma_cifras) if __name__ == "__main__": main()
1576cf4c297cdd063c684edbecb86405efbb3290
marvjaramillo/ulima-intro210-clases
/s031-repetitivas/ejemplo2.py
519
3.890625
4
''' Implemente un programa que reciba un numero "n" y calcule la cantidad de sus divisores. Ejemplo: 4 --> 1, 2, 4 Podemos decir que 4 tiene 3 divisores ''' def main(): n = int(input("Ingrese numero: ")) cantidad = 0 for i in range(1, n + 1): #[1, n + 1>: 1, 2, 3, 4, ...., n #Buscamos divisores: "i" es divisor de "n" si el residuo de la division es cero if(n % i == 0): cantidad = cantidad + 1 print("Cantidad de divisores:", cantidad) if __name__ == "__main__": main()
31f9b34ad89fdaafb0f232c5783a35fc811a1d70
marvjaramillo/ulima-intro210-clases
/s054-guia08/p08.py
1,030
4.25
4
''' Formato de los datos (ambos son cadenas): - clave: termino - valor: definicion del termino Ejemplo: glosario = {"termino1": "El termino1 es <definicion>"} ''' #Lee los valores del usuario y crea el diccionario def leer_glosario(): res = {} #Leemos la cantidad de terminos n = int(input("Ingrese la cantidad de terminos: ")) for i in range(n): #Por cada uno, leemos el termino y su definicion termino = input("Ingrese termino del glosario: ") definicion = input("Ingrese su definicion: ") #Agregamos elemento al diccionario res[termino] = definicion return res #Muestra los valores del glosario def mostrar_glosario(dic_glosario): lista_terminos = dic_glosario.keys() for termino in lista_terminos: print("*" * 30) print("Termino:", termino) print("Definicion:", dic_glosario[termino]) print("*" * 30) if __name__ == "__main__": dic_glosario = leer_glosario() mostrar_glosario(dic_glosario)
1a783d36b4b720fb7e1343cdb3e5e5ed6a31cbe0
ElliotB1996/Sandbox
/oddName.py
173
4.28125
4
"""Elliot Blair""" name = input("What is your name?") while name == "" or name == " ": print("Name must not be blank") name = input("What is your name?") print(name)
9d9535c059e5418c442a864834247c42ab33d6fd
dawnblade97/hackerrank_solution
/p54.py
222
3.78125
4
s=input() st=[] for i in s: if not st: st.append(i) else: if st[-1]==i: st.pop() else: st.append(i) if not st: print("Empty String") else: print(''.join(st))
ab80047e3563b43d3afe43fb38357cd17b78f8c0
Pranay-Tyagi/Assignment-5-extra
/main.py
143
4.0625
4
d = int(input('Diameter: ')) r = d/2 area = 3.14 * (r * r) circumference = 2 * 3.14 * r print(f'Area: {area}, Circumference: {circumference}')
a59e65391268d422fac1e4295f371cc44a46078f
utopik21/python
/apps/schools/schools.py
558
3.515625
4
import pandas as pd # CRITERES : # Taux Réussite Attendu France Total séries # Taux_Mention_attendu_toutes_series def get_datas_from_schools_csv(file_path): data_frame = pd.read_csv(file_path, low_memory=False, sep=';', skipinitialspace=False, usecols=['Code commune','Taux Brut de Réussite Total séries','Taux_Mention_brut_toutes_series']) print(data_frame.columns.tolist()) return data_frame def merge_row_by_insee_code(data_frame): data_frame_grouped = data_frame.groupby(['Code commune']).mean() return data_frame_grouped
693a5d23927283544290f339c9259b628f10657d
marycamila184/mastersdegree
/Inteligencia Artificial/Exercicios/Busca Classica/Sokoban/SokobanV3/pkg/cardinal.py
667
4
4
"""Pontos cardeais: o agente se movimenta em uma direção apontada por um dos pontos cardeais. São utilizados como parâmetros da ação ir(ponto)""" N = 0 L = 1 S = 2 O = 3 # Strings que correspondem as ações action = ["N","L","S","O"] # Incrementos na linha causado por cada ação # Exemplo: rowIncrement[0] = rowIncrement[N] = -1 (ao ir para o Norte a linha é decrementada) rowIncrement = [-1,0,1,0] # Incrementos na coluna causado por cada ação # Exemplo: colIncrement[0] = colIncrement[N] = 0 (ao ir para o Norte a coluna não é alterada) # colIncrement[2] = colIncrement[L] = 1 (ao ir para o Leste a coluna é incrementada) colIncrement = [0,1,0,-1]
28677fcdd42887c6d633ef50a26f289fbb4d938f
marycamila184/mastersdegree
/Inteligencia Artificial/Exercicios/Busca Classica/Sokoban/SokobanV3/pkg/tree.py
1,604
3.9375
4
from state import State class TreeNode: """Implementa nó de árvore de busca.""" def __init__(self, parent): """Construtor do nó. @param parent: pai do nó construído.""" self.parent = parent self.state = None # estado self.gn = -1 # g(n) custo acumulado até o nó self.hn = -1 # h(n) heurística a partir do nó self.depth = 0 # armazena a profundidade do nó self.children = [] self.action = -1 # ação que levou ao estado def setGnHn(self, gn, hn): """Atribui valores aos atributos gn e hn. @param gn: representa o custo acumulado da raiz até o nó. @param hn: representa o valor da heurística do nó até o objetivo.""" self.gn = gn self.hn = hn def getFn(self): """Retorna o valor da função de avaliação f(n)""" return self.gn + self.hn def addChild(self): """Este método instância um nó de self e cria uma associação entre o pai(self) e o filho. @return O nó filho instânciado.""" child = TreeNode(self) child.depth = self.depth + 1 self.children.append(child) return child def remove(self): """Remove-se da árvore cortando a ligação com o nó pai.""" removed = self.parent.children.remove(self) if not removed: print("### Erro na remoção do nó: {}".format(self)) def __str__(self): return "<{0} g:{1:.2f} h:{2:.2f} f:{3:.2f}>".format(self.state, self.gn, self.hn, self.getFn())
b99adcd7c27f9c7656cb58f4f207470465430e4f
alu-rwa-dsa/week-3---dynamic-array-achille_mageza_kidus-dsa-cohort2
/main.py
1,585
3.9375
4
class array: def __init__(self, array=None): if array is None: array = [5, 4, 6, 8, 10, 11,34] self.array = array # Space complexity and Time complexity is O(1) def length(self): print(len(self.array)) # Space complexity and Time complexity is O(1) # specification of item in our list def get_value(self): for n, i in enumerate(self.array): if i == 1: print(self.array[n]) # Spatial Competitiveness: in the top code, the function allows you to search for an element in a # list containing integers and scrolls through the list to determine the requested element. # The algorithm forms a kind of memory for a new element and the elements of the list. # then the space of the alogorithm becomes O(n) def replace(self): for n, i in enumerate(self.array): if i == 4: self.array[n] = 3 return self.array # subclass is simple class inherit class var(array): def __init__(self, array=None): super().__init__(array=[5, 4, 6, 8, 10, 11,34]) if array is None: array = [5, 4, 6, 8, 10, 11,34] # Space complexity and Time complexity is O(1) # this method add an item in list def Add_list(self): self.array.append(1111) print(self.array) # Space complexity and Time complexity is O(1) # this method delete an item from our list def deleted_list(self): del self.array[2:5] print(self.array) length_array = var() length_array.Add_list() length_array.deleted_list()
9bd6657961e1bfb002f4ffc291e534dc2c5ba85d
AleenaVarghese/myrepo
/Aleena/python/set1'/9.py
346
3.859375
4
fname = "demo.docx" num_lines = 0 num_words = 0 num_chars = 0 with open(fname, 'r') as f: for line in f: words = line.split() num_lines += 1 num_words += len(words) num_chars += len(line) print("number of lines :", num_lines) print("Number of Words :", num_words) print("Number of Charactors :", num_chars)
65a9d39583c9254920f32899cc676d970acde6a2
MikeJaras/learningGit
/main.py
272
3.71875
4
def main(): a = "ABC" b = "123" # for idx, t in enumerate(a): # print(t) # print(idx) # for t in a, b: # print(t) for p in range(len(a)): print(a[p]) print(b[p]) if __name__ == '__main__': main()
4cc7f64ce04d2b71b5ec9d7386a995a0a9f12f2f
yoavxyoav/CodeWars
/rice_chess.py
240
3.59375
4
# https://en.wikipedia.org/wiki/Wheat_and_chessboard_problem def squares_needed(grains): if grains == 0: return 0 square = 0 while grains > 0: grains -= 2**square square += 1 return square
b2b55975afedb5533801cdbe05df0b23ade308e1
shamilsons/Bioinformatics_Course_Codes
/seqCond.py
1,067
3.65625
4
from string import * from random import * def main(): seqBio1="ATTTGGCCCNNTTAAATGTTTTNAAAAGGNCCATGCN" seqBio2="ACGAUGUCCGGCCCNNAGUGNGCAAUAAGCC" seqSet=[seqBio1,seqBio2] rdnnum=randint(0,1) print "Random number:",rdnnum if 'U' in seqSet[rdnnum]: print "This is an RNA sequence" print "Number of Ns in SeqBio1",count(seqBio1,'N') print "Number of Ns in SeqBio2",count(seqBio2,'N') if count(seqBio1,'N')==count(seqBio2,'N'): print "Number of Ns are equal" elif count(seqBio1,'N')>count(seqBio2,'N'): print "SeqBio1 has more Ns" else: print "SeqBio2 has more Ns" else: print "This is DNA sequence" print "Seq1 len:",len(seqBio1) print "Seq2 len:",len(seqBio2) if len(seqBio1)==len(seqBio2): print "Seq 1 and Seq2 are equal in length" elif len(seqBio1)<len(seqBio2): print "Seq 1 is smaller than Seq2 in length" else: print "Seq 1 is bigger than Seq2 in length" main()
fdc2365c04257d6e5764819cb4ca6e2a30479c80
Mattias-/interview_bootcamp
/python/interviewstreet/palantir_sample/anagrams.py
399
3.703125
4
import sys def main(): s1 = sys.stdin.readline().rstrip() s2 = sys.stdin.readline().rstrip() if anagrams(s1, s2): print 'Anagrams!' else: print 'Not anagrams!' def anagrams(s1, s2): li = list(s1) for c in s2: if c in li: li.remove(c) else: return False return len(li) == 0 if __name__ == '__main__': main()
99e3a484814475a5ccc0627f5d875507a5213b0c
Mattias-/interview_bootcamp
/python/fizzbuzz.py
520
4.15625
4
# Using any language you want (even pseudocode), write a program or subroutine # that prints the numbers from 1 to 100, each number on a line, except for every # third number write "fizz", for every fifth number write "buzz", and if a # number is divisible by both 3 and 5 write "fizzbuzz". def fb(): for i in xrange(1, 100): s = "" if i % 3 == 0: s = "fizz" if i % 5 == 0: s += "buzz" if not s: print i else: print s fb()
a4440c01382cb80da816a637cda9e5866477e72b
victormmp/CodeCademyLearning
/Python/class.py
6,868
4.6875
5
""" LEARNNG CLASSES As mentioned, you can think of __init__() as the method that "boots up" a class' instance object: the init bit is short for "initialize." The first argument __init__() gets is used to refer to the instance object, and by convention, that argument is called self. If you add additional arguments—for instance, a name and age for your animal—setting each of those equal to self.name and self.age in the body of __init__() will make it so that when you create an instance object of your Animal class, you need to give each instance a name and an age, and those will be associated with the particular instance you create. SCOPE Another important aspect of Python classes is scope. The scope of a variable is the context in which it's visible to the program. It may surprise you to learn that not all variables are accessible to all parts of a Python program at all times. When dealing with classes, you can have variables that are available everywhere (global variables), variables that are only available to members of a certain class (member variables), and variables that are only available to particular instances of a class (instance variables). The same goes for functions: some are available everywhere, some are only available to members of a certain class, and still others are only available to particular instance objects. """ # Class definition class Animal(object): """Makes cute animals.""" # For initializing our instance objects is_alive = True def __init__(self, name, age, hungry): self.name = name self.age = age self.is_hungry = hungry def description(self): """description of the animal""" print self.name print self.age # Note that self is only used in the __init__() # function definition; we don't need to pass it # to our instance objects. zebra = Animal("Jeffrey", 2, True) giraffe = Animal("Bruce", 1, False) panda = Animal("Chad", 7, True) hippo = Animal("Joe", 12, False) print zebra.name, zebra.age, zebra.is_hungry, zebra.is_alive print giraffe.name, giraffe.age, giraffe.is_hungry, giraffe.is_alive print panda.name, panda.age, panda.is_hungry, panda.is_alive hippo.description() class ShoppingCart(object): """Creates shopping cart objects for users of our fine website.""" items_in_cart = {} def __init__(self, customer_name): self.customer_name = customer_name def add_item(self, product, price): """Add product to the cart.""" if not product in self.items_in_cart: self.items_in_cart[product] = price print product + " added." else: print product + " is already in the cart." def remove_item(self, product): """Remove product from the cart.""" if product in self.items_in_cart: del self.items_in_cart[product] print product + " removed." else: print product + " is not in the cart." my_cart = ShoppingCart("Joe") my_cart.add_item("Viagra", 10) """ INHERITANCE Inheritance is the process by which one class takes on the attributes and methods of another, and it's used to express an is-a relationship. For example, a Panda is a bear, so a Panda class could inherit from a Bear class. However, a Toyota is not a Tractor, so it shouldn't inherit from the Tractor class (even if they have a lot of attributes and methods in common). Instead, both Toyota and Tractor could ultimately inherit from the same Vehicle class. """ class Customer(object): """Produces objects that represent customers.""" def __init__(self, customer_id): self.customer_id = customer_id def display_cart(self): print "I'm a string that stands in for the contents of your shopping cart!" class ReturningCustomer(Customer): """For customers of the repeat variety.""" def display_order_history(self): print "I'm a string that stands in for your order history!" monty_python = ReturningCustomer("ID: 12345") monty_python.display_cart() monty_python.display_order_history() #Another example of inherited class class Shape(object): """Makes shapes!""" def __init__(self, number_of_sides): self.number_of_sides = number_of_sides # Add your Triangle class below! class Triangle(Shape): def __init__(self, side1, side2, side3): self.side1 = side1 self.side2 = side2 self.side3 = side3 """ OVERRIDE Sometimes you'll want one class that inherits from another to not only take on the methods and attributes of its parent, but to override one or more of them. """ """ class Employee(object): def __init__(self, name): self.name = name def greet(self, other): print "Hello, %s" % other.name class CEO(Employee): def greet(self, other): print "Get back to work, %s!" % other.name ceo = CEO("Emily") emp = Employee("Steve") emp.greet(ceo) # Hello, Emily ceo.greet(emp) # Get back to work, Steve! """ """ Rather than have a separate greet_underling method for our CEO, we override (or re-create) the greet method on top of the base Employee.greet method. This way, we don't need to know what type of Employee we have before we greet another Employee. On the flip side, sometimes you'll be working with a derived class (or subclass) and realize that you've overwritten a method or attribute defined in that class' base class (also called a parent or superclass) that you actually need. Have no fear! You can directly access the attributes or methods of a superclass with Python's built-in super call. """ class Employee(object): """Models real-life employees!""" def __init__(self, employee_name): self.employee_name = employee_name def calculate_wage(self, hours): self.hours = hours return hours * 20.00 # Add your code below! class PartTimeEmployee(Employee): def calculate_wage(self, hours): self.hours = hours return hours*12.00 def full_time_wage(self, hours): return super(PartTimeEmployee, self).calculate_wage(hours) milton = PartTimeEmployee("Milton") print milton.full_time_wage(10) """ REPRESENTATIONS One useful class method to override is the built-in __repr__() method, which is short for representation; by providing a return value in this method, we can tell Python how to represent an object of our class (for instance, when using a print statement). """ class Point3D(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self): return "(%d, %d, %d)" % (self.x, self.y, self.z) my_point = Point3D(1,2,3) print my_point
caea2274e53f444edb6f5e36232ba6929e3d5d1b
TejasaVi/miscellaneous
/python/searching/binary_search.py
677
3.75
4
#!/usr/bin/python class BinarySearcher(object): def __init__(self): print "BinarySearcher Object initialized." self.item_list = list() def __init_(self, input): print "BinarySearcher Object initialized with parameters." self.item_list = input def search(self, key): print("Array:%s\n"% self.item_list) print("SearchKey: %s\n"%key) if len(self.item_list) is 0: return -1 else: if key in self.item_list: return self.item_list.index(key)+ 1 if __name__ == "__main__": s = BinarySearcher() s.item_list = [1,2,3,4,5,6,7,8] print s.search(4)
1a98be3d822710e6bd32bcb59657b47f2751eeea
1987mxy/InternatofThings_ServiceCenter
/ServiceCenter/test/static/testClass.py
431
3.546875
4
''' Created on 2012-8-29 @author: XPMUser ''' class ParentClass(object): _test = 5 def __init__(self): ParentClass._test = 20 self._test1 = 10 class ChildClass(ParentClass): def __init__(self): super( ChildClass, self ).__init__() def run(self): print self._test1 print ChildClass._test if __name__=='__main__': c = ChildClass() c.run() print ChildClass._test print c._test1
a6383dd857601d4bf82b5091eb3fc98e25cde8ca
besson/my-lab
/algos/tests/test_binary_sum.py
439
3.671875
4
from unittest import TestCase from algos.binary_sum import sum_bin class BinarySum(TestCase): def test_should_sum_simple_numbers(self): a = "100" b = "101" self.assertEquals("1001", sum_bin(a, b)) def test_should_more_complex_numbers(self): a = "1111" b = "0011" self.assertEquals("10010", sum_bin(a, b)) def test_should_more_two_equal_numbers(self): a = "11" b = "11" self.assertEquals("110", sum_bin(a, b))
3c0cbad5e080ee8970366f1350e27d2cb6573192
besson/my-lab
/algos/algos/array_diagonal_print.py
415
3.890625
4
def print_diagonal(a): start = curr = 0 for i in range(len(a)): if i + start < len(a): start = start + i curr = start for j in range(i, len(a)): if (j + curr < len(a)): curr = curr + j print "%d " % a[curr], print "" print_diagonal([1, 2, 3,4,5,6,7,8]) print_diagonal([i for i in range(45)])
a066999c8adaadac1a9dc37075d529e6afb9851c
besson/my-lab
/algos/algos/merge_sort.py
693
3.6875
4
def sort(a): if (len(a) == 1): return a else: a1 = sort(a[0:len(a)/2]) a2 = sort(a[len(a)/2:len(a)]) return merge(a1, a2) def merge(a, b): size = len(a) + len(b) result = [] i = 0 j = 0 for k in range(0, size): if (i < len(a) and j < len(b)): if (a[i] <= b[j]): result.append(a[i]) i = i + 1 else: result.append(b[j]) j = j + 1 else: if (i < len(a)): result.append(a[i]) i = i + 1 else: result.append(b[j]) j = j + 1 return result
d0ab40fa3933033d1963427d7cf10f79ea2b744b
CDAT/cdat
/contrib/asciidata/Test/asv_example.py
789
4.0625
4
import ASV # Create an ASV instance asv = ASV.ASV() # Load our test data asv.input_from_file("example_data.csv", ASV.CSV(), has_field_names = 1) # Print out the ASV instance (just for fun) print asv print # Iterate over the ASV instance and print out the first cell of each row # and the cell from the column named Address even though we're unsure # of its exact number - ASV works it out for us for row in asv: print row[0], row["Address"] print # Add a row of data; notice our input file has 4 columns yet we're only # providing 3 bits of data. ASV will automatically fill in a blank value # for the row we haven't specified asv.append(["Laurie", "01234 567890", "Somerset"]) # Convert the ASV instance to TSV and print it out to screen print asv.output(ASV.TSV())
e42a0d9599876bfc336e2b4effbeb0a59ff46bfe
Lemonade-Go/dcp
/d108/solution.py
1,070
3.9375
4
def is_shifted(a, b): if len(a) != len(b): return False return b in a+a def extra_credit(a, b): if len(a) != len(b): return False if a == b: return "Match" count = 0 shift_right = a shift_left = a while(count < len(a)): print(len(a)-count) print("Solution: "+b) if shift_left == b: return "Shifted "+str(count)+" times to the right" elif shift_right == b: return "Shifted "+str(count)+" times to the left" else: shift_left = rotate_left(shift_left,1) shift_right = rotate_right(shift_right,1) count+=1 return False def rotate_right(a, d): lfirst = a[0:d] lsecond = a[d:] print("right shift: "+lsecond+lfirst) return lsecond+lfirst def rotate_left(a, d): rfirst = a[0 : len(a)-d] rsecond = a[len(a)-d :] print("left shift: "+rfirst+rsecond) return rsecond+rfirst if __name__ == "__main__": a = "abcde" b = "eabcd" print(is_shifted(a,b)) print(extra_credit(a,b))
49b49edafe82116647f53a5783c0112a5a726f04
badilet/Task4_
/Task4.py
252
3.671875
4
num = int(input("Hour:")) num1 = int(input("Min:")) num2 = int(input("Sec:")) num3 = int(input("Hour2:")) num4 = int(input("Min2:")) num5 = int(input("Sec2:")) result = (((num - num3) * 3600) + ((num1 - num4) * 60) + (num2 - num5)) print(abs(result))
8d61ad9df47405343f02a8f30640894b3ecc9014
MECU/exercisim-python
/largest-series-product/largest_series_product.py
595
3.5
4
import operator import functools def largest_product(series: str, size: int) -> int: if size < 0 or len(series) < size: raise ValueError('Length is less than one or larger than series length') if size < 1: return 1 string_length = len(series) - size + 1 result = [series[i:size+i] for i in range(0, string_length)] digits = list(map(list, result)) max_value = 0 for digitsList in digits: value = functools.reduce(operator.mul, list(map(int, digitsList))) if value > max_value: max_value = value return max_value
61afb266fdc0ae123d091fe4ff9b3d4418d79e5f
GabrielaVasileva/Exams
/Programming_Basics_Online_Exam_6_and_7_April_2019/solution/6ex/cinema_tickets.py
1,794
3.71875
4
total_tickets = 0 student_tickets = 0 standard_tickets = 0 kids_tickets = 0 # • След всеки филм да се отпечата, колко процента от кино залата е пълна # "{името на филма} - {процент запълненост на залата}% full." # • При получаване на командата "Finish" да се отпечатат четири реда: # o "Total tickets: {общият брой закупени билети за всички филми}" # o "{процент на студентските билети}% student tickets." # o "{процент на стандартните билети}% standard tickets." # o "{процент на детските билети}% kids tickets." def percentage(part, whole): percentage = 100 * float(part) / float(whole) return str(percentage) + "%" inputRow = input() while inputRow != "Finish": num = int(input()) total_local = 0 for i in range(0, num): ticket = input() if ticket == "End": break if ticket == "student": student_tickets += 1 if ticket == "standard": standard_tickets += 1 if ticket == "kid": kids_tickets += 1 total_tickets += 1 total_local += 1 print("%s - "%inputRow+"%.2f" % (100 * float(total_local) / float(num)) + "% full.") inputRow = input() print(f"Total tickets: {total_tickets}") print("%.2f" % (100 * float(student_tickets) / float(total_tickets)) + "% student tickets.") print("%.2f" % (100 * float(standard_tickets) / float(total_tickets)) + "% standard tickets.") print("%.2f" % (100 * float(kids_tickets) / float(total_tickets)) + "% kids tickets.")
1aae789149cce977556e11683e898dc039bdb9ad
derek-baker/Random-CS-Stuff
/python/SetCover/Implementation.py
1,542
4.1875
4
# INSPIRED BY: http://www.martinbroadhurst.com/greedy-set-cover-in-python.html # def test_that_subset_elements_contain_universe(universe, elements): # if elements != universe: # return False # return True def compute_set_cover(universe, subsets): # Get distinct set of elements from all subsets elements = set(el for setOfEls in subsets for el in setOfEls) print('ELEMENTS:') print(elements) # if test_that_subset_elements_contain_universe(universe, elements) == False: # return None covered = set() cover = [] # Add subsets with the greatest number of uncovered points # (As a heuristic for finding a solution) while covered != elements: # This will help us to find which subset can cover at the least cost compute_cost = lambda candidate_subset: len(candidate_subset - covered) subset = max(subsets, key = compute_cost) cover.append(subset) print('\nSELECTED SUBSET: ') print(subset) print('COVERED: ') print(covered) # Perform bitwise OR and assigns value to the left operand. covered |= subset return cover def main(): universe = set(range(1, 11)) subsets = [ set([1, 2, 3, 8, 9, 10]), set([1, 2, 3, 4, 5]), set([4, 5, 7]), set([5, 6, 7]), set([6, 7, 8, 9, 10]), ] cover = compute_set_cover(universe, subsets) print('\nLOW-COST SET COVER:') print(cover) if __name__ == '__main__': main()
f84309481b59511fd04e626b075ba3167f00cb69
xxks-kkk/project-euler
/005/python/euler5.py
1,179
3.921875
4
#!/usr/bin/env python """Solution to problem 5 in Project Euler copyright (c) 2013, Zeyuan Hu, zhu45@wisc.edu """ __author__ = "Zeyuan Hu (zhu45@wisc.edu)" __version__ = "$Revision: 0.1 $" __date__ = "$Date: 2013/01/11 03:12:10 $" __copyright_ = "Copyright (c) 2013 Zeyuan Hu" __license__ = "Python" from math import * import numpy as np def isPrime(n): if n<= 1: return False i = 2.0 while (i <= sqrt(n)): if n%i == 0: return False i += 1 return True def minDivisible(k): # N: the value the function is going to return N = 1 # index number i = 0 check = True # upper bound of the estimation process for a[i] limit = sqrt(k) a = np.zeros(20) # plist is the prime list plist = [] j = 1 while j <= k: if isPrime(j): plist.append(j) j += 1 while i < len(plist): #print "index of the list before increment:%d"%i a[i] = 1 if check: if plist[i] <= limit: a[i] = int( log10(k) / log10(plist[i]) ) else: check = False #print "N: %d"%N N = N * plist[i]**a[i] i = i + 1 #print "index of the list after increment:%d"%i #print a return N print"the smallest number divisible by each of the numbers 1 to 20 is: %d" % minDivisible(20)
9b9673b01d353c22cd74ddb9bf2d2aa8194874e7
daokh/pythonRepo
/xyz2lla.py
1,625
3.578125
4
#!/usr/bin/python # Convert XYZ coordinates to cartesien LLA (Latitude/Longitude/Altitude) # Alcatel Alenia Space - Nicolas Hennion # Version 0.1 # # Python version translation by John Villalovos # from optparse import OptionParser import os, sys from math import atan2, cos, pi, sin, sqrt, tan def main(): options, args = parseCommandLine() calculate(options) def parseCommandLine(): usage = "%prog X Y Z" parser = OptionParser(usage = usage) options, args = parser.parse_args() if len(args) != 3: print "Error: 3 arguments are required" displayUsage(parser) sys.exit(1) try: options.x = float(args[0]) options.y = float(args[1]) options.z = float(args[2]) except ValueError: print "Error: Arguments must be floating point numbers" displayUsage(parser) sys.exit(1) return options, args def calculate(options): x = options.x y = options.y z = options.z # Constants (WGS ellipsoid) a = 6378137 e = 8.1819190842622e-2 # Calculation b = sqrt(pow(a,2) * (1-pow(e,2))) ep = sqrt((pow(a,2)-pow(b,2))/pow(b,2)) p = sqrt(pow(x,2)+pow(y,2)) th = atan2(a*z, b*p) lon = atan2(y, x) lat = atan2((z+ep*ep*b*pow(sin(th),3)), (p-e*e*a*pow(cos(th),3))) n = a/sqrt(1-e*e*pow(sin(lat),2)) alt = p/cos(lat)-n lat = (lat*180)/pi lon = (lon*180)/pi print "%s %s %s" % (lat, lon, alt) def displayUsage(parser): parser.print_help() print "\nOutput: Latitude Longtitude Altitude" return if '__main__' == __name__: main()
183b55f26e3ef66b75d232f6ef91cb98954af30a
daokh/pythonRepo
/geoutils.py
3,447
3.546875
4
import math import json import copy class dict(dict): """Allows us to use "." notation on json instances""" def __init__(self, kwargs): self.update(kwargs) super(dict, self).__init__() __getattr__, __setattr__ = dict.__getitem__, dict.__setitem__ def __str__(self): #return json.dumps(self.__dict__.__str__()) return super(dict, self).__str__() class jsondict(dict): """Allows us to use "." notation on json instances""" def __init__(self, kwargs): self.update(kwargs) super(dict, self).__init__() def __setattr__(self,key,value): super(jsondict, self).__setitem__(key,value) def __str__(self): return super(dict, self).__str__() def __getitem__(self, key): if key in self: return super(jsondict, self).__getitem__(key) return None def __getattr__(self,key): """return None if key is not in dictionary""" #This will help for some operations: <somedict>.foo return None instead of getting Key Error when foo is not #in <somedict> if key in self: return super(jsondict, self).__getitem__(key) else: return None def __deepcopy__(self, memo): return jsondict([(copy.deepcopy(k, memo), copy.deepcopy(v, memo)) for k, v in self.items()]) def distance(pointA,pointB): return math.sqrt(pow( abs(pointA.lat - pointB.lat),2) + pow( abs(pointA.lon - pointB.lon),2)) def is_between(pointA,pointC,pointB): """ Check if point C is on the line between A and B """ return distance(pointA,pointC) + distance(pointC,pointB) == distance(pointA,pointB) def isInCircle(center,radius,point): return distance(center,point) <= radius def getNW_SE(southwest,northeast): southwest = dict(southwest) northeast = dict(northeast) northwest = dict({"lat": northeast.lat, "lon":southwest.lon}) southeast = dict({"lat": southwest.lat, "lon":northeast.lon}) return northwest,southeast def _sign(p1, p2, p3): """Supported function for isPointInTriangle""" p1 = dict(p1) p2 = dict(p2) p3 = dict(p3) return (p1.lon - p3.lon) * (p2.lat - p3.lat) - (p2.lon - p3.lon) * (p1.lat - p3.lat) def _isPointInTriangle(point, p1, p2, p3): """Check if the point is inside the Triangle""" b1 = _sign(point, p1, p2) < 0.0 b2 = _sign(point, p2, p3) < 0.0 b3 = _sign(point, p3, p1) < 0.0 return ((b1 == b2) and (b2 == b3)) def isPointInRectangular(point, sw, ne): """Check if the point is inside the Rectangular""" # If we divide the rectangular into 2 triangles, the point is determined inside rectangular only if the point # is inside at least 1 triangle nw,se = getNW_SE(sw,ne) return _isPointInTriangle(point,sw,nw,ne) or _isPointInTriangle(point,sw,se,ne) if __name__ == '__main__': A = '{"lat": 2, "lon":2}' B = '{"lat": 1, "lon":1}' pointA = json.loads(A,object_hook=dict ) pointB = json.loads(B,object_hook=dict ) radius = distance(pointA,pointB) C = dict({"lat": 1.5, "lon":1.5}) if isInCircle(pointA,radius,C): print "C is inside cirle" sw = dict({"lat": 1, "lon":1}) ne = dict({"lat": 4, "lon":4}) nw,se = getNW_SE(sw,ne) print "North West:%s and South East: %s" %(ne,sw) point = {"lat": 4, "lon":4.1} if isPointInRectangular(point,sw,ne): print "Point is inside Rectangular"
b9ab9353dd2621c32efca51709508a7c8c06e25a
Coni63/CG_repo
/training/hard/7-segment-display.py
2,259
3.640625
4
import sys import math digit = { "0" : [True, True, True, False, True, True, True], "1" : [False, False, True, False, False, True, False], "2" : [True, False, True, True, True, False, True], "3" : [True, False, True, True, False, True, True], "4" : [False, True, True, True, False, True, False], "5" : [True, True, False, True, False, True, True], "6" : [True, True, False, True, True, True, True], "7" : [True, False, True, False, False, True, False], "8" : [True, True, True, True, True, True, True], "9" : [True, True, True, True, False, True, True], } n = int(input()) c = input() s = int(input()) for line in range(2*s+3): result = [] for each in str(n): if line == 0: # barres horizontales sup if digit[each][0] == True: result.append(" " + s*c + " ") else: result.append((s+2)*" ") elif line == s+1: # barres horizontales mid if digit[each][3] == True: result.append(" " + s*c + " ") else: result.append((s+2)*" ") elif line == 2*(s+1): # barres horizontales bottom if digit[each][6] == True: result.append(" " + s*c + " ") else: result.append((s+2)*" ") elif 0 < line < s+1: #barres vert top if digit[each][1] == True and digit[each][2] == True: result.append(c + s*" " + c) elif digit[each][1] == True and digit[each][2] == False: result.append(c + s*" " + " ") elif digit[each][1] == False and digit[each][2] == True: result.append(" " + s*" " + c) elif s+1 < line < 2*(s+1): #barre vert bottom if digit[each][4] == True and digit[each][5] == True: result.append(c + s*" " + c) elif digit[each][4] == True and digit[each][5] == False: result.append(c + s*" " + " ") elif digit[each][4] == False and digit[each][5] == True: result.append(" " + s*" " + c) print(" ".join(result).rstrip()) # To debug: print("Debug messages...", file=sys.stderr)
e32f867cdaf363e5811d84f0326048122ea54a0b
Coni63/CG_repo
/training/medium/divide-the-factorial.py
738
3.6875
4
import sys import math # https://www.justquant.com/numbertheory/highest-power-of-a-number-in-a-factorial/ def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors a, b = [int(i) for i in input().split()] f = prime_factors(a) print(f, file=sys.stderr) g = [(value, f.count(value)) for value in set(f)] h = [] for value, power in g: b2 = b highest_power = 0 for i in range(1, 20): b2 = b2//value highest_power += b2 # k = int(b/value**i) # highest_power += k h.append(int(highest_power/power)) print(min(h))
a3bc75716f4641fcfad79f5443e347b288b2fb45
Coni63/CG_repo
/training/medium/de-fizzbuzzer.py
763
3.578125
4
import sys import math def div_count(x, d): n = 0 while True: if x % d == 0: x //= d n += 1 else: break return n def fizzbuzz(x): r ="" if "3" in str(x): r+= "Fizz" * str(x).count("3") if x % 3 == 0: r+= "Fizz" * div_count(x, 3) if "5" in str(x): r+= "Buzz" * str(x).count("5") if x % 5 == 0: r+= "Buzz" * div_count(x, 5) if r == "": return str(x) else: return r # l = {fizzbuzz(k):k for k in range(1, 1000)} # print(l, file=sys.stderr) l = [fizzbuzz(k) for k in range(1, 1000)] n = int(input()) for i in range(n): row = input() try: print(l.index(row)+1) except: print("ERROR")
341b993533144a360c8d29aa7d856d4b59f70cc2
ragcoder/Web_Scraping
/Weather_Scraping.py
2,104
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 15:46:25 2019 @author: RagCoder Source: https://www.dataquest.io/blog/web-scraping-tutorial-python/ """ '''Navigating a web page''' import requests from bs4 import BeautifulSoup import pandas as pd #Retrieves web page from server page = requests.get("http://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168") #parsing document soup = BeautifulSoup(page.content, 'html.parser') #Selecting tag with 7-day forecast seven_day = soup.find(id="seven-day-forecast") #Extracting all elements with class tombstone-container which holds the the days weather information forecast_items = seven_day.find_all(class_="tombstone-container") #Selecting today's forecast information today = forecast_items[0] print(today.prettify()) #Extracting time period, short description, and temperature period = today.find(class_="period-name").get_text() short_desc = today.find(class_="short-desc").get_text() temp = today.find(class_="temp").get_text() print(period) print(short_desc) print(temp) #Extract img information img = today.find("img") desc = img['title'] print(desc) #Extracting all information from page period_tags = seven_day.select(".tombstone-container .period-name") periods = [pt.get_text() for pt in period_tags] print(periods) short_descs = [sd.get_text() for sd in seven_day.select(".tombstone-container .short-desc")] temps = [t.get_text() for t in seven_day.select(".tombstone-container .temp")] descs = [d['title'] for d in seven_day.select(".tombstone-container img")] print(short_descs) print(temps) print(descs) #Collecting and Analyzing weather = pd.DataFrame({ "period": periods, "short_desc": short_descs, "temp": temps, "desc": descs }) print(weather) temp_nums = weather["temp"].str.extract("(?P<temp_num>\d+)", expand=False) weather["temp_num"] = temp_nums.astype('int') print(temp_nums) print("the average temp for this week: ", weather["temp_num"].mean()) is_night = weather["temp"].str.contains("Low") weather["is_night"] = is_night print(is_night) print(weather[is_night])
aed6af85dbe5b24b745a9080442b1f671522bc64
lasigeBioTM/BLiR
/Data_Preprocessing/classify_publications.py
2,431
3.640625
4
from variables import * def get_list_all_pmids(files): """ Read _pmids.txt file(s) to get all the pmids from the publications Requires: files: a list with the name(s) of the file(s). Ensures: all_pmids a list with all pmids. """ all_pmids = [] for file in files: in_file = open(PROCESSED_DATA_PATH / (file + PMIDS_FILE), 'r', encoding = "utf8") pmids = [pmid[:-1] for pmid in in_file.readlines()] in_file.close() all_pmids.extend(pmids) all_pmids = set(all_pmids) return all_pmids def get_relevant_pmids(): """ Use the file with all relevant publications to get a list with relevant pmids used to built the database Ensures: relevant_pmids a list with all pmids from relevant publications. """ in_file = open(REL_PMIDS_FILE, 'r', encoding = "utf8") relevant_pmids = [pmid[:-1] for pmid in in_file.readlines()] in_file.close() return relevant_pmids def get_irrelevant_pmids(all_pmids,relevant_pmids): """ Get the pmids from the irrelevant publications Requires: all_pmids a list with pmids from all publications; relevant_pmids a list with all pmids from relevant publications. Ensures: irrelevant_pmids a list with all pmids from irrelevant publications. """ irrelevant_pmids = list(set(all_pmids)-set(relevant_pmids)) return irrelevant_pmids def get_all_pmids_labels(files): """ Map pmids to the respective label Requires: files a list with the name(s) of the file(s). Ensures: all_pmids_labels a list with tuples (pmid, label). """ print("................................ Query Results ................................") all_pmids = get_list_all_pmids(files) relevant_pmids = get_relevant_pmids() irrelevant_pmids = get_irrelevant_pmids(all_pmids, relevant_pmids) print('Number of pubs:', len(all_pmids)) print('Number of relevant pubs:', len(all_pmids)-len(irrelevant_pmids)) print('Number of irrelevant pubs:', len(irrelevant_pmids), '\n') all_pmids_labels = [] for pmid in all_pmids: if pmid in relevant_pmids: all_pmids_labels.append((pmid, '1')) else: all_pmids_labels.append((pmid, '0')) return all_pmids_labels
0911a253c5529cf97c26223e1bfae805a32d01ea
swdotcom/swdc-sublime
/vendor/contracts/testing/test_class_contracts.py
2,155
3.546875
4
from contracts import contract, new_contract, ContractNotRespected import unittest class ClassContractsTests(unittest.TestCase): def test_class_contract1(self): class Game(object): def __init__(self, legal): self.legal = legal @new_contract def legal_move1(self, move): return move in self.legal @contract(move='legal_move1') def take_turn(self, move): pass g1 = Game([1, 2]) g1.take_turn(1) g1.take_turn(2) self.assertRaises(ContractNotRespected, g1.take_turn, 3) def test_class_contract2(self): class Game(object): def __init__(self, legal): self.legal = legal @new_contract def legal_move2(self, move): return move in self.legal @contract(move='legal_move2') def take_turn(self, move): pass g1 = Game([1, 2]) g1.take_turn(1) g1.take_turn(2) self.assertRaises(ContractNotRespected, g1.take_turn, 3) def test_class_contract3(self): class Game(object): def __init__(self, legal): self.legal = legal def legal_move(self, move): return move in self.legal new_contract('alegalmove', legal_move) @contract(move='alegalmove') def take_turn(self, move): pass g1 = Game([1, 2]) g1.take_turn(1) g1.take_turn(2) self.assertRaises(ContractNotRespected, g1.take_turn, 3) def test_class_contract1_bad(self): """ example of bad usage, using the contract from outside """ class Game(object): def __init__(self, legal): self.legal = legal @new_contract def legal_move4(self, move): return move in self.legal def go(): @contract(move='legal_move4') def take_turn(move): pass take_turn(0) self.assertRaises(ContractNotRespected, go)
e74add4e61a90087bb085b51a8734a718fd554f7
sador23/cc_assignment
/helloworld.py
602
4.28125
4
'''The program asks for a string input, and welcomes the person, or welcomes the world if nothing was given.''' def inputname(): '''Keeps asking until a string is inputted''' while True: try: name=input("Please enter your name!") int(name) print("This is not a string! Please enter a string") except ValueError: return name def greeting(name): '''Greets the person, depending on the name''' if not name: print("Hello World!") else: print("Hello " + str(name) + "!") greeting(inputname())
a87a6b9006f61f89e579d2df495de03c4a18933b
kleytonmr/levenshtein
/Python/levenshtein.py
1,333
3.59375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- def iterative_levenshtein(s, t): rows = len(s)+1 cols = len(t)+1 dist = [[0 for x in range(cols)] for x in range(rows)] # source prefixes can be transformed into empty strings # by deletions: for i in range(1, rows): dist[i][0] = i # target prefixes can be created from an empty source string # by inserting the characters for i in range(1, cols): dist[0][i] = i for col in range(1, cols): for row in range(1, rows): if s[row-1] == t[col-1]: cost = 0 else: cost = 1 dist[row][col] = min(dist[row-1][col] + 1, # deletion dist[row][col-1] + 1, # insertion dist[row-1][col-1] + cost) # substitution for r in range(rows): dist[r] return dist[row][col] # compare similarity in percentage def compare(a,b): distance = iterative_levenshtein(a, b) if distance == 0: return 100 lenght = max(len(a),len(b)) if distance == lenght: return 0 inverted = invert(distance, lenght) percent = (inverted/lenght)*100 return round(percent) def invert(min,max): return max-min
073012068ec13550d5667f64174dfff01541cf2e
Vasyl0206/orests_homework
/l4_7.py
126
4
4
def reverse(strng): word=strng.split() word.reverse() new_word=' '.join(word) print(new_word) reverse('help')
927535ef96107f1235f23d9bbd0e9f4c66505349
pytutorial/samples
/_summary/2.if/s22.py
286
3.71875
4
# Nhập vào điểm trung bình, in ra loại học lực x = input('Điểm trung bình: ') x = float(x) if x < 5.0: print('Học lực kém') elif x < 6.5: print('Học lực trung bình') elif x < 8.0: print('Học lực khá') else: print('Học lực giỏi')
b948e3c83ab173191d5c8eb4545d832a54c5243f
pytutorial/samples
/basic/guess_number.py
658
3.625
4
""" Chương trình đoán số tự nhiên. Bạn hãy nghĩ trong đầu một số từ 0 đến 1000 Máy tính sẽ hỏi dưới 10 câu, mỗi câu bạn chỉ trả lời Y/N xem câu đó đúng hay sai. Sau 10 câu hỏi, máy tính sẽ đưa ra số bạn đang nghĩ là gì. """ low = 0 high = 1000 print('Bạn hãy nghĩ một số trong phạm vi từ 0 đến 1000, sau đó trả lời các câu hỏi sau.') while low + 1 != high: mid = (low + high) // 2 a = input('Số đó lớn hơn ' + str(mid) + ' ? (Y/N) : ') if a == 'Y': low = mid else: high = mid print('Số bạn nghĩ là ', high)
39455aee460a3677d17492138962bd19c9a11e62
pytutorial/samples
/basic/num2text.py
1,054
3.71875
4
""" Chương trình chuyển một số có 3 chữ số thành phát âm tiếng Việt - Đầu vào : số tự nhiên trong phạm vi từ 0 đến 999 - Đầu ra : phát âm tiếng Việt của số đó """ bangso = ['không', 'một', 'hai', 'ba', 'bốn', 'năm', 'sáu', 'bảy', 'tám', 'chín'] def convert2digits(x): if x < 10: return bangso[x] chuc = x // 10 donvi = x % 10 text = (bangso[chuc] + ' mươi') if chuc > 1 else 'mười' if donvi > 0: text += ' ' if donvi == 5: text += 'lăm' elif donvi == 1 and chuc > 1: text += 'mốt' else: text += bangso[donvi] return text def convert3digits(x): if x < 100: return convert2digits(x) tram = x // 100 chuc = (x//10) % 10 donvi = x % 10 text = bangso[tram] + ' trăm' if chuc > 0: text += ' ' + convert2digits(x%100) elif donvi > 0: text += ' lẻ ' + bangso[donvi] return text print(convert3digits(105))
99c0d709a945242611f7c7f62267afc8c897907a
pytutorial/samples
/basic/decision_making.py
229
3.796875
4
""" Chương trình so sánh 2 biểu thức """ x = 1999 * 2001 y = 2000 * 2000 if x > y: print('1999 * 2001 > 2000 * 2000') elif x == y: print('1999 * 2001 = 2000 * 2000') else: print('1999 * 2001 < 2000 * 2000')
fc25a9ca928a58544c1e12b482dfac289aaae221
pytutorial/samples
/pandas/pd_data_analysis.py
797
3.515625
4
import pandas as pd df = pd.read_csv('sales.csv') df['date'] = df['date_order'].apply(lambda x : x[:10]) df['revenue'] = df['qty'] * df['price'] - df['promotion'] print(df.head()) #======================================== Total revenue ====================================== print('\nTotal revenue : ', df['revenue'].sum()) #======================================== Daily revenues ===================================== df_date = df.groupby('date')['revenue'].sum() print('\nRevenue for every day:') print(df_date) #======================================== Stores' revenues =================================== df_store = df.groupby('location_id')['revenue'].sum() df_store = df_store.sort_values(ascending=False) print('\nRevenue for each store :') print(df_store)
9b5c417104a00cb98693797f16e93c06d1172c80
pytutorial/samples
/basic/find_by_S_D.py
305
3.65625
4
""" Chương trình tìm 2 số khi biết tổng và hiệu - Đầu vào : + S : tổng của 2 số + D : hiệu của 2 số - Đầu ra: + Giá trị 2 số """ S = input('S = ') S = float(S) D = input('D = ') D = float(D) a = (S - D)/2 b = (S + D)/2 print('a = ', a) print('b = ', b)
7f4ba078086091f102102caf935cec9f19131281
Dilstom/Intro-Python
/src/days-2-4-adv/lecture/item.py
982
3.640625
4
class Item: def __init__(self, name, description): self.name = name self.description = description def __repr__(self): return f'{self.name}' def __str__(self): return f'{self.name}' def getDescription(self): return self.description def on_drop(self): print(f'\nYou have dropped {self.name}') # class Food(Item): # def __init__(self, name, description, calories): # Item.__init__(self, name, description) # self.calories = calories # def getDescription(self): # return self.description + f'\nIt seems to have {self.calories.' # def eat(self): # return class Treasure(Item): def __init__(self, name, description, value): self.name = name self.description = description self.value = value def on_take() class LightSource(Item): def __init__(self) def on_drop(self): print "It's not wise to drop your source of light!"
61e0294d7ef813c8051d84596305f78c679cbe87
Dilstom/Intro-Python
/src/python-example/rps.py
2,481
3.8125
4
import random class RPSAgent: def __init__(self, preferred_selection=1): self.preferred_selection = preferred_selection def getMove(self): """ This will get a move with some bias built in. """ randNumber = random.random() if self.preferred_selection == 1: if randNumber <= 0.6: return 1 elif randNumber <= 0.8: return 2 else: return 3 elif self.preferred_selection == 2: if randNumber <= 0.6: return 2 elif randNumber <= 0.8: return 3 else: return 1 else: if randNumber <= 0.6: return 3 elif randNumber <= 0.8: return 1 else: return 2 agent = RPSAgent(random.randint(1,3)) score = {"wins": 0, "losses": 0, "ties": 0} while True: inp = input("\nWhat is your input (r/p/s): ") computer_selection = agent.getMove() if computer_selection == 1: print ("\nComputer picks Rock") elif computer_selection == 2: print ("\nComputer picks Paper") elif computer_selection == 3: print ("\nComputer picks Scissors") if inp == "q": break elif inp == "r": if computer_selection == 1: score["ties"] += 1 print ("Tie") elif computer_selection == 2: score["losses"] += 1 print ("Loss") elif computer_selection == 3: score["wins"] += 1 print ("Win") elif inp == "p": if computer_selection == 1: score["wins"] += 1 print ("Win") elif computer_selection == 2: score["ties"] += 1 print ("Tie") elif computer_selection == 3: score["losses"] += 1 print ("Loss") elif inp == "s": if computer_selection == 1: score["losses"] += 1 print ("Loss") elif computer_selection == 2: score["wins"] += 1 print ("Win") elif computer_selection == 3: score["ties"] += 1 print ("Tie") elif inp == "score": print("Wins: %d, Losses: %d, Ties: %d" % (score["wins"], score["losses"], score["ties"])) elif inp == "agent": print(agent.preferred_selection) else: print ("I did not recognize that command")
d5cd407d72ef4e5e7c7f1d4aaa19320dd3df4093
vincenttian/Company_Profiles
/companyapp/companyapp/management/commands/company_api.py
15,645
3.640625
4
from api_helper import * # BEGIN VINCENT'S COMPANY API def company_api_function(company, api, data): """ To Use this API, set: company = string of the name of the company you want information on Ex. 23andMe api = string of the API that you want to use to get information. Choose from: 1. linkedin 2. crunchbase 3. glassdoor data = string of the data you are interested in For linkedin, there is 1. company_type 2. description 3. employee_range 4. founded_year 5. industry 6. location 7. status 8. website_url For crunchbase, there is 1. acquisitions 2. blog_url 3. competition 4. description 5. email_address 6. funding_rounds 7. homepage_url 8. investments 9. milestones 10. number_employees 11. offices 12. overview 13. phone_number 14. company_staff 15. total_money_raised 16. twitter_username For glassdoor, there is 1. ceo 2. meta 3. salary 4. satisfaction """ api = api.lower() company = company.lower() # GET INFORMATION FROM LINKEDIN if api == 'linkedin': # GETS DATA FROM LINKEDIN API # Get authorization set up and create the OAuth client client = get_auth() response = make_request(client, LINKEDIN_URL_1 + company + LINKEDIN_URL_2, {"x-li-format":'json'}) d1 = json.loads(response) try: d1 = json.loads(response) except Exception: return "Sorry. The LinkedIn API could not find information for company " + company """ Returns a JSON object of all information about company provided by linkedin """ if data == 'all': return d1 """ Returns a string that contains the company type: private or public. """ if data == 'company_type': try: return d1["companyType"]["name"] except Exception: return "Sorry. The LinkedIn API could not find " + data + "for company " + company """ Returns a string that contains a short description of the company. """ if data == 'description': try: return d1["description"] except Exception: return "Sorry. The LinkedIn API could not find " + data + "for company " + company """ Returns a string that contains an approximate range for number of employees. """ if data == 'employee_range': try: return d1["employeeCountRange"]["name"] except Exception: return "Sorry. The LinkedIn API could not find " + data + "for company " + company """ Returns an integer that contains the year the company was founded. """ if data == 'founded_year': try: return d1["foundedYear"] except Exception: return "Sorry. The LinkedIn API could not find " + data + "for company " + company """ Returns a JSON object that contains the industries the company is involved with. Ex. {u'industries': {u'_total': 1, u'values': [{u'code': u'12', u'name': u'Biotechnology'}]} """ if data == 'industry': try: return d1["industries"] except Exception: return "Sorry. The LinkedIn API could not find " + data + "for company " + company """ Returns a JSON object that contains the locations of the company. Ex. {u'locations': {u'_total': 1, u'values': [{u'address': {u'city': u'Mountain View', u'postalCode': u'94043', u'street1': u'1390 Shorebird Way'}, u'contactInfo': {u'fax': u'', u'phone1': u'650.938.6300'}}]} """ if data == 'location': try: return d1["locations"] except Exception: return "Sorry. The LinkedIn API could not find " + data + "for company " + company """ Returns a string that contains the status of the company: operating or not. """ if data == 'status': try: return d1["status"]["name"] except Exception: return "Sorry. The LinkedIn API could not find " + data + "for company " + company """ Returns a string that contains the website url of the company. """ if data == 'website_url': try: return d1["websiteUrl"] except Exception: return "Sorry. The LinkedIn API could not find " + data + "for company " + company # GET INFORMATION FROM CRUNCHBASE if api == 'crunchbase': # DATA FROM CRUNCHBASE r = requests.get(CRUNCHBASE_URL_1 + company + CRUNCHBASE_URL_2) data_crunch = r.text try: d2 = json.loads(data_crunch) except: return "Sorry. The Crunchbase API could not find information for company " + company """ Returns a JSON object of all information about company provided by crunchbase """ if data == 'all': return d2 """ Returns a JSON Object that contains the acquisitions the company has made Ex. {u'acquisitions': [{u'acquired_day': 10, u'acquired_month': 7, u'acquired_year': 2012, u'company': {u'name': u'CureTogether', u'permalink': u'curetogether'}, u'price_amount': None, u'price_currency_code': u'USD', u'source_description': u'23andMe Acquires CureTogether, Inc.', u'source_url': u'http://www.freshnews.com/news/673729/23andme-acquires-curetogether-inc-', u'term_code': None}] """ if data == 'acquisitions': try: return d2["acquisitions"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains the blog url of the company """ if data == 'blog_url': try: return d2["blog_url"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a JSON object that contains the competitors of the comapny Ex. {u'competitions': [{u'competitor': {u'name': u'GenePartner', u'permalink': u'genepartner'}}, {u'competitor': {u'name': u'ScientificMatch', u'permalink': u'scientificmatch'}}, {u'competitor': {u'name': u'Navigenics', u'permalink': u'navigenics'}}, {u'competitor': {u'name': u'AIBioTech', u'permalink': u'aibiotech'}}] """ if data == 'competition': try: return d2["competitions"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains a description of the company """ if data == 'description': try: return d2["description"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains the company email address """ if data == 'email_address': try: return d2["email_address"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a JSON Object that contains the funding rounds of a company Ex. {u'funding_rounds': [{u'funded_day': 1, u'funded_month': 5, u'funded_year': 2007, u'id': 764, u'investments': [{u'company': {u'name': u'Genentech', u'permalink': u'genentech'}, u'financial_org': None, u'person': None}, {u'company': {u'name': u'Google', u'permalink': u'google'}, u'financial_org': None, u'person': None}, {u'company': None, u'financial_org': {u'name': u'Mohr Davidow Ventures', u'permalink': u'mohr-davidow-ventures'}, u'person': None}, {u'company': None, u'financial_org': {u'name': u'New Enterprise Associates', u'permalink': u'new-enterprise-associates'}, u'person': None}], u'raised_amount': 9000000.0, u'raised_currency_code': u'USD', u'round_code': u'a', u'source_description': u'', u'source_url': u'http://23andme.com/press.html'} """ if data == 'funding_rounds': try: return d2["funding_rounds"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains the company homepage url """ if data == 'homepage_url': try: return d2["homepage_url"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a JSON Object that contains the company investments """ if data == 'investments': try: return d2["investments"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a JSON Object that contains company milestones Ex. {u'milestones': [{u'description': u'Price dropped to $399 per test. ', u'id': 579, u'source_description': u'23andMe Democratizes Personal Genomics With New Analytical Platform', u'source_text': u'', u'source_url': u'http://spittoon.23andme.com/2008/09/08/23andme-democratizes-personal-genomics-with-new-analytical-platform/', u'stoneable': {u'name': u'23andMe', u'permalink': u'23andme'}, u'stoneable_type': u'Company', u'stoned_acquirer': None, u'stoned_day': 8, u'stoned_month': 9, u'stoned_value': None, u'stoned_value_type': None, u'stoned_year': 2008}] """ if data == 'milestones': try: return d2["milestones"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains the number of employees """ if data == 'number_employees': try: return d2["number_of_employees"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a JSON Object that contains the company offices Ex. {u'offices': [{u'address1': u'2606 Bayshore Parkway', u'address2': u'', u'city': u'Mountain View', u'country_code': u'USA', u'description': u'', u'latitude': 37.09024, u'longitude': -95.712891, u'state_code': u'CA', u'zip_code': u'94042'}] """ if data == 'offices': try: return d2["offices"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains the """ if data == 'overview': try: return d2["overview"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains the company overview """ if data == 'phone_number': try: return d2["phone_number"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a JSON Object that contains the company staff Ex. {u'relationships': [{u'is_past': False, u'person': {u'first_name': u'Anne', u'last_name': u'Wojcicki', u'permalink': u'anne-wojcicki'}, u'title': u'CEO and Co-founder'} } """ if data == 'company_staff': try: return d2["relationships"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains the total money raised """ if data == 'total_money_raised': try: return d2["total_money_raised"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company """ Returns a string that contains the twitter username """ if data == 'twitter_username': try: return d2["twitter_username"] except Exception: return "Sorry. The Crunchbase API could not find " + data + "for company " + company # GET INFORMATION FROM GLASSDOOR if api == 'glassdoor': # GETS DATA FROM GLASSDOOR SCRAPING x, GLASSDOOR_URL = get(company) x_json = x.json() try: d3 = json.loads(x_json) except Exception: "Sorry. The Glassdoor API could not find information for company " + company """ """ if data == 'url': return GLASSDOOR_URL """ Returns a JSON object of all information about company provided by linkedin """ if data == 'all': return d3 """ Returns a JSON object that contains CEO information Ex. {u'ceo': {u'%approval': None, u'avatar': u'http://static.glassdoor.com/static/img/illustration/generic-person.png?v=dc63ecds', u'name': u'Anne Wojcicki', u'reviews': 0} """ if data == 'ceo': try: return d3["ceo"] except Exception: return "Sorry. The Glassdoor API could not find " + data + "for company " + company """ Returns a JSON object that contains information including competitors, year founded, industry, revenue, type, location, logo, score, size, and website Ex. { u'meta': {u'Competitors': u'Unknown', u'Founded': u'Unknown', u'Industry': u'Business Services', u'Revenue': u'Unknown / Non-Applicable per year', u'Type': u'Company - Private', u'connections': 0, u'location': u'Mountain View, CA', u'logo': u'http://static.glassdoor.com/static/img/sqLogo/generic-150.png?v=7fc3122vf', u'name': u'23andMe', u'reviews': 9, u'score': None, u'size': [], u'website': u'www.23andme.com'}} """ if data == 'meta': try: return d3["meta"] except Exception: return "Sorry. The Glassdoor API could not find " + data + "for company " + company """ Returns a JSON object that contains salary information Ex. { u'position': u'Computational Biologist', u'range': [94000, 106000], u'samples': 4}, {u'mean': 117763, u'position': u'Software Engineer', u'range': [113000, 123000], u'samples': 2}, {u'mean': 96672, u'position': u'Scientist', u'range': [84000, 109000], u'samples': 2}] } """ if data == 'salary': try: return d3["salary"] except Exception: return "Sorry. The Glassdoor API could not find " + data + "for company " + company """ Returns a JSON object that contains the satisfaction of employees Ex. { u'satisfaction': {u'ratings': 9, u'score': None }} """ if data == 'satisfaction': try: return d3["satisfaction"] except Exception: return "Sorry. The Glassdoor API could not find " + data + "for company " + company # TESTING API if __name__ == "__main__": print "Initial Test" company = "amazon" # CRUNCHBASEEE ----------------------------------- d2 = company_api_function(company, 'crunchbase', 'all') print "API: crunchbase" pprint.pprint(d2) # GLASSDOORRR ----------------------------------- d3 = company_api_function(company, 'glassdoor', 'all') print "\n\n\n\nAPI: glassdoor" pprint.pprint(d3) # LINKEDINNNN ----------------------------------- d1 = company_api_function(company, 'linkedin', 'all') print "\n\n\n\nAPI: linkedin" pprint.pprint(d1)
e101b049ce1187faaddb67ee58fc0cb11e42fd38
barjuegocreador93/Estadistica
/estadistica.py
1,448
3.78125
4
#Autor: Camilo Barbosa #pedir la poblacion: poblacion=input("Entre el numero de poblacion: ") #encontrar las muestras en una poblacion muestra=[] i=0 while i<poblacion: txt="Entre la muesta "+str(i+1)+": " x=input(txt) muestra.append(x) i+=1 #media geometrica 1: g=1.0 i=0 raizPoblacion=1.0/poblacion; while i<poblacion: g *= muestra[i] i+=1 g=pow(g,raizPoblacion) print "La media geometrica 1: ",g #media geometrica 2: mulmP=1.0 i=0 while i<poblacion: mulmP = mulmP * pow(muestra[i],poblacion) i+=1 g=pow(mulmP,raizPoblacion) print "La media geometrica 2: ",g #media aritmetica 1: mx = 0.0 i=0 while i<poblacion: mx += muestra[i] i+=1 mx = mx / poblacion print "La media aritmetica es 1: ", mx #media aritmetica 2: mx = 0.0 i=0 while i<poblacion: mx += muestra[i] * poblacion i+=1 mx = mx / poblacion print "La media aritmetica es 2: ", mx # medica Cuadratica 1: sumc=0.0 i=0 while i<poblacion: sumc += pow(muestra[i],2) i+=1 mc=pow(sumc/poblacion,0.5) print "La media cuadrada es 1: ", mc # medica Cuadratica 2: sumc=0.0 i=0 while i<poblacion: sumc += pow(muestra[i],2) * poblacion i+=1 mc=pow(sumc/poblacion,0.5) print "La media cuadrada es 2: ", mc #mediana: me=0.0 if(poblacion % 2==0): sumc=0.0 i=0 while i<poblacion: sumc += (muestra[i/2]) + (muestra[(i/2)+ 1]) i+=1 me=sumc/2 else: sumc=0.0 i=0 while i<poblacion: sumc += muestra[(i+1)/2] i+=1 me=sumc print "la mediana es: ", me
12c8a1cfe5a3583a1102414626bc5c2242218ef5
ddudu270/algo
/10988.py
346
3.6875
4
import sys def palindrome(p): for i in range(len(p) // 2): if p[i] == p[-1 - i]: continue else: return 0 return 1 p = list(sys.stdin.readline().rstrip()) x=palindrome(p) print(x) # from sys import stdin # # t = stdin.readline().strip() # if t == t[::-1]: # print(1) # else: # print(0)
56bd08fcda60d0d2df981edc2d17c66499590bc8
1000VIA/Platzi---Curso-de-Python
/miPrimerTurtle.py
323
3.75
4
import turtle window = turtle.Screen()#Indicarle a turtle que vamos a Generamos una ventana milvia = turtle.Turtle()#Indicamos que queremos generar una tortuga milvia.forward(100) milvia.left(90) milvia.forward(100) milvia.left(90) milvia.forward(100) milvia.left(90) milvia.forward(100) milvia.left(90) turtle.mainloop()
e00aee8881c15ebab9200e6489c7edfa8e392175
KamilMatejuk/University
/Python/Pattern_Search_KMP.py
1,929
3.90625
4
import os import sys def read_data(): if len(sys.argv) != 3: print('Wrong number of arguments') exit() _, pattern, given_file = sys.argv if not os.path.isfile(given_file): print('Last argument should be a patternh to file') exit() with open(given_file, 'r') as f: text = f.read() return str(pattern), str(text) def create_lps(pattern): longest_prefix_suffix = [0] * len(pattern) # length of the previous longest prefix suffix length = 0 i = 1 # fill array with longest proper prefix which is # also a suffix of given substring while i < len(pattern): if pattern[i] == pattern[length]: length += 1 longest_prefix_suffix[i] = length i += 1 else: if length != 0: length = longest_prefix_suffix[length-1] else: longest_prefix_suffix[i] = 0 i += 1 return longest_prefix_suffix def search(pattern, text): # calculate longest prefix suffix array lps = create_lps(pattern) i = 0 # index for text j = 0 # index for pattern indexes = [] # iterate through text and search for patterns and subpatterns while i < len(text): if pattern[j] == text[i]: i += 1 j += 1 # end of pattern if j == len(pattern): indexes.append(str(i - len(pattern))) j = lps[j-1] # mismatch after j matches elif i < len(text) and pattern[j] != text[i]: # Skip mathcing lps[0..lps[j-1]] characters if j != 0: j = lps[j-1] else: i += 1 if len(indexes) == 0: print('Pattern not found') else: print(f'Pattern found at index(es): {", ".join(indexes)}') if __name__ == '__main__': pattern, text = read_data() search(pattern, text)
6559e6c26269d0b82caead489ccb9637b28bd855
hpoleselo/SSFR
/src/motor_control.py
3,366
3.65625
4
import RPi.GPIO as GPIO from time import sleep flag=1 # ---- SETTING UP RASPBERRY PI GPIO PORTS! ----- en = 25 # PWM port enb = 17 # PWM2 port in1 = 24 # Motor A forward direction control in2 = 23 # Motor A backwards direction control # Escolhemos duas GPIOs proximas da do Motor A inB1 = 22 # Motor B forward direction control inB2 = 27 # Motor B backwards direction control # Mode of refering to the ports from Raspberry GPIO.setmode(GPIO.BCM) # Motor A, setting the ports to control the direction of the motor GPIO.setup(in1,GPIO.OUT) # Forward GPIO.setup(in2,GPIO.OUT) # Backwards # Motor B, setting the ports to control the direction of the motor GPIO.setup(inB1,GPIO.OUT) # Forward GPIO.setup(inB2,GPIO.OUT) # Backwards # PWM is output GPIO.setup(en,GPIO.OUT) GPIO.setup(enb,GPIO.OUT) # By default none of the motors should run GPIO.output(in1,GPIO.LOW) GPIO.output(in2,GPIO.LOW) GPIO.output(inB1,GPIO.LOW) GPIO.output(inB2,GPIO.LOW) # PWM on port 25 with 1000Hz of frequency pwm = GPIO.PWM(en,1000) pwm2 = GPIO.PWM(enb,1000) # Starts PWM with 25% pwm.start(25) pwm2.start(25) print("\n") print("The default speed & direction of motor is LOW & Forward.....") print("r-run s-stop f-forward b-backward l-low m-medium h-high e-exit") print("\n") # Infinite loop while(1): x = raw_input() if x=='r': print("Running Motor A") if (flag==1): # Motor goes forward GPIO.output(in1,GPIO.HIGH) # We must set then the other direction to low GPIO.output(in2,GPIO.LOW) print("forward") x='z' else: GPIO.output(in1,GPIO.LOW) GPIO.output(in2,GPIO.HIGH) print("backward") x='z' # Adicionei isso pro segundo motor elif x=='r2': print("Running Motor B") if (flag==1): # Motor goes forward GPIO.output(inB1,GPIO.HIGH) # We must set then the other direction to low GPIO.output(inB2,GPIO.LOW) print("forward motorB") x='z' else: GPIO.output(inB1,GPIO.LOW) GPIO.output(inB2,GPIO.HIGH) print("backward motor B") x='z' elif x=='s': print("stop") GPIO.output(in1,GPIO.LOW) GPIO.output(in2,GPIO.LOW) GPIO.output(inB1,GPIO.LOW) GPIO.output(inB2,GPIO.LOW) x='z' elif x=='f': print("forward") GPIO.output(in1,GPIO.LOW) GPIO.output(in2,GPIO.HIGH) # teste GPIO.output(inB1,GPIO.HIGH) GPIO.output(inB2,GPIO.LOW) flag=1 x='z' elif x=='b': print("backward") GPIO.output(in1,GPIO.HIGH) GPIO.output(in2,GPIO.LOW) # teste GPIO.output(inB1,GPIO.LOW) GPIO.output(inB2,GPIO.HIGH) flag=0 x='z' elif x=='m': print("medium") pwm.ChangeDutyCycle(50) pwm2.ChangeDutyCycle(50) x='z' elif x=='h': print("high") pwm.ChangeDutyCycle(75) pwm2.ChangeDutyCycle(75) x='z' elif x=='e': GPIO.cleanup() print("GPIO Clean up") break else: print("<<< wrong data >>>") print("please enter the defined data to continue.....")
761dbe29103dd69eef9e3df3d3ddfe64757303b3
maria1226/Basics_Python
/pet_shop.py
368
3.90625
4
#Write a program that calculates the necessary costs for the purchase of food for dogs and other animals. #One package of dog food costs BGN 2.50, and any other that is not for them costs BGN 4. number_of_dogs=int(input()) number_of_animals=int(input()) cost_dogs=number_of_dogs*2.5 cost_animals=number_of_animals*4 cost=cost_animals+cost_dogs print(f'{cost:.2f} lv.')
4627fbfa65dfa258fc59e605bf0119f9158e3c18
maria1226/Basics_Python
/sum_vowels.py
284
3.859375
4
input_text=input() vowels_sum=0 for char in input_text: if char=='a': vowels_sum+=1 elif char=='e': vowels_sum+=2 elif char=='i': vowels_sum+=3 elif char=='o': vowels_sum+=4 elif char=='u': vowels_sum+=5 print(vowels_sum)
2abe2c2de6d54d9a44b3abb3fc03c88997840e61
maria1226/Basics_Python
/aquarium.py
801
4.53125
5
# For his birthday, Lubomir received an aquarium in the shape of a parallelepiped. You have to calculate how much # liters of water will collect the aquarium if it is known that a certain percentage of its capacity is occupied by sand, # plants, heater and pump. # Its dimensions - length, width and height in centimeters will be entered by the console. # One liter of water is equal to one cubic decimeter. # Write a program that calculates the liters of water needed to fill the aquarium. length_in_cm=int(input()) width_in_cm=int(input()) height_in_cm=int(input()) percentage_occupied_volume=float(input()) volume_aquarium=length_in_cm*width_in_cm*height_in_cm total_liters=volume_aquarium*0.001 percentage=percentage_occupied_volume*0.01 liters=total_liters*(1-percentage) print(f'{liters:.3f}')
9749eb59d49d3d4b6f05ae83a64099ab7c49e32b
lagzda/Exercises
/PythonEx/numadd.py
295
4.09375
4
#A function that adds up all the numbers from 1 to num def numAdd(num): #A great explanation of why this works can be found here - http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/runsums/triNbProof.html return (num*(num+1)) / 2 #Much better than a for loop. print numAdd(4)
9f41e34ee5b9e474d282d93dda41a10b055f389a
lagzda/Exercises
/PythonEx/heapsort.py
3,278
4.34375
4
class max_heap(): def __init__(self, items = []): #Initialise the 0th element just as zero because we will ignore it (for finding purposes) self.heap = [0] #Add each element to the list via push which sorts it correctly for i in items: self.push(i) #For the print function to ouput the proper heap list def __str__(self): return str(self.heap[1 : len(self.heap)]) #Add element to the heap's end initially and find the right location for it via float_up def push(self, i): self.heap.append(i) self.__float_up(len(self.heap) - 1) #Get the max value if the heap is not empty def peek(self): if self.heap[1]: return self.heap[1] else: return False def pop(self): #If the heap contains more than one element swap the last element with the biggest and pop the biggest which is #now at the end. After bubble down the top element which was swapped to the correct location via bubble_down if len(self.heap) > 2: self.__swap(1, len(self.heap)-1) max = self.heap.pop() self.__bubble_down(1) #If the heap contains just one element just pop it (remember the ignored 0) elif len(self.heap) == 2: max = self.heap.pop() #If the heap is empty return false else: max = False return max #A helper swap function that does just that def __swap(self, i, j): self.heap[i], self.heap[j] = self.heap[j], self.heap[i] #When inserted find the right location for value def __float_up(self, i): #Get the parent node's index for the new inserted element parent = i // 2 #If is the only element return #Also this is the base case for the recursion if i <= 1: return #If child is bigger than parent then swap elif self.heap[i] > self.heap[parent]: self.__swap(i, parent) #Recursion continues with parent but it actually is the same value from before because of the swap(i <-> parent) self.__float_up(parent) def __bubble_down(self, i): #Get node's left child left = i * 2 #Get node's right child right = i * 2 + 1 #Initially asume that the peek value is indeed the largest largest = i #If the node has a left child compare it and if child is greater then swap if len(self.heap) > left and self.heap[left] > self.heap[largest]: largest = left #If the node has a right child compare it and if child is greater then swap if len(self.heap) > right and self.heap[right] > self.heap[largest]: largest = right #If there have been found new larger values than the initial largest value swap down and repeat recursion if largest != i: self.__swap(i, largest) #Again the largest value is actually the value that we started with because of the swap(i <-> largest) self.bubble_down(largest) #Tests m_h = max_heap([1,7,4]) print m_h m_h.push(10) print m_h
56a13bb22f6d53ef4e149941d2d4119cc8d4edd3
lagzda/Exercises
/PythonEx/intersection.py
450
4.125
4
def intersection(arr1, arr2): #This is so we always use the smallest array if len(arr1) > len(arr2): arr1, arr2 = arr2, arr1 #Initialise the intersection holder inter = [] for i in arr1: #If it is an intersection and avoid duplicates if i in arr2 and i not in inter: inter.append(i) return inter #Test arr1 = [54,26,93,17,77,31,44,55,20] arr2 = [54, 93, 93, 7] print intersection(arr1, arr2)
c7a03b6d3e45db145994005adc04b8a5d8e4f14a
biomanojo/taller-matrices
/matriz.py
5,615
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 import random class Matriz(object): def __init__(self,filas=None,columnas=None): if filas: self.filas=filas else: self.filas=int(raw_input("ingrese numero de filas")) if columnas: self.columnas=columnas else: self.columnas=int(raw_input("ingrese numero de columnas")) def crearMatriz(self): self.matriz=[] for f in range(self.filas): self.matriz.append([0]*self.columnas) def imprimirMatriz(self): print self.matriz def llenarMatriz(self): for f in range(self.filas): for c in range(self.columnas): #self.matriz[f][c] = int(raw_input("Ingrese %d, %d: " %(f,c) )) self.matriz[f][c] = random.randint(1,10) #matrizB[c][f] = random.randint(5, 15) def datam(self): return self.matriz def validar(self,columnaA,filaB): if columnaA != filaB: print"no tiene solucion " exit() def validarsuma(self, columnaA, filaB,columnaB,filaA): if (columnaA != columnaB) or (filaA != filaB): print"no se puede hacer " exit() def validarestaMatriz(self, filaA,columnaA, filaB,columnaB): if (columnaA != columnaB) or (filaA != filaB): print"no se puede hacer " exit() def multiMatriz(self,matrizA,matrizB,filaB): for f in range(self.filas): for c in range(self.columnas): for k in range(filaB): self.matriz[f][c]+=matrizA[f][k]*matrizB[k][c] def sumaMatriz(self,matrizA,matrizB): for f in range(self.filas): for c in range(self.columnas): self.matriz[f][c]= matrizA[f][c]+matrizB[f][c] def restaMatriz(self,matrizA,matrizB): for f in range(self.filas): for c in range(self.columnas): self.matriz[f][c]= matrizA[f][c]-matrizB[f][c] def multi_vMatriz(self,matrizA,valor): for f in range(self.filas): for c in range(self.columnas): #for k in range(filaB): self.matriz[f][c]=valor*matrizA[f][c] def simeMatriz(self): band = 'verdadero' for f in range(self.filas): for c in range(self.columnas): if( self.matriz[f][c]!=self.matriz[c][f]): band='falso' break if (band == "verdadero") : print"es simetrica" else: print"no es simetrica" def trasMatriz(self,matriz1): for f in range(self.filas): for c in range(self.columnas): self.matriz[f][c] = matriz1[c][f] #for f in range(self.columnas): #print(self.matriz[f]) def identidadMatriz(self): for f in range(self.filas): self.matriz[f][f]=1 def coMatriz(self, m): self.result = [] for f in m: self.result.append(f[:]) return self.result def combiMatriz(self, m, i, j, e): n = len(m) for c in range(n): m[j][c] = m[j][c] + e * m[i][c] def cambiofilasMatriz(self, m, i, j): m[i], m[j] = m[j], m[i] def multifilamatriz(self, m, f, e): n = len(m) for c in range(n): m[f][c] = m[f][c] * e def primeMatriz(self, m, i): result = i while result < len(m) and m[result][i] == 0: result = result + 1 return result def determinante(self, matr): m = self.coMatriz(matr) n = len(m) determ = 1 for i in range(n): j = self.primeMatriz(m, i) if j == n: return 0 if i != j: determ = -1 * determ self.cambiofilasMatriz(m, i, j) determ = determ * m[i][i] self.multifilamatriz(m, i, 1. / m[i][i]) for k in range(i + 1, n): self.combiMatriz(m, i, k, -m[k][i]) print int(determ) def cuadrada(self): if self.filas == self.columnas: return True else: return False def inversaMatriz(self,matrizA): self.determinante(determ) print int(determ) #for f in range(self.filas): # for c in range(self.columnas): # for k in range(filaB): # self.matriz[f][c] = determ * matrizA[f][c] def multipotMatriz(self, matriz1, matriz2, fila): res = [] for f in range(fila): res.append([0] * fila) for i, row in enumerate(res): for j in range(0, len(row)): for k in range(0, len(row)): res[i][j] += matriz1[i][k] * matriz2[k][j] return res def potenciaMatriz(self, pow): powerhash = {} if pow in powerhash.keys(): return powerhash[pow] if pow == 1: return self.matriz if pow == 2: powerhash[pow] = self.multipotMatriz(self.matriz, self.matriz, self.filas) return powerhash[pow] if pow % 2 == 0: powerhash[pow] = self.multipotMatriz(self.potenciaMatriz(pow / 2), self.potenciaMatriz(pow / 2), self.filas) else: powerhash[pow / 2 + 1] = self.multipotMatriz(self.potenciaMatriz(pow / 2), self.matriz, self.filas) powerhash[pow] = self.multipotMatriz(self.potenciaMatriz(pow / 2), powerhash[pow / 2 + 1], self.filas) return powerhash[pow]
91c45a8421ed5d9a808927abe4445fd336e93b80
JasonRafeMiller/LncRNA
/scripts/fasta_extractor.py
1,177
3.75
4
import sys ''' Input: fasta file with each sequence on one line. Input: sequence number to start with and number to print. Output: subset fasta file Example to extract just the first sequence. $ python extractor.py bigfile.fasta 1 1 > reduced.fasta ''' if len(sys.argv) != 4+1: print("Number of arguments was %d" % (len(sys.argv))) print("Usage: p script <infile> <start> <size> <outfile>") exit(4) filename = sys.argv[1] start_at = int(sys.argv[2]) group_size = int(sys.argv[3]) outfile = sys.argv[4] if start_at < 1: print("Staring position was %d" % (start_at)) print("Counting starts at 1.") exit(5) file1 = open (outfile,"w") with open (filename,'rt') as fastafile: even_odd = 0 num_in = 0 num_out = 0 defline = "" sequence = "" for oneLine in fastafile: if even_odd == 0: defline = oneLine even_odd = 1 else: even_odd = 0 num_in = num_in + 1 sequence = oneLine if (num_in >= start_at) and (num_out < group_size): num_out = num_out + 1 file1.write ( defline ) file1.write ( sequence )
6f77c3a1e04eb47c490eb339cf39fc5c925e453c
rudiirawan26/Bank-Saya
/bank_saya.py
1,114
4.15625
4
while True: if option == "x": print("============================") print("Selamat Datang di ATM saya") print("============================") print('') option1 = print("1. Chek Uang saya") option2 = print("2. Ambil Uang saya") option3 = print("3. Tabung Uang saya") print('') total = 0 option = int(input("Silakan pilih Option: ")) if option == 1: print("Uang kamu berjumlah: ",total) elif option == 2: ngambil_uang = eval(input("Masukan nominal uang yang akan di ambil: ")) rumus = total - ngambil_uang if ngambil_uang <= total: print("Selamat anda berhasil ngambil unang") else: print("Saldo anda tidak mencukupi") elif option == 3: menabung = eval(input("Masukan nominal uang yang kan di tabung: ")) rumus_menabung = menabung + total print("Proses menabung SUKSES") else: print("Masukan tidak di kenali") else: print("Anda telah keluar dari program")
21d3a26de87d53a385e8386d6c9ae54e223466ff
Toddrickson/Git-Tutorial
/the_if_statement.py
700
3.890625
4
#!/usr/bin/python def main(): running = True year = 2001 counter = 0 while running == True: try: if year >= 2001 and year < 2007: print "The were signed to Lookout Records" elif year >= 2007 and year < 2010: print "The were signed to Touch and Go Records" elif year >= 2010 < 2016: print "They were signed to Matador Records" else: print "They were unsigned" except: print "Something went wrong" counter = counter + 1 if counter > 0: running = False if __name__ == "__main__": main()
efbf2aa75956b9e23da9d4adbbe57a35fd4b6b45
yulianacastrodiaz/learning_python
/strings.py
577
4.09375
4
my_str = "Hello World" print(dir(my_str)) print("Saludar: " + my_str) print(f"Saludar: {my_str}") print(my_str) print(my_str.upper()) print(my_str.lower()) print(my_str.swapcase()) print(my_str.capitalize()) print(my_str.title()) print(my_str.replace("Hello", "Yuli")) print(my_str.startswith("H")) print(my_str.endswith("a")) print(my_str.isnumeric()) print(my_str.isalpha()) print(my_str.split()) print(my_str.find("o")) print(len(my_str)) print(my_str.index("e")) print(my_str.count("l")) print(",".join(["nombre", "apellido", "ciudad"])) print(",".join("nombre"))
dc962aad851c775b8bdc4bde9ba9025b733467d3
yulianacastrodiaz/learning_python
/numbers.py
180
3.796875
4
print(1 - 2) print(1 + 2) print(2 * 2) print(3 / 2) print(3 // 2) print(3 % 2) print(1 + 1.0) print(2 ** 2) age = input("Insert your age: ") new_age = int(age) + 5 print(new_age)
e58773f72ba31e9851afa7e35d6662728442280e
Pravleen/Python
/Hackerearth/pg2.py
288
3.90625
4
'''Jadoo hates numbers, but he requires to print a special number "420" to recharge the equation of life.He asks your help to print the number but Since he hates numbers, he asks you to write the program such that there would not be any number in the code. SOLUTION''' print(ord('Ƥ'))
dc09618c3d099642222d246f6e2a7a9af942934d
ychaparala/tdd_code
/code/customer_data.py
1,012
3.78125
4
#!/usr/bin/env python # ########################################### # # File: customer_data.py # Author: Ra Inta # Description: # Created: July 28, 2019 # Last Modified: July 28, 2019 # ########################################### class Customer(): """Create a Customer for our online game. They have an account_balance, which they can use to purchase level-ups within the game, via the purchase_level method. This increases their level and decreases their account_balance according to the current cost of a level.""" level_cost = 10 def __init__(self, user_name, email, account_balance, level): self.user_name = user_name self.email = email self.account_balance = account_balance self.level = level def purchase_level(self, n=1): self.account_balance = self.account_balance - n*self.level_cost self.level += n ########################################### # End of customer_data.py ###########################################
224ce21b5f87e3186d80a822d0bd5bf80a56ea7d
ychaparala/tdd_code
/code/test_customer_data.py
1,269
3.65625
4
#!/usr/bin/env python # ########################################### # # File: test_customer_data.py # Author: Ra Inta # Description: # Created: July 28, 2019 # Last Modified: July 28, 2019 # ########################################### import unittest from customer_data import Customer class TestCustomerData(unittest.TestCase): def setUp(self): print("setUp") self.customer1 = Customer("beeble", "bsmith@itsme.com", 350, 7) self.customer2 = Customer("KarenRulz", "kaz@yolo.com", 5, 2) def test_account_positive(self): print("test_account_positive") self.assertTrue(self.customer1.account_balance >= 0) self.assertTrue(self.customer2.account_balance >= 0) def test_purchase_level(self): print("test_purchase_level") self.customer1.purchase_level(2) self.customer2.purchase_level(1) self.assertEqual(self.customer1.level, 9) self.assertEqual(self.customer1.account_balance, 350 - 2*10) self.assertEqual(self.customer2.level, 3) self.assertEqual(self.customer2.account_balance, 5 - 1*10) if __name__ == '__main__': unittest.main() ########################################### # End of test_customer_data.py ###########################################
0e563e8d242d2fd9b240bf7bfb8c5320d1d21ff6
harrisonlingren/randomPython
/pigLatin/pigLatin.py
386
3.90625
4
print 'Welcome to the Pig Latin Translator!' original = (raw_input("Please type the word you wish to translate: ")) indexMax = len(original) pyg = 'ay' result = '' if len(original) > 0 and original.isalpha(): original.lower() for i in range(1, indexMax): result = result + original[i] result = result + original[0] + pyg else: print "empty" print result
503bf4a9807a1dccfc5c8284c9189ba270aa94d8
harrisonlingren/randomPython
/0-1KnapsackProblem/01knapsack.py
2,084
3.515625
4
import datetime, sys, dynamic, bruteforce, backtracking, firstBranchBound def run(): path = input("Which method do you want to use? \nBrute force (1), Dynamic (2), Best First Branch Bound (3), or Backtracking (4)?\nOr press q to quit : ") if path == '1': time1 = datetime.datetime.now() print( bruteforce.bruteforce(W, items[2], items[1], len(items[0])) ) time2 = datetime.datetime.now() tdelta = time2 - time1 print("Brute force: Time taken: %s ms" % int(tdelta.total_seconds()*1000) ) print("\n") run() elif path == '2': time1 = datetime.datetime.now() print( dynamic.dynamic(W, items[2], items[1], len(items[0])) ) time2 = datetime.datetime.now() tdelta = time2 - time1 print("Dynamic: Time taken: %s ms" % int(tdelta.total_seconds()*1000) ) print("\n") run() elif path == '3': time1 = datetime.datetime.now() print( firstBranchBound.firstBranchBound(W, items[2], items[1], len(items[0])) ) time2 = datetime.datetime.now() tdelta = time2 - time1 print("Best First Branch Bound: Time taken: %s ms" % int(tdelta.total_seconds()*1000) ) print("\n") run() elif path == '4': time1 = datetime.datetime.now() print( backtracking.backtracking(W, items[2], items[1], len(items[0])) ) time2 = datetime.datetime.now() tdelta = time2 - time1 print("Backtracking: Time taken: %s ms" % int(tdelta.total_seconds()*1000) ) print("\n") run() elif path == 'q': sys.exit("See ya!") else: print("Error: no valid option chosen. Please try again.") print("\n") run() # ---------------------------------------------------------------------- # Main program, load items n = int(input("Enter the number of items : ")) W = int(input("Enter total weight : ")) #init 2-dimensional array for items items = [[0]*4 for i in range(n)] # create 2-dimensional array for i in range(n): items[i][0] = i+1 items[i][1] = int(input("Enter profit for %s : " % (i+1) ) ) items[i][2] = int(input("Enter weight for %s : " % (i+1) ) ) items[i][3] = int(items[i][1] / items[i][2]) print() print("Items: %s" % items) run()
e307c3dba8504a6fdb175dafce3ed5b75d7e106c
adiada/Python-files
/stack_intro.py
582
3.953125
4
class Stack(): def __init__(self): self.items = [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def isEmpty(self): return self.items == [] def peek(self): if not self.isEmpty(): return self.items[-1] def get_stack(self): return self.items # myStack = Stack() # myStack.push(3) # myStack.push(2) # myStack.push(5) # myStack.push(8) # myStack.push(10) # print(myStack.get_stack()) # print(myStack.pop()) # print(myStack.peek()) # print(myStack.isEmpty())
3206e8d9bc0c7770ce31a3413b99ed87f61e7d9f
jtoscarson/plex_manage
/sql_test.py
1,128
3.640625
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) except Error as except_err: print(except_err) return conn def select_all_tasks(conn): """ Query all rows in the tasks table :param conn: the Connection object :return: """ cur = conn.cursor() cur.execute("""SELECT title FROM external_metadata_items WHERE title NOT LIKE "" AND id NOT IN (SELECT id FROM metadata_items)""") rows = cur.fetchall() for row in rows: print(row) def main(): database = r"/var/snap/plexmediaserver/common/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db" # create a database connection conn = create_connection(database) with conn: select_all_tasks(conn) if __name__ == '__main__': main()
5f0eea2933fad7b03421df1e9bf732a3de7240f0
happyhoneyb/Udacity-I2P-Stage2
/stage2_final.py
5,038
4.15625
4
#This game tests a player's knowledge of world capitals. #The player will be given a paragraph related to world capitals and asked to fill-in-the blanks. #There are three levels -- easy, medium, and hard. Each level has four questions. #The player has three chances to provide the corrct answer before it will be provided. #The player may repeat the game once gameplay ends. def IsCorrect(answer, capital): """Return true if player's answer matches the input capital.""" if answer == capital: return True return False sentence = " " def CorrectedSentence(sentence, blank, capital): """Return corrected sentence replacing the input blank with the input capital.""" sentence = sentence.replace(blank, capital) return sentence capital = [] blank = ['___1___', '___2___', '___3___', '___4___'] answer = 'nada' def play_level(sentence, blank, answer, capital): """Print corrected sentence for each input blank if player's answer matches the variable capital or after three attempts.""" print sentence i = 0 for number in blank: answer = raw_input("Which city is " + str(i+1) +"? ").title() attempt = 1 while IsCorrect(answer, capital[i]) == False and attempt < 3: print "Try again." answer = raw_input("Which city is " + str(i+1) +"? ").title() attempt += 1 if IsCorrect(answer, capital[i]) == True or attempt >= 3: sentence = CorrectedSentence(sentence, number, capital[i]) print sentence i += 1 return "Thank you for playing." easy_capital = ['Tokyo', 'London', 'Moscow', 'Beijing'] medium_capital = ['Ottawa', 'Jakarta', 'Canberra', 'Brasilia'] hard_capital = ['Abuja','Tallinn','Tegucigalpa','Tashkent'] def ChooseLevel_Capital(level): """Return correct answers when player inputs level.""" if level == 'easy': capital = easy_capital elif level == 'medium': capital = medium_capital elif level == 'hard': capital = hard_capital else: capital = easy_capital return capital easy_sentence = """ ___1___, the capital of Japan, is the world's largest metropolitan area. The capital of Great Britain, ___2___, is also the first city to host the modern Summer Olympic games three times. The capital of Russia is ___3___, although at one point before the Russian Revolution of 1917, it had been Saint Petersburg. The name ___4___, the capital of China, means "Northern Capital", and is meant to distinguish it from Nanjing, the "Southern Capital" during the Ming Dynasty.""" medium_sentence = """Many Americans do not know that the capital of their northern neighbor Canada is ___1___. ___2___, the capital of Indonesia, is nicknamed "the Big Durian", aka the New York City (the Big Apple) of Indonesia. Many outside Australia think that its capital is Sydney or Melbourne, but it is actually ___3___. In 1960, ___4___ became the capital of Brazil; it is a planned city founded specifically for this purpose.""" hard_sentence = """The capital of Nigeria is ___1___ since 1991 and the city was built specifically for that purpose. ___2___, the capital of Estonia, boasts the highest number of startups per person in Europe. If you're visiting ___3___, the capital of Honduras, be forewarned that it has what is considered one of the most difficult airports in the world to land a plane. The capital of Uzbekistan, ___4___, was destroyed by Genghis Khan in 1219 but rebuilt and prospered from the Silk Road.""" def ChooseLevel_Sentence(level): """Return fill-in-the-blank quiz when player inputs level of difficulty. Choose easy level if level chosen is not understood.""" if level == 'easy': sentence = easy_sentence elif level == 'medium': sentence = medium_sentence elif level == 'hard': sentence = hard_sentence else: sentence = "We'll start with the EASY level." + easy_sentence return sentence def play_game(sentence, blank, answer, capital): """Play game of fill-in-the-blanks with capital cities using clues provided. Prompt user to repeat game when finished.""" print """Hello. This game will test your knowledge of world capital cities. There are three levels of difficulty and four questions per level. After three wrong answers, the correct answer will be provided. Please begin by choosing a level.""" level = raw_input("Which level would you like to play? Easy, Medium, or Hard? ").lower() capital = ChooseLevel_Capital(level) sentence = ChooseLevel_Sentence(level) print play_level(sentence, blank, answer, capital) again = raw_input("Would you like to play again? Yes or no? ").lower() if again == 'yes': return play_again(sentence, blank, answer, capital) else: return "Thank you for playing. Good bye!" def play_again(sentence, blank, answer, capital): """Repeat the game.""" return play_game(sentence, blank, answer, capital) print play_game(sentence, blank, answer, capital)
f152e7e1c240d5266f781f8f4c90329b46266202
xiaoluome/algorithm
/Week_02/id_3/bstree/98/LeetCode_98_3_v3.py
637
3.734375
4
class Solution: def isValidBST(self, root): """ bst定义 左子树都比节点小 右子树都比节点大 并且所有子树都一样 写起来代码更好看,更优雅 """ return self.valid(root, None, None) def valid(self, node, left, right): if not node: return True if left is not None and left >= node.val: return False if right is not None and right <= node.val: return False return self.valid(node.left, left, node.val) and self.valid(node.right, node.val, right)
34ed13fb31e43aea6f64a41bf627b2694db1a5a8
xiaoluome/algorithm
/Week_02/id_26/LeetCode_783_26.py
1,645
3.6875
4
# # @lc app=leetcode.cn id=783 lang=python # # [783] 二叉搜索树结点最小距离 # # https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/description/ # # algorithms # Easy (51.59%) # Likes: 24 # Dislikes: 0 # Total Accepted: 3.2K # Total Submissions: 6.2K # Testcase Example: '[4,2,6,1,3,null,null]' # # 给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。 # # 示例: # # # 输入: root = [4,2,6,1,3,null,null] # 输出: 1 # 解释: # 注意,root是树结点对象(TreeNode object),而不是数组。 # # 给定的树 [4,2,6,1,3,null,null] 可表示为下图: # # ⁠ 4 # ⁠ / \ # ⁠ 2 6 # ⁠ / \ # ⁠ 1 3 # # 最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。 # # 注意: # # # 二叉树的大小范围在 2 到 100。 # 二叉树总是有效的,每个节点的值都是整数,且不重复。 # # # # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDiffInBST(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 31 << 1 self.last = -31 << 1 def dfs(root): if not root: return if root.left: dfs(root.left) self.ans = min(self.ans, root.val - self.last) self.last = root.val if root.right: dfs(root.right) dfs(root) return self.ans
f97e7309d3b6b685c2df70094f26ce46ade820db
xiaoluome/algorithm
/Week_03/id_26/LeetCode_703_26.py
1,720
3.84375
4
# # @lc app=leetcode.cn id=703 lang=python # # [703] 数据流中的第K大元素 # # https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/description/ # # algorithms # Easy (38.59%) # Likes: 56 # Dislikes: 0 # Total Accepted: 5.1K # Total Submissions: 13.1K # Testcase Example: '["KthLargest","add","add","add","add","add"]\n[[3,[4,5,8,2]],[3],[5],[10],[9],[4]]' # # 设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。 # # 你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 # KthLargest.add,返回当前数据流中第K大的元素。 # # 示例: # # # int k = 3; # int[] arr = [4,5,8,2]; # KthLargest kthLargest = new KthLargest(3, arr); # kthLargest.add(3);   // returns 4 # kthLargest.add(5);   // returns 5 # kthLargest.add(10);  // returns 5 # kthLargest.add(9);   // returns 8 # kthLargest.add(4);   // returns 8 # # # 说明: # 你可以假设 nums 的长度≥ k-1 且k ≥ 1。 # # import heapq class KthLargest(object): def __init__(self, k, nums): """ :type k: int :type nums: List[int] """ self.heap = [] self.k = k map(self.add, nums) def add(self, val): """ :type val: int :rtype: int """ if len(self.heap) < self.k: heapq.heappush(self.heap, val) elif val > self.heap[0]: heapq.heapreplace(self.heap, val) return self.heap[0] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val)
a2f2382aa5dd221ddb7171685dbf0bc0b70dd210
xiaoluome/algorithm
/Week_04/id_36/LeetCode_78_36.py
912
3.578125
4
# # @lc app=leetcode.cn id=78 lang=python3 # # [78] 子集 # # https://leetcode-cn.com/problems/subsets/description/ # # algorithms # Medium (73.91%) # Likes: 268 # Dislikes: 0 # Total Accepted: 23.5K # Total Submissions: 31.8K # Testcase Example: '[1,2,3]' # # 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 # # 说明:解集不能包含重复的子集。 # # 示例: # # 输入: nums = [1,2,3] # 输出: # [ # ⁠ [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # # class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n == 0: return [] res = [] def backtrack(i, tmp): res.append(tmp) for j in range(i, n): backtrack(j + 1, tmp + [nums[j]]) backtrack(0, []) return res
037fe7225c0b2235316db551a1f422c1819ee122
xiaoluome/algorithm
/Week_03/id_3/heap/LeetCode_703_3.py
643
3.640625
4
import heapq class KthLargest: def __init__(self, k: int, nums): self.heap = [] self.k = k for v in nums: self.add(v) def add(self, val: int): if len(self.heap) < self.k: heapq.heappush(self.heap, val) elif val > self.heap[0]: heapq.heapreplace(self.heap, val) return self.heap[0] kthLargest = KthLargest(3, [4, 5, 8, 2]) print(kthLargest.add(3) == 4) print(kthLargest.add(5) == 5) print(kthLargest.add(10) == 5) print(kthLargest.add(9) == 8) print(kthLargest.add(4) == 8) h = heapq.nlargest(3, [1, 2, 3, 4, 5]) heapq.heappush(h, 9) print(h)
670d08c03877c91a03decc53738a2e4c1bc35dd3
xiaoluome/algorithm
/Week_04/id_36/LeetCode_169_36.py
3,349
3.78125
4
# # @lc app=leetcode.cn id=169 lang=python3 # # [169] 求众数 # # https://leetcode-cn.com/problems/majority-element/description/ # # algorithms # Easy (59.73%) # Likes: 259 # Dislikes: 0 # Total Accepted: 49.1K # Total Submissions: 82.1K # Testcase Example: '[3,2,3]' # # 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 # # 你可以假设数组是非空的,并且给定的数组总是存在众数。 # # 示例 1: # # 输入: [3,2,3] # 输出: 3 # # 示例 2: # # 输入: [2,2,1,1,1,2,2] # 输出: 2 # # # # 暴力法 # class Solution: # def majorityElement(self, nums: List[int]) -> int: # majority_num = len(nums)//2 # for num in nums: # count = 0 # for n in nums: # if n == num: # count += 1 # if count > majority_num: # return num # return -1 # # 哈希表-1 # class Solution: # def majorityElement(self, nums: List[int]) -> int: # if not nums or len(nums) < 1: # return 0 # counts = {} # for num in nums: # if not counts.get(num): # counts[num] = 1 # else: # counts[num] += 1 # max_value = 0 # majority = 0 # for key, value in counts.items(): # if value > max_value: # max_value = value # majority = key # return majority # # 哈希表-2 # class Solution: # def majorityElement(self, nums: List[int]) -> int: # import collections # counts = collections.Counter(nums) # return max(counts.keys(), key = counts.get) # # 排序 # class Solution: # def majorityElement(self, nums: List[int]) -> int: # nums_len = len(nums) # if not nums or nums_len < 1: # return 0 # nums.sort() # return nums[nums_len // 2] # # 分治 # class Solution: # def majorityElement(self, nums: List[int]) -> int: # def majority_element_rec(low, high): # if low == high: # return nums[low] # middle = low + (high - low) // 2 # left = majority_element_rec(low, middle) # right = majority_element_rec(middle + 1, high) # if left == right: # return left # # left_count = sum(1 for i in range(low, high + 1) if nums[i] == left) # # right_count = sum(1 for i in range(low, high + 1) if nums[i] == right) # left_count = 0 # right_count = 0 # for i in range(low, high + 1): # if nums[i] == left: # left_count += 1 # elif nums[i] == right: # right_count += 1 # return left if left_count > right_count else right # return majority_element_rec(0, len(nums) - 1) # Boyer-Moore 投票算法 class Solution: def majorityElement(self, nums: List[int]) -> int: count = 0 candidate = None for num in nums: if count == 0: candidate = num count += (1 if num == candidate else -1) return candidate
f3ce0771cba30204cabbd3a53159b29143cc44d0
xiaoluome/algorithm
/Week_02/id_36/LeetCode_3_36.py
1,897
3.75
4
# # @lc app=leetcode.cn id=3 lang=python3 # # [3] 无重复字符的最长子串 # # https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/ # # algorithms # Medium (29.74%) # Likes: 1907 # Dislikes: 0 # Total Accepted: 136.6K # Total Submissions: 457.9K # Testcase Example: '"abcabcbb"' # # 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 # # 示例 1: # # 输入: "abcabcbb" # 输出: 3 # 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 # # # 示例 2: # # 输入: "bbbbb" # 输出: 1 # 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 # # # 示例 3: # # 输入: "pwwkew" # 输出: 3 # 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 # 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。 # # # # class Solution: # def lengthOfLongestSubstring(self, s: str) -> int: # n = len(s) # ans = 0 # for i in range(n): # for j in range(i + 1, n + 1): # if self.allUnique(s, i, j): # ans = max(ans, j - i) # return ans # def allUnique(self, s, start, end): # set_v = set() # for i in range(start, end): # ch = s[i] # if ch in set_v: # return False # set_v.add(ch) # return True class Solution: def lengthOfLongestSubstring(self, s: str) -> int: n = len(s) ans = 0 start = 0 dict_v = dict() for end in range(n): ch = s[end] if dict_v.get(ch, None): start = max(dict_v.get(ch), start) ans = max(ans, end - start + 1) dict_v[ch] = end + 1 return ans
9c42e78c87445c6506386f322be27e6be84af432
xiaoluome/algorithm
/Week_01/id_3/linked/21/LeetCode_21_3_v2.py
257
3.984375
4
# 本代码按python语法进行优化 查看之前得提交可以看到更远古的写法 def merge(l1, l2): if not l1 or not l2: return l1 or l2 if l1.val > l2.val: l1, l2 = l2, l1 l1.next = merge(l1.next, l2) return l1
a2c243b02a5e9daccc63e5108c74121cad0ec4b8
xiaoluome/algorithm
/Week_01/id_3/recursion/101/LeetCode_101_3_v2.py
636
3.8125
4
""" 参考答案 两颗子树的对称比较,除了比较根节点外,还要比较t1.left是否与t2.right对称, t1.right 是否与t2.left对称 在进行深度优先遍历的时候,每次针对要进行判断是否是镜像的子树进行迭代 1 / \ 2 2 / \ / \ 3 4 4 3 """ def is_symmetric(root): return is_mirror(root.left, root.right) def is_mirror(t1, t2): if not t1 and not t2: return True if bool(t1) != bool(t2): return False if t1.val != t2.val: return False return is_mirror(t1.left, t2.right) and is_mirror(t1.right, t2.left)
567b2867bba8e57dac0a14ba6d13a139779011fe
xiaoluome/algorithm
/Week_03/id_3/dfs/LeetCode_329_3_v1.py
1,479
3.5
4
""" 矩阵中的最长递增路径 思路:DFS + 缓存 DFS过程由于需求是数值递增,所以在下钻到过程中不会出现回路,不需要缓存去重。 由于需要找到全局最优解,所以也不需要依赖贪心。 """ class Solution: def longestIncreasingPath(self, matrix): if not matrix: return 0 col_length = len(matrix) row_length = len(matrix[0]) cache = [ [0] * row_length for _ in range(col_length) ] r = 0 for i in range(col_length): for j in range(row_length): r = max(r, self.dfs(matrix, cache, i, j, col_length, row_length, None)) return r def dfs(self, matrix, cache, i, j, col_length, row_length, prev): if i < 0 or i >= col_length or j < 0 or j >= row_length: return 0 curr = matrix[i][j] if prev is not None and prev >= curr: return 0 if cache[i][j]: return cache[i][j] r = 1 + max( self.dfs(matrix, cache, i+1, j, col_length, row_length, curr), self.dfs(matrix, cache, i-1, j, col_length, row_length, curr), self.dfs(matrix, cache, i, j+1, col_length, row_length, curr), self.dfs(matrix, cache, i, j-1, col_length, row_length, curr), ) cache[i][j] = r return r s = Solution() print(s.longestIncreasingPath( [ [9, 9, 4], [6, 6, 8], [2, 1, 1] ]))
b2839f17737aca2ebb9b6a440464065a3874aa99
xiaoluome/algorithm
/Week_01/id_3/recursion/104/test_104.py
718
3.625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def build(nums): if not nums: return None return build_node(nums, 1) def build_node(nums, i): if len(nums) < i or nums[i-1] is None: return None node = TreeNode(nums[i-1]) node.left = build_node(nums, 2 * i) node.right = build_node(nums, 2 * i + 1) return node import LeetCode_104_3_v1 import LeetCode_104_3_v2 # f = LeetCode_104_3_v1.max_depth f = LeetCode_104_3_v2.max_depth def check(nums, r): _r = f(build(nums)) print(_r, r, _r == r) check([3, 9, 20, None, None, 15, 7], 3) check([0, 2, 4, 1, None, 3, -1, 5, 1, None, 6, None, 8], 4)
0256c1c41c9b8f06978e0b6c6874ef0a7377c8dc
xiaoluome/algorithm
/Week_02/id_36/LeetCode_101_36.py
1,965
4.03125
4
# # @lc app=leetcode.cn id=101 lang=python3 # # [101] 对称二叉树 # # https://leetcode-cn.com/problems/symmetric-tree/description/ # # algorithms # Easy (46.79%) # Likes: 357 # Dislikes: 0 # Total Accepted: 36K # Total Submissions: 77K # Testcase Example: '[1,2,2,3,4,4,3]' # # 给定一个二叉树,检查它是否是镜像对称的。 # # 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 # # ⁠ 1 # ⁠ / \ # ⁠ 2 2 # ⁠/ \ / \ # 3 4 4 3 # # # 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: # # ⁠ 1 # ⁠ / \ # ⁠ 2 2 # ⁠ \ \ # ⁠ 3 3 # # # 说明: # # 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。 # # # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # # 递归 # class Solution: # def isSymmetric(self, root: TreeNode) -> bool: # return self.isMirror(root, root) # def isMirror(self, root1: TreeNode, root2: TreeNode) -> bool: # if root1 is None and root2 is None: # return True # if root1 is None or root2 is None: # return False # return root1.val == root2.val and self.isMirror(root1.right, root2.left) and self.isMirror(root1.left, root2.right) # 迭代 class Solution: def isSymmetric(self, root: TreeNode) -> bool: queue = [] queue.append(root) queue.append(root) while len(queue) > 0: t1 = queue.pop() t2 = queue.pop() if t1 is None and t2 is None: continue if t1 is None or t2 is None: return False if t1.val != t2.val: return False queue.append(t1.left) queue.append(t2.right) queue.append(t1.right) queue.append(t2.left) return True