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 |
|---|---|---|---|---|---|---|
cfad4c0eb56b669e9ae1998cf7dd51d31720dcc1 | alphashooter/python-examples | /homeworks-1/homework-4/linked_list.py | 4,081 | 3.875 | 4 | from typing import Any, Union, Optional, Iterable
class Node(object):
def __init__(self, value: Any):
self.value: Any = value
self.next: Optional[Node] = None
class LinkedList(object):
def __init__(self, iterable: Optional[Iterable] = None):
self.__head = Node(None)
self.__le... |
85d487fc20e736e80d46ade3bf10e08fd05435f1 | alphashooter/python-examples | /syntax-examples/func_example2.py | 114 | 3.625 | 4 | def foo(x, y=1):
return x + y
print(foo(2, 3)) # 2 + 3 = 5
print(foo(2)) # foo(2) = foo(2, 1) = 2 + 1 = 3
|
91a49b9217dd893d76cef0c185f91020b444db35 | alphashooter/python-examples | /homeworks-2/homework-1/task5_draft.py | 597 | 3.625 | 4 | s = input('Введите выражение: ')
tokens = []
while True:
for i in range(len(s)):
if s[i] not in {'+', '-', '*', '/'}:
continue
tokens += float(s[:i]), s[i]
s = s[i+1:]
break
else:
tokens += float(s),
break
i = 1
while i < len(tokens) - 1:
token =... |
30855448cc0f12cd7e0b41ee36431dfbfaafafcf | alphashooter/python-examples | /homeworks-1/homework-4/shapes_test.py | 2,437 | 3.703125 | 4 | from time import sleep
from random import random
from shapes import *
def rectangle_input():
width = int(input('Enter width: '))
height = int(input('Enter height: '))
color = input('Enter color (red, green, blue, cyan, magenta, yellow, white, black, etc.): ')
color = color.strip().lower()
return R... |
cb508d7081f8aa86e50ab106c085889e87a90730 | alphashooter/python-examples | /homeworks-2/homework-1/task2.py | 277 | 3.8125 | 4 | n = int(input('n = '))
x1 = int(input('x1 = '))
x2 = int(input('x2 = '))
if x1 < x2:
temp = x1
x1 = x2
x2 = temp
for i in range(2, n):
x = int(input(f'x{i + 1} = '))
if x > x1:
x2 = x1
x1 = x
elif x > x2:
x2 = x
print(x1, x2)
|
b2d7a4aa803e2f5fd5521ad4905fa74adbb7d66a | alphashooter/python-examples | /syntax-examples/iter_example1.py | 218 | 3.796875 | 4 | seq = [1, 2, 3, 4, 5]
for value in seq:
print(value)
print() # just a newline
iterator = iter(seq)
while True:
try:
value = next(iterator)
except StopIteration:
break
print(value)
|
075b89b5f42f78efdb850de0486ba8b3f487999f | alphashooter/python-examples | /class-examples/inheritance.py | 562 | 3.6875 | 4 | class A(object):
def foo(self):
print('A.foo()')
class B(A):
def __init__(self, x):
self.x = x
def bar(self):
print('B.bar()')
class C(B):
def __init__(self, x, y):
B.__init__(self, x)
self.y = y
def foo(self):
print('C.foo()')
def baz(self)... |
ecc4d29375e3c6200c6ac3b8f9f3b4f4c0769ca7 | alphashooter/python-examples | /homeworks-2/homework-2/task2.py | 574 | 4.125 | 4 | import calendar
from datetime import datetime
target: int
while True:
day_name = input(f'Enter day name ({calendar.day_name[0]}, etc.): ')
for day, name in enumerate(calendar.day_name):
if name == day_name:
target = day
break
else:
print('invalid input')
con... |
bb44bcf687220da4ef2a76d9379adfcc0f544b1e | Uwumuremyi/python | /sum.py | 151 | 4.15625 | 4 | """This program will sum all even integers from 2 to 100."""
sum = 0
for number in range(2, 101, 2):
sum = sum + number
print("Sum is %d" % sum) |
70fee32fe157151acbf58ea7161d7799d4f99afe | alfawzan1361/Python | /Sum&Product.py | 222 | 3.984375 | 4 | # sum and product
seq = input('Enter your list: ')
seq = [int(x) for x in seq.split()]
num = 0
num1 = 1
for sumProd in seq:
num += sumProd
num1 *= sumProd
print("The sum is: ", num)
print("The product is: ", num1) |
df95a42fc1f7aa782f0abe769fc8608ca7b094e5 | 0jdxt/AoC | /2018/day_5.py | 1,216 | 3.640625 | 4 | #!/usr/bin/env python3.7
"""--- Day 5: Alchemical Reduction ---"""
import string
import sys
def react(poly: str) -> str:
count = 1
while count:
i, count, new, top = 1, 0, "", len(poly)
while i < top:
a, b = poly[i - 1], poly[i]
if a.isupper() ^ b.isupper() and (a == b.l... |
4ee8c0a95419b8b5a5f129983e71db35d449eaf8 | Andy00097/hrinf-development | /2020-2021/DEV1/Chapter 4/BA13.py | 184 | 3.96875 | 4 | n = 15
print()
if (n % 3 == 0 and n % 5 == 0):
output = 'Purple'
elif n % 3 == 0:
output = 'Blue'
elif n % 5 == 0:
output = 'Red'
else:
output = 'Razzmatazz'
print() |
3b706769bf79937e58b3a32de38fc22adb92c15f | Andy00097/hrinf-development | /2020-2021/DEV1/Chapter 5/BA24.py | 266 | 4.03125 | 4 | number = 123
print()
numberAsString = str(number)
reverse = ""
palindrome = False
i = len(numberAsString) - 1
while i >= 0:
reverse = reverse + numberAsString[i]
i = i - 1
reverse = int(reverse)
if reverse == number:
palindrome = True
print() |
3263bfd1b0866c0df21043891cf406dae31261c9 | Andy00097/hrinf-development | /2020-2021/DEV1/Chapter 5/BA26.py | 91 | 3.625 | 4 | n = 5
print()
sigma = 0
i = n
while i > 0:
sigma = sigma + i
i = i - 1
print() |
0a6272aa56a91b28ad1fbb56d00edc57a1071fcd | Andy00097/hrinf-development | /2020-2021/DEV1/Chapter 4/BA17.py | 235 | 3.78125 | 4 | n = 123
print()
temp = n
rev = 0
while(temp > 0):
dig = temp % 10
rev = rev * 10 + dig
temp = temp // 10
if n == rev:
output = str(n) + ' is a palindrome'
else:
output = str(n) + ' is NOT a palindrome'
print() |
27f27560913da4a71f665f048b28d38a477f4da5 | Andy00097/hrinf-development | /2020-2021/DEV1/Chapter 5/BA4.py | 89 | 3.671875 | 4 | start = 0
end = 5
incr = 1
print()
i = start
while i < end:
i = i + incr
print() |
e2ca90eb3cca6577355dc92223db5fb6bc7458b9 | tulsishankarreddy/repository_training | /python_program/day2/cal_menu.py | 3,210 | 3.703125 | 4 | import sys
import os
sys.path.append('/home/karthik//python_program/modules')
import cal
while(1):
try:
# os.system('clear')
str1 = ' CALCULATOR '
print('#'.center(50,'#'))
print(str1.center(50,'#'))
print('#'.center(50,'#'))
print('MENU'.center(50,' '))
print('1.Simple calculator')
print('2.Sci calcu... |
f1567ac5d2c0e6c37b701db6fe875f27252bc25f | tulsishankarreddy/repository_training | /python/stack_queue/main.py | 797 | 3.984375 | 4 | def stck_push(List):
num=input("enter insert value\n")
List.append(num)
return;
def stck_pop(List):
num=List.pop()
print "number pop",num
return;
def en_que(List):
num=input("enter insert value\n")
List.append(num)
return;
def de_que(List):
num=List.pop(0)
print "number pop",num
return;
List=[1,2,3]
while ... |
1b51aea26d98600b0ceff191f4fc5ecf92cfe27c | tulsishankarreddy/repository_training | /python/cal.py | 209 | 4.0625 | 4 | op=input("option\n")
a=input("enter the value a\n")
b=input("enter the value b\n")
if op==1:
print "add",(a+b)
elif op==2:
print a-b
elif op==3:
print a*b
elif op==4:
print a/b
elif op==5:
print a**b
|
59b95467a2d8bbe1760e9d230825792ada4c728f | rudipop/Rudi_Aulas_Python | /exercicios python/exerciciosspyder/opflutuantes.py | 685 | 3.734375 | 4 | print ('\n'*100)
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 10 19:16:41 2019
@author: rudim
"""
# Operações com numeros inteiros
print ('operações com ponto flutuante')
a = float(input ('Entre com o valor de a:'))
b = float(input ('Entre com o valor de b:'))
#Operações básicas
soma = a+b
subtração... |
142b830d479e30ec7d77dcd07868c5cb58f77437 | karlhub/Exercism-Python | /pangram/pangram.py | 589 | 3.890625 | 4 | def is_pangram(sentence):
alphabet = {"a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0, "i":0, "j":0, "k":0, "l":0, "m":0, "n":0, "o":0, "p":0, "q":0, "r":0, "s":0, "t":0, "u":0, "v":0, "w":0, "x":0, "y":0, "z":0}
for letter in sentence.lower():
if letter in alphabet:
alphabet[letter]... |
962ec20dcc958d9bdd8b2f06c872fe9586019e73 | karlhub/Exercism-Python | /hamming/hamming.py | 739 | 3.984375 | 4 | def distance(strand_a, strand_b):
if len (strand_a) != len (strand_b):
raise ValueError("Error 1: strands are of different lengths")
return len ([(a, b) for (a, b) in zip(strand_a, strand_b) if a != b])
# Original solution
# hamdist = 0
# pos = 0
# while pos < len (strand_a):
# if str... |
79cc4c744516aeeb5bbf861e640762bb2d18d111 | karlhub/Exercism-Python | /book-store/book_store_ex1.py | 889 | 3.578125 | 4 | from typing import List
from collections import Counter
BOOK_PRICE = 800
DISCOUNT = [1, 1, 0.95, 0.9, 0.8, 0.75]
def total(basket: List[int]) -> int:
return int(price_calc(basket))
def price_calc(basket):
if len(basket) == 0:
return 0
different_books = set(basket)
number_of_books = Counter... |
a21e67207b8694b71d71aac73352bfb9a26f087c | mey1k/PythonPratice | /PythonPriatice/Brute-force_2.py | 950 | 3.640625 | 4 | '''
numbers return
17 3
011 2
'''
from itertools import permutations
def isPrimeNumber(n):
if n < 2:
return False
elif n == 2:
return True
else:
for i in range(2,n):
if n%i == 0:
return False
return True
def solution(numb... |
eca16d3794404a3659a448df344b120d26e9fe2e | mey1k/PythonPratice | /PythonPriatice/InsertionSort.py | 252 | 4.15625 | 4 | def insertionSort(x):
for size in range(1, len(x)):
val = x[size]
i = size
while i > 0 and x[i-1] > val:
x[i] = x[i-1]
i -= 1
x[i] = val
print(x)
insertionSort([3,23,14,123,124,123,12,3]) |
affbcc9d2efc578f0938301cfdaf8ad8d9dee2df | mey1k/PythonPratice | /PythonPriatice/heap.py | 2,766 | 3.65625 | 4 | #트리의 시작 인덱스는 1이다.
#따라서 리스트에 값을 접근할 때는 index-1 임에 유의하자.
class MinHeap:
def __init__(self):
self.queue = [] #초기화
self.resultHeapSort = []
@staticmethod
def parent(index): #index에 해당하는 원소의 부모 index를 리턴해주는 함수
return index//2
def insert(self, n):
self.queue.append(n)
... |
834a2f35de708b7a4d63cfc184f87b00a4902dbb | afroebel/bootcamp | /e3_2.py | 535 | 3.65625 | 4 | """
A function to complete theoretical fold change.
"""
import numpy as np
# Solves the top part of fraction in function.
def top_fold_change(RK, c, KdA):
return RK * (1 + c / KdA)**2
def bottom_fold_change(c, KdA, KdI, Kswitch):
return (1 + c / KdA)**2 + Kswitch * (1 + c / KdI)**2
# Complete function.
de... |
1761696b69850d198c352fd8ff10af746d731986 | afroebel/bootcamp | /luria_delbruck.py | 974 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# Specify parameters
# Number of generations
n_gen = 16
# Chance of having beneficial mutation
r = 1e-5
# Total number of cells
n_cells = 2**(n_gen - 1)
# Adaptive immunity binomial distribution
ai_samples = np.random.binomial(n_cell... |
4b7e0a3d38774d633ec0a6a5666cba926dc08b87 | lobzeg/machine_learning | /block_diagonal_matrix.py | 890 | 3.5625 | 4 | import numpy as np
#class of pseudo block diagonal matrices
#provides separate processing of inputs of different types
#at the first 2 layers of neural network
class BlockDiagonalMatrix:
def __init__(self, width, height, matrices):
self.width = width
self.height = height
self.matrices = ma... |
8a40fe22adca91b84eedc0dcfae9953806359b8d | alejandrobrusco/interprete-python | /Compilador/tests/test_comparaciones_diccionarios.py | 539 | 3.8125 | 4 | # Inicializacion de variables
d1 = { 1 : "H", 2 : "o" }
d2 = { 1 : "H", 2 : "o" }
d3 = { 1 : "H" }
d4 = { 1 : "H", 2 : "o", 3 : "l" }
d5 = { 4 : "a", 5 : "s" }
print 'd1 = ["a", "b", "c"]'
print 'd2 = ["a", "b", "c"]'
print 'd3 = ["a", "b"]'
print 'd4 = ["a", "b", "c", "d"]'
print 'd5 = ["e", "f", "g"]'
print ""
prin... |
09eece3494edcb1e41742cc2aa534b6a1ff4ea83 | alejandrobrusco/interprete-python | /Compilador/tests/manual_test_lista_fuera_rango.py | 307 | 3.6875 | 4 | print "\nTest de Rango de Lista:\n"
a = [1,2,3,4,5,6,7,8,9]
print "a=",a
print "Indices seleccionables: 0, 1, 2, 3, 4, 5, 6, 7, 8"
indice = raw_input("Elija el Indice del elemento a mostrar:")
indice_int = int(indice)
print "Usted selecciono", indice_int,". El valor de dicho indice es:",a[indice_int] |
b175f2940ee8c7aaa47c6a68216a6fb6f2835827 | alejandrobrusco/interprete-python | /Compilador/tests/test_comparaciones_listas.py | 1,699 | 3.734375 | 4 | # Inicializacion de variables
lista1 = ["a", "b", "c"]
lista2 = ["a", "b", "c"]
lista3 = ["a", "b"]
lista4 = ["a", "b", "c", "d"]
lista5 = ["e", "f", "g"]
print 'lista1 = ["a", "b", "c"]'
print 'lista2 = ["a", "b", "c"]'
print 'lista3 = ["a", "b"]'
print 'lista4 = ["a", "b", "c", "d"]'
print 'lista5 = ["e", "f", "g"]'... |
d883687909b6d04d655809c83bd7361691bb6bef | alejandrobrusco/interprete-python | /Compilador/tests/test_funciones_recursion_y_encadenadas.py | 567 | 3.9375 | 4 |
print "\nFunciones recursivas:\n"
def factorial(n):
if (n==0 or n==1):
return 1
return n*factorial(n-1)
number = 5
print "number=",5
print "factorial(number)=", factorial(5)
print "\nFunciones dentro de funciones (scope):\n"
def function1(a):
print a
c = 5
def function2(b):
print b+10
def funct... |
cf06771b1f3b32394e354accc6600f1aa51da92b | alejandrobrusco/interprete-python | /Python_Interpreter_Internet/tests/P3/25_dicts.py | 205 | 3.609375 | 4 | a = []
#b =
e = {1:2,3:4}
f = e
print f == e
f[1] = 4.0
print e == f
f = {1:2,4:4}
print e == f
f = {1:2,3:5}
print e == f
print e is f
print 12345678
g = {}
h = {}
g = {}
h = {3:4}
g = {}
h = {3:4}
|
ae7222673b440d33b69a834c12fe183521b384b5 | alejandrobrusco/interprete-python | /Python_Interpreter_Internet/tests/P3/list1.py | 134 | 3.796875 | 4 | print []
print [3]
print [3,True,1.0]
k = [[1,2]]
j = k[0]
j[0] = 3
print j,k
print j is k[0]
print [[]]
print [[],[[[]]],[3]],[]
|
663052c09ed2ae1f5d8a06c32829a0c5e0cc3f5a | OKNewman/Tradesman | /FunempMath.py | 606 | 3.828125 | 4 | import math
check_int = 123
check_float = 123.4
check_string = "Check"
check_bool = True
#intblaster: Checks data type of a variable, then either returns it as a floored integer, or returns a False boolean
def intblaster(var):
str_type = str(type(var))
if (str_type == "<class 'int'>"):
return var
... |
9c0e1d8c5bd16ab00563c2af70eea17f00688e25 | joeyhu/math | /ml/EuclideanNorm.py | 1,798 | 3.75 | 4 | '''
取欧几里得摸
'''
class EuclideanNorm:
def euclideanNorm(self, x):
l = len(x)
if l == 0:
return None
if l == 1:
return x[0]
s = 0
for i in range(l):
s += x[i] ** 2
return s ** 0.5
'''
n维空间坐标系下的两点距离
'''
def euclidean... |
440ff1e69fc80afab864abe9023b2b5250836460 | nogueral/Full-Stack-Python-Codo-a-Codo | /Python/sentencias.py | 202 | 3.65625 | 4 | print("Hola")#sencencia de una sola linea
a = 2 + 3 + 4 + 5 \
+ 6 + 7 + 8 \
+ 9 #sentencia dividida en lineas
print(a)
c = [1,2,3,4,5,
6,7,8,
9] #continuacion de linea implicita
print(c) |
6f83f55cc048eae62f60a0864c9e5511945fc058 | Sid3K1ck/verify-hash | /verifyHash.py | 1,894 | 3.609375 | 4 | #!/usr/bin/env python3
""" verifyHash.py
----------------------------------------------------------------------------------------------------
@Program: Verify Hash of file
@Author: Jamie R. Dayton
@Version: 1.21.02.05.001
-------------------------------------------------------------------------------------------------... |
60624d87e650e72bd395753dee3db69fadaf3200 | novotnyt94/cviceni_python | /assignment_1_2.py | 453 | 3.921875 | 4 | def sum_func(*numbers):
return sum(numbers)
def test_palindrome(string):
for i in range((len(string)+1)//2):
if string[i] != string[-i-1]:
return False
return True
print(sum_func(1,5,3,-4,-2.5,39.5)) #42
print(test_palindrome("asdfdsa")) #True
print(test_palindrome("asdffdsa")) #... |
bd40b86f7639ce864d19963092c1535a68118866 | kulvirvirk/list_methods | /main.py | 1,619 | 4.6875 | 5 |
# The list is a collection that is ordered and changeable. Allows duplicate members.
# List can contain other lists
# 1. create a list of fruits
# 2. using append(), add fruit to the list
# 3. use insert(), to insert another fruit in the list
# 4. use extend() method to add elements to the list
# 5. use pop() method ... |
d204769b195a01d1edc148998b1dbedabed1b6ed | nihar-mukhiya/text-generator | /matmul.py | 245 | 3.8125 | 4 | """
this program displays probability
import numpy as np
a = [0.6, 0.4]
b = [[0.7, 0.3], [0.6, 0.4]]
n = int(input("prediction of how many ahead u want: "))
while(n):
x = np.matmul(a, b)
a = x
n-=1
print(x)
""" |
df2a716a86be2683cdd7f7afbf22e48ff68820b4 | AlistairSaxby/FinalYearProject | /InitialScript.py | 1,927 | 3.578125 | 4 | import pandas as pd
import numpy as np
import sklearn
from sklearn import linear_model
import matplotlib.pyplot as pyplot
import pickle
from matplotlib import style
data = pd.read_csv("PYTHONDATA.csv", sep=",")
print(data.head()) # A test to ensure the data has been read in correctly by printing first 5 ro... |
bb28e4f86b10a818c8d34df54c0f16521b538092 | kiranjagz/Jefff.Trader | /Jefff.Py/Jefff.Py.py | 95 | 3.703125 | 4 | import sys
from math import sin, cos, radians
for i in range(360):
print(cos(radians(i)))
|
a232c1dbe330abefd09cb6c54916776cfae04c2b | darkscaryforest/example | /python/classes.py | 1,316 | 4.21875 | 4 | #!/usr/bin/python
class TestClass:
varList = []
varEx1 = 12
def __init__(self):
print "Special init function called."
self.varEx2 = 13
self.varEx3 = 14
def funcEx(self):
print self.varEx2
return "hello world"
x = TestClass()
print "1. Classes, like functions, must be declared before use.\n" \
"Calling... |
72e2a499d7d6068eda9bde43d585fff97a42440c | KhalerdAmeen/Password-Generator.Python | /password generator.py | 437 | 3.78125 | 4 | #khaleed Ameen
import random
chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*'
number = input('Number of password? - ')
number = int(number)
length = input('Password length? - ')
length = int(length)
for p in range(number):
password = ''
for c in range(length):
... |
538152bcd0bb7ae3a48165e1d4caad5631ece3db | GregBlockSU/iSchool | /ist652/Week3/so.py | 572 | 3.65625 | 4 | ###################code input#########################
####reading data
NBAfile=open('NBA-Attendance-1989.txt','r')
lines = NBAfile.readlines()
for line in lines:
line.strip();
items = line.split()
print(items)
if (items[1] == ""):
#
targetString = "YYYThe attendance at" + str(items... |
8cd5733039900e5dee760c19ecc6fdaee1dcfcdc | GregBlockSU/iSchool | /ist652/Week3/jay_12.py | 992 | 3.921875 | 4 | with open('state_satscores_2004.tsv') as StateScores: #open the file for use
StateScoreData = csv.reader(StateScores, delimiter='\t')
print("States with a mean Math SAT score >500:") #header to infrom user of what information follows
for StateData in StateScoreData: #loop through the file and assign each line ... |
fdf895beeb5f55cc594830ec9fb894f4bb8566db | GregBlockSU/iSchool | /ist652/Week3/power.py | 217 | 3.96875 | 4 | base = int(input('Enter the base integer:'))
exp = int(input('Enter the base exponent:'))
result = 1
for x in range(exp):
result = result * base
print(f'round {x} is {result}')
print(f'{base} ^ {exp} is {result}') |
12546e4c54e7f303133bfa95f4fb6e406c8d44b5 | GregBlockSU/iSchool | /ist652/Week3/matt.py | 846 | 3.96875 | 4 | # Lab 1 solution
# import pandas as pd
nbafile = open("NBA-Attendance-1989.txt","r")
nbalist=[]
for line in nbafile:
textline = line.strip() #remove whitespace
items = textline.split() #split entries onto separate lines
nbalist.append(items)
for game, attendance, price in nbalist:
print(f"The attendanc... |
22c104dd622a09f3b9ff9befafe62039f4184546 | markomijovic/mechanical-engineering-capstone | /src/main.py | 6,734 | 3.53125 | 4 | ### Author: Marko Mijovic, mijovicmarko11@gmail.com
### Date: March 26, 2021
"""
This program is a part of the 2020/21 mechanical engineering capstone project. The program preforms
statistical and ML analysis on bearing accelerometer data obtained from
https://www.kaggle.com/vinayak123tyagi/bearing-dataset?select=2nd_t... |
da3518b2df1d6f0cb276fdb6369fc9a21c69f4fe | wesenu/Computational-Thinking-and-Data-Science | /Lecture 3 - Graph Problems/shortestPath.py | 3,308 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 1 00:07:48 2016
@author: jpdjere
"""
import graphs
def printPath(path):
"""Assumes path is a list of nodes"""
result = ''
for i in range(len(path)):
result = result + str(path[i])
if i != len(path) - 1:
res... |
90dcb7cbf0007f40c5fd26454ca50f1e0a263d13 | wesenu/Computational-Thinking-and-Data-Science | /Mid-term Quiz/problem4.py | 3,514 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 28 21:13:44 2016
@author: jpdjere
"""
def checkSum(L,mults,s):
if len(L) == len(mults):
return sum([i*j for (i, j) in zip(L, mults)]) == s
else:
return "Different lengths of lists"
def greedySu... |
844cddf630ef107c067ee98496831bdb59f5b235 | lw000/new_python_demo | /python/flask_demo/src/main.py | 2,845 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding=utf-8 -*-
'''
Created on 2018年1月3日
@author: Administrator
'''
from flask import Flask
from flask import request
from flask import session
from flask import render_template
from flask import redirect
from flask import url_for
# from flask import sessions
app = Fl... |
074a3eef428f999206413049082ac8ea112bd049 | lw000/new_python_demo | /python/test/src/gevent_demo.py | 2,338 | 3.59375 | 4 | # -*- coding: UTF-8 -*-
'''
Created on 2017年12月19日
@author: Administrator
'''
import gevent
from gevent.event import Event
from gevent.event import AsyncResult
from gevent.queue import Queue
# from gevent.lock.RLock import RLock
# from gevent.lock.Semaphore import Semaphore
evt = Event()
a = AsyncRe... |
8402173f940522ccb8a69b2fae968c432f7305c9 | jcbraswell/Book-Recommender-System | /Simple User CF/loaddata.py | 2,896 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 22 18:18:05 2019
@author: Jon
"""
import pandas as pd
from surprise import Reader, Dataset
#import numpy as np
def GetBookData(items,ratings,users):
# items = pd.read_csv('C:/Users/Jon/Documents/Statistics/Machine Learning/Project/Book Crossing/BX Project/BX-Books.cs... |
6bb663c2c6b0691456cb10d3f1eaee9e15289608 | lemonied/python-test | /closure.py | 304 | 3.6875 | 4 | def func():
a = 20
def func2():
return a
return func2
f = func()
# __closure__ 闭包的标志
print(f.__closure__)
def func3():
a = 0
def func4():
nonlocal a
a += 1
return a
return func4
f2 = func3()
print(f2())
print(f2())
print(f2())
|
055a8d2ae106fe3a3f19c795af311bb8da14318d | MOAMSA/FunClock | /myClock.py | 3,451 | 3.8125 | 4 | import datetime
import random
import time
# Get current time
now=datetime.datetime.now()
seconds=now.second
minutes=now.minute
hours=now.hour
# Calculate the result by applying first operator on two first operands
def firstOperator(op1,op2,operator):
if operator == 1:
op12 = op1 + op2
operatorChar="+"
el... |
fd7bef36969bb8a0fd7952ffe3ac96e844ae9336 | neohope/spark-book-example | /sparkpython/pythondemo/demos/BasicMap.py | 458 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from pyspark import SparkContext
"""
平均值计算
"""
sc = SparkContext("local", "BasicMap")
def basicSquare(rdd):
return rdd.map(lambda x: x * x)
def basicMap(nums):
rdd = sc.parallelize(nums)
return sorted(basicSquare(rdd).collect())
if __name__ == "__main__":... |
c73e3968a546f728514d471c76424a02ef5460fb | alina1921/course-2130 | /year_2021/python/hw2/custom_dts.py | 6,272 | 3.71875 | 4 | from __future__ import annotations
from typing import List, Any
class CycledList:
def __init__(self, size: int):
self._inner_idx = 0
self._data = []
self.size = size
def append(self, item):
if len(self._data) < self.size:
self._data.append(item)
else:
... |
91c02273e26e8a8ef3fb9aa485f28458e2b6b8b4 | orlafoley/My_Projects | /usgeography.py | 4,093 | 4.03125 | 4 | # all raw data in .txt files taken from jetpunk.com
def stateToCounties(filename):
"""
:param filename: text containing state name, tab, county name, enter button...
:return: { state name : [list of counties in that state] }
"""
filein = open(filename, 'r')
lines = filein.readlines()
rawda... |
ed7b9a544f7ba430ff964d88cb159c57597856e9 | foivospolykarpou/ergasies47913 | /13.py | 150 | 3.65625 | 4 | #!/usr/bin/python
import codecs
string=raw_input("Enter string: ")
decoded=string.decode('rot13')
print "The decoded string is: ", decoded |
0a403952f4d4a544362aa981fdbddeb8a6ffa11a | pinchiachen/playground | /algorithm/bfs.py | 575 | 4.0625 | 4 | def bfs(graph, s):
queue = []
queue.append(s)
node_set = set()
node_set.add(s)
while len(queue) > 0:
vertex = queue.pop(0)
nodes = graph[vertex]
for node in nodes:
if node not in node_set:
queue.append(node)
node_set.add(node)
... |
2f942fb7fe80731d29adcec78dececea6d259e25 | pinchiachen/playground | /algorithm/dijkstra.py | 1,282 | 3.828125 | 4 | def dijkstra(matrix, n, start):
# Initialize book
book = [0] * (n + 1) # 1-indexed
book[start] = 1
# Initialize dis
dis = [0] * (n + 1) # 1-indexed
for end in range(1, n+1):
dis[end] = 0 if end == start else matrix[start][end]
# Dijkstra algorithm
for _ in range(n-1):
#... |
bae1624171f9dd642f998650e62723620dd71232 | ADL175/Data-Structures-and-Sorting | /DS/doubly_linked.py | 3,192 | 4.15625 | 4 | u"""Implementation of a doubly-linked list via Nick Hunt-Walker.
push(val) will insert the value ‘val’ at the head of the list
append(val) will append the value ‘val’ at the tail of the list
pop() will pop the first value off the head of the list and return it.
shift() will remove the last value from the tail of the l... |
4387853629c3b69b71269aeb1f7fdc141c0b5751 | ADL175/Data-Structures-and-Sorting | /DS/hash_table.py | 2,623 | 3.96875 | 4 | """Implement a hash table in Python.
Partnered with Elyanil, James Feore and Kurt Maurer
"""
from store_bst import BinTree
class HashTable(object):
"""Define a hash table and it's methods."""
pass
def __init__(self, size=None, hash_function=None):
"""Initialize a hash table."""
if not si... |
877d69b72a1e8b42c70377ef818e59ddefdc285c | adityamonga/HarvardPythonAI | /Search/tictactoe/exp.py | 4,053 | 3.828125 | 4 | import tictactoe as ttt
from sys import maxsize as MAXSIZE
X = 'X'
O = 'O'
EMPTY = None
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
def straight_lines():
## checks if any player has completed the horizontal or verticle line
## takes len(board) iteration... |
fc7c2f146bffd791ff8202725adb37b7c7605e43 | Holly089/solving-math-probles | /excersie one Q2a.10.py | 398 | 3.671875 | 4 | #Holly McClelland
#17/7/20
#data420 scalable data science
#excerise one Q2a.10
primes = [2,3]
numbers = list(range(1,2000001))
for num in numbers:
dividers = list(range(2,num-1))
count = 0
for divider in dividers:
if num % divider != 0:
count += 1
if count =... |
6ba0bef243e82eb7781086399d2182697e273386 | cjdevany/Fall2020-CS2450-Project | /src/cell.py | 1,788 | 3.859375 | 4 | #-------------------------------------------------------------------
# cell.py - Contains the methods for the cell object.
#
# Authors: Shadrac Reyes, Kelton Palmer, Kory Adams, Corey De Vany
#-------------------------------------------------------------------
"""
A Cell has a key, a value, and a bool array for curren... |
f96e76e4d741ad52f4bc765674a57c3200d0670a | jonas054/mlmutate | /test/test_bank_machine.py | 1,220 | 3.609375 | 4 | import bank_machine
import unittest
class TestBankMachine(unittest.TestCase):
def test_1(self):
m = bank_machine.BankMachine()
m.fillCash(1000000)
self.assertEqual(1000000, m.cash)
jonas = "19670223-2973"
m.addUser(jonas, 1234)
self.assertEqual(1, m.nrOf... |
0d3ea4123385980f8b24ecc5b59397e5e813372d | SnakeTweaker/PyStuff | /module 6 grocery list.py | 1,490 | 4.125 | 4 |
'''
Author: CJ Busca
Class: IT-140
Instructor: Lisa Fulton
Project: Grocery List Final
Date: 20284
'''
#Creation of empty data sctructures
grocery_item = {}
grocery_history = []
#Loop function for the while loop
stop = 'go'
while stop !='q':
#This block asks the user to input name, quantity, ... |
0c4f077fa6e50d24ad81f1e7de30b08e60ac34f6 | radishmouse/2019-11-function-demo | /adding-quiz.py | 437 | 4.3125 | 4 | def add(a, b):
return a + b
# print(a + b)
# if you don't have a `return`
# your function automatically
# returns `None`
# Write a function that can be called like so:
add(1, 1)
# I expect the result to be 2
num1 = int(input("first number: "))
num2 = int(input("second number: "))
num3 = int(input(... |
277409e0e15b321221f9bd105e089aa17473d820 | gottben/EC602 | /HW2/PartC/w2c_adding_half.py | 3,058 | 3.625 | 4 | # AUTHOR BrianAppleton appleton@bu.edu
# AUTHOR AlexBennett gottbenn@bu.edu
# AUTHOR CathrynCallahan cathcal@bu.edu
# AUTHOR PreranaHaridoss preranah@bu.edu
# git repository https://github.com/gottben/EC602
# w2c_addinghalf.py
from math import inf
def number_from_half(s : str):
s = int(s,16)
#return the ... |
21e783fc5101c5cc328ec3fb5ea750e4f3773f72 | Sushmitha2708/Python | /Data Modules/JSONModulesFromFiles.py | 926 | 4.21875 | 4 | #this progam deals with how to load JSON files into python objects and then write those
# objects back to JSON files
import json
# to load a JSON file into a python object we use JSON 'load' method
#load method--> loads a file into python object
#loads method --> loads a string into a python object
# to l... |
d794c23009665d8bb53269f89d9b150676281ecd | Sushmitha2708/Python | /Data Modules/CSVmodule.py | 399 | 3.78125 | 4 | import csv
with open('names.csv','r') as csv_file:
#csv_reader=csv.reader(csv_file) to read
csv_reader=csv.DictReader(csv_file)
for line in csv_reader:
print(line['Computer Science and Engineering'])
with open('new_names.csv','w') as new_file:
csv_writer=csv.writer(new_file,delimiter='\t')
for line in csv_r... |
b6d0f2e9b62f82970b371114f8734acc87026c0a | Sushmitha2708/Python | /Loops and Conditionals/ForLoop.py | 236 | 4.125 | 4 | #SET COMPREHENSIONS
# set is similar to list but with unique values
nums=[1,1,1,2,3,5,5,5,4,6,7,7,8,9,9] #list
my_set=set()
for n in nums:
my_set.add(n)
print(my_set)
#comprehension
my_set={n for n in nums}
print(my_set) |
f7df786c21abb5c1be0d47da9331030707bdefa8 | emetko/project-euler | /py/euler_037.py | 1,409 | 3.609375 | 4 | #!/usr/bin/env python
import sys
sys.path.insert(0, "..")
"""
Author: Eltjon Metko
Problem 37 - Truncatable primes
-----------------------------------------------------------------------------
The number 3797 has an interesting property. Being prime itself,
it is possible to continuously remove digits from left to rig... |
fa99b2f780ba7a70bda7d73bc3ad86a3d4207fa5 | emetko/project-euler | /py/utils/poker.py | 2,952 | 3.765625 | 4 | import random
def poker(hands):
"Return a list of winning hands: poker([hand,...]) => [hand,...]"
return allmax(hands, key=hand_rank)
def allmax(iterable, key=lambda x: x):
"Return a list of all items equal to the max of the iterable."
maxi = max(iterable, key=key)
return [(i, element) for i, el... |
2f25787fe97c0c5400873dd3e3bf322d47415ee0 | emetko/project-euler | /py/euler_019.py | 958 | 4.03125 | 4 | #!/usr/bin/python
"""
Problem 19
------------------------------------------------------------------------------
You are given the following information,
but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
S... |
8a2d069ef9f5afa4053e6f7cc93f0d0f29dcc7fd | emetko/project-euler | /py/euler_038.py | 1,585 | 4 | 4 | #!/usr/bin/env python
import sys
sys.path.insert(0, "..")
"""
Author: Eltjon Metko
Problem 38 - Pandigital multiples
-----------------------------------------------------------------------------
Take the number 192 and multiply it by each of 1, 2, and 3:
192 x 1 = 192
192 x 2 = 384
192 x 3 = 576
By concatenating each ... |
d97b078e90721a5b5dcc9682770bb506034b65d1 | Suryash-00/Python_Learning | /Test_Case1.py | 91 | 3.9375 | 4 | ans= input()
ans= ans.capitalize()
if ans=="Apple":
print("Gravity")
else:
print("Space") |
f3d3b37f00fce36a2ff411c3ab2f38b906ff3197 | Suryash-00/Python_Learning | /AdvancedPythonDevelopment/regularExpressions.py | 169 | 3.609375 | 4 | import re
email= 'suryash35@gmail.com'
expression= '[a-z\.]+'
matches= re.findall(expression, email)
print(matches)
name= matches[0]
domain= matches[1]
print(name)
print(domain) |
b6c875cdca2c3f73c62e20686f3a2202626be4f6 | Suryash-00/Python_Learning | /OOP/Classes_part1.py | 428 | 3.796875 | 4 | class Student:
def __init__(self, new_name, new_grades):
self.name=new_name
self.grades=new_grades
def average(self):
return sum(self.grades)/len(self.grades)
student_one= Student('Suryash', [70,88,90,99])
student_two= Student('Rahul', [90,80,80,100])
print(student_one.name)
print(stud... |
584c2a089fa746cf6e55f176830d7cd5de5df324 | Kaua-Sousa/Kaua-Sousa | /Aula5.py | 874 | 3.875 | 4 | lista = [12, 10, 7, 5]
lista_animal = ['cachorro', 'gato', 'elefante', 'lobo', 'arara']
lista_animal[0] = 'macaco'
print(lista_animal)
tupla = (1, 10, 12, 14)
print(len(tupla))
print(len(lista_animal))
tupla_animal = tuple(lista_animal)
print(type(tupla_animal))
print(tupla_animal)
lista_numerica = list(t... |
b8a25af14fa7bbc39227418c6aa6a8f57edc3200 | LLjiahai/python-django-web | /pdjango_web/python_note/基础/python3-5/regex_study.py | 1,005 | 4.34375 | 4 | import re
'''
python的正则表达式可以通过re模块来访问,这是在查找函数中使用非常频繁的一个组件。re.search返回一个匹配对象
随后可以用这个对象的group或者groups方法获取匹配的模式
python re模块的match(),search()
re模块的match()匹配是从字符串的开始位置匹配,只有从0位置匹配成功才有返回,否则返回none
search()匹配字符串中有无符合模式要求的子串
例如:
re.match('world','hello world'),会返回none
re.search(‘world’,‘hello world’).span()返回(6,10)
group和gro... |
bc34f3156bcebb0190464e44b1c9011cb3d96353 | tthoonee2/pythonlearning | /exercises/circle.py | 363 | 3.9375 | 4 | import turtle
import math
bob = turtle.Turtle()
def polygon(t,n,lenght):
angle = 360/n
for i in range(n):
t.fd(lenght)
t.lt(angle)
def circle(t,r):
circumference=2*math.pi*r
n=50
lenght = circumference
polygon(t,n,lenght) #i can recall the polygon function inside this function... |
c08a7d7d4ad611636250a7ff7d851ab6a5ac73d5 | tthoonee2/pythonlearning | /exercises/3-3.py | 439 | 3.65625 | 4 | def table(col_w, lenght_of_row,nlines):
for i in range(lenght_of_row): #the lenght of the raw is indicated in number of columns
print('+',col_w*'-','+',col_w*'-','+')
for ii in range(lenght_of_row):
print('|', col_w*' ','|', col_w*' ','|')
if nlines == 1 :
... |
03b159b9d6cc9b40242b781094b5fe44452a6787 | tthoonee2/pythonlearning | /exercises/turtletest.py | 202 | 3.5 | 4 | import turtle
i = 1
bob = turtle.Turtle()
bob.pd()
while i < 20 :
bob.fd(100)
bob.lt(90)
bob.fd(100)
i = i + 1
turtle.mainloop()
#idea on turtle: graphing a distribution with turtle.
|
0019935061c720c8ccc696b8b15d45a78972685f | sjwilczynski/Studies | /15-16/Winter/Python/lista2zad2.py | 880 | 3.78125 | 4 | class ObiektyDodawalne:
def __init__(self,name):
self.name = name
def __add__(self,obj):
if(isinstance(obj,ObiektyDodawalne)):
ds = self.__dict__
do = obj.__dict__
for i in do:
if(i in ds.keys()):
print("UWAGA! atrybut '%s' już istnieje" %(i))
ds[i] = do[i]
else:
print("Nie można dodać"... |
1cd4f799d229acf3f5aeb084197e4df17dcc93ac | ninaprus/hillel_python_hw | /home_work_2.py | 6,410 | 3.984375 | 4 | # 1) Сгенерировать dict() из списка ключей ниже по формуле (key : key* key).
#
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ожидаемый результат:
# {1: 1, 2: 4, 3: 9 …}
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print({key: key*key for key in keys})
# 2) Сгенерировать массив(list()). Из диапазона чисел
# от 0 до 100 записать ... |
6ffa16054fe624afcfbbe9623b667dd4803ad8b0 | sarangrakhecha/Python-Practice | /ex18.py | 345 | 3.546875 | 4 | def print_two(*args):
args1,args2=args
print "args1 : %r args2: %r" %(args1,args2)
def print_two_again(arg1,arg2):
print "args1 : %r \n args2: %r" %(arg1,arg2)
def print_one(arg1):
print "args1 : ",arg1
def print_zero():
print "Nothing"
print_two("Sarang","Rakhecha")
print_two_again("James","Bond")
print_... |
d27c534f85f4b92deb22269e98df392757fd9530 | sarangrakhecha/Python-Practice | /ex40.py | 404 | 3.6875 | 4 | class Song(object):
def __init__(self,lyrics):
self.lyrics=lyrics
def sing_song(self):
for line in self.lyrics:
print line
#print self.lyrics
song="asdsadfsdfasd"
happy_bday = Song(["Happy birthday to u",
"asdasdasd",
"asdasdasddfehrgh"])
trial=Song(["helloz"])
thanku = Song(["Thank u so... |
ce4e57510d73f543ea58cd158d1bb874b46afc67 | fyb-july/python-game | /first.py | 505 | 3.703125 | 4 | # Author Fyb
# 用七彩颜色画圆
# api具体用法请见 https://docs.python.org/zh-cn/3/library/turtle.html#turtle-methods
import turtle as t
import random
t.pensize(3)
t.speed(100)
t.penup()
t.goto(0, 0)
t.pendown()
# tracer直接跳过过程到结尾
# t.tracer(False)
t.bgcolor('black')
r, g, b = 0, 0, 0
for i in range(180):
r = random.random()
g ... |
c0be8db2b10db10c3d7c5db073adbe6c35d015a0 | xoempire/Python-Challanges | /22-reading-from-a-file.py | 524 | 4.0625 | 4 | # logc:
# reading from a file which has multiple names in it
# we woudl print the content of the file
# the program woudl tell us how many names there are in the list
# the program would also tell us the number of times that a name has been repeated
counter_dict = {}
with open("/Users/xoempire/Desktop/names.txt") as fi... |
b68c921324ff28784a3a5b7aab4e74b4a59e6ce9 | xoempire/Python-Challanges | /19-article-extractor.py | 695 | 3.671875 | 4 | # logic:
# make a request to the website that we are going be working with
# have the request processed in beautifulsoupe ----> parse it
# find the part of the article that you want
# print the whole thing
import requests
import sys
from bs4 import BeautifulSoup
page = requests.get('https://www.vanityfair.com/style/s... |
50c0e9bbe7f0ec71be357c35ccf2ba254cd18973 | xoempire/Python-Challanges | /25-Computer-gusses.py | 4,126 | 4.28125 | 4 | # logic:
# the user woudl have a number in her mind
# the program wudl try to guss it by giving it a number
# the user would give the program instructions wheather the nmber is higher or lower
# the program would guss different numbers based on the user input
# the number of gusses done by the program would be logged b... |
a57a4e68fb7a7558c0b9f533284072c026f559c3 | thimotyb/real-world-machine-learning | /decision-tree.py | 2,406 | 3.578125 | 4 |
from sklearn.tree import DecisionTreeClassifier
import pandas
import numpy as np
import os
os.chdir('C:/Users/thimo/Dropbox/corsi/machine_learning/real-world-machine-learning-master')
data = pandas.read_csv("data/titanic.csv")
data[:5]
data_train = data[:int(0.8*len(data))]
data_test = data[int(0.8*len(d... |
f734ed6a058a70ab05a83b7a67df9d0dc42769f8 | choupingru/leetcode | /easy/python/0020.py | 411 | 3.8125 | 4 | class Solution:
def isValid(self, s):
table = {'(':')', '{':'}', '[':']'}
answer = []
while(s):
if s[0] in ['(', '[', '{']:
answer.append(table[s[0]])
elif not answer or answer[-1] != s[0]:
return False
else:
... |
0c55596ebf17c49c42c283fbba767a62a23e83cf | LuAnVaRmO/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 644 | 3.8125 | 4 | #!/usr/bin/python3
""" island_perimeter module"""
def island_perimeter(grid):
""" Return the perimeter of a grid"""
h = len(grid) - 1
w = len(grid[0]) - 1
if h == 0 or w == 0:
return 0
per = 0
for x in range(w + 1):
for y in range(h + 1):
if grid[y][x] == 1:
... |
5b50666b13c7b144e73df4b87db015a8a5b724ef | amssdias/python-battleship | /battleship.py | 1,967 | 3.75 | 4 | from string import ascii_uppercase
from game_sets import *
# Create square matrix
alphabet = [letter for letter in ascii_uppercase if letter <= "J"]
table = [['.' for _ in range(10)] for _ in range(10)]
table.insert(0, alphabet)
new_ships = [create_ship(2), create_ship(3), create_ship(4), create_ship(5)]
ships = va... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.