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
2564b805465fe17ed12affabc466e7420fc8d1c3
iamsabhoho/PythonProgramming
/Q1-3/WUP#12/reversingwords.py
150
4.3125
4
#Write a Python program that accept a word from the user and reverse it using for loops. for j in range(len(i)-1, -1, -1): s = i[j] print(s)
d6d026988df36a63136417082122ec0053e91bfc
iamsabhoho/PythonProgramming
/Q1-3/key.py
3,521
4.28125
4
def get_alphabet(): """ This function returns the alphabet in a list :return: list """ alphabet = list() for a in range(26): alphabet.append(chr(97+a)) return alphabet def cipher_alphabet(key='meowc'): """ Creates the cipher alphabet with the key provided :param key: st...
60140c55c6e6b002931c8fe16280ce14bed7186c
iamsabhoho/PythonProgramming
/Q1-3/MasteringFunctions/PrintingMenu.py
713
4.21875
4
#Write a function for printing menus in the terminal. #The input is a list of options, and the output is the option selected by the user. print('The options are: ') #list = input() #menu = ['Meat','Chicken','Fish'] menu = [] print(menu) print() def options(menu): menu = input('Please enter the options: ') for...
c7c547252f8deb024b850f43dea0e73c3e8d849f
iamsabhoho/PythonProgramming
/Q1-3/WUP#7/Driving.py
1,121
4.375
4
#You are driving a little too fast, and a police officer stops you. Write an script that computes the result as “no ticket”, “small ticket”, and “big ticket”. If speed is 60 or less, the result is “no ticket”. If speed is between 61 and 80 inclusive, the result is “small ticket”. If speed is 81 or more, the result is “...
c514760a50455fecbfc23ce0c8efc4749bcd14d5
lyubomyrr/For_test
/Class work 2.py
1,096
4.03125
4
#for i in range(0, 100, 2): # print(i) # for i in range(1, 100, 2): # print(i) # if i == 5: # break # print(i) #print ("end") # list_number=[2,4,5,8,9,10] #contain_odd=False #for item in list_number: # if not item % 2==0: # contain_odd=True # break #if contain_odd: # print ("the...
31b72e290f02aaf458ae7f3689a383bb8edcaa96
lyubomyrr/For_test
/clas_work_3.py
1,597
4.0625
4
# my_list = [int(input("Enter int {}: ".format(i+1))) for i in range(10)] # print(" Max number is:", max(num_list)) # print(" Min number is:", min(num_list)) # print(my_list) #or # amount_of_numbers=int(input('Input amount of numbers\n')) # list_of_numbers=[int(input('input number\n')) for i in range(amount_of_...
cbed7ee6660fa870e613ec09ba30a5b938243897
adamkerz/akData
/akData/format/number.py
1,497
3.796875
4
from decimal import Decimal def formatDollars(d,noneValue='',zeroValue='$0'): """Formats a number as a whole dollar value with alternatives for None and 0.""" if d is None: return noneValue elif d==0: return zeroValue return '${:.0f}'.format(d) def formatDollarsCents(d,none...
702a9b9f74e2bf5b5ec5751965f2e6e8d2c9400b
AlexandraKar/Alexandra-Karaseva
/python%20homework/hw4.py
73
3.84375
4
s = input('enter a word:') for i in range(len(s)): print(s[:i+1])
6b14b65dcf792f2c6525bd2341f360fe5a110849
alvercau/dsp
/python/advanced_python_dict.py
2,152
3.59375
4
import pandas as pd from collections import defaultdict faculty_dict = defaultdict(list) # Q6 with open("faculty.csv") as f: data = pd.read_csv(f) data = data.rename(columns=lambda x: x.strip()) df = data['name'].str.rsplit(' ', expand=True, n=1) data = data.join(df[1]) data = data.ix[:, ['degree'...
aa2886b2e59bc35ce98e9f7f89b398b7c8c31972
naviroa92/prueba1
/Guia 1 - Pandas.py
4,378
3.796875
4
# Ejercicio 1 import ast import pandas as pd import re df_books = pd.read_csv("data/books.csv", dtype={'postal_code': str}, converters={'books': ast.literal_eval}) df_ratings = pd.read_csv("data/books_rating.csv") print('') print('') print('|' * 50) print( 'DF_BOOKS.INFO - ORIGINAL') print('|'...
dbece212a7cbf94c2bc33dc0b26dee6c0933cb81
ATLS1300/pc04-generative-section11-sydney-green
/PC04_GenArt.py
2,373
4.1875
4
""" Created on Thu Sep 15 11:39:56 2020 PC04 start code @author: Sydney Green This code creates two circle patterns from two seperate turtles. This is different than my pseudocode as I struggled bringing that to life but I was able to make something I liked so much more. Turtle 1 is a larger circle with larger cirlce...
0da07a59dbb070270d770c8a0e940b35b36375e5
nelvinpoulose999/Pythonfiles
/Fileio/filesop1.py
180
3.578125
4
f=open('news','r') name=set() for line in f: words=line.rstrip('\n,.,,').split(' ') for word in words: name.add(word) print(name) for word in name: print(word)
64246927e8e7fe56a178fc96a7195abd755e3b49
nelvinpoulose999/Pythonfiles
/oops/bankapplication.py
871
4.0625
4
class Bank: bankname='SBK' # class variable/static variable it is used for reduce memory allocations def create_account(self,accno,pname,minbalance): self.accno=accno #} self.personname=pname #} instance variable(self.accno,self.personname,etc self.balance=minbalance #} ...
b6a1e7ea40436cb92ed481da960fa99573d7874a
nelvinpoulose999/Pythonfiles
/Fileio/fileop.py
231
3.59375
4
f=open("demofile","r") #path of file or file name ,operation lst=[] name=set() for lines in f: lst.append(lines.rstrip('\n')) #.rstrip used to strip the unwanted elements name.add(lines.rstrip('\n')) print(lst) print(name)
1a796e09dad209f1957eb41e31da6173fcead274
nelvinpoulose999/Pythonfiles
/LanguageFundamentals/flowcontrols/looping/primenumberfrom_nnumbers.py
403
4.03125
4
# prime numbers from 1-num num=int(input("enter the limit")) for i in range(1,num+1):# i=1,2 flag=0 for j in range (2,i):# (2,1),(2,2) if(i%j==0):# 1%2==0-not equal,2%2==0,3%2==0-not equal flag=1 break else: pass if(flag==0): print("the numbe...
15718d9d613431c7bb4b7ed189c3dae7e395c005
nelvinpoulose999/Pythonfiles
/LanguageFundamentals/flowcontrols/decisionMaking/negitiveorpositive.py
166
4.21875
4
num = int(input("enter the number")) if (num<0): print("the number is negitive") elif(num==0): print("the number is zero") else: print("the number is positive")
5e4da675ae102831a30af49576b89c665f7ed89c
nelvinpoulose999/Pythonfiles
/practice_prgms/factorial.py
222
4.21875
4
num=int(input('enter the number')) factorial=1 if num<0: print('no should be positive') elif num==0: print('the number is 1') else: for i in range (1,num+1): factorial=factorial*i print(factorial)
533cfd4eec3edea45929103b02d734dcc0e10fa8
nelvinpoulose999/Pythonfiles
/pythoncollections/listprograms/patternprinting.py
160
3.671875
4
# print pattern # 1 # 12 # 123 # 1234 for i in range(1,5): # row elements for j in range(1,i+1): # column elements print(j,end=' ') print()
3732aa440a8b2ff3c7ad30a50674a363078bea67
nelvinpoulose999/Pythonfiles
/LanguageFundamentals/flowcontrols/looping/addpowers.py
179
4.09375
4
# print the output :123=1^3+2^3+3^3=36 num =int(input("enter the number")) sum=0 while num!=0: digit=num%10 print(digit) sum=(digit**3)+sum num=num//10 print(sum)
81541e01f3906af84b5a038418cacd75f156a9b5
JuliaAlmaLuna/KexJobbProject
/relu.py
361
3.796875
4
import matplotlib.pyplot as plt import numpy as np data = [7, 1, 10, 0.5, 11, 4, 18, 13] x = [1, 2, 3, 4, 5, 6, 7, 8] y = np.multiply(x, 1.8) plt.plot(x, data, '-', label='a)') plt.plot(x, y, label='b)') plt.plot(x, np.exp(x)*0.01 + 3, label='c)') plt.scatter(x, data, c='k', label='data') plt.title('Example of a Reg...
9bfc470a0656f879c729e2963675c71f00c06d02
mercury9181/data_structure_using_python
/factorial.py
269
4.28125
4
def factorial_using_recursion(n): if n==0: return 1 else: return n * factorial_using_recursion(n-1) number = int(input('enter the number: ')) result = factorial_using_recursion(number) print("factorial of "+ str(number)+ " = " + str(result))
11fed74e0d762fca43c1f68b5bd99d89fda82d25
IvyArbor/RightAtSchool
/readers/textreader.py
459
3.828125
4
class TextReader(object): '''Reads lines of a file and splits them to the map''' def __init__(self, stream, column_mapping): self.stream = stream self.column_mapping = column_mapping def rows(self): for line in self.stream.lines(): result = {} for (name, sta...
2e1aaaf780ba9b1b1d0c3c3a0b8f1eaf4105a4fe
timzk/AID1811
/aid1811/pbase/Python/day18/super_init.py
492
3.78125
4
#显示调用基类的初始化方法__init__ class Human: def __init__(self,n,a): self.name = n self.age = a def show_info(self): print("姓名:",self.name) print("年龄:",self.age) class Student(Human): def __init__(self,n,a,s =0): self.score = s super().__init__(n,a) #显示调用父类的方法 d...
ccc4603d3dfba8e23c7c567eb068d0a42e9ea8fb
timzk/AID1811
/aid1811/pbase/Python/day15/myyield.py
728
3.765625
4
# #此示例示意生成器函数的创建和调用 def myyield(): yield 2 #一旦使用yield便是一个生成器函数 print("即将生成3") yield 3 yield 5 yield 7 print("生成器生成结果") gen = myyield() #调用生成器函数生成一个生成器 print(gen)#generator it = iter(gen) #从生成器中获取一个迭代器 print(next(it)) #向迭代器要数据,此时生成器函数才会执行一步 ,打印2 print(next(it)) # def myyield(): # yield 2...
7a92486fe3f57a8cb23046c2a5802b882757c8f2
timzk/AID1811
/aid1811/pbase/Python/day18/class_method.py
800
3.890625
4
#此示例示意用类方法来访问类属性和改变类变量 #类方法是用于描述类的行为的方法,类方法属于类,不属于类的实例 class A: v = 0 #类属性 @classmethod def get_v(cls): return cls.v @classmethod def set_v(cls,v): cls.v = v #类方法需要使用@classmethod装饰器定义 #类方法至少有一个形参,第一个形参用于绑定类,约定写为'cls' # print(A.v) # print(A.get_v()) # A.set_v(80) # print(A.get_v()...
75a96f566ca8f2cfc5374bbf57069845505fdb60
timzk/AID1811
/aid1811/pbase/Python/day10/day10.py
13,669
4
4
# def f1(): # print("f1") # def f2(): # print("f2") # f1,f2 = f2,f1 # f1() # def f1(): # print("f1函数被调用") # def f2(): # print("f2函数被调用") # def fx(fn): #<function f1 at 0x7f5c1282ef28> # print(fn)#"f1函数被调用" # fn() # fx(f1) # fx(print) #可以的,打印的是print的内建函数地址 # def myfun(fn): # L=[1,3,5,7,9] #...
f7dff6b6388136edf248bb7a3624f42ec1c66a3f
timzk/AID1811
/aid1811/pbase/张天成/exercise1220.py
736
3.578125
4
def fn(n): l = [] for i in range(n): l.append(lambda x:x*i) return l l = fn(4) print(l[0](10)) print(l[1](10)) print(l[2](10)) #首先这个属于是一个闭包,fn(4)调用,l为空列表,for i in range(n):这里,i第一次为0, # 然后执行l.append(lambda x:x*i),把匿名函数lambda x:x*i追加到列表l里面, # 此时l列表里面就会产生l=[(lambda x:x*i),(lambda x:x*i),(lambda x:x*i),...
fe1ad136b43ec57813631263d6e94d9389139307
timzk/AID1811
/aid1811/pbase/Python/day15/myinteger.py
559
3.90625
4
# #此示例示意用生成器函数生成一系列的整数 # def myinteger(n): #生成器函数 # i = 0 # while i<n: # yield i # i += 1 # for x in myinteger(10): # print(x) # it =iter(myinteger(20)) # print(next(it)) #0 # print(next(it)) #1 # L = [x for x in myinteger(20) if x %2 ==1] # print(L) def myeven(start,stop): i = sta...
27af7ce58c38a97fb2c8d67217a565e3d1227f94
timzk/AID1811
/aid1811/pbase/PythonNet/day07/thread2.py
376
3.765625
4
#同时执行多个线程 from threading import Thread from time import sleep #线程函数 def fun(sec,name): print("线程函数传参") sleep(sec) print('%s线程执行完毕'%name) #创建多个线程 thread = [] for i in range(3): t = Thread(target=fun,args=(2,),kwargs={'name':'t%d'%i}) thread.append(t) t.start() for i in thread: i.join()
d887ab1de38590c34617a82b64d2c49fccf66497
timzk/AID1811
/aid1811/pbase/总结/class_test2.py
299
3.609375
4
class Singleton(object): def __new__(cls,*args,**kwargs): if not hasattr(cls,"_instance"): cls._instance = object.__new__(cls,*args,**kwargs) return cls._instance class Foo(Singleton): pass f1 = Foo() f2 = Foo() f1.value = 10 print(f2.value) print(f1 is f2)
3be3c692dd4d39933cb4fcb12c47401b240ee7a2
rushigandhi/CCC-Practice
/2016/Junior/J3/HiddenPalindrome.py
406
3.6875
4
line = input() newLine = line lenList = [] lenLine = len(line) def check_drome(dromeline): reverse_line = str(dromeline[::-1]) if(dromeline == reverse_line): lenList.append(len(dromeline)) for x in range(lenLine): check_drome(newLine) for y in range(0, lenLine): check_drome(newLine[:...
312ba285f10b955839bebfc26a86a1fc6c751560
rushigandhi/CCC-Practice
/2008/Senior/S12008.py
238
4.03125
4
lowestTemp = 201 lowestCity = "" while True: city,temp = input().split() if city == "Waterloo": break temp = int(temp) if lowestTemp > temp: lowestTemp = temp lowestCity = city print(lowestCity)
28f41b27e0efc58a6892a590ea2bbcde62decd62
rushigandhi/CCC-Practice
/2006/Senior/Attack_of_the_CipherTexts.py
1,171
3.984375
4
# Get texts decrypted = list(input()) encrypted = list(input()) new = list(input()) # initialize an empty dictionary in which the key will be the # decrypted character and the value will be the encrypted character conversion = dict() # for each character in the message for i in range(len(decrypted)): # if the ch...
54fd6ae765a3feb42ecf9425be18da4d42cee8f3
akakura/AtCoder
/ABC152/E.py
375
3.515625
4
import functools def euclid(a, b): if b == 0: return a else: return euclid(b, a%b) def multiple(a, b): return a*b // euclid(a, b) def lcm(nums): return functools.reduce(multiple, nums) N = int(input()) A = list(map(int, input().split())) NumLCM = lcm(A) ans = 0 for i in range(len...
f488250f58ea2c9349700bccbb45a40007d86388
taha-shahid/all-files
/name.py
79
3.6875
4
#Taha Shahid N=raw_input("Please enter your name ") print("Welcome " +str(N)+ "!")
6a7713ceaf4b78977f8ac298c727e0b586002013
taha-shahid/all-files
/taha_gpa4.py
716
3.84375
4
#Taha Shahid GPA def report_card(): def avgGPA(listofgpa): total = 0 length = len(listofgpa) for gpa in listofgpa: total += gpa return total/length classes = input("How many classes did you take? ") classNames = [] gradeList = [] gpaList = [] ...
df117f5bf941f855a2a55a1ea60cec8f3485c455
zhaozhg81/fun_turtle_project
/car_v2.py
2,716
3.890625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jun 5 09:14:37 2021 @author: zhaozhg """ #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jun 4 19:17:45 2021 @author: zhaozhg """ def draw(rad): for i in range(2): # two arcs turtle.circle(rad,90) turtle.circle(rad//2...
85263ed8c3d2b28a3502e947024e1c9aaafaec39
ShreyasJothish/ML-Precourse
/precourse.py
1,771
4.25
4
# Machine Learning/Data Science Precourse Work # ### # LAMBDA SCHOOL # ### # MIT LICENSE # ### # Free example function definition # This function passes one of the 11 tests contained inside of test.py. Write the rest, defined in README.md, here, and execute python test.py to test. Passing this precourse work will gre...
e3dbbaeda6cfbc5668e279e211c2e1a7aba0cf24
niv26222/HolidaysUSA
/HolidaysUSA.py
257
3.75
4
# Python script to print holidays in year 2019(USA) # pip install holidays from datetime import date import holidays import sys # Select country uk_holidays = holidays.UnitedStates() for ptr in holidays.UnitedStates(year=2019).items(): print(ptr)
e1863e9e0ba33e3b347660ebd151a6b158cb41ef
RohithYogi/Spoj-Solutions
/Spoj/TOANDFRO - To and Fro.py
484
3.6875
4
col=int(raw_input()) while(col!=0): string=raw_input() row=(len(string))/col b="" for i in range(0,row): if i%2==0: b+=string[i*col:(i+1)*col] print b else: b+=(string[i*col:(i+1)*col])[::-1] print b c="" for k in range(0,col)...
b87aac384c247d2c857bc67e7293c7692e961220
RohithYogi/Spoj-Solutions
/Spoj/test.py
296
3.6875
4
import math def sumfact(n): s=0 for i in range(1,int(math.sqrt(n)+1)): if(n%i==0): s=s+i if(i!=(n/i)): s=s+(n/i) print s for j in range(2,int(math.sqrt(s)+1)): if(s%j==0): return 0 return 1 print sumfact(81)
74bb9bf1887acf303204fa2f16bafefa9ad937f2
amarelopiupiu/python-exercicios
/ex65.py
665
4.21875
4
# Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. Exemplos de palíndromos: # APÓS A SOPA, A SACADA DA CASA, A TORRE DA DERROTA, O LOBO AMA O BOLO, ANOTARAM A DATA DA MARATONA. (palíndromo é uma palavra que se lê igual de trás para frente e de frente para trás). f...
770699d93c01420aea23fd0a6e9386a015fc0686
amarelopiupiu/python-exercicios
/ex28.py
273
4.125
4
# Importando apenas uma funcionalidade da biblioteca - peça a raiz quadrada de um número e arredonde ele para cima. from math import sqrt, ceil n = float(input('Digite um número para ver a sua raiz quadrada: ')) print('A raiz quadrada de {} é {}' .format(n, sqrt(n)))
696ef79ae1671e910260abd979404a36349844de
amarelopiupiu/python-exercicios
/ex41.py
468
3.90625
4
# Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 para viagens mais longas. d = float(input('Qual a distância da sua viagem? ')) print(f'Você está prestes a começar uma viagem de {d}Km') if d <= 200: vc = 0....
6e418233ebbec67eee6a958b511bf5b7dfbc4910
amarelopiupiu/python-exercicios
/ex24.py
265
3.703125
4
# Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. salário = float(input('Qual é o seu salário? R$')) aumento = salário + (salário * 15 / 100) print(f'O seu salário com aumento de 15% é de {aumento}')
10902336348620c8a9163eed06e0ced058bdbc6d
amarelopiupiu/python-exercicios
/ex47.py
740
4.25
4
# Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. (se você coloca 3 aspas, é possível adicionar mais linhas no print). n = int(input('Digite um número inteiro: ')) bases = int(input(''' Es...
526733f56ceaa3613df6c687a0d3b125600fc8c6
amarelopiupiu/python-exercicios
/ex21.py
264
3.859375
4
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar. carteira = float(input('Quantos R$ você tem na carteira? R$')) print('Com R${} você consegue comprar US${:.2f}' .format(carteira, carteira/5.596))
5f155e5eef12ddb114acfbf8099c59bf224b7d72
amarelopiupiu/python-exercicios
/ex78.py
371
4.09375
4
# Crie um programa que vai gerar números de 1 a 10 e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla. num = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(f'Os números gerados foram {num}') print(f'O maior número sorteado foi {max(num)}') prin...
28a95a1ee64dc92b431d4aae855e9d3fec3b8a4f
amarelopiupiu/python-exercicios
/ex29.py
246
3.8125
4
# Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira. from math import trunc v = float(input('Digite um valor: ')) raiz = trunc(v) print(f'O valor digitado foi {v} e sua porção é {(raiz)}')
82de539f29099ccb07283227bc2f3b9df586040c
LeemHyeRin/Leetcode
/invert-binary-tree/invert-binary-tree.py
672
3.84375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import collections class Solution(object): def invertTree(self, root): """ :type root: TreeNode ...
29775912584cbf014fe4a2820dd8a5694c9dc7d1
jossrc/LearningPython
/D012_Scope/project.py
803
4.15625
4
import random random_number = random.randint(1, 100) # GUESS THE NUMBER attempts = { "easy": 10, "hard": 5 } print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100") difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") attempts_remaining = attempts[dif...
8a9d266866367fb2769f200cfc1ba1553084a2d8
jossrc/LearningPython
/D024_Files/main.py
1,100
4.34375
4
# LEER ARCHIVO """ FORMA 01 : Para leer un archivo se debe seguir una secuencia de pasos: 1. Abrir el archivo : Uso de la función open(). 2. Leer el archivo : Uso del método read(). 3. Cerrar el archivo : Uso del método close(). """ file = open("my_file.txt") contents = file.read(...
72788abb25313dc1e8d96ae48959f949adf93514
jossrc/LearningPython
/D003_ControlFlow/exercise_05/main.py
872
3.953125
4
print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 # TRUE full = name1 + " " + name2 true_t = full.lower().count('t') true_r = full.lower().count('r') true_u = full.lower().co...
7bd52926f8ca01cdc76c5c1c31f6425874af37b6
jossrc/LearningPython
/D012_Scope/scope.py
1,107
3.671875
4
# Scope enemies = 1 def increase_enemies(): enemies = 2 print(f"enemies inside function: {enemies}") # 2 increase_enemies() print(f"enemies outside function: {enemies}") # 1 # Local Scope def drink_potion(): potion_strength = 2 print(potion_strength) drink_potion() # print(potion_strength) <...
994a6754d079ec456e5a240262afa62a5000e5ec
orochidrake/Python_Kivy
/aulas/exercicios/ex_1.py
2,064
4.03125
4
print("Andre Augusto Zaguette Fernandes") nome = input("Digite Seu Nome: ") idade = input("Digite Sua Idade: ") num = int(input("Digite Um Numero: ")) num_2 = int(input("Digite Um Numero: ")) num_3 = int(input("Digite Um Numero: ")) soma = num + num_2 + num_3 quad = num ** 2 cubo = num ** 3 nota_1 = float(input("...
ddb88b645bd9a812e95bd6e0dc1f937c7cabd874
kt-17/alfaragh
/Other/WWII Game.py
478
3.703125
4
import random TEAMS = {"Britain": 0, "France": 0, "Germany": 0, "Japan": 0, "Russia": 0} print("Welcome to the WWII Game!\n\n") print("Mexican War group, You will be RUSSIA for this game.\n") print("War on Terror group, You will be RUSSIA for this game.\n") print("Korean War group, You will be RUSSIA for this game.\...
adc19d49f37770c5fb3112635f0327bf1c902b7c
ryand231/TestGit
/test_python.py
212
3.671875
4
print('Hello World') print('This is going to be an amazing build') print('Now we begin') startnum = 0 listvar = [2, 4, 1, 8] for num in listvar: startnum = startnum+num print(startnum) print(startnum)
35eb7b4f8ce9723f9452d06ffd91c6c0db2dd9fe
kiyokosaito/Collatz
/collatz.py
480
4.34375
4
# The number we will perform the Collatz opperation on. n = int(input ("Enter a positive integer : ")) # Keep looping until we reach 1. # Note : this assumes the Collatz congecture is true. while n != 1: # Print the current value of n. print (n) #chech if n is even. if n % 2 == 0: #If n is eve...
0a7538856599ed3e475bdbcbba526b3305a80e8a
ErinnM/DataStructuresHomework
/integration calc.py
4,586
3.546875
4
from graphics import * import math #set up window win=GraphWin("Numerical Integration Calculator",800,800) win.setBackground("lightsteelblue") title=Text(Point(400,30),"Numerical Integration Calculator") title.setSize(30) title.setFace("times roman") title.setStyle("bold italic") title.draw(win) #bounds e...
ddbe8e3c00699661a6d02a940bcc9cc80ac29f5d
FrankYingda/ML-Project2
/Perceptron/Perceptron-c.py
1,142
3.625
4
import numpy as np from pylab import * # <GRADED> def classifyLinear(xs, w, b): """ function preds=classifyLinear(xs,w,b) Make predictions with a linear classifier Input: xs : n input vectors of d dimensions (nxd) [could also be a single vector of d dimensions] w : weight vector of dimensional...
33677ecf438ea5097710e22c473d2df60b5873c1
tecknork/30DaysOfCode
/day10/character.py
1,781
3.671875
4
import itertools as it def alternate(s): val = list(s) set_val = sorted(set(val),key=val.index) alter_str = [] #print(val) #print(set_val) for i in range(len(set_val)+1): permu_val= it.combinations(set_val,i) permu_val = set(permu_val) print(list(permu_val...
6ee54353ac759803566d787a2d03a4fc919959b1
tecknork/30DaysOfCode
/day2/timeconversion.py
791
3.953125
4
#07:05:45PM #07:05:45AM time_str = "12:01:29PM" def convert_time(time_str): time_str = list(time_str) val = time_str[-2:] if "".join(val) == "AM": hour = time_str[:2] return "{:02d}".format(hour%12) + "".join(time_str[2:-2]) return "".join(time_str[:-2]) else: hour = ...
6dbfc73dc67b860c7fdb27ecaf21e099e7dfbc89
vinayak25/ml_py_samples
/linear_regression/linear_regression.py
2,697
4.0625
4
# coding: utf-8 # # Salary Prediction On basis of Years of Experience using Simple Linear Regression # In[1]: #importing primary libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt # In[2]: #Reading Dataset from Sample CSV file dataset = pd.read_csv('Salary_Data.csv') #Printing th...
b6a94173e3cefebd2337793a28b06a2a6082cfea
clarkb7/Pebble_RPI_Shuttle_Schedule
/src/schedule_parser/txt_to_json.py
2,149
3.765625
4
#!/usr/bin/python """ Copyright (c) 2014 Branden Clark MIT License, see LICENSE for details. """""" Converts list output of shuttle stops to json format Usage: python txt_to_json.py data_dir """ import sys INTERNAL_INDENT = ' ' def txt_to_json(schedule_name, schedule_file): """ Writes out a shuttle schedule i...
f5e3c786d3fc549fd94cd0a40b391217dfc8268e
nosrac77/data-structures
/src/linked_list.py
1,620
4.0625
4
"""Contains class function for generating linked lists.""" class LinkedList(object): """Creating LinkedList class.""" def __init__(self, iterable=()): """Initialize LinkedList class.""" self.head = None self._counter = 0 if isinstance(iterable, (str, list, tuple)): ...
8402c6bc1f2ea4184645b46c97f011e3d0774959
shuangmw/hello-world
/reverse_linkedlist.py
828
3.765625
4
class ListNode: def __init__(self, x): self.val = x self.next = None def reverse_recursion(head): if head == None or head.next == None: return head head_new = reverse_recursion(head.next) head.next.next = head head.next = None return head_new def reverse_loop(head): ...
af6586d3ef401e076612eac841e6c96221875381
shuangmw/hello-world
/fibonacci.py
691
3.953125
4
# Fibonacci # Solution 1: Recursion class Solution: def jumpFloor(self, number): # write code here if number == 1: return 1 elif number == 2: return 2 else: return self.jumpFloor(number-1) + self.jumpFloor(number-2) # Solution 2: loop class Solutio...
5f8cb11ea4991d0ea6ac9e920b433cb53414eedb
jindalkanika/Search-Algorithms-Implementation
/astar.py
7,761
3.5625
4
import math from collections import deque import os from main import accessible_locations if os.path.exists('/Users/kjindal/Downloads/Code/HW1_FOAI/Run grading_HW01_cases/output.txt'): os.remove('/Users/kjindal/Downloads/Code/HW1_FOAI/Run grading_HW01_cases/output.txt') import collections from main import * d...
d41db68df8a2d22a19518c8a5e6af49d2a29a29e
Selvaganapathi06/Python
/day4/Day4.py
452
4.34375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #List Reverse cars = ["bmw", "audi", "toyota", "benz"] cars.reverse() print(cars) # In[3]: #list sort and reverse cars = ["bmw", "audi", "toyota", "benz"] cars.sort() print(cars) cars.reverse() print(cars) # In[4]: #creating empty list a = [] print("created empt...
bb40d33e9bf091ae3be7652cc60fa12d80c27b71
Selvaganapathi06/Python
/day3/Day3.py
700
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #sample list and print bicycles = ["trek", "redline","hero"] print(bicycles) # In[2]: #accessing first element in the list print(bicycles[0]) # In[4]: #Apply title() print(bicycles[0].title()) # In[5]: #replace element values bicycles[0] = "Honda" print(bic...
5e9b2290612e3e0aa5ef6890ceba178ffa652746
Selvaganapathi06/Python
/day11/day11.py
593
3.84375
4
#!/usr/bin/env python # coding: utf-8 # In[4]: #looping through dictionaries un = {'uname':'first','first':'selva','last':'gana', } for key,value in un.items(): print(f"\nkey :{key}") print(f"value: {value}") # In[5]: #looping through dictionaries only in key un = {'uname':'first','first':'selva','...
4ae7aa620a792d6572689a306d945872c5eea614
Selvaganapathi06/Python
/day22/day22.py
641
3.984375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #with out module x = int(input("Enter X: ")) y = int(input("Enter y: ")) def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): return a*b ans1 = add(x,y) ans2 = sub(x,y) ans3 = mul(x,y) print(ans1) print(ans2) print(ans3) # In[7]: #module impo...
eb7cb8206114685a655baf3fc8c43f9862743eca
jatinsinghal1921/TkinterPractice
/src/tkinter/dropdownMenu.py
529
4.0625
4
from tkinter import * root = Tk() root.title("Tk dropdown example") label = Label(root, text="Choose a dish") label.grid(row = 1, column = 1) tkvar = StringVar(root) choices = ['Pizza','Lasagne','Fries','Fish','Potatoe'] popupMenu = OptionMenu(root, tkvar, *choices) popupMenu.grid(row = 2, column =1) tkvar....
e78c2aa541993df0a90cd216ea20b4f726efb7d1
zackaryjwright-jcu/Tutorials
/prac_02/random_module_test.py
266
3.78125
4
import random def main(): print(random.randint(5, 20)) # range between 5 & 20 print(random.randrange(3, 10, 2)) # range between 3 & 10, in steps of 2 print(random.uniform(2.5, 5.5)) # range between 2.5 & 5.5 (random floating point numbers) main()
0faebc3fc76c558d4f942a46686b0e6580f9e47e
zackaryjwright-jcu/Tutorials
/prac_01/sales_bonus.py
431
3.96875
4
""" Program to calculate and display a user's bonus based on sales. If sales are under $1,000, the user gets a 10% bonus. If sales are $1,000 or over, the bonus is 15%. """ sales_value = float(input("Please enter the value of the Sales: $")) if sales_value < 1000: bonus = sales_value * 0.1 print("User's Bonus:...
7bc130847c8522ab5980dd0beedf333811f42ece
maj3r1819/Data-Structures-and-Algorithms
/Sorting Algorithms/MergeSort.py
439
4.0625
4
""" -Merge sort is a divide and sort algorithm -Divide the input arrays into two halves and we keep halving recursively until they become too small that they cannot be broken further -Merge halves by sorting them """ def mergeSort(customList, l, m, r): n1 = m - l +1 n2 = r - m L = [0] * n1 R = [0] * n2...
177c7094bbfcd9eb79097b45e64bf5eaa5fcfb72
maj3r1819/Data-Structures-and-Algorithms
/Linked List/Practice Questions/Remove_Duplicates.py
1,075
3.875
4
import sys sys.path.insert(0, 'D:\Projects\Data-Structures-and-Algorithms\Linked List\Singly Linked List') from SinglyLinkedListOperations import SLinkedList, Node #Method to delete duplicates in a Linked List def remove_duplicates(linked_list): if linked_list.head is None: return else: currNo...
20f0f8306f263e15b0a2b25c1c8d6be02b3b5cdd
maj3r1819/Data-Structures-and-Algorithms
/Linked List/Singly Linked List/SinglyLinkedList.py
363
3.578125
4
class Node: def __init__(self, value = None): self.value = value self.next = None class SLinkedList: def __init__(self): self.head = None self.tail = None singlylinkedlist = SLinkedList() node1 = Node(1) node2 = Node(2) singlylinkedlist.head = node1 singlylinkedlist.head...
80621b13fdeda586254ceee24d48f9cdcccc7b85
maj3r1819/Data-Structures-and-Algorithms
/Linked List/Practice Questions/sum.py
676
3.671875
4
import sys sys.path.insert(0, 'D:\Projects\Data-Structures-and-Algorithms\Linked List\Singly Linked List') from SinglyLinkedListOperations import SLinkedList, Node def num(linked_list): num1 = 0 if linked_list.head is None: return None else: currNode = linked_list.head while currNo...
5199fbf404b12654c03c0ac45b9e7d8e8098ed14
lero003/python
/繰り返し.py
380
3.953125
4
#for文 for i in range(5): print(i) #break文 for i in range(5): if i == 3: break print(i) #continue文 for i in range(5): if i == 3: continue print(i) #for文ネスト構造(sep引数) for i in range(3): for j in range(3): print(i,j,sep="-") #組み合わせ arr = [2,4,6,8,10] sum = 0 for i in arr:...
b6099f7526fed35f165a9bff642904fbfb543c17
Knifesurge/Hjalmion-The-Rise-Of-Fencor
/player.py
917
3.640625
4
#Nick Mills class player(): def __init__(self, hp, max_hp, level, xp, xp_to_level, victory): self.hp = hp self.max_hp = max_hp self.level = level self.xp = xp self.xp_to_level = xp_to_level self.victory = victory def is_alive(self): return self.h...
b8b174f5b2a7d9854362c688ce86f1c4b373c990
csitedexperts/CSE1321Python
/review/User.py
493
4.03125
4
# https://www.w3schools.com/python/python_classes.asp class Student: id name = "" age = 20 def __init__(self, id, name, age): self.id = id self.name = name self.age = age def sayHello(self): print("Hello my name is: " + self.name ) print (" my id is ", self...
aff18d22d5353a8efcc12df358fec2ef580fe4c9
rgraybeal/IntroToProg-Python
/Module05Assignment.py
4,661
4.25
4
# -------------------------------------------------# # Title: Working with Dictionaries # Dev: RRGraybeal # Date: August 11, 2018 # ChangeLog: (Who, When, What) # RRoot, 11/02/2016, Created starting template # RRGraybeal, August 11,2018, Added code to complete assignment 5 # https://www.tutorialspoint.com...
4f42463a24b317ac80bdb1a878510e2da9696b7e
Foxious/phEngine
/proto/DungeonGenerator.py
2,747
3.71875
4
# -*- coding: utf-8 -*- """ Spyder Editor This temporary script file is located here: C:\Users\Drachis\.spyder2\.temp.py """ import random import math class point(): def __init__(self,position = (0,0)): self.position = position class room(): def __init__(self): #generate a room that will conec...
fa18f4de7c79fd258c18cceb2ff6fb5b3d69970e
watsonwanda/soulsurfer
/study/chapter_03/5-2.py
992
3.6875
4
def getArrayByIndex(index): list = ['A','B','C','D','E','F','G','H'] if index < len(list): print('선택한 값은 ', list[index], '입니다.') else: print(len(list), ' 보다 작은수를 입력하세요.') print('수를 선택하세요.') index = int(input()) getArrayByIndex(index) listArray = ['A','B','C','D','E','F','G','H'] print(lis...
f45f0ba4bed8108779744d20296703b7b71616db
watsonwanda/soulsurfer
/study/chapter_08/8-6.py
3,708
3.609375
4
class Food(): # 음식을 나타내는 클래스 def __init__(self, taste, calorie, name): # 인스턴스 초기화 self._taste = taste # 맛 self._calorie = calorie # 칼로리 self._name = name # 이름 def __str__(self): # 음식 설명 return self._name + ' 은 ' + str(self._taste) + ' 이런 맛이고 '...
00c71b45bda6460044e50a5d6966af191d907908
iainrwolfheart/pythonpractice
/loop1.py
162
3.578125
4
msg=input("Write a sentence and I'll repeat: ") i=0 word="" while i<len(msg): if msg[i]==" ": print(word) word="" else: word=word+msg[i] i+=1 print(word)
171ef477a1b1649bf005cbfb08b0b738f29a86d2
iainrwolfheart/pythonpractice
/Changecalc2.py
339
3.71875
4
name=(input("What is your name?")) sal=int(input("What's your salary?")) ni=sal/100*12 if sal>=50000: tax=sal/100*40 if sal in range(30000, 49999): tax=sal/100*25 if sal in range(12500, 29999): tax=sal/100*20 if sal<12500: tax=0 print("Name:",name) print("Salary:",sal) print("N.I.:",ni) print("Tax:",tax) print("Net...
aa41fbe812065538940ca7db0f2e0b1a1d5b4ad5
MartijnWillemsAltran/DigitsRecognizer
/mlflow_runner/digits_recognizer.py
1,376
3.640625
4
from sklearn.datasets import load_digits from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.preprocessing import StandardScaler import mlflow with mlflow.start_run(): mlflow.sklearn.autolog() # Loadin...
28137d27ee05e26935519f5a037b52bf2dcbe2c9
joren485/Sudokuplotter
/Main code/comb.py
2,752
3.59375
4
## import all the neccessary libraries, os and the custom ones import os import algx import finder import motor_control ## Take the photo using raspistill. print "Taking photo" os.system("sudo raspistill -roi .4,0.05,1,1 -cfx 128:128 -w 600 -h 450 -q 100 -ex night -e jpg -sh 100 -co 100 -o image.jpg") ## Find the su...
f46f595c87f154ddb2dc131e80cf13f23489fe30
surajbarailee/PythonExercise
/python_topics/file_handling.py
5,380
4.375
4
# text file and binary file # Python Image Library # inbuilt open function # open(filename, mode) # Modes # r = for reading – The file pointer is placed at the beginning of the file. This is the default mode. # The r throws an error if the file does not exist or opens an existing file without truncating it for readi...
edb0162e3d1c5b0582c9305da3fe9aff1d9a317b
surajbarailee/PythonExercise
/python_topics/generators.py
2,369
4.53125
5
""" Retur:. A function that returns a value is called once. The return statement returns a value and exits the function altogether. Yield: A function that yields values, is called repeatedly. The yield statement pauses the execution of a function and returns a value. When called again, the function continues execution...
2b9430393d60953cbcab7a207f6c4e637814d4a1
surajbarailee/PythonExercise
/python_topics/randoms/polymorphism-3 methodoverloadingoverriding.py
368
3.890625
4
#Method overloading class Student: def __init__(self,m1,m2): self.m1=m1 self.m2=m2 def sum(self,a,b,c=None): s=a+b return s s1=Student(58,69) print(s1.sum(5,9)) #Method overriding class A: def show(self): print("in a show") class B(A): def show(self): ...
a04dac292585096e840d4a039907724754b29b69
surajbarailee/PythonExercise
/python_topics/randoms/Sets.py
278
3.765625
4
#not duplicate unordered and unindexed thisset={"apple","mango","mango","apple"} print(thisset) #cannot change but add thisset.add("another apple") thisset.update(["another mango","another kela"]) print(thisset) abcd="aabbccddssdfsdfsddddfsdfsdfsdf" abcd=set(abcd) print(abcd)
b03282cb9349e6bbad73609dcfe369287d6fa6e6
surajbarailee/PythonExercise
/python_topics/strings.py
973
4.375
4
""" Strings in python """ string = "Hello*World!" """ H e l l o * W o r l d ! 0 1 2 3 4 5 6 7 8 9 10 11 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 """ print(string[2:]) # get every element from second index print(string[-2:]) # get every element from -2 print(stri...
c971d2c838a4e3d69730865fc072be9974a70a6f
haojian/python_learning
/1. twosum.py
1,000
3.75
4
# Given an array of integers, find two numbers such that they add up to a specific target number. # # The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-bas...
e6c6fef0b0262ef221e5b0d366b754dd6aad3a9c
haojian/python_learning
/4. add2num.py
763
3.65625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): preHeader = ListNode(0) cur = preHeader carry = 0 while l1 and l2: tmp = l1.val + l2.val + carry...
d116a621877ed86d22fcc2d83aee141196172652
haojian/python_learning
/37. solveSudoku.py
924
3.8125
4
class Solution: # @param board, a 9x9 2D array # Solve the Sudoku by modifying the input board in-place. # Do not return any value. def solveSudoku(self, board): self.dfs(board) def dfs(self, board): for row in range(9): for col in range(9): if board[row][col] == '.': for k in "12345678...
27a3f6e6bf1aa242ba93b4607cc7c652051bc71a
haojian/python_learning
/20. validparentheses.py
496
3.796875
4
class Solution: # @return a boolean def isValid(self, s): leftP = ['(', '{', '[' ] rightP = [')', '}', ']'] stack = [] for char in s: if char in leftP: stack.append(char) elif char in rightP: if len(stack) == 0: return False left = stack.pop() if leftP.index(left) != rightP.inde...
ef8d060d4b11278ae846fd163b4daf4866ea6007
haojian/python_learning
/14. longestcommonprefix.py
629
3.796875
4
class Solution: # @return a string def longestCommonPrefix(self, strs): if len(strs) == 0: return '' if len(strs) == 1: return strs[0] if len(strs) == 2: return self.getCommonPrefix(strs[0], strs[1]) left = strs[:len(strs)/2] right = strs[len(strs)/2:] return self.getCommonPrefix( self.longestCom...