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 |
|---|---|---|---|---|---|---|
62786b607ef2f8e22d07f61b0c0fae1e5bbf9418 | moussandiaye20/algorithm_on_graph_coursera | /week2_graph_decomposition2/1_cs_curriculum/acyclicity.py | 863 | 3.5625 | 4 | #Uses python3
import sys
def acyclic(adj):
from collections import defaultdict
visited=defaultdict(int)
def dfs(x):
visited[x]=1
for neighbor in adj[x]:
if visited[neighbor]==0:
if dfs(neighbor)==1:
return 1
elif visi... |
7d86d10ec528bce3a88d6e7f10279f0f216c2fec | harasees-singh/Notes | /Searching/Binary_Search_Monotonic_sequence.py | 2,164 | 3.953125 | 4 | # given a perfect square value S between 1 and 10**9
# find it's square root
n = 16
li = [i for i in range(n)]
def BinarySearch(li, left, right):
if left == right:
return left
mid = (left+right)//2
if mid*mid < n:
left = mid+1
else:
right = mid
ans = BinarySearch(li, left, r... |
edfcc0b98db78aa300f6cf4a804757129cf53321 | harasees-singh/Notes | /Searching/Binary_Search_Bisect.py | 947 | 4.125 | 4 | import bisect
# time complexities of bisect left and right are O(logn)
li = [8, 10, 45, 46, 47, 45, 42, 12]
index_where_x_should_be_inserted_is = bisect.bisect_right(li, 13) # 2 returned
index_where_x_should_be_inserted_is = bisect.bisect_left(li, 46) # 4 returned
print(index_where_x_should_be_inserted_is)
p... |
32b9bf1cf80dec0a1e9cbf8eb8697d7a40e03ace | xuxife/rlrouting | /shortest.py | 4,524 | 3.6875 | 4 | import numpy as np
from base_policy import Policy
class Shortest(Policy):
""" Shortest agent determine the action based on Dijkstra algorithm.
Parameters:
multiway(bool): whether store ALL possible shortest paths or not.
random(bool): only affect when `multiway=True`, choose the shortest pa... |
abeaffac5a701e2e5a9b8b765f40f3bee8054ccb | zfy1989lee/MachineLearning | /04Building Machine Learning System with Python/ch1Getting Started with Python Machine Learning/i5scatter_demo.py | 390 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def main():
N = 10
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
print('x=',x,'y=',y,'colors=',colors,'area=',area)
plt.scatter(x, y, s=area,c=co... |
d02d65a049097664b302450e31f5e631c163628b | zfy1989lee/MachineLearning | /01SciPy and NumPy/ch3SciPy/i8multivariate.py | 832 | 3.609375 | 4 | from termcolor import colored,cprint
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
# Defining a function
ripple = lambda x, y: np.sqrt(x**2 + y**2)+np.sin(x**2 + y**2)
# Generating gridded data. The complex number defines
# how many steps the grid data should have. Without ... |
e3883990ba622306280c71dc114310715395e6db | zfy1989lee/MachineLearning | /04Building Machine Learning System with Python/ch7Regression/i0boston.py | 952 | 3.765625 | 4 | import numpy as np
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot as plt
boston = load_boston()
x = boston.data
y = boston.target
print(len(x), len(y),x[0:5], y[0:5])
# Fitting a model is trivial: call the ``fit`` method in LinearRegression:
l... |
eed7780c70712a43c93ba30236c8464adefc07c0 | brLestad/Code-Excersize | /kullanıcı_girisi_whiletrue.py | 867 | 3.5 | 4 | print("""""
****************
KULLANICI GİRİŞİ PROGRAMI
****************
""")
sys_kullanıcı_adi = "muhiddinkaymak"
sys_sifre = "2124545"
giris_hakki = 3
while True:
kullanıcı_adı = input("KALLANICI ADINIZ: ")
sifre = input("ŞİFRENİZ: ")
if (kullanıcı_adı == sys_kullanıcı_adi and sifre != sys_sifre):
... |
c02c46f7aec4dc4be1e588bca27191bf44f18690 | brLestad/Code-Excersize | /indeks.py | 319 | 3.9375 | 4 | print("BEDEN İNDEKSİ HESAPLAMA")
boy = float(input("BOYUNUZ: "))
kilo = int(input("BOYUNUZ: "))
indeks = (kilo / (boy ** 2))
if indeks < 18.5:
print("ZAYIFSINIZ")
elif indeks >= 18.5 and indeks < 25:
print("NORMASLİNİZ")
elif indeks >= 25 and indeks < 30:
print("FAZLA KİLOLUSUNUZ")
else:
print("OBEZİ... |
b7fc78a9455c3a1991aad7636f4aca5fdd0ca581 | fabriciolelis/python_studying | /Curso em Video/ex061.py | 486 | 3.859375 | 4 | print('=' * 40)
print('{:^40}'.format('10 Termos de uma PA'))
print('=' * 40)
primeiro_termo = int(input('Primeiro termo da PA: '))
razao = int(input('Razão: '))
n = 1
termos = 1
total = 10
while termos != 0:
while n <= total:
print(primeiro_termo + (n-1) * razao, end=' → ')
n += 1
print('PAUS... |
068f6e070210541d4eb196ebdc797c120745b0d0 | fabriciolelis/python_studying | /HackerRank/Basic Data Types/Lists/main.py | 624 | 3.796875 | 4 | if __name__ == '__main__':
N = int(input())
lista = []
for i in range(0, N):
entrada = input().split()
if 'insert' in entrada:
lista.insert(int(entrada[1]), int(entrada[2]))
elif 'remove' in entrada:
lista.remove(int(entrada[1]))
elif 'append' in e... |
7512321635fc2ef32cf6c5a8163ce874089324bb | fabriciolelis/python_studying | /coursera/USP/course_1/week6/teste.py | 109 | 3.890625 | 4 | x = 1
while x < 3:
y = 1
while y < 3:
print(x*y, end = "\t")
y = y + 1
x = x + 1
|
60c25d2da7ab37147820147afd8c2b3d11779aa7 | fabriciolelis/python_studying | /HackerRank/Basic Data Types/Nested Lists/main.py | 628 | 3.609375 | 4 | if __name__ == '__main__':
python_students = []
for _ in range(int(input())):
name = input()
score = float(input())
student = []
student.append(name)
student.append(score)
python_students.append(student)
python_students.sort(key=lambda student: student[1])
... |
4fd5ca895efc0b1f738aa1879c5ade581ed92328 | fabriciolelis/python_studying | /coursera/Michigan/chapter_10/timeofday.py | 467 | 3.625 | 4 | fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
count = dict()
for line in fhand:
words = line.split()
if len(words) == 0:
continue
if words[0] != 'From':
continue
hours = words[5].split(':')
count[ho... |
7d35a5aa1210b5b4a4224dcc418ad829e34dc15e | fabriciolelis/python_studying | /Curso em Video/ex041.py | 415 | 3.96875 | 4 | from datetime import date
ano = int(input('Digite o ano de nascimento: '))
idade = date.today().year - ano
print('O atleta tem {} anos.'.format(idade))
if idade <= 9:
print('Classificação: MIRIM')
elif idade <= 14:
print('Classificação: INFANTIL')
elif idade <= 19:
print('Classificação: JÚNIOR')
elif idade ... |
03cf832b806a7b3220df43852aecf509a220cb92 | fabriciolelis/python_studying | /coursera/Michigan/chapter_10/histogram_email.py | 463 | 3.796875 | 4 | fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
count = dict()
for line in fhand:
words = line.split()
if len(words) == 0:
continue
if words[0] != 'From':
continue
count[words[1]] = count.get(words[1], 0)... |
3cb0d0b43d13fe8829d278ad2a74da229a2a9dcf | fabriciolelis/python_studying | /Curso em Video/ex031.py | 234 | 3.71875 | 4 | dist = float(input('Qual a distância da sua viagem: '))
if dist <= 200:
print('Sua viagem de {}Km vai custar R${:.2f}'.format(dist, dist * 0.5))
else:
print('Sua viagem de {}Km vai custar R${:.2f}'.format(dist, dist * 0.45))
|
a9732703e0dc80a8179e8c18b71f9711877ee648 | fabriciolelis/python_studying | /coursera/USP/course_1/week4/exe5.py | 271 | 3.734375 | 4 | inteiro = int(input("Digite o valor de inteiro: "))
n = 2
primo = True
while n < inteiro and primo:
if inteiro % n == 0:
primo = False
n += 1
print("primo" if primo else "não primo")
# if(primo):
# print("primo")
# else:
# print("não primo")
|
751e0094a30825eecce3585a531192cec4173622 | fabriciolelis/python_studying | /coursera/USP/course_1/week5/binomial.py | 323 | 3.890625 | 4 | def fatorial(n):
fatorial_value = 1
while n > 1:
fatorial_value = n * fatorial_value;
n -= 1
return fatorial_value
n = int(input("Digite o valor de n: "))
k = int(input("Digite o valor de k: "))
binomio = fatorial(n) // (fatorial(k) * fatorial(n - k))
print("O valor do binomio é ", binomio... |
33a50acf97981f2705ce16deaaf894b34c161c1d | hhelibeb/leetcode | /112. Path Sum.py | 619 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def hasPathSum1(self, root, sum):
if not root:
return False
if root and not root.left and not root.right and... |
174f95e484d36e7196ca63b090ea24fb33fc8246 | renatoalencar/spotivrau | /src/python/spotivrau/lib/worker.py | 879 | 3.53125 | 4 | import threading
class Worker:
def __init__(self, queue):
self.queue = queue
self.jobs = {}
def job(self, name):
def decorator(fn):
self.create_job(name, fn)
return fn
return decorator
def create_job(self, name, fn):
if name not in self.jo... |
65d4a28a36756c01a1d3c84b81dc58f8c72a178c | fields8-1863299/CSE163_Final_Project | /process_files.py | 6,620 | 4.0625 | 4 | """
Contains methods to produce datasets for use in the final project.
Each dataset is created by importing a csv file, cleaning the file,
and sometimes combining with other files based on similar row
or column data.
"""
import pandas as pd
import re
def getDF_A():
"""
Produces dataset A. Dataset A c... |
64380c0aca01d9b6e9069d08e83e1204657c8b52 | ericzhai918/Python | /Structure/stackDemo.py | 911 | 4 | 4 | class Stack(object):
def __init__(self, limit=10):
self.__items = []
self.__limit = limit
def isEmpty(self):
return self.__items == []
def peek(self):
return self.__items[len(self.__items) - 1]
def size(self):
return len(self.__items)
def pus... |
fd4af3a66824d99c428e39fbf843e536c15a4e71 | ericzhai918/Python | /JZ-Offer/find_more_than_half_num_in_2d.py | 1,389 | 3.65625 | 4 | import unittest
class Solution:
def findMoreThanHalfNumIn2d(self, numbers):
if numbers == []:
return 0
val, cnt = None, 0
for num in numbers:
if cnt == 0:
val, cnt = num, 1
else:
if val == num:
cnt += 1
... |
c3231050b14c3767a075b52879b77843b9d4ce93 | ericzhai918/Python | /LXF_Python/Function_test/func_positional_para.py | 282 | 4.125 | 4 | # 计算x的平方
def power(x):
return x * x
print(power(2))
# 如果要计算x的三次方,四次方呢?x*x*x,x*x*x*x这样显然很冗余
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(5,2))
print(power(5,3))
|
d2cf1861586e8fbea1836864e9cf8b7ce828b356 | ericzhai918/Python | /LXF_Python/Advanced_Feature_test/generator.py | 595 | 3.6875 | 4 | L = [x * x for x in range(10)]
print(L)
g = (x * x for x in range(10) )
print(g)
print(next(g))
print(next(g))
print(next(g))
g = (x*x for x in range(10))
for n in g:
print(n)
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
f = ... |
cd05b52a46ffcfcf7069f53b17e2176393cba810 | ericzhai918/Python | /Python_Cookbook/Chapter02/0207.py | 289 | 3.90625 | 4 | # 最短匹配模式
import re
str_pat = re.compile(r'\"(.*)\"')
text1 = 'Computer says "no."'
a = str_pat.findall(text1)
print(a)
text2 = 'Computer says "no." Phone says "yes."'
b = str_pat.findall(text2)
print(b)
str_pat = re.compile(r'\"(.*?)\"')
c = str_pat.findall(text2)
print(c)
|
0f85983eecf8fa4b554dfd54f4c12bafd8329657 | ericzhai918/Python | /My_Python_Test/Tuple/tuple_to_multi_value_01.py | 495 | 3.90625 | 4 | # 解压序列赋值给多个变量
p = (4, 5)
x, y = p
print(x)
print(y)
data = ['ACE', 50, 45.3, (2012, 20, 12)]
name, shares, price, date = data
print(name)
print(date)
name, shares, price, (year, mon, day) = data
print(year)
print(day)
# 这种解压赋值可以用在任何可迭代对象上面,而不仅仅是列表或者元组
s = 'Hello'
a, b, c, d, e = s
print(a)
print(e)
# 只想解压一部分
data... |
8d26adb2c46e6997106a81a36914f5bca5e13467 | ericzhai918/Python | /Python_Cookbook/Chapter02/0211.py | 452 | 4.03125 | 4 | #删除字符串中不需要的字符
s = ' hello world \n'
print(s.strip())
print(s.lstrip())
print(s.rstrip())
t = '-----hello====='
print(t.lstrip('-'))
print(t.strip('-='))
#中间有空格
s = ' hello world \n'
s = s.strip()
print(s)
#replace()
print(s.replace(' ',''))
#re
import re
print(re.sub('\s+',' ',s))
#应用
# with open(filename) a... |
df9d885bd6d837f5faf1a3411cf756c0181e7ca6 | ericzhai918/Python | /My_Python_Test/Re/re_match_search.py | 285 | 3.96875 | 4 | import re
line = "Cats are smarter than dogs"
matchObj = re.match(r'dog', line, re.M | re.I)
searchObj = re.search(r'dog', line, re.M | re.I)
if matchObj:
print(matchObj.group())
else:
print('No match')
if searchObj:
print(searchObj.group())
else:
print('No match') |
0eb5abcb587e285855ad3a4f4f376297920a38b4 | ericzhai918/Python | /Fluent_Python/Chapter02/listsort_sorted.py | 298 | 4.0625 | 4 | fruits = ['grape', 'raspberry', 'apple', 'banana']
print(sorted(fruits))
print(fruits)
print(sorted(fruits,reverse=True))
print(sorted(fruits,key=len))
#长度一样时, grape 和 apple的相对位置不会改变
print(sorted(fruits,key=len,reverse=True))
print(fruits)
print(fruits.sort())
|
cde858df3fcf42cedabaad28523d11e5bc9b6bd6 | ericzhai918/Python | /My_Python_Test/Function/Functional/operator.py | 422 | 3.6875 | 4 | # 使用 reduce 函数和一个匿名函数计算阶乘
from functools import reduce
def fact(n):
return reduce(lambda a, b: a * b, range(1, n + 1))
print(fact(4))
# operator模块为多个算术运算符提供了对应的函数,从而避免编写lambda a, b: a*b 这种平凡的匿名函数
from functools import reduce
from operator import mul
def fact(n):
return reduce(mul,range(1,n+1))
print(fact... |
6406c6d635122f5e7c65763af79eb0720b615212 | ericzhai918/Python | /Garden_Python/day_1110/loop_test.py | 392 | 3.59375 | 4 |
#for..in循环list
# names = ['A','B','C']
# for name in names:
# print(name)
#for..in累加1-10
# sum = 0
# for x in [1,2,3,4,5,6,7,8,9,10]:
# sum = sum + x
# print(sum)
#for...in累加1-1000
# sum = 0
# for x in range(1001):
# sum = sum + x
# print(sum)
#while计算100内所有奇数的和
# sum = 0
# n = 99
# while n > 0:
# s... |
e94da08fe1cf08699eeda014d9167eebd32236ee | packetfairy/mines | /Miner.py | 2,916 | 4.0625 | 4 | import random
class setmines:
def __init__(self, length=10, width=10, minecount=10):
self.length = length
self.width = width
self.minecount = minecount
self.totalspaces = self.length * self.width
def placemines(self):
'''uses the predefined length, width, and minecoun... |
8f95a332dff497949d598de5d8f3983247ab183b | liangweile1994/pythontest | /python推导式/test.py | 600 | 3.96875 | 4 | #coding:utf-8
#列表推导式
multiples1 = [i for i in range(30) if i%3 is 0]
print multiples1
def squared(x):
return x*x
multiples2 = [squared(i) for i in range(30) if i%3 is 0]
print multiples2
#生成器
multiples3 = (i for i in range(30) if i%3 is 0)
print(type(multiples3))
#字典推倒式
mcase = {'a':10, 'b':34, 'A':7,'Z':3}
mcas... |
e84375fdd41c25211742aff32131f8bd5de9650e | nicknovoa03/FunctionsNote3 | /ReturnNothing.py | 244 | 4.09375 | 4 | # function printList prints the contents of its argument
# if it encounters a negative value, it returns
def printList(lis):
for x in lis:
if x < 0:
return
print(x)
nums = [10, 20, 30, -25, 50]
printList(nums)
|
a056e12d0b20670c50d34e5462c8072cc07aefdc | enessgurkan21/myRepo | /Pycharm projeleri/Hesap Makinesi v1.py | 2,045 | 3.96875 | 4 | print("Hesap Makinesine Hoşgeldiniz :")
giriş="""
(1) Topla
(2) Çıkar
(3) Çarp
(4) Böl
(5) Karesini hesapla
(6) Kökünü hesapla
"""
print(giriş)
soru=input("Yapmak İstediğiniz İşlemin Numarasını Giriniz :")
if soru=="1":
sayı1=int(input("Lütfen Toplamak İstediğiniz Birinci Sayıyı Giriniz :"))
sayı2 = int(inp... |
d169d0a7be5119ed5e0b355dd55e9be32d3988d5 | SuneastChen/python_basic | /文件读写/pickle模块/pickle模块.py | 443 | 3.546875 | 4 | # _*_ coding:utf-8 _*_
#!/usr/bin/python34
print('-------------------pickle写入,读取文件4--------------------')
import pickle
b2=[99,88,77,'我爱你','世界!']
f=open('my_list.pkl','wb')
#只有二进制可写模式,方可倒入,ab,wb效果一样的,创建一个新的,不会追加写入;文件名后缀可任意
pickle.dump(b2*2,f)
f.close()
f=open('my_list.pkl','rb') #只能用'rb'模式来读取
b3=pickle.load(f)
... |
c384c6b56bf626be00e909fde41a1d69ca444ae6 | pgr-me/PRasmussenLab3 | /lab3/evaluators/evaluate.py | 3,290 | 3.90625 | 4 | """Peter Rasmussen, Lab 3, evaluate.py
This module parses the evaluation input and uses a two-dimensional singly-linked list (linked list
of linked lists) to store variable: value pairs. Each evaluation term is provided as its own line,
and each term is validated so that it conforms to the pattern variable-value ... v... |
a4a3c0e43ff5538a6320f361e2aaf5bf4dd49a36 | harryghgim/py4e | /exercises/datastructures/7.2.py | 560 | 3.625 | 4 | # 7.2.py
# https://www.py4e.com/lessons/files
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ") # mbox-short.txt
fh = open(fname) # file handler object
sm = 0
count = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
# line = line.rstrip()
# pri... |
196e92760eabef878c411102e17b66fc2c791a14 | SamReji123/Scripting | /Python/PFA/colatz.py | 305 | 3.921875 | 4 | def colatz(num):
if(num%2==0):
num=num/2
print(num)
else:
num = (3*num)+1
print(num)
if(num==1):
exit()
else:
colatz(num)
print('enter the number')
try:
number=int(input())
except:
print('Incorrect entry')
exit()
colatz(number)
|
d4a5eff0be81c32b128c94c9177c903b1113ead3 | JoshuaRomanV/Ejercicios-Python | /traductor.py | 212 | 3.890625 | 4 | import goslate
print("Hola bienvenido!\n")
print("Traductor español-ingles\n")
palabra = input("Ingrese la palabra que desea Traducir al ingles:")
Tr = goslate.Goslate()
print(Tr.translate(palabra, 'en'))
|
6e3f959bd6edc44c52fee07447fd04a12996c99e | srikanteswartalluri/cdlty | /PermCheck.py | 302 | 3.53125 | 4 | def solution(A):
# write your code in Python 3.6
if len(A) == 1 and A[0] == 1:
return 1
A.sort()
#print(A)
count = 1
for i in A:
if count != i:
return 0
count = count + 1
return 1
if __name__ == "__main__":
print(solution([1, 2]))
|
fa19c156326fc1f7e83d0dc8c6b8e33d2007c90e | tanjaik/GirlsWhoDev | /Ex4_2_Counts.py | 190 | 3.609375 | 4 | import csv
csv_file = open('girls_learning_python.csv')
csv_data = csv.DictReader(csv_file)
count = 0
for row in csv_data:
count +=1
print ("There are " + str (count) + " attendees")
|
9fe5ca38e70b98cffbfafd273c233056c41d9001 | fadedmax/testingscripts | /andthetdaygoeson.py | 712 | 4.0625 | 4 | import datetime
while True:
user_input = input("Enter a list of real numbers separated by space: ")
try:
my_list = [float(x) for x in user_input.split()]
except ValueError:
print("Some of the values were invalid. Try again.")
continue
if not my_list:
print("You didn't ent... |
d4dd62baef1734197c92c60ae26b7105f229e5d3 | fadedmax/testingscripts | /testcodeagain.py | 1,538 | 4.03125 | 4 | def calculator():
print ("1. Addition")
print ("2. Subtraction")
print ("3. Multiplacation")
print ("4. Division")
print ("5. Primes to 100")
print ("6. Find factors")
print ("")
question = input("Please select a option")
if question == "1":
num1 = int(input("Enter first number: "))
print (num1)
n... |
2c569fd0d64171e926e6d10aaaac6aeb618448e0 | lahsivvishal/algorithms-in-python | /Easy/Nth_fib.py | 654 | 4.03125 | 4 | # General
"""
if n == 2:
return 1
elif n == 1:
return 0
elif:
return fib(n-1)+fib(n-2)
"""
# Memoize
"""
def getNthFib(n, memoize = {1:0, 2:1}):
if n in memoize:
return memoize[n]
else:
memoize[n] = getNthFib(n-1, memoize) + getNthFib(n-2, memoize)
return memo... |
eb9535403b61c41c1d9c0e127ffc4433227d185e | jenphillips/pythonds | /6-trees/list_trees.py | 1,901 | 3.75 | 4 | # class Node():
# def __init__(self):
# self.key = None
# class BinaryTree():
# def __init__(self):
# self.nodes = []
# self.currentNode = None
# def getLeftChild(self, node):
# pass
# def getRightChild(self, node):
# pass
# def setRootVal(self, val):
# ... |
bb31203a9fc49fb102f9cf3e4964a314e676ef01 | jenphillips/pythonds | /5-sort_search/searching.py | 3,502 | 3.921875 | 4 | def sequentialSearch(listToSearch, item):
found = False
# for i in listToSearch:
# if i == item:
# found = True
pos = 0
while pos < len(listToSearch) and not found:
if listToSearch[pos] == item:
found = True
else:
pos += 1
return found
... |
081e15ee8df4f36397ee61413cf9607d646cf438 | molleweide/dorothy | /commands/python-regex | 686 | 3.578125 | 4 | #!/usr/bin/env python
import re
import argparse
import sys
# import fileinput
def run():
parser = argparse.ArgumentParser(description='Find and optionally replace with Python regular expressions.')
parser.add_argument('find', type=str, help='Regular Expression Find')
parser.add_argument('replace', nargs='*', defau... |
2732c25f4f93631ff1380356018583e565c0d947 | nithylsairam/python | /companyLogo.py | 217 | 3.765625 | 4 | from collections import Counter
s = input()
lettr_freq = Counter(s)
most_comn = list(lettr_freq.items())
most_comn.sort(key=lambda t: (-t[1], t[0]))
for lettr, freq in most_comn[:3]:
print(lettr, freq)
|
d90ada5f17ae027ccf192b8b7a901ca7ad1feb4c | asan99/day-18 | /task8.py | 53 | 3.546875 | 4 | s = ["qwerty", "phone"]
print(s)
s.reverse()
print(s) |
5fc71ec6d2fae5890202e744240004c875ffda8d | hongzhangMu/testrun | /testtrail/examples/allroadstime.py | 5,123 | 3.5 | 4 | #coding:utf-8
import os
import time
#定义每路口剩余红绿灯剩余
def lefttime_per_reads(miletime_now,start_time,greentime,yellowtime,redtime):
"""
miletime_now :当前时间乘以1000,为毫秒时间戳
start_time:当前路口绿灯开始时间,如9点半直行为绿灯,毫秒时间戳
greentime 直行路口绿灯秒数
redtime:直行红灯秒数
yellowtime:黄灯秒数时间
"""
# miletime_now = 1587609000000
allti... |
343ec9642b902f06b50790c7b27c0856d3225742 | gbroques/cozplay-demos | /tapatan/grid_control.py | 13,441 | 3.859375 | 4 | """
grid_control.py:
- Support class for Tapatan game
- Draws the grid using Pygame and updates the cells based on the current state of the game
@author - Team Cozplay
"""
# Standard python modules
import pygame
from pygame.locals import *
import math
# Import Tapatan GameState
from tapatan import GameState
... |
64efd7d5cf4e7742c20d7cfe5ec938934482f65d | daniellomelino/KenzieConsoleArcade | /main.py | 4,363 | 3.59375 | 4 | # 1. Display a numbered list of available games and token total
# 2. Choose a game
# 3. Play that game
# - exit at any time by entering "exit"
import hashlib
import importlib
import os
from helpers import con, cur, status_bar, add_commas
START_TOKENS = 20
DISABLED = ['poker', 'wheel-of-python']
available_games... |
40f2489b130af2d66cf6e76e94abd2a3b8c80000 | AfiqYahya/advent2020 | /advent2020/day19.py | 3,141 | 3.625 | 4 | from __future__ import annotations
from typing import NamedTuple, List, Optional, Tuple, Iterator
from collections import deque
class Rule(NamedTuple):
id: int
literal: Optional[str] = None
subrules: List[List[int]] = []
@staticmethod
def parse(line: str) -> Rule:
rule_id, rest = line.stri... |
1ff955f93ded9f8937fefbc1224b4cf169d18e7c | AfiqYahya/advent2020 | /advent2020/day25.py | 1,308 | 3.78125 | 4 | from __future__ import annotations
from typing import Iterator
"""
The handshake used by the card and the door involves an operation
that transforms a subject number. To transform a subject number,
start with the value 1. Then, a number of times called the loop size,
perform the following steps:
Set the value to i... |
f993c10f6a3980a8871d5b026f50a3ff33bb0931 | DAyurzana/hello-world | /player_actions.py | 344 | 3.84375 | 4 | #player_actions.py
#Duke A.
#02/11/2021
def check_play_again(user_input):
if user_input == "y":
print("Yes, play again")
elif user_input == "n":
print("No, quit the game")
else:
print("invalid input")
check_play_again(input("Would you like to play again? Type Y for ... |
675ecb48dc2fa46b002985318389d94911496d02 | Keksoj/school_algos | /parcours_de_graphe/NearestTownGraph.py | 2,869 | 3.75 | 4 | from Graph import Graph
from time import perf_counter_ns
from Path import Path
from Town import Town
from pprint import pprint
import random
import string
import copy
import time
import csv
import math
class NearestTownGraph(Graph):
"""
This child class of Graph finds a path by choosing the nearest town as th... |
0832c17a73c1ba442ba6fd6cb13b5e8af3e71e98 | Keksoj/school_algos | /pytactx/Path.py | 1,034 | 4.03125 | 4 | from Town import Town
class Path:
def __init__(self):
"""
properties:
towns: list of Town instances, in the order of the path
length: total travel distance driven by the salesman
"""
self.towns = []
self.length = 0
def append_town(self, town, ve... |
e0f2814b26a5e7ca996a89f3dc343e4fded7b324 | alanduda/python-solutions | /URI/Iniciante/Fórmula de Bhaskara.py | 306 | 3.5625 | 4 | values = input().split(' ')
A = float(values[0]); B = float(values[1]); C = float(values[2])
delta = (B**2) - (4*A*C)
if( delta >= 0 and A != 0.0):
print((-B + delta**0.5))
print(f'R1 = {((-B + delta**0.5)/(2*A)):0.5f}\nR2 = {((-B - delta**0.5)/(2*A)):0.5f}')
else:
print('Impossivel calcular') |
7d19e951c93430142e5c3da607063dc5da602fb3 | Deepak3211/python-_refresher | /assignment.py | 1,058 | 4.21875 | 4 | #Question 1
x=['Python','Java','Ruby']
x
#Question 2
x=['Python','Java','Ruby']
y=['c++','c','php']
x+y
#Question 3
x=['Deepak','Deepak','Rohan','Ayush']
x.count('Deepak')
#Question 4
x=['Deepak','Deepak','Rohan','Ayush']
x.sort()
x
#Question 5
x=['Deepak','Deepak','Rohan','Ayush']
x.sort()
x
y=['Surya','Rock','Pu... |
52e8682f189619c13303d034734f1e349bfcde85 | waarning/basic | /iprecent.py | 934 | 3.828125 | 4 | #David Neundorfer
#9/24/2020
#
def Welcome():
print("Welcome to CSU Airlines")
print()
print("Tickets are $300 each")
print("Carry-on bags cost $25 per bag")
print("Checked baggage costs $55 per bag")
#Helper functions
def carry_on_bags(x):
total_carryon = x * 25
retu... |
8c541cec767a78a84fdb6df14559032a92ec9f4d | vottie/lang | /python/calc/calc.py | 341 | 3.75 | 4 | class Calc:
# need self.
# occur below
# typeError: add() takes exactly 2 arguments (3 given)
def add(self, x, y):
if not isinstance(x, int):
raise TypeError("%r: integer expected" % (x))
if not isinstance(y, int):
raise TypeError("%r: integer expected" % (y))
... |
c3877867f8a58766bfd67ca004522d68699fc4f2 | maninder2295/PONG-GAME | /scoreboard.py | 1,056 | 3.796875 | 4 | from turtle import Turtle
ALIGN = 'center'
FONT = ("Ariel", 40, 'bold')
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score_left = 0
self.score_right = 0
self.color("white")
self.penup()
self.hideturtle()
self.create_le... |
eb441c9bde0472a0f1efdfedba1e827c1a231d82 | HaseebSyed82/Python | /voltage.py | 446 | 3.515625 | 4 | #
#
#
voltageOne = input("1st generator: ")
if (voltageOne == 0):
print (voltageOne)
voltageTwo = input("2nd generator: ")
if (voltageTwo == 0):
print (voltageTwo)
voltageThree = input("3rd generator: ")
if (voltageThree == 0):
print (voltageThree)
... |
8954222ecba2c5183747730a8d1ff9036836d0b5 | HaseebSyed82/Python | /rectangleOutput.py | 587 | 3.625 | 4 | Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
============ RESTART: C:\Users\cod_user\Desktop\TestRectangle.py ============
The height of the rectangle is: 40
The width of the rectangle is: 4
The... |
3883bd79221948135df3958b7e4b0e90c69c6636 | HaseebSyed82/Python | /assignment 12/Employee3.py | 596 | 3.75 | 4 | # This is the object for Employee 3
# Assignment 12
# Haseeb Syed
# CIS 1400
class Employee3:
def __init__(self,name = "Joy Rogers",idnumber = 81774,department = "Manufacturing",position = "Engineer"):
self.name = "Joy Rogers"
self.idnumber = 81774
self.department = "Manufacturi... |
716f2d8b4514405129919ae714db3f6a7cbd3eee | aboudiop/sunny-side-up | /Baseline/Bayes-NLTK/import_stanford_twitter.py | 3,172 | 3.84375 | 4 | import csv
import logging
# Dictionary that defines the Sentiment features
Sentiment = {0: 'neg', 2: 'neutral', 4: 'pos'}
def latin_csv_reader(csv_data, dialect=csv.excel, **kwargs):
''' Function that takes an opened CSV file with
ASCII or UTF-8 encoding and convert's to Latin-1
@Arguments:
... |
6333b66085b4fc566de5df8abbe329071742ffd1 | vanditkhurana/Speed-and-Distance-Calculator | /3.py | 651 | 3.984375 | 4 | from tkinter import *
def calculate():
#print("Aie!")
#print("The double of ",e.get()," is ",2*int(e.get()))
x=float(e.get())
v.set(str(2*x))
window=Tk()
window.title("Double")
l1=Label(window,text="x")
l1.grid(row=0,column=0)
e=Entry(window,bg="yellow")
e.grid(row=0,column=1)
l1=Label(windo... |
e137dff9c627dea8c8ac955d4d46e40c7f52cb7f | CGump/leetcode-everyday | /020_Easy_ValidParentheses.py | 2,677 | 3.703125 | 4 | class Solution:
'''
给定一个只包括 `'('`,`')'`,`'{'`,`'}'`,`'['`,`']'` 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: f... |
1ab0213b885fb5912a3245a47a4d657190339a48 | CGump/leetcode-everyday | /035_SearchInsertPosition.py | 723 | 3.90625 | 4 | class Solution(object):
'''
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 7
输出: 4
'''
def searchInsert(self, nums, target):
"""
:type nums: List[int]... |
5e7ae739885bdf21e4514e352a0eb449cb6d3e19 | treewojima/sudoku_solver | /solver/solvers/elimination.py | 863 | 3.703125 | 4 | def elimination(sudoku):
altered = False
for column in sudoku.get_columns():
altered += work(set(column))
for row in sudoku.get_rows():
altered += work(set(row))
for box in sudoku.get_boxes():
altered += work(set(box))
return altered
def work(cellset):
altered = Fals... |
7f6ebf101dbb64e1182e760de2248b6be6504187 | dittonjs/game_dev | /maze/circles.py | 1,243 | 4.09375 | 4 | #Dillon Sant
#CS1400-1
#Assignment 7
'''
Requirement Specifications-
Write a program that asks the user for radius of two circles, and coordinates. Then draw those circles, and determine whether or not they are intersecting.
System Analysis-
System Design-
1.import random
2. define 0, 1, and 2 as rock paper scissor... |
b005ccca5ad2d7b0a0a05ffe28de93b745037f8a | lagorma/3_semestr_2020 | /w7/my_mathematics/linear_algebra.py | 908 | 3.828125 | 4 | #!/bin/python
class Vector:
def __init__(self, a):
A=list(map(int,a.split(',')))
self.x = A[0]
self.y = A[1]
self.z = A[2]
def __add__(self, other):
return Vector('{},{},{}'.format(self.x + other.x, self.y + other.y, self.z + other.z))
def __sub__(self, other):... |
62af54ba5eec882b3eb633ecff8a6040b8894069 | lagorma/3_semestr_2020 | /w9/w9_1.py | 1,193 | 3.765625 | 4 | #!/bin/python
class BinTree:
def update_tree(self):
self.dfs_iter = iter(self.DFS(self))
def __init__(self, name):
self.left = None
self.right = None
self.name = name
self.update_tree()
def add(self, name):
if self.name:
if name < self.name:
... |
00974c1e9d5df82575c8cd93570d40a45348f76f | lagorma/3_semestr_2020 | /w13/class_to_serialize.py | 766 | 3.625 | 4 | import json
class MyClass:
def __init__(self, name, surname, is_hired):
self.name = name
self.surname = surname
self.is_hired = is_hired
def __dict__(self):
return {'name': self.name, 'surname': self.surname, 'is_hired': self.is_hired}
def __str__(self):
return f'M... |
63243c81131bb131a0a3fc05193fd516b79d45a7 | lagorma/3_semestr_2020 | /w3/number_6.py | 427 | 3.5 | 4 | import csv
def r_csv(c):
with open(c, 'r') as out:
reader = csv.reader(out)
for row in reader:
print(row)
r_csv('table.csv')
import pandas as pd
import numpy as np
a= pd.read_csv('table.csv', sep = ';', header = None)
b=pd.DataFrame(np.insert(a.values, int(len (a)/2), values = [-200, -... |
e23dedc04920a9a53170795bd73b192aed22bcf7 | josie-smith/Project-Euler | /19.py | 932 | 3.75 | 4 | import sys
sys.setrecursionlimit(1500)
def daysInMonth(month,year) :
month = month%12
if month in [1,3,5,7,8,10,0] :
return 31
elif month in [4,6,9,11] :
return 30
elif year%4 == 0 :
if year%100 == 0 :
if year%400 == 0 :
return 29
... |
203463a69302ebec115506e30908f6b98dc2a5a3 | Robin-1995/BlockChain | /Blockchain.py | 2,100 | 3.53125 | 4 | import hashlib
import datetime
class Block:
def __init__(self, timestamp, data=None, previous_hash=None):
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.calc_hash(data)
self.next = None
def calc_hash(self, da... |
62b6bcd482dd774b75a816056a21247487f32b86 | maindolaamit/tutorials | /python/Beginer/higher_lower_guess_game.py | 1,519 | 4.3125 | 4 | """ A sample game to guess a number between 1 and 100 """
import random
rules = """
=========================================================================================================
= Hi, Below are the rules of the game !!!! =
= 1. At the Start of th... |
b23ea24401518faa40cc24d07672077cd3168001 | sugu24/python-app | /english_typing_app_python/temp1.py | 5,409 | 3.5 | 4 | import tkinter as tk
from tkinter import messagebox
import pyautogui as pa
import csv
import random
# 問題数
l = 5
class App(tk.Tk):
def __init__(self):
# ウィンドウの初期化
self.master = tk.Tk()
self.master.title('英単語勉強タイピング')
self.master.geometry("600x400")
self.__ini... |
fe286721ff7c80c93c04ead102440a9172c2264f | angeladt/todoUpdate.py | /todoUpdate.py | 719 | 3.890625 | 4 | import datetime
import fileinput
import sys
# set variables for today's date and yesterday's date in yyyy-mm-dd format
today = str(datetime.date.today())
yesterday = str(datetime.date.today() + datetime.timedelta(days=-1))
# go through todo.txt and replace all instances of yesterday's date with today's date
for line ... |
db03001c3893edd77a2f913478a07f9c2e6a8010 | gluppes/crypto-wizard | /keywords.py | 504 | 3.765625 | 4 | # This file generates the search queries dynamically so you don't have to manually type them in.
KEYWORDS = []
cryptos = ["iota", "bitcoin", "ethereum", "litecoin", "ripple"]
prefixes = ["how to buy ", "what is "]
suffixes = [" price", " announcements"]
for crypto in cryptos:
for prefix in prefixes:
KEYWORDS.appen... |
f3c573c78bb5fcbc8e9fb501777afaa6a52bd7e6 | ahsif/Airport-Database-sorting-Python | /flight.py | 2,050 | 3.765625 | 4 | #Written by Ahsif Safdar. Ahsif.Safdar@gmail.com
class Flight:
def __init__(self, year, month, day, airline, flight_num, origin_airport, dest_airport, scheduled_departure, departure_time, departure_delay, scheduled_arrival, arrival_time, arrival_delay):
self._date = str(year)+'-'+ str(f'{int(month):02d}') +'-'+ s... |
191b9eab940e9dd7d665236857a9a33ef8bce787 | Justin-Van-Olderen/Python-Basic | /5-eindopdracht/EindOpdracht.py | 1,636 | 3.734375 | 4 | import time #Importeer de time library
#Geeft de variablen aan
h = int(input("Enter hours:"))
m = int(input("Enter minutes:"))
s = int(input("Enter seconds:"))
while True:
if(h==24 and m==60 and s==60): #Waaneer de tijd 23:59:59, reset de timer en gaat terug 00:00:00
#Dit geeft de waarde 0 van de tijd... |
8e5bb8029b3eb3a57cca33daaa092e2017b1c1f7 | johnrohith/new-world | /first class 6.py | 102 | 3.859375 | 4 | a=int(input ("enter a value for a"))
b=int(input ("enter a value for b"))
c=a+b
print (c)
|
424817715b5614d661be52bc193a93d2f135069e | johnrohith/new-world | /2nd class 3.py | 163 | 3.921875 | 4 | marks=int(input("enter your marks"))
if marks>90:
print("grade A")
if marks>80:
print("grade B")
if marks>70:
print("grade c")
else:
print("fail")
|
4ad42519005fda9e39d55b594b514f6bb1ffea34 | MyFang97/CommonDemo | /算法道路/leetcode/20210528/demo.py | 1,701 | 3.5 | 4 | # author_='Fang';
# date: 2021/5/28 10:11
# 汉明距离
from typing import List
ans = 0
nums = [2, 4, 7]
for i in range(30):
c = sum(((val >> i) & 1) for val in nums)
ans += c * (len(nums) - c)
# 1537. 最大得分
def maxSum(nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
best1 = best2 =... |
67b485328b092419244a59806c0cff1254517127 | OrangeInSouth/Simplex | /main.py | 5,242 | 4.09375 | 4 | """
This project aims at implementing the Simplex method in Linear Programming problem.
Author: YiChong Huang (黄毅翀)
Student_Code: 20S103272
"""
import torch
def simplex():
"""
for a Optimization problem:
Max z = c^T * X
s.t. A * X = b
X > 0
1. read the size of coefficie... |
371852ac36714fc92c4ed266c6af9b61447885e0 | AleksanderUrbanowicz/Python_exercises | /os_exercise.py | 2,410 | 3.65625 | 4 | import os
from datetime import datetime
def print_dir(print_all=False):
print(f'Path: {os.getcwd()}')
print(f'List: {os.listdir()}')
if print_all:
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
print(f'Path: {dirpath}')
print(f'DirNames: {dirnames}')
... |
7da4ca31c7a40eb4ce9822dfc63dab942cbb9fd9 | m0dular/support-tooling | /bin/modules_format_v1.py | 1,206 | 3.546875 | 4 | #!/usr/bin/env python
"""
Script to create a json string containing a list of environments and their modules
input: the name of a file containing the name of the environment and a pipe delimited list of modules
e.g. production:ntp|stdlib|foo
output: a json string of the format:
[
{ "name": <environment>,... |
77fca3593996f5a007fd6b6bd8a4f97ab86dd8a7 | abduqah/problem-solving | /right-tangent-median.py | 157 | 3.703125 | 4 | import math
ab = int(input())
bc = int(input())
ac = math.sqrt(ab**2 + bc**2)
theta = math.acos(bc/ac)
print( int( math.degrees(theta) ), '°', sep='' )
|
3ea5829c88db810269c21709952825956f6dcea5 | sandeep-kaur123/project | /duck typing.py | 137 | 3.640625 | 4 | def compute(a,b,c):
return(a+b)*c
print(compute(1,2,3))
print(compute([1],[2,3],2))
a="hello"
print(a*2)
print(compute('l','olo',4))
|
708085f9399f3243821bf59f7325a796eafa87dd | okcomputer/advent-of-code | /2019/01/fuel_requirements.py | 586 | 3.734375 | 4 | #!/usr/bin/env python
import math
FUEL_TOTAL = 0
def main(input_file=None):
"""
Take file with list of fuel mass
"""
with open(input_file) as data:
lines = data.read().splitlines()
return lines
def get_fuel_req(mass):
"""
"""
div_floor = math.floor(int(mass) / 3) - 2
if ... |
ecf870ac240d1faf8202039bcc235bdb14bb8440 | vsandadi/dna_sequence_design | /generating_dna_sequences.py | 2,007 | 4.28125 | 4 | '''
Function to generate DNA sequences for each bit string.
'''
#initial_sequence = 'ATTCCGAGA'
#mutation_list = [(2, 'T', 'C'), (4, 'C', 'A')]
#bitstring = ['101', '100']
def generating_sequences(initial_sequence, mutation_list, bitstring):
'''
Inputs: initial_sequence as a string of DNA bases
... |
4d2a6ba07ca3e95101ff18504fcd74afeeb2315e | AlexologyEU/CMPU4060 | /Semester 1/1-3 Exercises.py | 3,111 | 4.3125 | 4 | # Lecture notes
# x = 0
# while x < 10:
# print (x)
# x = x + 1
# print ("Final value of x: ", x)
# for i in range(1,21):
# if i%2 == 0:
# print(i)
# s = int(input("Keep entering numbers. Enter 0 to end. Enter a number here: \n"))
# while s!=0:
# print ("You've entered ", s)
# s = int(input("Enter n... |
990d6207f6bfe7851564e3c8942907fa3950b789 | janetschel/exercises | /week_01/03_loops/02_sum-of-numbers-from-1-to-n.py | 468 | 3.71875 | 4 | """
Schreibt ein Programm, welches die Summe aller Zahlen von 1 bis zu der
Zahl berechnet, die der Benutzer eingegeben hat.
Für die Lösung beide Varianten (for- und while-Schleife) implementieren!
"""
userInput: str = input("Zahl: ")
number: int = int(userInput)
result: int = 0
for n in range(1, number + 1):
re... |
c94e9353f23c7b746c123d928db75e5474b1ca57 | janetschel/exercises | /week_01/01_input-output/04_circle_circumference-and-surface-area.py | 356 | 4.25 | 4 | """
Schreibt ein Programm, welches den Umfang und den Flächeninhalt eines
Kreises berechnet. Der Benutzer gibt den Radius an.
"""
PI = 3.141592653589793
radiusInput = input("Radius: ")
radius = float(radiusInput)
circumference = 2 * PI * radius
surfaceArea = PI * radius ** 2
print(f"Umfang: {circumference}")
print... |
4995d7a87dec7e7791baa70c3b5576277e1c5afd | janetschel/exercises | /week_02/01_loop_revision/02_fizz-buzz-variation.py | 1,064 | 4.03125 | 4 | """
Schreibt eine for-Schleife, welche die Zahlen 0 bis 100 (inklusive) durchläuft, und sich folgendermaßen verhält:
- Falls die Zahl durch 4 teilbar ist, gebe "Durch 4 teilbar" auf der Konsole aus
- Falls die Zahl 50 ist, gebe "Wir sind bei der Hälfte" aus
- Falls die Zahl 0 ist, gebe "Start" aus
- Falls nichts der o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.