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 |
|---|---|---|---|---|---|---|
a9a4caf86458c65669d46b741ba4970ed112a613 | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/ejercicio12.py | 3,944 | 4.46875 | 4 | #PYTHON CONDITIONS AND IF STATEMENTS
#Supports the usual logical conditiions from mathematics:
# Equals: a==b
# Not Equals: a!=b
# Less than: a<b
# Less than or equal to: a<=b
# Greater than: a>b
# Greater than or equal to: a>=b
#These conditios can be used in several ways, mos commonly in "if statements" and loops,
#A... |
39773f7d4aa077701cbb9b8bd826f63c5b6169a4 | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 3 - File Handling/writeFiles.py | 1,040 | 4.65625 | 5 | # PYTHON FILE WRITE #
#Create a new File:
# To create a new file in Python, use the open() method, with one of the
# following parameter:
# "x" - Create - will create a file, returns an error if the file exist
# "a" - Append - will create a file if the specified file does not exist
#Example:
# Cre... |
ec8095ecaad2420600904be9428c0860bdd821ef | JeanBarbosa27/curso_alura_testes_com_python | /src/leilao/dominio.py | 2,294 | 3.59375 | 4 | from src.leilao.excecoes.lance_invalido import LanceInvalido
class Usuario:
def __init__(self, nome, carteira):
self.__nome = nome
self.__carteira = carteira
@property
def nome(self):
return self.__nome
@property
def carteira(self):
return self.__c... |
c7c3ed0fcd2015ffbcbf7fb4f38f92b89f6d7242 | repinnick/codewars | /7kyu_vowel_count.py | 237 | 4 | 4 | input_str = input('Say something: ')
def get_count(input_str):
num_vowels = 0
vowels = 'aeiou'
for i in input_str:
if i.lower() in vowels:
num_vowels += 1
return num_vowels
print(get_count(input_str)) |
b5f275bc6cf69d91f03372f898774c0ea6a8fa2e | repinnick/codewars | /7kyu_grouth_of_population.py | 1,174 | 3.5 | 4 | """
В небольшом городке население p0 = 1000в начале года.
Население регулярно увеличивается на 2 процента каждым годом, и,
кроме того, 50 ежегодно в городе приезжают новые жители.
Сколько лет нужно городу, чтобы население было больше или равно p = 1200населению?
p0 - популяция на данный момент
persent - на сколько про... |
99f84a4593a7ff1a6e6cc7a013e689c29abf53d1 | Cylra/py3Learn | /PAT/B/1013.py | 850 | 3.765625 | 4 | #! /usr/bin/env python3
import math
#质数生成器
def genPrime(max):
count = 0
yield 2
count = 1
yield 3
count = 2
num = 5
while(count < max):
val = int(math.sqrt(num)) + 1 #取平方根
for i in range(2, val):
if num %i == 0: #被整除,说明不是质数
break
if i ... |
f108b27cd2eb6e28806bece75d9d44c712b79bbb | Cylra/py3Learn | /PAT/B/1015.py | 1,220 | 3.734375 | 4 | #! /usr/bin/env python3
def Rule(listAll, L, H):
list1 = []
list2 = []
list3 = []
list4 = []
for i in listAll:
deGrade = i[1]
caiGrade = i[2]
if deGrade >= H and caiGrade >= H:
list1.append(i)
elif deGrade >= H and caiGrade< H:
list2.append(i)... |
5f129f83354dfe3885e3b301689000bbd93a5cc2 | smorenovial/intensivo-nivelacion | /19082019/001712.py | 417 | 3.875 | 4 | # se indican los datos de la persona (nombre, peso y estatura)
name = "YK"
height_m = 1.8
weight_kg = 80
# se desarrollo la formula para verificar si la persona esta en sobre peso o no
bmi = weight_kg / (height_m ** 2)
print "bmi:",bmi
#aqui se condiciona el valor del bmi para ver si la persona esta o no en sobr... |
3dc966f9827661e7db1c0c1c37f9012d3726e5b2 | smorenovial/intensivo-nivelacion | /23082019/tarea siclo while.py | 450 | 3.703125 | 4 | given_list3 = [7,5,4,4,3,1,-2,-3,-5,-7]
i = 0
total = 0
while i <= 9:
if given_list3[i] >= 0: # si el elemento de la lista es un valor positivo, lo rechazo
print given_list3[i], "no me sirve"
i += 1
else: #si el elemento de la lista no es un valor positivo, entramos en este codigo
total += given_list3[i... |
711b02ef5113473afd56ab565a90584ca06ce9d6 | smorenovial/intensivo-nivelacion | /28082019/000608.py | 3,439 | 4.15625 | 4 | import numpy as np
a = np.array([2,3,4]) # se crea una matriz
print a
a = np.arange(1,12,2) # primer valor indica el numero con el cual empieza la matriz, segunod valor indica en que numero termina la matriz excluyendo dicho numero y el tercer valor indica el espaciamiento entre cada valor de la matriz
print a
a ... |
dfb03131abfd1d3493b1bc1da8a621e392520570 | smorenovial/intensivo-nivelacion | /21082019/000132.py | 418 | 3.859375 | 4 | a = [1,2,3,4]
print a
a.append(1) #.append sirve para agregar un elemento al final de la lista
print a
a.append("hola")
print a
a.append([1,2])
print a
a.pop() #sirve para eliminar el ultimo elemnto de la lista
print a
print a[1] #sirve para saber la posicion de un elemento en la lista, esto me arroja el valo... |
509000c52808020e45a2e7fa8397ebd7e40239a7 | goodguyJaX/AoC2020 | /task12.py | 2,431 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 17:36:15 2020
@author: jakas
"""
import fileinput
instruction = []
for line in fileinput.input('input12.txt'):
instruction.append(line.strip())
direction_dict = {'N' : 0,
'E' : 1,
'S' : 2,
'... |
c3bb0a28832d1e61c892ccc7937fb4e4466c386c | YoungsooNa/mathpuzzle | /P11.py | 269 | 3.5625 | 4 | a = 1
b = 1
c = 2
n = 0
def sumOfEach(string : str) :
sum = 0;
for c in string:
sum += int(c)
return sum
while True:
c = a + b
a = b
b = c
if c % sumOfEach(str(c)) == 0 :
print(c)
n+=1
if n == 11:
break
|
e74bc1744ceb82b1036032a763d707ae05f064c0 | YoungsooNa/mathpuzzle | /P09.py | 595 | 3.625 | 4 | """
A string consist of word 20 m and 10 w
Find a order of string that
Even if split the one point of string can't make number of m and n equals at least in one part.
points = 30 > 2n > 0
w_1 = k < 10 and k < points
m_1 = points - w_1
w_2 = 10 - w_1
m_2 = 20 - m_1
"""
count = 0;
for point in range(2, 30, 2):
for... |
2fb1136955d6d976668c41cbf04b09c033288115 | juneja2/Error-handling-in-python | /Handling_Errors.py | 582 | 3.75 | 4 |
try:
for i in ['a', 'b', 'c']:
print(i ** 2)
except TypeError:
print("You are doing pow operation on string")
try:
x = 100
y = 0
z = x/y
except ZeroDivisionError:
print("Division by zero is not allowed")
finally:
print("End try/except/finally")
def ask():
wh... |
0663f1986d43764b32f2af2db2bfc3269a0862f1 | gtfotis/python_functions | /functionsExercise.py | 1,542 | 4.125 | 4 | #1. Madlib Function
def make_formal_greeting(name, game):
return ("%s's favorite video game is %s" % (name, game))
def ask_for_user_info():
name = input("What is your name? ")
game = input("What is favorite video game? ")
if len(name) < 1 or len(game) < 1:
print("Terminating since you don't want... |
5d38bf2a11ff1de766d26c0dcdeec38ee94e664e | adelq/project-euler | /58.py | 913 | 3.859375 | 4 | from math import sqrt
def prime(n):
"""Returns a boolean indicating whether an integer is a prime"""
if n <= 1:
return False
for i in range(2, int(sqrt(n) + 1)):
if n % i == 0:
return False
return True
# Set of helper functions along each diagonal
def upright(d):
return 4*d**2-10*d+7
def upleft(d):
retur... |
5950e83b113bac2267af66276a5acce37b545b2e | adelq/project-euler | /6.py | 201 | 3.609375 | 4 | def sumsq(num):
s = 0
for i in range(num + 1):
s += i**2
return s
def sqsum(num):
s = 0
for i in range(num + 1):
s += i
return s**2
def main(num):
print(sqsum(num) - sumsq(num))
main(100) |
f67ddc50fe49e527dd6516009320b9f44b2d4d6f | adelq/project-euler | /92.py | 299 | 3.515625 | 4 | def sqdigits(num):
num = str(num)
sum = 0
for char in num:
sum += int(char)**2
return sum
def digchain(num):
if num == 1:
return 1
elif num == 89:
return 89
else:
return digchain(sqdigits(num))
num89 = 0
for i in range(1,10000000):
if digchain(i) == 89:
num89 += 1
print(num89)
|
192ff57094fc17a6caf4edea5c42bf763bf4970b | adelq/project-euler | /34.py | 213 | 3.828125 | 4 | from math import factorial
factorialdigit = []
for num in range(3,100000):
strsum = 0
for i in str(num):
strsum += factorial(int(i))
if num == strsum:
factorialdigit.append(num)
print(sum(factorialdigit)) |
0a60dbd62ab940dfdfdc0510033930914cd2b416 | adelq/project-euler | /38.py | 957 | 3.984375 | 4 | # Set to check if a number is pandigital
pan = set("123456789")
# Not used in this problem but may come in handy
# def setmaker(n):
# return set(x for x in str(n))
def concatProduct(n, pan):
"""
Input is a fixed number and a list, function will return concatenated
product of the fixed number with individual eleme... |
68cb89bdc45b418afd5022ab5819a029dc5f2e2f | uasif13/cs115 | /hw3_roughdraft.py | 1,254 | 3.828125 | 4 | # Author: Asif Uddin
# Pledge: I pledge my honor that I have abided by the Stevens Honor System.
# Date: September 19, 2019
def change(amount, coins):
## print (amount)
## print (coins)
'''Returns the minimum number of coins from a given coin system to make a certain amount
Returns infinity if... |
4d4ad00bb476c24c42477dbeef8bb905a0625df5 | LordOfNightmares/IPP-Labs | /Prototype.py | 1,095 | 3.984375 | 4 | import copy
class Prototype:
""" Object, that can be cloned.
This is just a base class, so the clone() method
is not implemented. But all subclasses have to
override it.
"""
_type = None
_value = None
def clone(self):
pass
def getType(self):
return self._type
... |
429f9f55f17d32174ab5c856728622926b38c861 | juanmunoz00/python_classes | /ej_validate_user_input.py | 829 | 4.40625 | 4 | ##This code validates if the user's input is a number, it's type or it's a string
##So far no library's needed
##Method that performs the validation
def ValidateInput(user_input):
try:
# Verify input is an integer by direct casting
is_int = int(user_input)
print("Input is an integer: ", is_... |
990ec67661736d370d9f1046815abef5533e5efd | RichtigToll/TestSysex | /Small Conversation.py | 90 | 3.6875 | 4 | name = input ("Hello there! What is your name? \n")
print("Hello nice to meet you!",name) |
75e1d536a52e2aea681f27e1fb45dcbad13c0501 | nehcili/coding-exercises | /Python/RSA/expmod.py | 576 | 3.84375 | 4 | # in_binary : int --> list
# take an integer e > 0 and produces its binary expansion in a list
def in_binary(e):
ans = []
while e != 0:
ans.append(e % 2)
e = e >> 1
return ans
# expmod : int, int, int --> int
# compute base^e mod modulus quickly by using
# binary exponentiation
def expmo... |
1af6e34b568f7615ffbec35404ca39f4ba851c8b | gjf2a/date_triples | /date_triples.py | 540 | 4.125 | 4 | import calendar
def pythagorean_triple(a, b, c):
return a ** 2 + b ** 2 == c ** 2
def pythagorean_dates(start_year, end_year):
dates = []
c = calendar.Calendar()
for year in range(start_year, end_year + 1):
for month in range(1, 13):
for day in (d for d in c.itermonthdays(year, m... |
030c3974db54a6ff21210eb19127df665d00eb7f | Krankdud/dustforce-level-utils | /key_inject.py | 1,861 | 3.5 | 4 | import sys
def set_key(filename, key_type):
if key_type < 0 or key_type > 3:
return
try:
f = open(filename, 'r+b')
except IOError:
print '*** Error: File was not found'
return
header = '\xB4\x9C\x34\x79\xE3\xA5\x4D\x9A\x33\x0E\x00'
level = f.read()
after_header = level.find(header) + len(header)
# ... |
40fd2b0e34c7dd0b08820d1c037ca880cc71ec9b | zeionara/ampligraph-demo | /utils/timers.py | 553 | 3.5 | 4 | import functools
import time
def measure_execution_time(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Completed in {stringify_elapsed_time(time.time() - start)}")
return result
return wrapper
def st... |
31c8bbaac80fddcc2dd979b1a9c0d296eae0b9fe | poduszeczka3/JSP2019 | /lista2/zad9l2.py | 223 | 3.875 | 4 | #zmniejszenie stopnia zagnieżdżenia listy: chain
import itertools as it
lista = [[2, 4, 3], [1, 5, 6], [9], [7, 9, 0]]
listapodzielona = list(it.chain(*lista))
print("Mniej zagnieżdżona lista:")
print(listapodzielona) |
bf1ccd2f70da4d814d4029836cdae0f1d6f159b1 | poduszeczka3/JSP2019 | /lista4/zad3l4.py | 447 | 3.6875 | 4 | import numpy as np
print("podaj kąt")
kat = float(input())
def przelicznik_na_rad(a):
return a*np.pi/180.
def przelicznik_na_deg(b):
return b*180./np.pi
print("Chcesz przeliczyć podany kąt na radiany czy stopnie? (rad/deg)")
tak = str(input())
if tak=="rad":
print("podany kąt w radianach =", przelicznik... |
c64add4153fabd58c37f5b8e77e6edc76a469c45 | poduszeczka3/JSP2019 | /lista6/zad1l6.py | 560 | 3.5625 | 4 | import trojkat as tr
def main(args):
print("Wpisz rosnąco długości boków trójkąta:")
a=float(input())
b=float(input())
c=float(input())
if a>0 and b>0 and c>0 and a+b > c:
print("Obwód trójkąta:\t", tr.obwod(a,b,c))
print("Pole trójkąta:\t", tr.pole(a,b,c))
print("Ten trójką... |
92e36a653ee264cd4c1ccc7b13ad595904bf3cac | poduszeczka3/JSP2019 | /lista2/zad10l2.py | 549 | 3.921875 | 4 | print("Naturalne wielokrotności trójki mniejsze od 100 to:")
x = range(0, 100, 3)
lista = []
for i in x:
lista.append(i)
print(lista)
print("Usunięcie co trzeciego elementu z powyższej listy począwszy od piątego:")
n = len(lista)
lista2 = []
for i in range(4,n,3):
lista2.append(lista[i]) #tworzy listę zawieraj... |
0cd3050cd614bc7c1557d263b2f2d589d2e4cb18 | shatskaya/testing_labs | /app_calculate_test.py | 968 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import unittest
from app_calculate import Calculate
class TestCalculate(unittest.TestCase):
def setUp(self):
self.c = Calculate()
#def test_add_method_returns_correct_result(self):
# self.assertEqual(4, self.c.add(2,2))
#self.assertEqual(4, self.c.add(2,3))
#def test_add_method_retur... |
9e761bc553ea69ad93d3243e712304f049266fd4 | Cawb07/projecteulerstuff | /python/22.py | 1,193 | 3.625 | 4 | '''
Created on Aug 18, 2013
https://projecteuler.net/problem=22
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into alphabetical
order. Then working out the alphabetical value for each name, multiply this value
by its alphabet... |
d989e18870d573556c587ad2e7736eec4aa5af7e | Cawb07/projecteulerstuff | /python/23.py | 1,576 | 3.734375 | 4 | '''
Created on Aug 29, 2013
http://projecteuler.net/problem=23
A perfect number is a number for which the sum of its proper divisors is exactly
equal to the number. For example, the sum of the proper divisors of 28 would be
1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called defici... |
bb8b1538d1a0fabf5e1819e8bacf906ac179e953 | Cawb07/projecteulerstuff | /python/30.py | 919 | 3.78125 | 4 | '''
Created on Sep 1, 2013
https://projecteuler.net/problem=30
Surprisingly there are only three numbers that can be written
as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of th... |
a55fbc92aa61dee5ad580cf924b018a410d33808 | Cawb07/projecteulerstuff | /python/24.py | 758 | 3.640625 | 4 | '''
Created on Aug 30, 2013
https://projecteuler.net/problem=24
A permutation is an ordered arrangement of objects. For example,
3124 is one possible permutation of the digits 1, 2, 3 and 4.
If all of the permutations are listed numerically or
alphabetically, we call it lexicographic order. The
lexicographic permutat... |
626dc70789de6e61963051996357f3ba6aae42e6 | noisebridge/PythonClass | /instructors/course-2015/errors_and_introspection/project/primetester4.py | 1,242 | 4.46875 | 4 | """
For any given number, we only need to test the primes below it.
e.g. 9 -- we need only test 1,2,3,5,7
e.g. 8 -- we need only test 1,2,3,5,7
for example, the number 12 has factors 1,2,3,6,12.
We could find the six factor but we will find the two factor first.
The definition of a composite number is that it is co... |
9c81264446ef2fd968208b79fd0d696409bb5f83 | noisebridge/PythonClass | /instructors/lessons/higher_order_functions/examples/closure1.py | 1,509 | 4.15625 | 4 | """
This example intentionally doesn't work.
Go through this code and predict what will happen, then run
the code.
The below function fixes i in the parent scope, which means
that the function 'f' 'gets updates' as i progresses through
the loop.
Clearly we need to somehow fix i to be contained in the local
scope for... |
5a16bce450faf707319495d6d504c79bba38013f | noisebridge/PythonClass | /instructors/course-2015/functions_gens_and_ducks/examples/gen_countdown.py | 516 | 3.9375 | 4 | def countdown_from_n(n):
print "Counting down!"
while n > 0:
yield n
n -= 1
countdown = countdown_from_n(5)
first_gen_var = countdown.next()
print first_gen_var
print countdown.next()
print countdown.next()
print countdown.next()
print countdown.next()
#why is it running out?
countdown_fr... |
b2a732c6f5127298dcd36c2ec36b6bbcac015199 | noisebridge/PythonClass | /instructors/course-2015/errors_and_introspection/project/primetester2.py | 412 | 3.75 | 4 |
def prime_test(i):
"""
Cases:
Return False if i is not prime
Return True if i is prime
Caveat: cannot test 1.
Caveat 2: Cannot test 2.
It is fortuitous that these tests both return true.
"""
for possible_factor in range(2,i):
if i % possible_factor == 0:
return... |
be8d3b17b7b4a9b28a06af5ff3ba57e1514bc5fc | noisebridge/PythonClass | /instructors/need-rework/24_curses/cu0.py | 1,099 | 3.921875 | 4 | import curses
def main(stdscr):
""" Curses is controlled from here.
This might be called 'the loop' in a game.
game loop: http://gameprogrammingpatterns.com/game-loop.html
"""
curses.textpad.rectangle(stdscr,0,0,10,10)
keypress = int()
# 113 is the lowercase 'q' key.
while ke... |
cf305774166007db8752af9bed6e4557373290f3 | noisebridge/PythonClass | /instructors/projects/munge_and_analyze/examples/csv2pickle.py | 565 | 3.859375 | 4 | """
A simple little snippet that will:
1. import a csv file - the file must be a single row of comma-separated values.
2. import the row to a single dimensional list.
3. pickle the list and dump it to a pickle file.
"""
import pickle
import csv
mode = 'r'
input_filename = 'ngsl1.01.csv'
output_filename = 'ngsl.pickle... |
395a922194abb0980d79be094eac94f23d61e005 | noisebridge/PythonClass | /instructors/projects/project_euler/euler59/euler59_hackerrank.py | 1,563 | 4.09375 | 4 | """
messages ascii codes can only include: 20,21,32,39-41,44-46,48-59,63,65-90,97-122
encrypt includes 3 ascii codes in range of: 97-122
"""
def isValid(arr, key):
dec = map(lambda x, y: x^y, arr, key)
for e in dec:
# note: there may be a nicer way to encapsulate this query in
# a da... |
94403d673f6703114c2657214ab2163aba072c91 | noisebridge/PythonClass | /instructors/lessons/keywords_and_control_flow/examples/control-ex1.py | 4,302 | 3.984375 | 4 | """
Control Flow keywords: ['while', 'if', 'elif', 'raise', 'for', 'break', 'continue', 'else', 'pass', 'try', 'except', 'finally', 'with', 'as']
Comparison Keywords ['and', 'in', 'is', 'not', 'or']
"""
letter_frequency_dict = {}
word = "noisebridge"
for letter in word:
times = letter_frequency_dict.get(letter, 0... |
3406f52a5687011e513a069d5dc97556faac9863 | noisebridge/PythonClass | /instructors/lessons/logging/examples/log_ex2.py | 369 | 3.578125 | 4 | """
This slight modification of example 1 introduces logging to a file.
"""
import logging
logging.basicConfig(filename='ex1.log', level='DEBUG')
logging.debug("This is a string that we want to log.")
logging.info("info: this string is cool.")
# Now we just read the file back to ourselves to confirm it worked.
wit... |
7509b03615b2e50d10ed9235d60d01cddda68e87 | noisebridge/PythonClass | /instructors/course-2015/sqlite3_module/examples/readsample.py | 856 | 3.8125 | 4 | """
"""
import sqlite3
dbdir = "db/"
sql_filename = 'sampledb.sqlite'
sqlite_fileandpath = dbdir + sql_filename
if __name__ == '__main__':
# DB connection per file.
conn = sqlite3.connect(sqlite_fileandpath)
# return bytestrings instead of unicode
# https://docs.python.org/2/library/sqlite3.html#... |
8a0be2bbaae3766ea626a001567cf54ce20f818c | noisebridge/PythonClass | /instructors/need-rework/19_algos_and_recursion/recursum_fib.py | 723 | 3.875 | 4 | import time
#recursive sumlist
def list_sum(numList):
print "numList", numList
start = time.time()
if len(numList) == 1:
print "time taken %10.7f" %(time.time() - start)
return numList[0]
else:
print numList[0], "and the rest", numList[1:]
#what is happening with thi... |
f412f50e278ad7ba058891a8e463625155bffdfb | noisebridge/PythonClass | /instructors/projects-2015/workshop_100515/quick_sort.py | 1,124 | 4.1875 | 4 | """ Quick Sort
Implement a simple quick sort in Python.
"""
# we'll use a random pivot.
import random
def my_sorter(mylist):
""" The atomic component of recursive quick sort
"""
# we are missing a base case
if len(mylist) == 1:
return mylist
# do we need this?
if len(mylist) == 0:
... |
9db3cd6f2fbadcfa1e558ac85e38bb1129f163b2 | noisebridge/PythonClass | /instructors/lessons/functions_and_gens/examples/example0.py | 618 | 4.1875 | 4 | #Return the absolute value of the number x. Floats as well as ints are accepted values.
abs(-100)
abs(-77.312304986)
abs(10)
#Return True if any element of the iterable is true. If the iterable is empty, return False.
any([0,1,2,3])
any([0, False, "", {}, []])
#enumerate() returns an iterator which yields a tuple tha... |
bd3d4731c01b47a50ac8f2f397c7368d944afe62 | noisebridge/PythonClass | /guest-talks/20170213-optional-static-types/syntax.py | 180 | 3.6875 | 4 | # Basic type checking: no types necessary
x = 3
x + 'a'
def return_type() -> float:
return 'a'
return_type(9)
def argument_type(x: float):
return
argument_type()
|
ddee53390ee64c22a41d21cf377bae3db423f3d3 | noisebridge/PythonClass | /instructors/course-2015/unittest/examples/simpletest2.py | 399 | 3.609375 | 4 | """
"""
mytestconditions = [ ([1,2],3), ([2,4],6), ([3,6],9) ]
def sum_my_list(mylist):
myresult = 0
for item in mylist:
myresult += item
return myresult
try:
for condition, result in mytestconditions:
# check that the conditions produce the result
assert sum_my_list(conditi... |
aff76641076cd805c764b3a954f225e7f565aa19 | noisebridge/PythonClass | /instructors/need-rework/7_built-ins_and_idioms/7_ex_answers.py | 737 | 3.5625 | 4 | l1 = range(0,100, 5)
l2 = range(0,660, 33)
paired_tup = zip(l1, l2)
print(paired_tup)
paired_dict = dict(paired_tup)
print(paired_dict)
numbered = dict(enumerate(paired_tup))
print(numbered)
sorted(numbered, reverse=True)
print type(numbered)
#add ten to each item in list
#for i in d:
# d[i] += 10
#not sure w... |
6ca89d6ec3490c782cf25fe81c13e206ee3711ac | noisebridge/PythonClass | /instructors/need-rework/15_classy_OOP/cat_class.py | 852 | 3.671875 | 4 | import random
class Cat(object):
#import random
enemies = 5
def __init__(self, name=None, top_speed=9223372036854775808L, cat=None, hunger=None, food=None):
self.name = name
self.top_speed = top_speed
self.hunger = random.randint(1,10)
self.food = []
self.at_vet = False
#if self.hunger >= 10:
# retu... |
ba2f4e7603153cdcdbce19aefd0a5d164b682884 | noisebridge/PythonClass | /instructors/course-2015/oop/examples/inherit_from_string.py | 746 | 3.84375 | 4 | class Word(str):
'''Class for words, defining comparison based on word length.'''
def __new__(cls, word):
# Note that we have to use __new__. This is because str is an immutable
# type, so we have to initialize it early (at creation)
if ' ' in word:
print "Value contains spa... |
97ea8c4d0ff620278c424cd082df030bd02eff5a | noisebridge/PythonClass | /instructors/course-2015/functions_gens_and_ducks/examples/in_class/warm_up/calc_tax.py | 300 | 3.75 | 4 | def print_15perc_total_tax(bill):
'''return the amount of money to pay in tax in US dollars
'''
bill = float(bill)
total_tax = str( bill * .15 )
return "please graciously pay at least the amount of {} in total tax ".format(total_tax)
print print_15perc_total_tax(79)
|
b49418de6e7b3c7dc76de57c91f79782cd092361 | noisebridge/PythonClass | /instructors/course-2015/regular_expressions/project/email_checker.py | 1,616 | 3.640625 | 4 | """
Checks each line of a file for valid emails.
Use Django's email validator regex.
Store the result in one of 2 files:
1. valid emails.
2. invalid emails.
NOTE: This project still fails on a case when the email has a trailing string. This is because the re.match() method only matches the beginning of the ... |
bb5c6147f5671e553df38888b94e2a1f219d0182 | noisebridge/PythonClass | /instructors/course-2015/keywords_and_control_flow/examples/ex3.py | 224 | 3.546875 | 4 |
for i in range(10):
if i == 5:
break
else:
print "i = ", i
try:
for each in Cardamom:
print each
except Exception as e:
print "Exception:", e
finally:
print "And we're done"
|
a0c93c5496078e37282ca2724fec2114ff2bdd9a | sugertimeone/learnight | /findMinAndMax.py | 271 | 3.65625 | 4 | # _*_ coding: utf-8 _*_
def findMinAndMax(L):
if L == []:
return (None, None)
min = L[0]
max = L[0]
for value in L:
if min > value:
min = value
if max < value:
max = value
print(L)
return (min, max) |
9846b1a24c40d2da5e5737d15c2a92725560e7c0 | otobin/CSSI-stuff | /Python/Playground.py | 2,806 | 4.46875 | 4 | # #!/usr/bin/python
#
#
# # # # print("Hello, World!")
# # # #
# # # #
# # # #
# # # # i = 0
# # # #
# # # # while (i < 3):
# # # # num = int(input("Enter a number"))
# # # #
# # # # if num > 0:
# # # # print("This number is positive")
# # # # elif num < 0:
# # # # print("This number is nega... |
faac6d3557770a3d1ebb5d2d2dbaab4487ed422b | jefinagilbert/problemSolving | /hr97_findMedian.py | 112 | 3.71875 | 4 | def findMedian(arr):
arr.sort()
return arr[len(arr)//2]
arr = [5,3,1,2,4]
print(findMedian(arr)) |
c915c13dbcd54bcd0ca8fd1aad5a431448d8b2d9 | jefinagilbert/problemSolving | /hr21_algo.py | 375 | 3.828125 | 4 | def diagonalDifference(arr):
val = 0
j = len(arr)
val1 = 0
for i in range(len(arr)):
val += arr[i][i]
for i in range(len(arr)):
j -= 1
val1 += arr[i][j]
val2 = val-val1
if val2<0:
val2 -= val2*2
return val2
n = int(input())
arr = []
for i in range(n):
arr.append(list(map(int, input(... |
9382723fac4cb1580d403ce3c04fc0960bc5479a | jefinagilbert/problemSolving | /hr113_decentNumber.py | 462 | 3.78125 | 4 | def decentNumber(n):
i = 3
a = n//3
b = n%3
j = 5
if b != 0:
while b%j != 0:
b += 3
a -= 1
if b > n:
break
k = a*3
if a < 0 or b < 0:
return '-1'
elif a == 0 and b == 0:
return '-1'
elif a == ... |
17bea732f9350976abc5130abb5f82c3e3ffbd75 | jefinagilbert/problemSolving | /hr23_pyramid.py | 156 | 3.921875 | 4 | def staircase(n):
k = n
for i in range(1,n+1):
k -= 1
print(' '*k+'#'*i)
if __name__ == '__main__':
n = int(input())
staircase(n) |
9794530e59a070c7545bca1dce5c7fadc0f6c760 | jefinagilbert/problemSolving | /hr105_missingNumbers.py | 398 | 3.828125 | 4 | def missingNumbers(arr, brr):
arr1 = []
for i in brr:
if i in arr:
arr.remove(i)
else:
if i not in arr1:
arr1.append(i)
arr1.sort()
return arr1
arr = []
brr = []
k = input().split()
for i in k:
arr.append(int(i))
k = input().... |
86d8d928aac5da664ce126ed04cc9f7e75f6f230 | aflisiak/PythonSS19 | /ex_00.py | 1,409 | 4.09375 | 4 | """
Universität Tübingen - Seminar für Sprachwissenschaft
VL 'Programming and Data Analysis' SS 2019
© Johannes Dellert, Maxim Korniyenko, Natalie Clarius, Gerhard Jäger
Assignment 00: Ungraded Test Assignment
Template
"""
# This is part of the program initialization, we will use it to test your code on different thr... |
4cee8784426ed1d803936a4f17b4d7c1bb5a95b7 | agnynureza/datacamp-dataengineer | /3. streamlines data ingestion with pandas/importing JSON data and working with API.py | 1,481 | 3.734375 | 4 | """ Introduction to JSON """
death_causes = pd.read_json("file you want to read",
orient="split") # ini penting
# soalnya bentuk json itu redundant, jadi klu dibikin column-oriented , biar enak dirubah ke dataframenya
""" Introduction to APIs """
request.get("url string",
para... |
3cfcb3b59a682b5246cf7ccd7ed8f349d2a20d47 | agnynureza/datacamp-dataengineer | /5. writing function in python/context manager.py | 614 | 3.59375 | 4 | """ Using Context Manager """
with open("file.txt") as my_file:
open() does 3 things :
set up context by opening file
let you run any code you want on that file
remove context by closing
""" Context Manager """
2 cara untuk mendeskripsikan context manager
1. class based -> __enter__()
2. function based
... |
908accf654cd559a95b1ce89dd9b4b1e332cabe1 | makcipes/budg-intensive | /day_1/scope/task_1/question.py | 580 | 4.25 | 4 | """
Что будет выведено после выполнения кода? Почему?
"""
x = 42
def some_func():
global x
x = x + 1
print(x)
some_func()
print(x)
"""выведет 2 раза чилсло 43 тк в функции мы определили глобальную переменную и прибавили к ней единицу
тоесть, при выполнении some_func мы прибавили единицу к числу , a... |
492c95dabf183d73c8909f8f8763458c837e871e | cmsandiga/grooking-algorithms | /unit-3/selection_sort.py | 486 | 3.953125 | 4 |
def find_min_index(elements):
min_e = elements[0]
min_i = 0
for i in range(len(elements)):
if elements[i] < min_e:
min_e = elements[i]
min_i = i
return min_i
def selection_sort(elements):
result = []
for i in range(len(elements)) :
min_in... |
26f420bc792d82af5c1d4bc59d1eadaa3e8142d4 | sohaas/MLinPractice | /test/preprocessing/lemmatizer_test.py | 2,165 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 17 16:43:17 2021
@author: sohaas
"""
import ast
import unittest
import pandas as pd
from code.preprocessing.lemmatizer import Lemmatizer
class LemmatizerTest(unittest.TestCase):
def setUp(self):
self.INPUT_COLUMN = "input tweet"
... |
b8e5f55fd006eac5766338183f44ea8884a7e4a0 | sohaas/MLinPractice | /test/feature_extraction/character_length_test.py | 1,069 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 17 17:51:34 2021
@author: sohaas
"""
import unittest
import pandas as pd
from code.feature_extraction.character_length import CharacterLength
class CharacterLengthTest(unittest.TestCase):
def setUp(self):
self.INPUT_COLUMN = "inpu... |
fd0be7bcf9c7c41ce72b2e8d48fca76176edbc02 | zariuq/Project-Euler | /euler5.py | 317 | 3.640625 | 4 | import math
def first_factor (num):
for i in range (2,num):
if num % i == 0:
return i
return num
divto = 20
num = 1.0
for i in range (1,divto):
print "iter: " + str(i)
if num % i != 0:
num = num * (first_factor(i))
print "num: " + str(num)
print num
|
4fbfd24ecc381fcdbe1f52ccb3cefc398c49cd00 | jlovoi/DS-and-Algorithms | /algorithms/insertion_sort.py | 184 | 3.78125 | 4 | def insertion(arr):
ret = arr
for i in range(1, len(arr)):
key = ret[i]
j = i - 1
while key < ret[j] and j >= 0:
ret[j+1] = ret[j]
j = j - 1
ret[j+1] = key
return ret
|
730cf85874cadb126f95d7e49b7b4aad78b24171 | hyeinkim1305/TIL | /pjt/pjt01/problem_d_answer.py | 1,403 | 3.5625 | 4 | import json
def max_revenue(movies):
# 후에 추출할 revenue와 title의 딕셔너리 모음들을 넣을 리스트를 새로 만든다.
revenue_list = []
# movies 폴더 안에 많은 json들을 불러온다.
for movie in movies:
movie_id = movie.get('id')
movie_json = open(f'data/movies/{movie_id}.json', encoding='UTF8')
movies_dict = json.... |
a062f1a36e5fd68762d8a7cdac529baedde0e6f4 | PhuocThienTran/Learning-Python-During-Lockdown | /30DaysOfPython/day_5/lists.py | 5,678 | 4.09375 | 4 | import statistics #lib for exercise lvl 2 calcs
# -----------------------------------------------------#
#Exercise
#1
empty_list = []
#2
q2_list = ["Apple","Orange","Maple","Rice","Tran"] #list with 5 items
#3
print(len(q2_list)) #list length
#4
item1, item2, item3, item4, item5 = q2_list
print(item1,item3,item5) #ge... |
3d7581fb9378298bd491df6a5f54063a659ae965 | PhuocThienTran/Learning-Python-During-Lockdown | /30DaysOfPython/chapter6/strings.py | 720 | 4.125 | 4 | word = "Ishini"
def backward(word):
index = len(word) - 1
while index >= 0:
print(word[index])
index -= 1
backward(word)
fruit = "apple"
def count(fruit, count):
count = 0
for letter in fruit:
if letter == "p":
count = count + 1
print("Amount of p:", count)
coun... |
b1d766d3d8a6a7635f7c928e085844594e0eb329 | PhuocThienTran/Learning-Python-During-Lockdown | /30DaysOfPython/chapter5/iteration.py | 1,479 | 4.3125 | 4 | import math
n = 5
while n > 0:
print(n)
n =- 1
print("Launched!")
while True:
line = input('> ')
if line == 'done':
break #this means if input is "done" -> break the while loop
print(line)
print('Done!')
while True:
usr_line = input('> ')
if usr_line[0] == '#':
continue #... |
f980318a7bffd913eea97b5aee71f3be2d16747b | pujaaryal89/PythonAssignment | /function/function4.py | 182 | 4.59375 | 5 | def reverse(string):
string=string[::-1]
return string
string=input("Enter the string: ")
strings=reverse(string)
print(f"the reverse of string is:{strings}")
|
c617f3ed30cb0d3842a2615ee39b7fce1febac5a | pujaaryal89/PythonAssignment | /Datatype/datatype2.py | 304 | 4.03125 | 4 | def translate(word):
translation=""
if len(word)>=2:
translation=translation+word[0:2] + word[-2:]
else:
print("invalid")
return translation
print(translate(input("Enter the word: ")))
|
59923b6747d289a273b59ec32abd8dfb534aa9db | pujaaryal89/PythonAssignment | /function/function7.py | 414 | 4 | 4 | def check_function(str):
count1=0
count2=0
for n in str:
if (n.isupper()):
count1+=1
elif (n.islower()):
count2+=1
print("the uppercase is :",count1)
print("the lowercase is :",count2)
return count1,count2
... |
425a7de115ec728612aa7bdbbe81d2b3c0395fe3 | pujaaryal89/PythonAssignment | /function/function1.py | 555 | 4.125 | 4 | def max_num(num_list):
largest_num=num_list[0]
for num in num_list[1:]:
if num >largest_num:
largest_num=num
return largest_num
number = input('Enter a number separate by comma: ').split(',')
# print(number)
#split le pailai , bata split garera list ma leraauxa
num=[int(x) ... |
a5ed9c9287501c0e28bfafba0d149018a85f4377 | rakshithvasudev/Datacamp-Solutions | /Importing Data in Python part 2/Cleaning data in python/Tidying data for Analysis/ex6.py | 546 | 3.640625 | 4 | """
Print the head of airquality_melt.
Pivot airquality_melt by using .pivot_table() with the rows indexed by 'Month' and 'Day', the columns indexed by 'measurement', and the values populated with 'reading'.
Print the head of airquality_pivot.
"""
# Print the head of airquality_melt
print(airquality_melt.head())
# Pi... |
ad1894bc97e870b14a06d8dd46bcc6ff9875cdb5 | rakshithvasudev/Datacamp-Solutions | /Recommendation Engines in Pyspark/How ALS works/ex16.py | 606 | 4.28125 | 4 | """
Get RMSE
Now that you know how to build a model and generate predictions, and have an evaluator to tell us how well it predicts ratings, we can calculate the RMSE to see how well an ALS model performed. We'll use the evaluator that we built in the previous exercise to calculate and print the rmse.
Instructions
100... |
b1d82fcf348ed41617cddc19cff00309344bf8d1 | rakshithvasudev/Datacamp-Solutions | /Recommendation Engines in Pyspark/How ALS works/ex12.py | 1,085 | 3.9375 | 4 | """
Assigning integer id's to movies
Let's now do the same thing to the movies. Then let's join the new user id's and movie id's into one dataframe.
Instructions
100 XP
Use the .select() and the .distinct() methods to extract all unique Movie's from the ratings dataframe.
Repartition the movies dataframe to one partit... |
2516fa4cf613b1a5104c9e9728e771404fe5c9a0 | grance1/b | /function.py | 979 | 3.765625 | 4 | #!/usr/bin/python2.7
print abs(100)
print abs(-20)
print abs(12.34)
print cmp(1,2)
print cmp(2,1)
print cmp(3,3)
print int('123')
from math import fsum
L = []
# print L
L=list(map(lambda x: x*x,range(1,101)))
print sum(L)
L = range(1,101)
#print L
#for x in L:
print sum(x*x for x in L)
print abs(100)
print abs(-20)
p... |
50a380fc90575a20c61f465ae2f37213238cfcfc | grance1/b | /args.py | 322 | 3.734375 | 4 | #!/usr/bin/python2.7
def fn(*args):
print args
print fn()
print fn('a')
print fn('a','b')
print fn('a','b','c')
def aversge(*args):
sum = 0.0
if len(args) == 0:
return sum
for x in args:
sum = sum + x
return sum / len(args)
print aversge()
print aversge(1,2)
print aversge(1,2,2,3,4)... |
5bea85b2224b714342640994599e54a9141bb2b4 | wahyuief/simple-hashing | /main.py | 1,149 | 3.609375 | 4 | #!/usr/bin/env python
# Simple hashing data
# Made with love by wahyuief
import hashlib, os
rechoice = ''
while rechoice != 'n':
print("1. Md5")
print("2. Sha1")
print("3. Sha224")
print("4. Sha256")
print("5. Sha384")
print("6. Sha512")
choice = int(input("Choice: "))
if choice =... |
dad3465aedb6bfa022d32886baa6e989e06905cd | medinachuck/python-challenge | /PyBank/main.py | 3,897 | 4.28125 | 4 |
import os
import csv
#import the csv data
filepath = os.path.join('Resources', 'budget_data.csv')
#print(filepath)
with open(filepath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
#print(csvreader)
#Turn iterable into a list
bank_data = list(csvreader)
# Your task is to creat... |
f418b5787d8f3cf22203ec138352c91895279268 | sebastianwaleka/excersises | /PESEL.py | 778 | 3.96875 | 4 | '''
This program will check person's sex basing on PESEL number.
It won't check whether number is correct or not. (FOR NOW)
'''
def pesel(number):
if len(number) < 11:
return 'Number too short.'
elif len(number) > 11:
return 'Number too long.'
else:
if number[-2] in ('0','2','4','6'... |
0995d6d841ba2717f1f45a2fa4880e50e4a5f988 | mil-tokyo/neural_network | /mano/practice_NN/ml_perceptron.py | 3,131 | 3.6875 | 4 | # ! c:/Python2.7/python.exe
# -*- coding: utf-8 -*-
""" Multi Layer Perceptron
Three Layer: input-hidden-output """
import numpy as np
import sys
class MultiLayerPerceptron:
def __init__(self, numInput, numHidden, numOutput, actHidden="tanh", actOutput="sigmoid"):
"""
Function Inputs:
num... |
c34d4873e498d568971b362d20e40af0a16d0a16 | kopxiong/Leetcode | /sort/python3/01_bubble_sort.py | 1,315 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# 冒泡排序 (Bubble Sort) 是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,
# 如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
# 这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
# Time complexity: O(n^2)
class Solution(object):
def bubbleSort(self, lists):
n = len(lists)
# after each iteration, the ... |
8c9ab2fa0cb9abee376d2086bb19725d03d94812 | kopxiong/Leetcode | /python3/082_remove_duplicates_from_sorted_list_II.py | 2,237 | 3.84375 | 4 | # Given a sorted linked list, delete all duplicates such that each element appear only once.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.n... |
4c7cb9fdeebb56abbaa5373852c723d2996a4429 | kopxiong/Leetcode | /sort/python3/05_bucket_sort.py | 2,782 | 4.0625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# 桶排序 (Bucket sort)或箱排序 (Bin sort),桶排序算是计数排序的一种改进和推广,原理是将数组分到有限数量的桶里。每个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。桶排序是鸽巢排序 (Pigeonhole sort) 的一种归纳结果。当要被排序的数组内的数值是均匀分配的时候,桶排序使用线性时间 O(n)。但桶排序并不是比较排序,他不受到 O(n\log n)下限的影响。
# 1. 设置一个定量的数组当作空桶子
# 2. 寻访序列,并且把项目一个一个放到对应的桶子去
# 3. 对每个不... |
52a26ce129421ee3ee486a657e95fbe2277a193f | kopxiong/Leetcode | /python3/095_unique_binary_search_trees_II.py | 2,126 | 3.84375 | 4 | # Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
from __future__ import print_function
import numpy as np
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None... |
d0086ec7fa27d3482b41f03142594d2380f48e03 | kopxiong/Leetcode | /python3/169_majority_element.py | 1,871 | 3.6875 | 4 | # Given an array of size n, find the majority element.
# The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element always exist in the array.
# Binary search: Time complexity: O(N); Space complexity: O(N) (call stack)
import collec... |
992c771bca076b3ed52891d809431224e7cd6a3b | kenziSY/UECM3033_assign3 | /task2.py | 1,327 | 3.671875 | 4 | import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def ode(y, t, a, b):
y0, y1 = y
dydt = [a*(y0-y0*y1), b*(-y1+y0*y1)]
return dydt
#initial conditions
a = 1.0
b = 0.2
y_init = [0.1, 1.0]
t = np.linspace(0, 5, 101)
sol = odeint(ode, y_init, t, args=(a, b))
#plot t... |
1a838d351e2989a59dea7b2ae040910cb0f482db | PathriseFellows/interview-practice | /JustinHackerRank/set_intersection.py | 1,927 | 3.796875 | 4 | '''
Given a list of sets, find the set that should be excluded to
maximize the size of the intersection of the remaining sets
'''
def max_intersection(sets):
size = len(sets)
if size <= 1:
return -1
memo = {(0,0): sets[0]}
for i in range(1, size):
memo[(0,i)] = memo[(0,i-1)] & sets[i]
... |
0762f7882b4c25e834724036b0471f4c3325c7b8 | AndrewLuckett/NeuroKeying | /src/Activators.py | 1,620 | 3.5625 | 4 | from math import exp # Global since sigmoid may be called a lot
"""
Pattern of:
class name(Activator):
def activator(in):
return out
def derivative(in):
return out
more so static than OO
Just a grouping of two related funcs
functional prog?
"""
class Activator:
def __listAct__(this,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.