blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
34aa6c0c5e3e2a0d4f9fefc84c7d5ce1dc6cc60a | robpalbrah/RedditDailyProgrammer | /easy/dp_218_easy.py | 927 | 3.8125 | 4 | """
[2015-06-08] Challenge #218 [Easy] Making numbers palindromic
https://tinyurl.com/dp-218-easy
"""
# Status: Done
def calculate_palindrome(number, STEPS = 10000):
"""Calculates palindromic number. Returns (palindrome, counter).
Returns None if no palindrome exists for this number."""
for i in r... |
8b4f13c7b8f7feabf288f53eab25f5f1a94631a4 | pzhao5/CSSI_Python_Day_4 | /if_fruit.py | 194 | 3.9375 | 4 | your_fruit = raw_input('What is your favorite fruit?\n')
my_fruit = 'apple'
if your_fruit == my_fruit:
print 'That\'s my favorite fruit, too!'
else:
print 'That\'s not my favorite fruit' |
45ab1be0380bf10c2ca3a618f075cb2ff2ee4a8a | Kavindu1997/Gnu-Octave | /Activity 06/customers.py | 714 | 4.125 | 4 | # Import sys module
import sys
# Total number of arguments
print('Total arguments:', len(sys.argv))
#print("Argument values are:")
# Iterate command-line arguments using for loop
#for i in sys.argv:
#print(i)
# Define a dictionary
customers = {'9876':'Kamal Perera','9873':'Amal Fernando',
'9865':'Vimal Gunasena','... |
dd6d3e75f2bbfe996d9bf32f797e19f8e98d3b93 | danielzyla/Python_intermediate | /121.py | 1,345 | 4.125 | 4 | class Cake:
"""Cake - class operatin on cakes available in bakery """
bakery_offer = []
def __init__(self, name, kind, taste, additives, filling):
"""
init = agruments accepted
name - name of the cake
taste - taste of the cake
additives - li... |
e5f20641b1f611a8c363f9a53f1eedc507f9a3db | danielzyla/Python_intermediate | /151.py | 496 | 3.546875 | 4 | def Combinations(products, promotions, customers):
for prod in products:
for promo in promotions:
for cust in customers:
yield "{} - {} -{}".format(prod, promo, cust)
products = ["Product {}".format(i) for i in range(1, 4)]
promotions = ["Promotion {}".format(i) for i in ra... |
486e73d4b1a853edef1ade3d7d7bf322f22df651 | danielzyla/Python_intermediate | /12test2.py | 323 | 3.734375 | 4 | import os
def readfile(filepath):
file=open(filepath,'r')
text=file.read()
txtsplitted=text.split()
return print('There are %d words in the file'%(len(txtsplitted)))
path = r'/home/danielz/Documents/file.txt'
if os.path.isfile(path):
readfile(path)
result = os.path.isfile(path) and readfile(pat... |
9fc339122e827a2500239fbf62d78bbea484dfcf | ClaudioSiqueira/URI | /python/uri2344.py | 225 | 3.890625 | 4 | num = int(input())
resposta = ''
if num == 0:
resposta = 'E'
elif 1 < num <= 35:
resposta = 'D'
elif 36 < num <= 60:
resposta = 'C'
elif 61 < num <= 85:
resposta = 'B'
else:
resposta = 'A'
print(resposta)
|
0db26ff17cddf69fe2d329fc318db7bcfdb4bf67 | ClaudioSiqueira/URI | /python/uri2787.py | 101 | 3.578125 | 4 | n1 = int(input())
n2 = int(input())
soma = n1 + n2
if soma % 2 == 0:
print(1)
else:
print(0)
|
249c0b638ddbe6a85f4f52642a7e703d8fd13b65 | ClaudioSiqueira/URI | /python/uri1172.py | 171 | 3.546875 | 4 | lista = []
for i in range(0, 10):
x = int(input())
if x <= 0:
x = 1
lista.append(x)
for i, v in enumerate(lista):
print('X[{}] = {}'.format(i, v))
|
148de4714afbe1b4a53f52404ac5656d3b66cd60 | ClaudioSiqueira/URI | /python/uri1150.py | 198 | 3.625 | 4 | x = int(input())
cont = 1
while True:
z = int(input())
if z > x:
break
x2 = x
while True:
x += x2
cont += 1
if x > z:
break
else:
x2 += 1
print(cont)
|
3e97e750c402379d9bd8f2b1a93690b459316244 | ClaudioSiqueira/URI | /python/uri1132.py | 270 | 3.640625 | 4 | cont = 0
X = int(input())
Y = int(input())
if X < Y:
for i in range(X, Y + 1):
if i % 13 != 0:
cont += i
print(cont)
elif X > Y:
for i in range(Y, X + 1):
if i % 13 != 0:
cont += i
print(cont)
else:
print(0)
|
77107e1d65bb220c655172f76d956f2aba5c6c81 | ClaudioSiqueira/URI | /python/uri2544.py | 303 | 3.53125 | 4 | while True:
try:
cont = 0
n = int(input())
if n == 1:
print(0)
else:
while True:
n = n/2
cont += 1
if n == 1:
break
print(cont)
except EOFError:
break
|
e42be5c02fd26a1e9601960bb17e1893f871c3ac | ClaudioSiqueira/URI | /python/uri1015.py | 202 | 3.53125 | 4 | x1, y1 = input().split(' ')
x2, y2 = input().split(' ')
x1 = float(x1)
x2 = float(x2)
y1 = float(y1)
y2 = float(y2)
dist = ((x2 - x1)**2) + ((y2 - y1)**2)
fim = dist** (1/2)
print('{:.4f}'.format(fim))
|
8e0d0f825d85512ee2b29c168d96090adcefd3f7 | ClaudioSiqueira/URI | /python/uri1515.py | 515 | 3.515625 | 4 | while True:
c = int(input())
if c == 0:
break
else:
planeta_menor = ''
menor = 0
for i in range(c):
nome, ano, tempo = input().split()
a = int(ano)
t = int(tempo)
conta = a - t
if i == 0:
menor = cont... |
5f48524335a1579fd48f1c4c0598ea3e430f70ed | venomouscyanide/TrafficProblem | /Classes/vehicle.py | 469 | 3.703125 | 4 | class vehicle:
'''
class vehicle with speed, time to clear a crater and name
'''
def __init__(self,speed=0,crater_time=0,name=""):
self.__speed=speed
self.__crater_time=crater_time
self.__name=name
def getname(self):
'''
simple method to get the vehicle name
'''
return self.__name
def get_details... |
eb2c0407aa1d82eb12de89e3e7a305a76b15c428 | Vagacoder/Python_for_everyone | /Ch12/P12_16.py | 350 | 3.96875 | 4 | # -*- coding: utf-8 -*-
## P12.16
# merge sort w/o recursive
# for list whose length is pow of 2,
def mergeSortNoRecursive(numbers):
size = 1
while size <= len(numbers):
segmentNumber = len(numbers)/size
for i in range(1, segmentNumber + 1):
print(i)
... |
b1275df376df98edf769f8b021d1a95db0fb8533 | Vagacoder/Python_for_everyone | /Ch11/filefinder.py | 653 | 4.1875 | 4 | ##
# This program lists all Python files in a directory and its subdirectories.
#
from os import listdir
from os.path import isdir, join
def main() :
# startingDirectory = "/home/myname/pythonforeveryone"
startingDirectory = "/home/"
find(startingDirectory, ".py")
## Prints all files whose names end in a giv... |
f1b9fa6b60d99cc5603329afbfee8ddc1a17bbda | Vagacoder/Python_for_everyone | /Ch06/P6-1.py | 410 | 3.78125 | 4 | ##Ch06 P6.1
from random import *
list = []
for i in range(10):
number = randint(1,100)
list.append(number)
print(list)
evenList =[]
oddList= []
reverseList = []
for i in range(len(list)):
if i%2 == 0:
evenList.append(list[i])
elif i%2 == 1:
oddList.append(list[i])
... |
1672b020c057dcd5c7ba643b66853123e3f6883b | Vagacoder/Python_for_everyone | /P4EO_source/ch03/toolbox_2/linegraph.py | 862 | 4.3125 | 4 | ##
# This program creates a simple line graph that illustrates many
# of the features of the matplotlib module.
#
from matplotlib import pyplot
# Plot data on the graph.
pyplot.plot([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[1.1, 10.0, 25.4, 44.5, 61.0, 71.6, 72.7, 65.9, 54.6, 31.9, 10.9, 4.8])
pyplot.plot([1, 2... |
894074de985e1bf689b5c9ab53b7b8201b43c7c7 | Vagacoder/Python_for_everyone | /Ch02/2017-7-26_2.py | 790 | 3.828125 | 4 | ## Ch02 P2.12
#drive = input('Please enter the drive: ')
#path = input('Please enter the path: ')
#fileName = input('Please enter the file name: ')
#fileExtension = input('Please enter the file extension: ')
#print('%s:%s\\%s.%s' %(drive.upper(), path, fileName, fileExtension))
## Ch02 P2.13 2.14
number ... |
1aadcdb69497fb0cf3893d18be123c970a848c8f | Vagacoder/Python_for_everyone | /P4EO_source/ch08/toolbox_1/weather.py | 868 | 4.25 | 4 | ##
# This program prints information about the current weather in a user-chosen city.
#
import urllib.request
import urllib.parse
import json
# Get the location information from the user.
city = input("Enter the location: ")
# Build and encode the URL parameters.
params = {"q": city, "units": "imperial" }
arguments... |
c13bc830019fcd9c3b275fd110bb787118a01450 | Vagacoder/Python_for_everyone | /Ch04/2017-8-7_1.py | 305 | 3.921875 | 4 | ## Cho4 SC 22
total = 0
count = 0
num = input('Please enter a integer (press ENTER to finish): ')
while num != '':
num1 = int(num)
if num1 > 0:
total += num1
count += 1
num = input('Please enter a integer: ')
print('Total positive number is: %d' %total)
|
a6f4155f2a485ec9b5eb5d4635338f799f1ea5e6 | Vagacoder/Python_for_everyone | /Ch08/P8-17.py | 726 | 3.65625 | 4 | ## Ch08 P8.17
from urllib.request import urlopen
dict1 = {}
website = urlopen('https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt')
encoding = 'utf-8'
for line in website:
line = str(line, encoding)
#print(line)
data = line.split(' ',1)
data1 = data[1].st... |
1608ab8ba5955128b9dc32f37a64bb1708215984 | Vagacoder/Python_for_everyone | /Ch01/2017-7-17_1.py | 834 | 4.40625 | 4 | ## CH1 P2.1
## This program is calculating the dimesions (in mm) of letter size (8x11 inch) paper
#25.4 millimeter = 1 inch
MM_PER_INCH = 25.4
#the size of letter size paper (in inch)
widthINCH = 11
heightINCH = 8
print('The width of letter size paper is', widthINCH*MM_PER_INCH, 'mm.')
print('The height o... |
d09da6f029442ed7bde583443f3662191a0f4f1e | Vagacoder/Python_for_everyone | /Ch08/polynomial.py | 862 | 3.640625 | 4 | ## Ch08 P8.7
# module for P8-7.py using list
def newPolynomial(coefficient, power):
polynomial = []
polynomial.append((coefficient, power))
return polynomial
def addTerm(polyList, coefficient, power):
for i in range(len(polyList)):
item = polyList[i]
oldCoe... |
0110c750748638459b66444b0dfee2e37837af67 | Vagacoder/Python_for_everyone | /Ch11/P11_11.py | 467 | 3.828125 | 4 | # -*- coding: utf-8 -*-
## P11.11
# recursive squareroot
def squareRoot(x):
if x > 0:
return squareRootGuess(x, x/2)
else:
return "wrong input"
# recursive help function
def squareRootGuess(x, g):
if abs(x - g**2) < 1E-14: # abs() is important!!!
return g
else:
... |
205e480af3d5137e45bd62cb9b85636ebb1ba47e | Vagacoder/Python_for_everyone | /Ch12/P12_15.py | 1,047 | 3.921875 | 4 | ## P12.15
# improve binary search function, return -k-1, k is the position before
# which the element should inserted
from random import randint
def binarySearch1(values, low, high, target):
if low <= high:
mid = (low + high) // 2
if values[mid] == target:
return mid
elif valu... |
dfcde7dba6682c0da1047cf82431160949fbf050 | Vagacoder/Python_for_everyone | /Ch06/R6-8.py | 422 | 3.71875 | 4 | ##Ch06 R6.8
#make table
values = []
for i in range(1,11):
values.append(i)
print(values)
#a
for i in values:
if i >values[0]:
print(", ", end= "")
print(i, end="")
else:
print (i, end ="")
print()
#b
product = 1
for i in values:
product = product*i
p... |
6084251306d02fcc3a32c16ff32e8c4c95fe3f1e | Vagacoder/Python_for_everyone | /Ch06/P6-9.py | 342 | 4 | 4 | a = [1, 4, 9, 16, 7, 4, 9, 1]
def reverseList(list):
temp = []
for i in list:
temp.insert(0, i)
return temp
print(a)
print(reverseList(a))
print(a)
print()
def reverseList(list):
temp = []
for i in list:
temp.insert(0, i)
list[:] = temp
print(a)
reverseL... |
914c4b2c52a023ce3bfb2cc5414f4edb3267d47f | Vagacoder/Python_for_everyone | /Ch06/P6-23.py | 590 | 3.921875 | 4 | ##Ch06 P6.23
MAX_NUMBER_ASTRTISK = 40
def inputNumber():
list = []
number = input("Please enter an integer (enter Q for finish): ")
while number != "Q" and number != "q":
list.append(int(number))
number = input("Please enter an integer (enter Q for finish): ")
return li... |
1f5c45d8f5919ba40b028c3cf13eb190ca111974 | Vagacoder/Python_for_everyone | /Ch03/2017-8-3_5.py | 1,524 | 3.515625 | 4 | ## Ch03 P3.28
num = int(input('please enter an integer (1-3999): '))
if num > 3999 or num < 1:
exit('Wrong input, please try again.')
thou = num//1000
hun = (num - thou*1000)//100
ten = (num - thou*1000 - hun*100)//10
one = (num - thou*1000 - hun*100 - ten*10)
print(thou, hun, ten, one)
hun_C_front... |
f1dbe99fea6262a8436769e06798c59cdb353fdd | Vagacoder/Python_for_everyone | /Ch08/polynomial1.py | 785 | 3.71875 | 4 | ## Ch08 P8.8
# module for P8-8.py using dictionary
def newPolynomial(coefficient, power):
polynomial = {}
polynomial[power] = coefficient
return polynomial
def addTerm(polyDict, coefficient, power):
for oldPower in polyDict:
if oldPower == power:
... |
8ea3db4d7c6c506fff8c65ad06a31bb998fdb5a7 | Vagacoder/Python_for_everyone | /P4EO_source/ch12/special_topic_3/quickdemo.py | 310 | 4.28125 | 4 | ##
# This program demonstrates the quick sort algorithm by sorting a list
# that is filled with random numbers.
#
from random import randint
from quicksort import quickSort
n = 20
values = []
for i in range(n) :
values.append(randint(1, 100))
print(values)
quickSort(values, 0, n - 1)
print(values)
|
30e875a29877fa68cf9b4df8968bb4a8f185930d | Vagacoder/Python_for_everyone | /P4EO_source/ch06/exercises/animation.py | 854 | 3.8125 | 4 | ##
# This program draws a moving block.
#
from graphics import GraphicsWindow
from time import sleep
def main() :
# Do not look at the code in the main function.
# Your code will go into the draw function below.
WIN_WIDTH = 400
WIN_HEIGHT = 400
win = GraphicsWindow(WIN_WIDTH, WIN_HEIGHT)
... |
0788585ea34d82e2c0de7d5926ea38df4378e5b1 | Vagacoder/Python_for_everyone | /Ch07/P7-13.py | 411 | 4.0625 | 4 | ##Ch07 P7.13
sum = 0
inputString = input('Please input an float number: ')
count = 1
while inputString != 'Q' and inputString != 'q' and count < 2:
try:
number = float(inputString)
count = 1
sum += number
except ValueError:
print('Wrong input, please try again')
... |
34b64673ff08d394dce6f7563327c1fdc93549b7 | Vagacoder/Python_for_everyone | /Ch06/2017-9-25.py | 671 | 3.84375 | 4 | ##Ch06 R6.5
from random import *
count = 0
value = []
while count<10:
randomNumber = randint(1,10)
while randomNumber in value:
randomNumber = randint(1, 10)
value.append(randomNumber)
count += 1
print (value)
##Ch06 R6.6
from random import *
count = 0
value = []
while count<1... |
58ba55a1c7230b551d721c6261fd6c61fbe5af4e | Vagacoder/Python_for_everyone | /Ch03/2017-7-28_1.py | 2,397 | 4.0625 | 4 | ## Ch03 R3.9
x = input('Please enter x axis (a, b, ... g, h): ')
y = int(input('Please enter y axis (1-8): '))
#x = 'g'
#y = 5
if x == 'a' or x == 'c' or x == 'e' or x =='g':
if y%2 == 1:
#print('The grid is black')
color = 'black'
else:
#print('The grid is white')
... |
28647af44ea1e2f0acb4bdf7b5e682dc2d7749ad | Vagacoder/Python_for_everyone | /Ch10/P10-2.py | 228 | 3.546875 | 4 | ## Ch10 P10.2
from questions import Question
from fillinquestion import FillInQuestion
fq1 = FillInQuestion("The inventor of Python was _Guido van Rossum_")
fq1.display()
print(fq1.checkAnswer('Guido van Rossum'))
print(fq1.checkAnswer('uido van Rossum')) |
444cb2585ac5a66e258ef98f2d1dbabecd3a3fe4 | Vagacoder/Python_for_everyone | /Ch03/2017-8-2_2.py | 2,080 | 4.125 | 4 | ## Ch03 P3.14
#card = input('Please enter your card notation: ').upper()
card = 'QS'
if 'A' in card:
number = 'Ace'
elif '2' in card:
number = '2'
elif '3' in card:
number = '3'
elif '4' in card:
number = '4'
elif '5' in card:
number = '5'
elif '6' in card:
number = '6'
elif '... |
e010ce13793f9bfed2e5a63aac20d881bdb5adfc | Vagacoder/Python_for_everyone | /Ch04/2017-8-7_2.py | 847 | 4.125 | 4 | ## Ch04 P4.5
num_raw = input('Please enter a number (enter Q to finish): ')
if num_raw == 'Q' or num_raw == 'q' or num_raw == '' or num_raw.isalpha():
exit('Thanks for using.')
else:
num = float(num_raw)
small = num
large = num
total = 0
count = 0
difference = 0
while num_... |
f65881188c4268c168ada5828b19ed637a943207 | Vagacoder/Python_for_everyone | /Ch06/2017-8-31.py | 503 | 3.515625 | 4 | ## Ch06 P6.1
from random import *
list = []
for i in range(10):
list.append(randint(1,100))
print(list)
#a
for i in range(10):
if i%2 == 0:
print(list[i], end = " ")
print()
for i in range(10):
if i%2 != 0:
print(list[i], end = " ")
print()
#b
for i in list:
... |
341ffebb03d7cfbaafee95bfc224ce0056642497 | Vagacoder/Python_for_everyone | /P4EO_source/ch07/sec02/items.py | 1,192 | 4.21875 | 4 | ##
# This program reads a file whose lines contain items and prices, like this:
# item name 1: price1
# item name 2: price2
# ...
# Each item name is terminated with a colon.
# The program writes a file in which the items are left-aligned and the
# prices are right-aligned. The last line has the total of the pr... |
13532874199a1dc344fe151e7a66fa6f09ab9f77 | Vagacoder/Python_for_everyone | /Ch05/2017-8-21_3.py | 2,669 | 3.84375 | 4 | ## Ch05 P 5.27
def read_single_roman_number(n):
if n == 'I': return 1
if n == 'V': return 5
if n == 'X': return 10
if n == 'L': return 50
if n == 'C': return 100
if n == 'D': return 500
if n == 'M': return 1000
return 0
def read_roman_number(number):
total = 0
whi... |
99b44832412812c538cb0a98c74b2134c22b4864 | Vagacoder/Python_for_everyone | /Ch11/P11_2.py | 520 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 9 17:00:22 2018
@author: qhu
"""
# P11.2
# class of square, providing recursive getArea method
class Square:
def __init__(self, width = 0):
self._width = width
def getArea(self):
if self._width >0:
newSq = Square(s... |
9da6c6cb794166c6a0fd8a4f3422dc833f5311db | Vagacoder/Python_for_everyone | /P4EO_source/ch09/worked_example_2/die.py | 3,268 | 4.125 | 4 | ##
# This module defines a class that models a 6-sided die
#
from random import randint
## A simulated 6-sided die that can be rolled and drawn on a canvas.
#
class Die :
## Constructs the die.
# @param x the upper-left x-coordinate of the die
# @param y the upper-left y-coordinate of the die
# @param ... |
893a347faeeef7f9cbef305b4d5efa77b13a4ca1 | Vagacoder/Python_for_everyone | /Ch06/2017-9-2_3.py | 204 | 3.53125 | 4 | ## Ch06 P6.17
from random import *
raw_list = [1,2,3,4,5,6,7,8,9,10,]
new_list = []
for i in range(10):
index = randint(0,9-i)
new_list.append(raw_list.pop(index))
print(new_list) |
88b764cf3c3ebc41d234236b35ec2f99a4d28cc2 | Vagacoder/Python_for_everyone | /Ch06/2017-9-16.py | 502 | 3.890625 | 4 | ## Ch06 SC39
# method1
table =[]
for i in range(8):
row = []
for j in range(8):
row.append((i+j)%2)
table.append(row)
print(table)
new_t = []
# method 2
for i in range(8):
row = [0]*8
new_t.append(row)
for i in range(8):
for j in range(8):
new_t[i][j... |
5f149776527c580d6ec509301be2a12af58f618b | Vagacoder/Python_for_everyone | /Ch11/towersofhanoi.py | 771 | 4.03125 | 4 | ##
# This program solves the Towers of Hanoi puzzle.
#
def main() :
NDISKS = 5
towers = [list(range(1, NDISKS + 1)), [], []]
print(towers)
move(towers, NDISKS, 0, 2)
## Moves a pile of disks from one peg to another and displays the movement.
# @param towers a list of three lists of disks
# @param disk... |
bff5f8b33e75d805cd7cc604a54370bbc15a238d | Vagacoder/Python_for_everyone | /Ch12/country.py | 372 | 3.765625 | 4 | ## country class for P12.13
class Country:
def __init__(self, name, area):
self._name = name
self._area = area
# note: the __lt__ return boolean, not integer like in Java
def __lt__(self, other):
return self._area < other.getArea()
def getArea(self):
return self._ar... |
caad8b3cda0e3f83cb8bce02c63e9916e396001e | Vagacoder/Python_for_everyone | /Ch11/recursivefib.py | 424 | 4.28125 | 4 | ##
# This program computes Fibonacci numbers using a recursive function.
#
def main() :
n = int(input("Enter n: "))
for i in range(1, n + 1) :
f = fib(i)
print("fib(%d) = %d" % (i, f))
## Computes a Fibonacci number.
# @param n an integer
# @return the nth Fibonacci number
#
def fib(n) :
if n ... |
3590c65ab2cf896197bd26a1f90e93c2148cadc2 | Vagacoder/Python_for_everyone | /Ch08/P8-19.py | 893 | 3.640625 | 4 | ## Ch08 P8.19
inFile = open('alice30.txt', 'r')
line = inFile.readline()
wordCount = dict()
while line != '':
words = line.split()
for word in words:
word = word.strip()
word = word.strip('.,!?;')
newWord = ''
for char in word:
if char.isalp... |
e8ce0047b7ed60b6979b7e6d4326a6fca3d66c7f | Vagacoder/Python_for_everyone | /Ch06/R6-11.py | 322 | 3.890625 | 4 | ##Ch06 R6.11
values = []
valuesNumber =10
count = 0
while count < valuesNumber :
inputNumber = int(input("Please enter a number: "))
count +=1
values.append(inputNumber)
print(values)
valuesLength = len(values)
for i in range(valuesLength-1, -1, -1):
print(values[i])
... |
08aef9cd0a2a488d795d245eaffc39e19f3f213d | Vagacoder/Python_for_everyone | /P4EO_source/ch10/worked_example_1/employees.py | 2,369 | 3.890625 | 4 | ##
# This module defines an employee class hierarchy for payroll processing.
#
## An employee has a name and a mechanism for computing weekly pay.
#
class Employee :
## Constructs an employee with a given name.
# @param name the name of the employee
#
def __init__(self, name) :
self._name = name
... |
d0c60fd460daf2851cb7aac5952c3ce6d2f53f1a | calvinlsliang/project_euler | /Calvin.py | 2,133 | 3.96875 | 4 | '''
factorial(n)
fib(n)
quicksort(arr)
mergesort(arr)
bin2dec(n)
dec2bin(n)
prime(n)
smallprime(n)
'''
def factorial(n):
if n == 1 or n == 0: return 1
else: return n * factorial(n-1)
def fib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
def quicksort(myList):
if myList =... |
dd5a5ce7c30962a00749403606923bdf8e113bfd | calvinlsliang/project_euler | /euler11/euler11.py | 976 | 3.578125 | 4 | import string
bound = 20
big = 0
def adjacent(arr, x, y):
big = 0
temp = 0
#right
if y < 17:
temp = int(arr[x][y]) * int(arr[x][y+1]) * int(arr[x][y+2]) * int(arr[x][y+3])
if temp > big: big = temp
#down
if x < 17:
temp = int(arr[x][y]) * int(arr[x+1][y]) ... |
c46373ac8b5688783226becdad4394388231d771 | tobiasware/Codewars | /iq_test.py | 203 | 3.5625 | 4 | def iq_test(numbers):
l = [int(x) % 2 for x in numbers.split(" ")]
if l.count(0) > 1:
return l.index(1)+1
else:
return l.index(0)+1
print(iq_test("2 4 7 8 10")) #3
print(iq_test("1 2 2")) #1 |
e74825c3839e835fdd6dc466f76e11c9cc4e8fc9 | Kennytian/learning-python | /liaoxuefeng/listAndTuple.py | 709 | 3.90625 | 4 | # coding: utf-8
print('--List--')
classmates = ['Angla', '天天', '森碟']
print(classmates)
print(len(classmates))
print('classmates[-1]:', classmates[-1])
print('classmates[-2]:', classmates[-2])
print('classmates[-3]:', classmates[-3])
classmates.append('Jerry')
print(classmates)
print('classmates[0]:', classmates[0])
pri... |
2d21634ccdb04ae0b9ed7c22756cc65508099486 | lyuboangelov/Python-Advanced-January-2021 | /8_Miner.py | 3,489 | 3.515625 | 4 | def read_matrix(r):
matrix = []
for _ in range(r):
row = [el for el in list(input().split())]
matrix.append(row)
return matrix
def check_out_of_range(row, col, r, c):
return (0 <= row < r) and (0 <= col < c)
def player_move(direction, movement, p_pos, matrix):
if... |
b13919c26f9329a76ad1fb4df7d8bc0846e144fe | LienNguyen79/nguyenthilien-fundamental-c4e19 | /session03/tren lop/number.py | 217 | 3.921875 | 4 |
number= int(input(" nhap so bat ki : "))
original_number = number
n = True
count = 0
while number > 0:
number = number//10
count += 1
print("{0} has {1} digits".format(original_number, count)) |
f50db570ccf36f364c797e943de8b25368fff1a8 | LienNguyen79/nguyenthilien-fundamental-c4e19 | /session02/homework/turtle02.py | 316 | 3.78125 | 4 | from turtle import *
speed(-1)
for i in range (3):
color("green")
forward(100)
left(120)
for i in range (4):
color("red")
forward(100)
left(90)
for i in range (5):
color("green")
forward(100)
left(72)
for i in range (6):
color("red")
forward(100)
left(60)
mainloop() |
0a7b985d9fbaeea4470fc3d50aa0377902813d31 | LienNguyen79/nguyenthilien-fundamental-c4e19 | /session02/homework/bai2.py | 94 | 3.5625 | 4 | n=int(input("so bat ki: "))
s=1
for i in range (1,n+1):
s*=i
print("tich can tim la: ", s) |
e575d09fff64b0dfbf3d666ad3d01ed361291f3b | HiGreg/project1 | /day5/test01.py | 509 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# __author__ = "Hexing"
a = {'name':'jiajia','age':23,'sex':'female'}
defaulterror = "your input the number no valid "
def longestlineinfile(path):
f = open(path,'r')
#lines = f.readlines()
#f.close()
longest = 0
for line in f:
print line
... |
83cfd64fcc99c1d9de7ffd5d80ccdf05be4f572d | raufer/pytorch-ner | /src/ops/weights.py | 1,577 | 3.859375 | 4 | from collections import Counter
from typing import Iterator
from typing import List
def calculate_multiclass_weights(labels: Iterator) -> List[float]:
"""
Calculates best weights for a classification problem with various classes
f :: Max(Number of occurrences in most common class) / (Number of occurrence... |
1740a6226bde26e79130d81ab4ac0b6bf574d3d6 | olivia2549/FishFight | /fish.py | 9,990 | 3.734375 | 4 | import random
class FriendlyCard:
def __init__(self, name, card_type, description, attack, health): # defining instance variables
self.name = name
self.card_type = card_type
self.description = description
self.attack = attack
self.health = health
def print_card(sel... |
4a21012b4f94d5d700eedbc432b74c8215905cf3 | yassarq/Python | /Python_basics/product_assignments.py | 1,284 | 3.6875 | 4 | class Product:
def __init__(self, price, itemName, weight, brand):
self.price = price
self.itemName = itemName
self.weight = weight
self.brand = brand
self.status = "for sale"
def sell(self):
self.status = "sold"
return self
def addTax(self, tax):
... |
54b00daca7ff12e8d8b79b08a667406460e93488 | deepaksharma36/Python-Assignements | /lab4/bitcoin.py | 7,770 | 4.40625 | 4 | """
This is an exercise from:
http://www.righto.com/2014/09/mining-bitcoin-with-pencil-and-paper.html
that demonstrates how bitcoin mining works. It performs only a single
pass of the SHA-256 algorithm to encrypt the first 32 bits of data.
Author: Mayank Jain mj2997
Deepak Sharma ds5930
"""
# constants
B... |
523b1df20b14d86408b4611ee2da2865bed7a511 | deepaksharma36/Python-Assignements | /lab10/linkedhashtable.py | 9,168 | 3.90625 | 4 | """
description: Linked chained Hash Map with resizing
language: python3
author: ds5930@cs.rit.edu Deepak Sharma
author: mj2997@cs.rit.edu Mayank Jain
"""
from set import SetType
from collections.abc import Iterable, Iterator
class Data:
"""
A value entry plus a two link to make it a node in a double linked... |
45ccb4ed27b58b62ef5de9815cebf2f5083fc460 | LeeKim0932/python_study | /08_12/read.py | 715 | 3.625 | 4 |
poem = '''There was a young lady named Bright,
Whose speed was far faster than light;
She started ond day
In a relative way,
And returned on the previous night.'''
fin open('relativity', 'rt')
poem = fin.read()
fin.close()
len(poem)
# read()
poem = ''
fin = open('relativity', 'rt')
chunk = 100
while True:
fragm... |
a8506e25d5553877b88d4b708fa410ee108a3297 | arusv81/hp-py-201906 | /unit-testing/modules/primeutils.py | 1,154 | 4.0625 | 4 | def is_prime(number):
'''
checks if the given number is prime or not
>>> is_prime(0)
False
>>> is_prime(2)
True
>>> is_prime(9)
True
>>> is_prime(-4)
False
>>> is_prime(-2)
True
'''
number=abs(number)
if number<2: return False
for checker in range(2... |
c655b776f531352b2b07821a91e2a74bb3d979c6 | arusv81/hp-py-201906 | /module-demo-01/appmain.py | 752 | 3.875 | 4 | '''
1. accept a range from user
2. find all primes in the range
3. find the sum and average of all primes
4. ask user if they want to try another round
'''
import maths
import consoleutils
import primes
def main():
global primes
repeat=True
while repeat:
lo= consoleutils.read_int('min? ',2)
... |
15b968d260356fd058dec31b52315d373402acfd | arusv81/hp-py-201906 | /multi-threading/06thread-countdown.py | 805 | 3.90625 | 4 | from threading import Thread,currentThread
from time import sleep
def print_thread(msg):
print('[{}] {}'.format(currentThread().getName(),msg))
def count_down(max):
try:
print_thread('starts')
while max>=0:
print_thread('counts {}'.format(max))
max-=1
print_thr... |
2aa9f5b42ecfb98eb152175912f18e3246166f16 | JUKYUNGYOO/algorithm2 | /venv/include/26_class_생성자.py | 824 | 3.53125 | 4 | #
# __init__(self)
#
# 생성자, 클래스 인스턴스가 생성될 때 호출됨
# self인자는 항상 첫번째에 오며 자기 자신을 가리킴
# 이름이 꼭 self일 필요는 없지만, 관례적으로
# self로 사용
# 생성자에서는 해당 클래스가 다루는 데이터를 정의
# 이 데이터를 멤버변수 또는 속성이라고 함.
#
# self
# 파이썬의 method는 항상 첫번째 인자로
# self를 전달
# self는 현재 메쏘드가 호출되는
# 객체 자신을 가리킴
class Person:
def __init__(self,name,age=10):
print(... |
d548f84ad6471cd4bd481c85a997f6aa87fa7ac9 | PeterCardenas/daily-coding-problems | /553.py | 1,569 | 4.3125 | 4 | '''
You are given an N by M 2D matrix of lower case letters. Determine the minimum number of columns
that can be removed to ensure that each row is ordered from top to bottom lexicographically. That
is, the letter at each column is lexicographically later as you go down each row. It does not
matter whether each row it... |
da5c189ba0587d7f322c3b80807fe6d0bd4318b9 | fabricio24530/UriOnlineJudge | /1049.py | 1,161 | 3.8125 | 4 | # -*- coding: utf-8 -*-
def animal(a, b, c):
if a == 'vertebrado' and b == 'ave' and c == 'carnivoro':
return print('aguia')
elif a == 'vertebrado' and b == 'ave' and c == 'onivoro':
return print('pomba')
elif a == 'vertebrado' and b == 'mamifero' and c == 'onivoro':
return print('h... |
ad3d7bbaabef1368d6850027450a34693a13c63b | fabricio24530/UriOnlineJudge | /1080.py | 184 | 3.5625 | 4 |
lista = []
for i in range(0, 100):
aux = int(input())
if (aux > 0):
lista.append(aux)
else:
pass
print(max(lista))
print(lista.index(max(lista)) + 1)
|
4aa7e36b3088ea496b33178a708c6aba8aeede28 | fabricio24530/UriOnlineJudge | /1015.py | 212 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import math
x = input().split(' ')
y = input().split(' ')
distancia = math.sqrt(pow((float(y[0])-float(x[0])), 2) + pow((float(y[1]) - float(x[1])), 2))
print('{:.4f}'.format(distancia)) |
aad91c0a8dfb6ca5302accc5f0e9a1492e575ddf | anand14327sagar/Python_Learning | /Set.py | 430 | 3.9375 | 4 | myset = {10, 20, 30, 40, 50, 50}
for x in myset:
print(x)
# clear() clears the items from a set
# copy() returns the copy of the set
# difference() returns a set with the difference of the two sets
# isdisjoint() returns if the sets have intersection
# issubset() returns if the set is a subset
# symme... |
0c4c42daaa27418df66d6c7b2a030bdbcacf6b95 | reddyprasade/Turtle_Graphics_In_Python3 | /spider web.py | 463 | 3.96875 | 4 | #Python program to draw spider web in turtle programming
import turtle
t = turtle.Turtle()
t.speed(0)
#Code for building radical thread
for i in range(6):
t.forward(150)
t.backward(150)
t.right(60)
#Code for building spiral thread
side = 150
for i in range(15):
t.penup()
t.goto(0,0)
t.pe... |
c6da28083ef4e769c267d7ec5abb48525617606e | drudolpho/Algorithms | /stock_prices/stock_prices.py | 900 | 3.765625 | 4 | #!/usr/bin/python
import argparse
# find_max_profit([1050, 270, 1540, 3800, 2]) should return 3530,
prices = [1050, 270, 1540, 3800, 2]
def find_max_profit(prices):
biggest_difference = -9999
for i in range(len(prices) - 1, 0, -1):
for j in range(i - 1, 0, -1):
diff = prices[i] - prices... |
5cd11dbf59178a43eaea3b4926de03294e36fd0b | wq2012/SimpleDER | /simpleder/der.py | 5,431 | 3.515625 | 4 | import numpy as np
from scipy import optimize
def check_input(hyp):
"""Check whether a hypothesis/reference is valid.
Args:
hyp: a list of tuples, where each tuple is (speaker, start, end)
of type (string, float, float)
Raises:
TypeError: if the type of `hyp` is incorrect
... |
faf3b1e13ceb6812b901bc214b58fda7c6ac6365 | Ueeek/Lib | /WeightedUnionFind.py | 1,775 | 3.71875 | 4 | class WeightedUnionFind:
"""
重み付きUnion Find
"""
def __init__(self, n):
"""
:param:n size of nodes
par : show parent of each node
rank : show height
weight: dist from root to the node
"""
self.par = [i for i in range(n+1)]
self.rank = [0] ... |
5dc42c23889f457d1711d85d32872c9a585cc3c0 | Ueeek/Lib | /SizeUnionFind.py | 1,469 | 3.890625 | 4 | class UnionFind:
"""
sizeによる実装
"""
def __init__(self, N):
self.parent = [i for i in range(N)]
self.size = [1 for _ in range(N)]
def find(self, x):
"""
x: child
ret-> node
xのグループの代表を見つける
"""
if self.parent[x] == x:
return x... |
a3d896c3522f6d0fbf1b439debb1b7da4f5ab420 | oenomel87/euler | /prob04.py | 672 | 3.75 | 4 | '''
두개의 세자리수를 곱해서 만들 수 있는 가장 큰 palindromic number를 구하라
'''
def isPalindromic(num):
numToStr = str(num)
leng = len(numToStr)
for i in range(0, leng):
if numToStr[i] != numToStr[leng - 1 - i]:
return False
return True
def findDigit(palindromic):
for i in range(999, 99, -1):
... |
0c2cb93053a74deb78445d4f1f8297ff08331372 | oenomel87/euler | /prob07.py | 378 | 3.921875 | 4 | '''
10001번째 소수를 찾아라
'''
def getNthPrime(target):
number = 1
index = 0
while index < target:
number = number + 1
if isPrime(number):
index = index + 1
return number
def isPrime(number):
for n in range(2, number):
if number % n == 0:
return False
... |
01de5d94826564e9d57a4e815a3682a4bf9aea08 | jesus-r-mendoza/Walmart-Store-Sales-Forecasting | /src/py/PCA-FeatureReduction.py | 5,203 | 3.53125 | 4 |
# coding: utf-8
# # PCA - Feature Reduction
# In[1]:
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.decompositi... |
f96b2a179b8d60ef8fd68deb5f428e58a70039e4 | tcosmo/OptimalSupSpePython | /StageFev1-2018/correc.py | 1,518 | 3.765625 | 4 | def une_suite(L):
# astuce, on transforme L en chaine de caractère
# pour utiliser les méthodes .find et .replace qui vont
# faire le taf pour nous
L_str = "".join(map(str,L))# transforme [1,1,0] en "110"
max_len_ones = -1
where = -1
for len_ones in range(1,len(L_str)):
new_wher... |
e1c42c169fba89155fdff15de06cabc13582209f | ncommella/automate-boring | /ch09/regex.py | 1,115 | 4.34375 | 4 | #!/usr/bin/python3
# regex.py - Opens all .txt files in a specified directory and searches them for
# a user-defined regular expression. Uses interactive prompts rather than arguments
# Usage: ./regex.py
import re, os, sys
#Get directory from user & validate it
while True:
targetDirectory = input('Enter the direc... |
f86f50dc38e17f4d13ab293896534daf5927befb | raickhr/langevin | /langevin/langevin.py | 5,329 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""Main module."""
import numpy as np
import argparse
import random
import matplotlib.pyplot as plt
#List of functions
def calc__vis_force(velocity):
#function to calculae the viscous force
vis_force = - gamma * velocity
#returning the viscous force
return vis_force
def ca... |
7b6a262119661b884fe10b0d89f87991658f37eb | musa16-meet/MEET-YL1 | /lab3/randomness.py | 133 | 3.71875 | 4 | import random
1=H
2=T
print("chose how many flips do you want")
def flip ():
n=input()
for i in range(10)
random.randint(1,2)
|
292b0564d5eac5b7f8b0d3776bb4d3cb2552528d | bopopescu/cobapython | /url.py | 686 | 3.5 | 4 | # import urllib2
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import threading
def get_content_len(url):
response = urlopen(url)
content = response.read()
print(len(content))
urls = [
... |
9490aae7034e87f070dd39e1a3b7987d933697e2 | astg606/py_materials | /scipy/linRegres_populationUrban.py | 1,287 | 4.03125 | 4 | #!/usr/bin/env python
'''
We analyze the percentage US urban population since 1790.
We calculate a linear regression model and plot the data
'''
#-------------
# Load modules
#-------------
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
def predict_line(x, m, b):
'''
... |
e2fca4ac93a0fae10da3f40b86dee279fbaf43d0 | DustyHatz/CS50projects | /pset6/hello.py | 185 | 3.90625 | 4 | # This program takes in a users name and says hello to that person!
from cs50 import get_int, get_float, get_string
name = get_string("What is your name?\n")
print("hello, " + name)
|
66fe1b38384e72827f1d772767c36f177c1ab94c | fchacks/mini-fchacks | /zorkExample.py | 982 | 3.9375 | 4 | exit = False
position = (0,0)
inventory = []
print("running....")
while not exit:
command = input("command >> ")
print(command)
if command == "north":
x, y = position
position = (x, y+1)
elif command == "south":
x, y = position
position = (x, y-1)
elif command == "eas... |
b3c00493ce84a6f4a62dca90ad5a394c3e6fc2ae | tharunkarnekota/voice-assistant | /baby.py | 2,699 | 3.5625 | 4 | import speech_recognition as sr
import pyttsx3
import datetime as dt
import pywhatkit as pk
import wikipedia as wiki
listener = sr.Recognizer()
speaker = pyttsx3.init()
""" RATE"""
rate = speaker.getProperty('rate') # getting details of current speaking rate #printing current voice rate
speak... |
26a92371307e712169ed0093bb8ffecae297a222 | YakirAvrahami/Python | /02_ID/homework_02-ID.py | 1,385 | 3.65625 | 4 | print(" ")
print(" ")
ID=input("enter your ID: ")
ID_12=[1,2,1,2,1,2,1,2,1]
ID_mul=[0,0,0,0,0,0,0,0,0]
ID_sum=[0,0,0,0,0,0,0,0,0]
while 1:
if len(ID)==9:
print("Your ID is: ",end="")
for i in ID:
print(i," , ",end="")
print()
print("the 1,2,1 : ",end="")... |
1bfaece1e32cae76db49ff68b582bd48dde39c97 | vanadium23/interpreters.py | /calc/interpreter.py | 2,001 | 3.78125 | 4 | # coding: utf-8
from tokens import INTEGER, PLUS, MINUS, MULTIPLY, DIVISION, LPAR, RPAR
# lexer for this abstract grammar
# expr = term((PLUS|MINUS)term)*
# term = factor((MULTIPLY|DIVISION)factor)*
# factor = INTEGER
class Interpreter(object):
def __init__(self, lexer):
self.lexer = lexer
sel... |
68bc3de36cb773130c43760b63928a487f4e1d41 | caiquetgr/exerciciosPythonBrasil | /EstruturaSequencial/exercicio006.py | 621 | 4.3125 | 4 | ## http://wiki.python.org.br/ListaDeExercicios
## Caique Borges
## Exercicios de estrutura sequencial
## http://wiki.python.org.br/EstruturaSequencial
<<<<<<< HEAD
## EXERCICIO 6
import math
raio = float(input('Insira o raio do círculo: '))
area = float((math.pi * math.pow(raio, 2)))
print('A area do circulo eh %f... |
6a6aca1cfd015345a92fef4365e44390925501a3 | caiquetgr/exerciciosPythonBrasil | /EstruturaDeDecisao/exercicio004.py | 367 | 4.0625 | 4 | ## http://wiki.python.org.br/ListaDeExercicios
## Caique Borges
## Exercicios de estrutura de decisao
## https://wiki.python.org.br/EstruturaDeRepeticao
## EXERCICIO 04
letra = input('Digite uma letra: ').lower()
vogais = ['a','e','i','o','u']
if( letra in vogais ):
print('Letra {} é uma vogal!'.format(letra))
els... |
f6a84ae47ebd508aabdd25b4ebdd8fddc06cde46 | caiquetgr/exerciciosPythonBrasil | /EstruturaSequencial/exercicio005.py | 289 | 4 | 4 | ## http://wiki.python.org.br/ListaDeExercicios
## Caique Borges
## Exercicios de estrutura sequencial
## http://wiki.python.org.br/EstruturaSequencial
## EXERCICIO 5
metros = float( input('Insira a quantidade de metros: ') )
centimetros = metros * 100;
print(metros, 'm ->', centimetros, 'cm') |
5c89a7cd33b1c76536a04fc3d93c7f00037cb3ac | PontusSven/python-course | /file-IO/file.py | 782 | 3.515625 | 4 | myfile = open('/Users/pontussvensson/python/education/file-IO/myfile.txt')
# read whole file
print(myfile.read())
# reset the curser
myfile.seek(0)
# put all files into a list
fileList = myfile.readlines()
print(fileList)
# close the file
myfile.close()
# best practise - no need to close the file -
# read
with op... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.