blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
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")
... |
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 ... |
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 ope... |
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 = n... |
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 eq... |
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__... |
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(n... |
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: "))
participaci... |
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")... |
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 qu... |
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 ... |
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 /... |
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)
... |
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"... |
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(... |
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_Me... |
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] = rowIncreme... |
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é ... |
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... |
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... |
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"
pr... |
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:
... |
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 xr... |
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 argume... |
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)... |
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 Child... |
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, ... |
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],
... |
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)):
... |
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 na... |
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(... |
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... |
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: {общият... |
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
... |
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 ... |
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():
opti... |
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 js... |
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, Fals... |
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)
... |
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, ... |
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.... |
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:
... |
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_... |
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... |
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
... |
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á... |
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]
chu... |
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']... |
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):
p... |
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:
... |
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.... |
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<po... |
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(... |
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.mainloo... |
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:
... |
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 ... |
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... |
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 centimete... |
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 t... |
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:
... |
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
e... |
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" %... |
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 s... |
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 ... |
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.en... |
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 accoun... |
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(unitte... |
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 ... |
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.brute... |
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]
... |
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)
ex... |
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 provid... |
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 ... |
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]'
#
# 给定一个二叉搜索树... |
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","... |
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,返回该数组所有可能的子集(幂集)。
#
# 说明:解集不能包含重复... |
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... |
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 ⌋ ... |
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"'
#
# 给定一个... |
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 T... |
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 fo... |
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-... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.