blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
2c6339f7d99d3cce98ea92d7bd71a80ff6d0efd9
|
Sahale/algo_and_structures_python
|
/Lesson_2/2.py
| 1,370
| 4.15625
| 4
|
"""
2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, то у него 3 четные цифры
(4, 6 и 0) и 2 нечетные (3 и 5).
"""
# Отсутствует обработка для случая, если пользователь ввел не число
def cycle():
while True:
a = str(input('Введите число: '))
even = 0
odd = 0
for i in a:
if int(i) % 2 == 0:
even += int(i)
else:
odd += int(i)
print('Сумма четных:', even)
print('Сумма нечетных:', odd)
# Понимание пришло не сразу...(
def recursion(digit, even, odd):
check = digit % 10
if digit == 0:
print('Четное:', even)
print('Нечетное', odd)
digit = int(input('Введите число: '))
recursion(digit, even = 0, odd = 0)
elif check % 2 == 0:
even += check
recursion(digit // 10, even, odd)
else:
odd += check
recursion(digit // 10, even, odd)
if __name__ == '__main__':
# cycle()
dig = int(input('Введите число: '))
even = 0
odd = 0
recursion(dig, even, odd)
| false
|
081d354575e425e7e2a8f9f32d6729df27b3ca88
|
Cyansnail/Backup
|
/PythonLists.py
| 1,378
| 4.28125
| 4
|
# how to make a list
favMovies = ["Star Wars", "Avengers", "LOTR"]
# prints the whole list
print(favMovies)
#prints only one of the items
print(favMovies[1])
# to add you can append or insert
# append adds to the end
favMovies.append("Iron Man 1")
print(favMovies)
# insert will put the item wherevre you want
favMovies.insert(1, "Harry Potter")
print(favMovies)
# how to remove items
# remove by name or by index
# remove by name use remove
favMovies.remove("LOTR")
print(favMovies)
#favMovies.remove("Kill Bill")
# pop will remove the last item, unless index is given
favMovies.pop()
print(favMovies)
favMovies.pop(1) # will remove whatever is in index 1
print(favMovies)
# get the length of a list
# this is a function
# the function name is len
print("My list has " + str(len(favMovies)) + " items.")
favMovie = input("What is your favorite movie? ")
favMovies.append(favMovie)
print(favMovies)
print(favMovies[len(favMovies)-1])
#loop through a list
count = 1
for movie in favMovies:
print("My number " + str(count) + " movie is " + movie )
count = count + 1
numList = [1, 3, 5, 7, 9, 11, 13, 15]
# challenge: Loop through the list and add all of the numbers together
total = 0
for totall in numList:
total = total + totall
print(total)
if "Harry Potter" in favMovies:
favMovies.remove("Endgame")
else:
print("Not in list")
| true
|
b0a55be05b1fc2e33561b8e676a8e3bd8916e489
|
Munster2020/HDIP_CSDA
|
/labs/Topic04-flow/lab04.05-topthree.py
| 687
| 4.1875
| 4
|
# This program generates 10 random numbers.
# prints them out, then
# prints out the top 3
# I will use a list to store and
# manipulate the number
import random
# I programming the general case
howMany = 10
topHowMany = 3
rangeFrom = 0
rangeto = 100
numbers = []
for i in range(0,10):
numbers.append(random.randint(rangeFrom, rangeto))
print("{} random numbers\t {}".format(howMany, numbers))
# I am keeping the original list maybe I don't need to
# I got the idea to sort and split the list from stackover flow
# https://stackoverflow.com/q/32296887
topOnes = numbers.copy()
topOnes.sort(reverse=True)
print("The top {} are \t\t {}".format(topHowMany, topOnes[0:topHowMany]))
| true
|
a1a02e09b242546b8003baf6caff98e293370a50
|
makthrow/6.00x
|
/ProblemSet3/ps3_newton.py
| 2,692
| 4.34375
| 4
|
# 6.00x Problem Set 3
#
# Successive Approximation: Newton's Method
#
# Problem 1: Polynomials
def evaluatePoly(poly, x):
'''
Computes the value of a polynomial function at given value x. Returns that
value as a float.
poly: list of numbers, length > 0
x: number
returns: float
'''
indexValue = 0
total = 0.0
power = 0 # count the index. this is the power
for c in poly:
total += c * (x ** power)
power += 1
return total
# Problem 2: Derivatives
def computeDeriv(poly):
'''
Computes and returns the derivative of a polynomial function as a list of
floats. If the derivative is 0, returns [0.0].
poly: list of numbers, length > 0
returns: list of numbers (floats)
'''
"""
example case:
- 13.39 + 17.5x^2 + 3x^3 + x^4
poly = [-13.39, 0.0, 17.5, 3.0, 1.0]
print computeDeriv(poly)
[0.0, 35.0, 9.0, 4.0] # 35x + 9x^2 + 4x^3
"""
# FILL IN YOUR CODE HERE...
# poly value. muliply by its power
# then put in a new list, omit first poly value
power = 0.0 # count the index. this is the power. omit first value
derivList = []
if len(poly) == 1:
# print "length poly is 0"
derivList.append(0.0)
return derivList
else:
for c in poly:
value = c * power
power += 1
derivList.append(value)
derivList.pop(0)
return derivList
# Problem 3: Newton's Method
def computeRoot(poly, x_0, epsilon):
iter = 0
rootiter = [] # return list
# calculate x0
calcguess = evaluatePoly(poly, x_0)
#print "calcguess: %r " % calcguess
while abs(calcguess) > epsilon:
# use recursion call to calculate x1
iter += 1
# print "iter: %r" % iter
# print "x_0: %r" % x_0
x_0 = x_0 - (evaluatePoly(poly, x_0) / evaluatePoly(computeDeriv(poly), x_0))
calcguess = evaluatePoly(poly, x_0)
rootiter.append(x_0)
rootiter.append(iter)
return rootiter
print computeRoot([-13.39, 0.0, 17.5, 3.0, 1.0], 0.1, .0001)
print computeRoot([1, 9, 8], -3, .01)
print computeRoot([1, -1, 1, -1], 2, .001)
print evaluatePoly(computeDeriv([1, 9, 8]),2)
"""
def computeRoot(poly, x_0, epsilon):
iter = 0
x1 = 0
rootiter = []
# calculate x0
calcguess = evaluatePoly(poly, x_0)
if calcguess < epsilon:
rootiter.append(calcguess)
rootiter.append(iter)
return rootiter
else: # use recursion call to calculate x1
x1 = x_0 - evaluatePoly(poly, x_0) / evaluatePoly(computeDeriv(poly), x_0)
computeRoot(poly, x1, epsilon)
#returns: list [float, int]
return
"""
| true
|
b39ca0c3cfb9a13ef5b02d0b8f705e89e9b4971f
|
makthrow/6.00x
|
/ProblemSet2/PS2-2.py
| 1,165
| 4.21875
| 4
|
balance = 4773
annualInterestRate = 0.2
# result code should generate: Lowest Payment: 360
# Variables:
# balance - the outstanding balance on the credit card
# annualInterestRate - annual interest rate as a decimal
# The monthly payment must be a multiple of $10 and is the same for all months
# TODO: CALCULATE MONTHLY PAYMENT BASED ON INITIAL BALANCE
""" MATHS:
Monthly interest rate = (Annual interest rate) / 12
Updated balance each month = (Previous balance - Minimum monthly payment) x (1 + Monthly interest rate)
"""
monthlyInterestRate = annualInterestRate / 12
fixedMonthlyPayment = 0
updatedBalance = balance
def remainingBalance(fixedMonthlyPayment):
month = 1
updatedBalance = balance
while month <= 12:
updatedBalance = round((updatedBalance - fixedMonthlyPayment) * (1 + monthlyInterestRate), 2)
month += 1
return updatedBalance
def balancePaidInFull(updatedBalance):
return updatedBalance <= 0
while not balancePaidInFull(updatedBalance):
fixedMonthlyPayment += 10
updatedBalance = remainingBalance(fixedMonthlyPayment)
print "Lowest Payment: %r" % fixedMonthlyPayment
| true
|
f2a6bda380939c9e4514a736633121a5270a9a44
|
AnthonyArg1/mc-AntonioArguello
|
/Taller 7/programaA.py
| 1,540
| 4.125
| 4
|
import math
# Se pide x en: e^-x
valor = int(input('Digite x en e^-x: '))
# Definiciones
error_esperado = ((0.5 * math.pow(10, -7)) * 100)
error_relativo = 100
iteraciones = 0
potencia = 0
x = 0
y = 0
# Bucle infinito
while True:
# Mientras el error esperado sea menor que el error relativo
if(error_esperado<error_relativo):
# Si el modulo 2 del iterador es 0, suma, sino, resta
if(iteraciones%2==0):
y = x
x = x + (math.pow(valor, potencia)/math.factorial(potencia))
iteraciones += 1
potencia += 1
else:
y = x
x = x - (math.pow(valor, potencia)/math.factorial(potencia))
iteraciones += 1
potencia += 1
# Calcular el error relativo
error_relativo = abs((x - y )/x) * 100
# Imprimir iteración realizada, valor de la iteración y error relativo de la iteración
print('-' * 20)
print(f'La iteración actual es: {iteraciones}')
print(f'El valor de la iteracion actual es: {x}')
print(f'Su error relativo es: {error_relativo}')
print('-' * 20)
print('\n' * 3)
# Terminar la ejecución del programa, imprimir la última iteración, el valor y su error relativo
else:
print('\n' * 3)
print('-' * 20)
print(f'La iteración final es: {iteraciones}')
print(f'El valor de la iteracion final es: {x}')
print(f'Su error relativo es: {error_relativo}')
print('-' * 20)
exit(0)
| false
|
ca3e671fd66ef9063da94334696dd8b11ebab69a
|
yueyueyang/inf1340_2015_asst2
|
/exercise1.py
| 1,481
| 4.125
| 4
|
vowels = "aeiou"
def pig_latinify(word):
"""
Main translator function.
:param : string from function call
:return: word in pig latin
:raises:
"""
# convert string to all lowercase
word = word.lower()
# if string has numbers -> error
if not word.isalpha():
result = "Please only enter alphabetic characters."
# check if the first letter is a vowel
elif word[0] in ("a", "e", "i", "o", "u"):
result = word + "yay"
# there is a vowel in the word somewhere other than the first letter
elif check_for_any_vowels(word) == 1:
index = get_first_vowel_position(word)
word = word[index:] + word[0:index]
result = word + "ay"
# there are no vowels in the word
else:
if check_for_any_vowels(word) == 0:
result = word + "ay"
return result
def get_first_vowel_position(word):
"""
Figures out where the first vowel is
:param : word from pig_latinify
:return: index of vowel
:raises:
"""
no_vowel = False
if not no_vowel:
for c in word:
if c in vowels:
return word.index(c)
def check_for_any_vowels(word):
"""
Figures out if the word has any vowels
:param : word from pig_latinify
:return: 1 if any vowels, 0 if no vowerls
:raises:
"""
for c in vowels:
if c in word:
return 1
return 0
#pig_latinify("apple")
| true
|
02272ce4fee1b49d2c7d137bf7d930a18d3b6394
|
key36ra/m_python
|
/log/0723_PickleSqlite3/note_sqlite3.py
| 2,033
| 4.125
| 4
|
import sqlite3
"""
Overview
"""
# Create "connection" obect.
conn = sqlite3.connect('example.db')
# Create "cursor" onject from "connection" object.
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
"""
Rule to input securely
"""
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())
# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
"""
Get data from 'SELECT' command
"""
# Iterator
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
print(row)
# fetchone()
c.execute('SELECT * FROM stocks ORDER BY price')
print(c.fetchone())
# fetchall()
c.execute('SELECT * FROM stocks ORDER BY prince')
print(c.fetchall())
"""
Cursor object
"""
# class sqlite3.connect().cursor()
# execute(sql[,parameters)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table peaple (name_last, age)")
# This is the qmark style:
cur.execute("insert into people values (?,?)",(who,age))
# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age",{"who":who,"age":age})
print(cur.fetchone())
# executemany(sql, seq_of_parameters)
# executescript(sql_script)
# fetchone(), fetchmany(size=cursor.arraysize), fetchall()
# close()
"""
Row object
"""
# class sqlite3.Row
| true
|
f5f3cdd35da4181147b35d2ba1f300117a04978c
|
key36ra/m_python
|
/seireki-gengou.py
| 935
| 4.125
| 4
|
#!/usr/bin/env python3
"""
We post our birthday.
And this code translate the year to the gengou,
for example "heisei", "shouwa" and so on.
"""
from datetime import datetime
now = datetime.now()
print("あなたの生まれ年(西暦)を元号に変換します")
# python3では、input()はstr型になっている(python2はint型)
year = int(input("生まれ年:"))
print()
if year in range(1868, now.year):
print("あなたの生まれ年は、元号で表すと、")
if year in range(1868, 1912):
print("明治{}年".format(year-1867))
elif year in range(1913, 1926):
print("大正{}年".format(year-1911))
elif year in range(1926, 1989):
print("昭和{}年".format(year-1925))
elif year in range(1989, now.year+1):
print("平成{}年".format(year-1988))
print("です。")
else:
print("すんまへんな。明治から平成しかわかりまへんで!(_ _)!")
| false
|
8bc413580dd92b6ab78befe3ec6cc045b6698cd4
|
GMcghn/42---Python-Bootcamp-Week1
|
/day01/ex01/game.py
| 1,498
| 4.25
| 4
|
class GotCharacter:
# https://www.w3schools.com/python/python_inheritance.asp
def __init__(self, first_name, is_alive = True):
#properties (ne doivent pas forcément être en attributes)
self.first_name = first_name
self.is_alive = is_alive
# Inheritance allows us to define a class that inherits all the methods and properties from another class
# To create a class that inherits the functionality from another class,
# send the parent class as a parameter when creating the child class
class Lannister(GotCharacter):
""" class representing the Lannister family. Definitely the most badass of the saga. """
# When you add the __init__() function, the child class will no longer
# inherit the parent's __init__() function.
# To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function
# Python also has a super() function that will make the child class inherit all the methods and properties from its parent
def __init__(self, first_name, family_name = 'Lannister', house_words = "A Lannister always pays his debts."):
self.family_name = family_name
self.house_words = house_words
# no 'self'
# define a value (is_alive) if not in child properties (first_name)
super().__init__(first_name, is_alive = True)
def print_house_words(self):
print(self.house_words)
def die(self):
self.is_alive = False
return self.is_alive
| true
|
7cc8e38f5fcd767d522c5289fc2f9e60ecb00e71
|
Sepp1324/Python---Course
|
/tut010.py
| 595
| 4.53125
| 5
|
#!/usr/bin/env python3
# strip() -> Removes Spacings at the beginning and the end of a string
# len() -> Returns the length of a String (w/0 \n)
# lower() -> Returns the string with all lowercase-letters
# upper() -> Returns the string with all uppercase-letters
# split() -> Split a string into a list where each word is a list item
_text = input('Input something: ')
print('Strip:',_text.strip())
print('Length:', len(_text))
print('Lower:', _text.lower())
print('Upper:', _text.upper())
print('Split:', _text.split()) # Default-Deliminator: Spacing; Other Indicator e.g: _text.split('.')
| true
|
4a9bdc08f081dee7c1e469e016eaba575cece2f8
|
kalpanayadav/shweta
|
/shweta1.py
| 776
| 4.3125
| 4
|
def arearectangle(length,breadth):
'''
objective: to calculate the area of rectangle
input:
length and breadth of rectangle
'''
# approach: multiply length and breadth
area = length*breadth
return area
def areasquare(side):
'''
objective: to calculate the area of square
input:
length of square
approach: multiply side by itself
'''
return(arearectangle(side,side))
def main():
'''
objective: to calculate the area of square
input: length of square
approach: multiply side by side itself
'''
a = int(input("enter the length of a side"))
print("area of square is",areasquare(a))
print("end of output")
if __name__ == '__main__':
main()
print("end of program")
| true
|
0f6fc453225f9495703a7e4118e2e2d3b146860b
|
MnAkash/Python-programming-exercises
|
/My solutions/Q21.py
| 1,248
| 4.59375
| 5
|
'''
A robot moves in a plane starting from the origin point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.
The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps.
Please write a program to compute the distance from current position after a sequence of movement and original point.
If the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
'''
from math import sqrt
updown_dist=0
leftright_dist=0
while True:
str = input ("Enter movement: ")
movement = str.split(" ")
type = movement [0]
dist = int (movement [1])
if type=="DOWN":
updown_dist += dist
elif type=="UP":
updown_dist -= dist
elif type=="LEFT":
leftright_dist += dist
elif type=="RIGHT":
leftright_dist -= dist
str = input ("Continue?(y/n):")
if not (str[0] =="Y" or str[0] =="y") :
break
#print(updown_dist,leftright_dist)
approx_pythagorian_dist=round(sqrt(updown_dist**2+leftright_dist**2))
print ("\nApprox Pythagorian Distancee: ", approx_pythagorian_dist)
| true
|
79fc392902b97b50a7506f7e83441e1f04dc53e9
|
timeispreciousFeng/pythonForTest
|
/test20180716-Function/test4-parameter.py
| 2,313
| 4.4375
| 4
|
# -*- coding: UTF-8 -*-
# 参数
# 以下是调用函数时可使用的正式参数类型:
#
# 必备参数
# 关键字参数
# 默认参数
# 不定长参数
#=====================================================================#
# 必备参数
# 必备参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。
#可写函数说明
def printme( str ):
"打印任何传入的字符串"
print(str);
return;
#调用printme函数
# printme();
printme("11");
#=====================================================================#
# 关键字参数
# 关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。
#
# 使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。
#
# 以下实例在函数 printme() 调用时使用参数名:
def printme1( str ):
"打印任何传入的字符串"
print(str);
return;
#调用printme函数
printme1( str = "My string");
def printinfo( name, age ):
"打印任何传入的字符串"
print("Name: ", name)
print("Age ", age);
return;
#调用printinfo函数
printinfo( age=50, name="miki" );
#=====================================================================#
# 缺省参数
# 调用函数时,缺省参数的值如果没有传入,则被认为是默认值。下例会打印默认的age,如果age没有被传入:
#可写函数说明
def printinfo( name, age = 35 ):
"打印任何传入的字符串"
print("Name: ", name)
print("Age ", age)
return;
#调用printinfo函数
printinfo( age=50, name="miki" );
printinfo( name="miki" );
#=====================================================================#
# 不定长参数
# 你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数,和上述2种参数不同,声明时不会命名。基本语法如下:
# 可写函数说明
def printinfo2( arg1, *vartuple ):
"打印任何传入的参数"
print("输出: ")
print(arg1)
for var in vartuple:
print(var)
return;
# 调用printinfo 函数
printinfo2( 10 );
printinfo2( 70, 60, 50 );
#=====================================================================#
| false
|
4074246e3cb5b70bd035663133ce58f9a68a69b8
|
KaptejnSzyma/pythonexercises
|
/ifChallenge/ifChallenge.py
| 233
| 4.1875
| 4
|
name = input("Please enter your name: ")
age = int(input("Enter your age: "))
if 18 <= age < 31:
# if age <= 18 or age > 31:
print("Welcome to holiday, {}".format(name))
else:
print("Kindly, fuck off {}".format(name))
| true
|
99f672c74e220a309801e670abfed73990a36d9a
|
mepragati/100_days_of_Python
|
/Day 019/TurtleRace.py
| 1,229
| 4.34375
| 4
|
from turtle import Turtle, Screen
import random
is_race_on = False
all_turtles = []
screen = Screen()
screen.setup(width=500,height=400)
color_list = ["red","green","blue","yellow","orange","purple"]
y_position = [-70,-40,-10,20,50,80]
user_input = screen.textinput("Enter here: ","Who do you think will win the race out of (red/green/blue/yellow/orange/purple)? Enter the colour: ").capitalize()
for turtle_count in range(6):
new_turtle = Turtle(shape='turtle')
new_turtle.penup()
new_turtle.goto(x=-230,y=y_position[turtle_count])
new_turtle.color(color_list[turtle_count])
all_turtles.append(new_turtle)
if user_input:
is_race_on = True
while is_race_on:
for turtle in all_turtles:
if turtle.xcor()>230:
is_race_on = False
winning_color = turtle.pencolor()
if winning_color.lower() == user_input.lower():
print(f"You won.The {winning_color.capitalize()} turtle is the winner!")
else:
print(f"You lost.The {winning_color.capitalize()} turtle is the winner and you chose {user_input}!")
random_distance = random.randint(0,10)
turtle.forward(random_distance)
screen.exitonclick()
| true
|
4d3abca3e150456c322d7ea7b2dd276ea5f98d37
|
hyqinloveslife/javabasetest
|
/PythonDemo/com/test.py
| 427
| 4.125
| 4
|
# -*- coding: UTF-8 -*-
'''
Created on 2017年12月7日
@author: 黄叶钦
'''
##循环 将奇数和偶数分开 感觉Python语言好傻,语法太不符合规范了
numbers_ = [12,37,8,65,25]
even =[]
odd = []
while len(numbers_)>0:
element__ = numbers_.pop()
if(element__%2==0):
even.append(element__)
else:
odd.append(element__)
print even
print odd
| false
|
b218e1c5be5716b1b0e645018e64ea2f76a4e593
|
SeyyedMahdiHP/WhiteHatPython
|
/python_note.py
| 1,361
| 4.21875
| 4
|
#PYTHON note
##########################List Slicing: list[start:end:step]######################################
user_args = sys.argv[1:] #sys.argv[1],sys.argv[2],....
#note that sys.argv is a collection or list of stringsT and then with above operation , user_args will be too
user_args = sys.argv[2:4]#sys.argv[2],sys.argv[3],sys.argv[4]
#Suppose you want the last argument (last argument is always -1,second last argument is -2 ,....
#so what is happening here is we start the count from back. So start is last, no end, no step) :
user_args = sys.argv[-1]
#Suppose you want the last two arguments :
user_args = sys.argv[-2:]
#Suppose you want the arguments in reverse order :
user_args = sys.argv[::-1]
#server.accept() output is a collection of {[socket object],[socket(ip,port)]}: (<socket._socketobject object at 0x02E3C998>, ('127.0.0.1', 25129))
#item1,item2,....=collection
client, addr=server.accept()# now we can use client as a socket object, and use addr[0] for ip, and addr[1] is port
#######################################################################
str = "doesn't or dosn\'t" * 10
1j + 3j
list_kharid[1:3]
#['sibzamini', 'mast']
list_kharid[1:3]=["sir"]
list_kharid[:]=[]
list_kharid
#[]
list_kharid.append("goje")
| true
|
77c2de7efe762112bd76127282348f28fa9235f0
|
Nishanky/Know-Your-Age
|
/main.py
| 1,236
| 4.28125
| 4
|
thisyear = 2021
name = input("Hey there! Please Enter your name..")
if name.isnumeric():
print("You entered some numbers instead of your name!!")
exit()
age = 0
try:
age = int(input(f"Hello {name}:)\nEnter your age or year of birth:"))
except ValueError:
print("Enter a numeric value..")
exit()
birth_year = age
if len(str(age)) <= 3:
print("You Entered your age..")
birth_year = thisyear - age
print("Your birth year is:", birth_year)
if birth_year > thisyear:
print("You are not yet born..")
exit()
if thisyear - birth_year > 150:
print("You are oldest person alive!!")
choice = int(input("What you want to know??\n"
"1. When you will turn 100 years old\n"
"2. Your current age\n"
"3. Your age in any particular year"))
if choice == 1:
print("You will turn 100 years old in:", birth_year + 100)
elif choice == 2:
print("Your current age is:", thisyear - birth_year)
elif choice == 3:
year = int(input("Enter the year in which you want to know your age.."))
if year < birth_year:
raise Exception(f"Your were not born in {year}")
print(f"Your age in {year} will be {year - birth_year}")
else:
print("You selected wrong option")
| false
|
74f6bb45f38a8351d3a5b918ca3e571bfaec6441
|
Vlad-Yekat/py-scripts
|
/sort/sort_stack.py
| 454
| 4.15625
| 4
|
# sort stack recursively using only push, pop and isepmpty
def insert(element, stack):
if len(stack) != 0 and element > stack[-1]:
top = stack.pop()
insert(element, stack)
stack.append(top)
else:
stack.append(element)
def stack_sort(stack):
if len(stack) != 0:
top = stack.pop()
stack_sort(stack)
insert(top, stack)
stack = [1, 2, 3, 4]
print(stack)
stack_sort(stack)
print(stack)
| true
|
cfca498a6f0f3f73f698ba67ea6589fac8f7d29d
|
Nithi07/hello_world
|
/sum_of_lists.py
| 335
| 4.375
| 4
|
"""1.(2) Write a python program to find the sum of all numbers in a list"""
def sum_list(numbers):
a = range(numbers)
c = []
for _ in a:
b = int(input('enter your number: '))
c.append(b)
return sum(c)
message = int(input('how many numbers you calculate: '))
print(sum_list(message))
| true
|
809e901bd59261096a299234c7fc7e45d996f5c1
|
Nithi07/hello_world
|
/sum&avg.py
| 336
| 4.15625
| 4
|
""" 8. (3)Given a string, return the sum and average of the digits that appear in the string,
ignoring all other characters
"""
message = input('Enter: ')
a = []
for i in message:
if i.isdigit():
a.append(int(i))
tot = sum(a)
ave = tot / len(a)
print(f'sum of digit: {tot}\n average of digits: {ave}')
| true
|
eb7d3ce1447378e96790b98903528afc3a2efc5f
|
Nithi07/hello_world
|
/div3and5.py
| 437
| 4.25
| 4
|
"""
Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter).
For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20.
"""
def sum (limit):
i = limit + 1
x = range(0, i)
res = []
for num in x:
if num % 3 == 0 or num % 5 == 0:
res.append(num)
return res
message = int(input('upto: '))
print(sum(message))
| true
|
70a74f5c8a7603f20958dea54051eb4b842168a3
|
emellars/euler-sol
|
/019.py
| 1,672
| 4.40625
| 4
|
#Runtime ~0.07s.
#Determines if the year "n" is a leap year.
def is_leap_year(n):
if n % 400 == 0: return True
elif n % 100 == 0: return False
elif n % 4 == 0: return True
else: return False
#Determines if a month started with Sunday.
def month_starting_sunday(days):
if days % 7 == 2: return 1
else: return 0
#1 Jan 1900 begins on a Monday and the year has 365 days. Since 365 % 7 = 1, Jan 1901 must begin on a Tuesday.
#1901 % 7 = 4 corresponds to Tuesday. So we may take the current year (adjusted for leap years) and add the number of days in each month and divide by 7. If the remainder is 2, that month began with a Sunday.
year=1901
remaining_months = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
cumulative_leap_years = 0
cumulative_sundays = 0
while year < 2001:
if is_leap_year(year - 1): cumulative_leap_years += 1
adjusted_year = year + cumulative_leap_years #If the preceding year was a leap year, then, since 365 % 7 = 2, the January of that year starts on a day advanced one more than would be expected if all years were 365 days long.
#Determine if each month of the year started with a Monday.
#January.
if adjusted_year % 7 == 2:
cumulative_sundays += 1
#February.
if is_leap_year(year): number_of_days = 31 + 29
else: number_of_days = 31 + 28
cumulative_sundays += month_starting_sunday(adjusted_year + number_of_days)
#Remaining months in year.
for days in remaining_months:
number_of_days += days
cumulative_sundays += month_starting_sunday(adjusted_year + number_of_days)
year += 1
print(cumulative_sundays)
| true
|
f9398e1f459c0713816924539bd642ba9d206a76
|
sry19/python5001
|
/hw06/turtle_draw.py
| 2,003
| 4.8125
| 5
|
# Author: Ruoyun Sun
# The program uses the star's segment to draw a star and a circle around the
# star
import turtle
import math
TRIANGLE_DEGREE = 180
TAN_18_DEGREE = 0.325
STAR_SEG = 500
COS_18_DEGREE = 0.951
STAR_DEGREE = 36
STAR_SIDE = 5
CIRCLE_ANGLE = 360
def main():
'''give the star's segment, draw a star and a circle around star
None -> None'''
turtle.hideturtle()
radius = STAR_SEG / 2 / COS_18_DEGREE
circle_x, circle_y = 0, -radius
draw_circle(radius, circle_x, circle_y)
star_x, star_y = -STAR_SEG / 2, STAR_SEG / 2 * TAN_18_DEGREE
draw_star(STAR_SEG, star_x, star_y)
turtle.exitonclick()
def draw_circle(radius, circle_x, circle_y):
'''use the radius to draw a circle
radius, x, y -> None'''
CIRCLE_LINE_COLOR = "blue"
CIRCLE_FILL_COLOR = "cyan"
ACCURACY = 400
turtle.color(CIRCLE_LINE_COLOR, CIRCLE_FILL_COLOR)
turtle.penup()
turtle.setposition(circle_x, circle_y)
turtle.pendown()
turtle.begin_fill()
# To simplify, we can use 'turtle.circle(radius)'
circle(radius, CIRCLE_ANGLE, ACCURACY)
turtle.end_fill()
turtle.penup()
def circle(radius, angle, step):
'''draw a circle. angle usually equals 360. The more steps, the more
accurate.
number, number, number -> None'''
distance = 2 * radius * math.sin(angle / CIRCLE_ANGLE / step * math.pi)
for i in range(step):
turtle.left(angle / step)
turtle.forward(distance)
def draw_star(star_seg, star_x, star_y):
'''use the star's segments to draw a star
size, x, y -> None'''
STAR_LINE_COLOR = 'red'
STAR_FILL_COLOR = "yellow"
turtle.pencolor(STAR_LINE_COLOR)
turtle.penup()
turtle.setposition(star_x, star_y)
turtle.pendown()
turtle.fillcolor(STAR_FILL_COLOR)
turtle.begin_fill()
for i in range(STAR_SIDE):
turtle.forward(star_seg)
turtle.right(TRIANGLE_DEGREE - STAR_DEGREE)
turtle.end_fill()
turtle.penup()
main()
| true
|
9d162e4b60638bc81f79889ad5adc8d223fc8f1c
|
STJRush/handycode
|
/Python Basics Loops, Lists, Logic, Quiz etc/time&date/timesDates.py
| 794
| 4.25
| 4
|
from time import sleep
from datetime import datetime
now = datetime.now()
print("The full datetime object from the computer is", now)
print("\n We don't want all that, so we can just pick out parts of the object using strftime. \n")
# It's not necessary to list all of these in your own program, think of this a selection box of delicious
# chocolate chunks of code to choose from.
yearNow = now.strftime("%Y")
print("year:", yearNow)
monthNow = now.strftime("%m")
print("month:", monthNow)
dayOfDaMonth = now.strftime("%d")
print("day:", dayOfDaMonth)
timeNow = now.strftime("%H:%M:%S")
print("time:", timeNow)
hoursNow = now.strftime("%H")
print("hours:", hoursNow)
minsNow = now.strftime("%M")
print("mins:", minsNow)
secsNow = now.strftime("%S")
print("seconds:", secsNow)
| true
|
0b569dc264fb884868bd7d98ebe2ade16b153c1e
|
STJRush/handycode
|
/ALT2 Analytics and Graphing/Live Web Data/openWeatherMapperino.py
| 2,512
| 4.125
| 4
|
# Python program to find current
# weather details of any city
# using openweathermap api
# 0K = 273.15 °C
# import required modules
import requests, json
# Enter your API key here. Uf you're using this in a progect, you should sign up and get your OWN API key. This one is Kevin's.
api_key = "a19c355c905cbcb821b784d45a9cb1de"
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
# Give city name
city_name = "Rush"
# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
# get method of requests module
# return response object
response = requests.get(complete_url)
# json method of response object
# convert json format data into
# python format data
x = response.json()
"""play with this to see the raw, full output from the data stream"""
# print(x)
# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":
# store the value of "main"
# key in variable y
y = x["main"]
#print(y)
# store the value corresponding
# to the "temp" key of y
current_temperature = y["temp"]
# store the value corresponding
# to the "pressure" key of y
current_pressure = y["pressure"]
# store the value corresponding
# to the "humidity" key of y
current_humidiy = y["humidity"]
# store the value of "weather"
# key in variable z
z = x["weather"]
# store the value corresponding
# to the "description" key at
# the 0th index of z
weather_description = z[0]["description"]
# Here are those outputs printed very plainly so that you can use them
print(current_temperature)
print(current_pressure)
print(current_humidiy)
print(weather_description)
# Things to do:
# Displaty the temperature in °C instead of kelvin (subtract 273.15)
# Round this number using: whatYouWant = round(number_to_round, 2) That's 2 decimal places.
# COVID SAFETY ALARM IDEA:
# Run this program on a Raspberri Pi. Use a DHT sensor to measure the actual room temperature indoors.
# Compare the Room Temperature to the Outside Weathermap Temperature. If the room temperature is 23°C and the outside temperature is 4°C then someone is very wrong. There is no way those classroom windows could be open (unless you're burning a fire indoors). You should notify the students in the room with an alarm sound or bright flashy LED lights! They're in a poorly ventilated area!
| true
|
b4f7d2810b41752a75c3c457e44a3af88972dc8b
|
STJRush/handycode
|
/Python Basics Loops, Lists, Logic, Quiz etc/runBetweenHoursOf.py
| 810
| 4.4375
| 4
|
# modified from https://stackoverflow.com/questions/20518122/python-working-out-if-time-now-is-between-two-times
import datetime
def is_hour_between(start, end):
# Get the time now
now = datetime.datetime.now().time()
print("The time now is", now)
# Format the datetime string to just be hours and minutes
time_format = '%H:%M'
# Convert the start and end datetime to just time
start = datetime.datetime.strptime(start, time_format).time()
end = datetime.datetime.strptime(end, time_format).time()
is_between = False
is_between |= start <= now <= end
is_between |= end <= start and (start <= now or now <= end)
return is_between
check = is_hour_between('08:30', '15:30') #spans to the next day
print("time check", check) # result = True
| true
|
76d7ff9b2e77cc3e3b0027c3d816339cd137002a
|
pparaska/pythonAssignments
|
/stringAssignment/stringOfMiddleThreeNumber.py
| 514
| 4.40625
| 4
|
def get_three_middle_characters(given_string):
print('given String is', given_string)
index_of_middle_character = int(len(given_string) / 2)
print(
f'index of middle character is : {index_of_middle_character} and middle character is {given_string[index_of_middle_character]}')
three_middle_characters = given_string[index_of_middle_character - 1:index_of_middle_character + 2]
print('Three middle characters are: ', three_middle_characters)
get_three_middle_characters('JhonDipPeta')
| false
|
273f452623d2bc46108bcf359ab1d02b8d54ddac
|
TheMacte/Py
|
/lesson_2/task_5.py
| 750
| 4.40625
| 4
|
"""
5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно.
Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке.
"""
def tbl(start, stop, cnt=10, string='') -> str:
if start == stop + 1:
return string
else:
if cnt > 0:
if start < 100:
string += ' '
string += f'{start}-"{chr(start)}" '
cnt -= 1
else:
string += '\n'
cnt = 10
start += 1
return tbl(start, stop, cnt, string)
print(tbl(32, 127))
| false
|
1b6c299cc1dfde6fb9049cba1af4b37494123774
|
AyushGupta05/Coding-Lessons
|
/Python/string.py
| 594
| 4.3125
| 4
|
username=input("Please enter your name")
print("Hello",username,"welcome to this class")
print("Hello "+username+ " welcome to this class")
print(f"Hello {username},welcome to this class")
print ("Hello {},welcome to this class".format(username))
#Ways to put a print statement
age=input("Please enter your age")
print("Your age is cofirmed as",age)
print("Your name is",username, "and your age is",age)
print(f"Your name is {username}, and your age is {age}")
print("Your name is {}, and your age is {}".format(username,age))
print("Your name is {1}, and your age is {0}".format(age,username))
| true
|
cd2f045291ce3ce1d0b9c1653752b989fb3a1860
|
jordan-carson/Data_Structures_Algos
|
/HackerRank/staircase.py
| 594
| 4.15625
| 4
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
# get the number of the base
# calculate the number of blank spaces for the first row, (do we need an empty row)
# so if we are at 1 and n = 10 then we need to print 1 '#' while also printing 9 ' '
for i in range(1, n+1):
print(' ' * (n-i) + '#' * i)
# for i in range(1, n+1):
# print(' '*(n-i) + '#'*i)
# [print(' '*(n-i) + '#'*i) for i in range(1,n+1)]
if __name__ == '__main__':
n = int(input())
staircase(n)
| true
|
a6ee152b820fa607e090e0d5c44a8f8e854fb190
|
jordan-carson/Data_Structures_Algos
|
/Udacity/1. Data Structures/0. Strings/anagram_checker.py
| 1,085
| 4.28125
| 4
|
# Code
def anagram_checker(str1, str2):
"""
Check if the input strings are anagrams of each other
Args:
str1(string),str2(string): Strings to be checked
Returns:
bool: Indicates whether strings are anagrams
"""
if len(str1) != len(str2):
# remove the spaces and lower the strings
str1_update = str1.replace(' ', '').lower()
str2_update = str2.replace(' ', '').lower()
if len(str1_update) == len(str2_update):
if ''.join(sorted(str1_update)) == ''.join(sorted(str2_update)):
return True
return False
if __name__ == '__main__':
# Test Cases
print("Pass" if not (anagram_checker('water', 'waiter')) else "Fail")
print("Pass" if anagram_checker('Dormitory', 'Dirty room') else "Fail")
print("Pass" if anagram_checker('Slot machines', 'Cash lost in me') else "Fail")
print("Pass" if not (anagram_checker('A gentleman', 'Elegant men')) else "Fail")
print("Pass" if anagram_checker('Time and tide wait for no man', 'Notified madman into water') else "Fail")
| true
|
a5e5305b4997a6fa42444dc521c311506558fbfc
|
jordan-carson/Data_Structures_Algos
|
/HackerRank/30daysofcode/day3.py
| 837
| 4.40625
| 4
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
# Complete the stub code provided in your editor to print whether or not is weird.
def isOdd(n):
return n % 2 != 0
def isEven(n):
return n % 2 == 0
def solution(inp):
N = inp
if isOdd(N):
print('Weird')
elif isEven(N) and N >= 2 and N <= 5:
print('Not Weird')
elif isEven(N) and N >= 6 and N <= 20:
print('Weird')
elif isEven(N) and N > 20:
print('Not Weird')
if __name__ == '__main__':
N = int(input())
solution(N)
| true
|
7ee8d81ca6f796c8a6934e30ac80873de2d9034b
|
jordan-carson/Data_Structures_Algos
|
/Udacity/0. Introduction/Project 1/Task4.py
| 1,575
| 4.21875
| 4
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
# Declare variables
PRINT_MSG_4 = """These numbers could be telemarketers: """
incoming_calls, incoming_texts, outgoing_calls, outgoing_texts = set(), set(), set(), set()
def print_task4(print_msg, list_of_numbers, formatter=52):
print(print_msg)
for i in list_of_numbers: print(i)
for call in calls:
outgoing_calls.add(call[0])
incoming_calls.add(call[1])
for text in texts:
outgoing_texts.add(text[0])
incoming_texts.add(text[1])
if __name__ == '__main__':
# final_set = {element for element in incoming_calls if element not in outgoing_calls and element not in outgoing_texts and element not in incoming_texts}
final_list = list(sorted(outgoing_calls - (incoming_calls | incoming_texts | outgoing_texts))) # set difference = outgoing_calls - incoming_calls - incoming_texts - outgoing_texts
print_task4(PRINT_MSG_4, final_list)
| true
|
7bf93a3bc135b7981e7d51910f7bbd78a745a0bf
|
jordan-carson/Data_Structures_Algos
|
/Coursera/1. AlgorithmicToolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.py
| 1,951
| 4.21875
| 4
|
# Uses python3
from sys import stdin
import time
## a simple Fibonacci number genarator
def get_next_fib():
previous, current = 0, 1
yield previous
yield current
while True:
previous, current = current, previous + current
yield current
## find the Pisano sequence for any given number
## https://en.wikipedia.org/wiki/Pisano_period
"""
In number theory, the nth Pisano period, written π(n),
is the period with which the sequence of Fibonacci numbers taken modulo n repeats
"""
def get_pisano_seq(m):
def check(candidate):
middle = len(candidate) // 2
if middle == 0:
return False
for i in range(middle):
if candidate[i] != candidate[middle + i]:
return False
return True
seq = []
for fib in get_next_fib():
seq.append(fib % m)
if (len(seq) % 2):
if check(seq):
return seq[:len(seq) // 2]
## get the last digits of the n-th and (n+1)-th Fib number
## by using the Pisano sequence for 10
def get_last_digits(n):
seq = get_pisano_seq(10)
return seq[n % len(seq)], seq[(n+1) % len(seq)]
## calculate the last digit of the sum of squared Fib numbers
## by using that F0^2+F1^2+.....+Fn^2 = Fn * F(n+1)
## https://math.stackexchange.com/questions/2469236/prove-that-sum-of-the-square-of-fibonacci-numbers-from-1-to-n-is-equal-to-the-nt
def fibonacci_sum_squares_naive(n):
previous, current = get_last_digits(n)
return (previous * current) % 10
# def fibonacci_sum_squares_naive(n):
# if (n <= 0):
# return 0
#
# fibo = [0] * (n + 1)
# fibo[1] = 1
#
# # Initialize result
# sm = fibo[0] + fibo[1]
#
# # Add remaining terms
# for i in range(2, n + 1):
# fibo[i] = fibo[i - 1] + fibo[i - 2]
# sm = sm + fibo[i]
#
# return sm
if __name__ == '__main__':
n = int(stdin.read())
print(fibonacci_sum_squares_naive(n))
| true
|
6829e40eebf18276067138b8e59cb87c3a091073
|
jordan-carson/Data_Structures_Algos
|
/Udacity/1. Data Structures/5. Recursion/staircase.py
| 609
| 4.375
| 4
|
def staircase(n):
"""
Write a function that returns the number of steps you can climb a staircase that
has n steps.
You can climb in either 3 steps, 2 steps or 1 step.
Example:
n = 3
output = 4
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
4. 3 steps
"""
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 4
return staircase(n - 1) + staircase(n - 2) + staircase(n - 3)
if __name__ == '__main__':
print(staircase(4) == 7)
print(staircase(3) == 4)
| true
|
fcd90e605a660a2a6190b8a28411c943adfc8ac5
|
cleelee097/MIS3640
|
/Session06/calc.py
| 2,695
| 4.1875
| 4
|
# age = input('please enter your age:')
# if int(age) >= 18:
# print('adult')
# elif int(age) >=6:
# print('teenager')
# else:
# print('kid')
# if x == y:
# print('x and y are equal')
# else:
# if x < y:
# print('x is less than y')
# else:
# print('x is greater than y')
# import webbrowser
# def calculate_bmi(weight, height):
# bmi=weight/(height*hegiht)
# if bmi<=18.5:
# print("your bmi is {:.1f}. You are underweighted.".format (bmi))
# elif 18.5 < bmi <= 25:
# print('y')
# print('Overweight')
# elif 18.5<=int(bmi)<=24.9:
# print('Normal weight')
# else:
# print('underweight')
# 2. Assume that two variables, varA and varB, are assigned values, either numbers or strings.
# Write a piece of Python code that prints out one of the following messages:
# "string involved" if either varA or varB are strings
# "bigger" if varA is larger than varB
# "equal" if varA is equal to varB
# "smaller" if varA is smaller than varB
def compare(varA, varB):
if isinstnace(varA, str) or isinstance(varB, str):
print('string involved')
else:
if varA > varB:
print('bigger')
elif varA==varB:
print('equal')
else:
print('smaller')
a='hello'
b=3
c=5
compare(a,b)
compare(b,c)
def diff21(n):
if n<=21:
return 21-n
else:
return (n-21)*2
#hen squirrels get together for a party, they like to have cigars.
# A squirrel party is successful when the number of cigars is between 40 and 60, inclusive.
# Unless it is the weekend, in which case there is no upper bound on the number of cigars.
# Return True if the party with the given values is successful, or False otherwise.
return is_weekend and cigars >=40 or 40 <=cigars <=60
print(cigar_party(30,False)) #False
print(cigar_party(50,False)) #True
print(cigar_party(70,False))#True
# def cigar_party(cigars, is_weekend):
# if is_weekend and cigars
# return True
# else:
# if 40<=cigars<=60:
# return True
# else:
# return False
print(cigar_party(30,False)) #False
print(cigar_party(50,False)) #True
print(cigar_party(70,False))#True
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(5)
def print_n(s, n):
if n <= 0:
return
print(s)
print_n(s, n-1)
#countdown(5)
def fabonacci(n):
if n == 1 or n == 2:
return 1
return fabonacci(n-2) + fabonacci(n-1)
# print(fabonacci(6))
# print(fabonacci(2))
def factorial(n):
if n == 1:
return 1
else:
return factorial(n-1)*n
print(factorial(3))
| true
|
2f5d0a2673e142b6753b704659fef639b0b586d3
|
JdeH/LightOn
|
/LightOn/prog/pong/pong4.py
| 2,526
| 4.125
| 4
|
class Attribute: # Attribute in the gaming sense of the word, rather than of an object
def __init__ (self, game):
self.game = game # Done in a central place now
self.game.attributes.append (self) # Insert each attribute into a list held by the game
# ============ Standard interface starts here
def reset (self):
pass
def predict (self):
pass
def interact (self):
pass
def commit (self):
pass
# ============ Standard interface ends here
class Sprite (Attribute): # Here, a sprite is an rectangularly shaped attribute that can move
def __init__ (self, game, width, height):
self.width = width
self.height = height
Attribute.__init__ (self, game) # Call parent constructor to set game attribute
class Paddle (Sprite):
width = 10 # Constants are defined per class, rather than per individual object
height = 100 # since they are the same for all objects of that class
# They are defined BEFORE the __init__, not INSIDE it
def __init__ (self, game, index):
self.index = index # Paddle knows its player index, 0 == left, 1 == right
Sprite.__init__ (self, game, self.width, self.height)
class Ball (Sprite):
side = 8
def __init__ (self, game):
Sprite.__init__ (self, game, self.side, self.side)
class Scoreboard (Attribute): # The scoreboard doesn't move, so it's an attribute but not a sprite
pass
class Game:
def __init__ (self):
self.attributes = [] # All attributes will insert themselves into this polymorphic list
self.paddles = [Paddle (self, index) for index in range (2)]
self.ball = Ball (self)
self.scoreboard = Scoreboard (self)
for attribute in self.attributes:
attribute.reset ()
def update (self): # To be called cyclically by game engine
for attribute in self.attributes: # Compute predicted values
attribute.predict ()
for attribute in self.attributes: # Correct values for bouncing and scoring
attribute.interact ()
for attribute in self.attributes: # Commit them to game engine for display
attribute.commit ()
game = Game () # Create and run game
| true
|
e9be930cb5bf1cab43b288ccb2b68d0d8f1dd003
|
felipeng/python-exercises
|
/12.py
| 370
| 4.34375
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
'''
a = [5, 10, 15, 20, 25]
def first_last(list):
return [list[0], list[-1]]
print(first_last(a))
| true
|
25c85e50548c1d465bdccb3e396f3c98b1f74c4c
|
felipeng/python-exercises
|
/11.py
| 615
| 4.25
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten,
a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you.
Take this opportunity to practice using functions, described below.
'''
n = raw_input("Number: ")
n = int(n)
def prime(n):
c = []
for x in range(2,n):
if (n % x) == 0:
c.append(x)
if len(c) != 0:
r = " NOT"
else:
r = ""
print("The number {} is{} prime.".format(n,r))
prime(n)
| true
|
d38a0334a8851b5e69809e73aef8cc758ea0e9a6
|
harrytouche/project-euler
|
/023/main.py
| 2,669
| 4.1875
| 4
|
"""
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
"""
from functools import reduce
import math
import numpy as np
def SumOfTwoNumbers(a, b):
return a + b
def SumOfDivisorsOfNumber(n):
output = []
max_iteration = math.ceil(n / 2) + 1
for i in range(1, max_iteration):
if n % i == 0:
if i not in output:
output.append(i)
# only append the other factor if no the sqrt
if i ** 2 != n and int(n / i) != n and int(n / i) not in output:
output.append(int(n / i))
return reduce(SumOfTwoNumbers, output)
def GetAbundantNumbersUpToN(n):
abundant_numbers_ceiling = n
abundant_numbers = []
for i in range(1, abundant_numbers_ceiling + 1):
if SumOfDivisorsOfNumber(i) > i:
abundant_numbers.append(i)
return abundant_numbers
abundant_max = 28123
try:
print(
"There are {} abundant numbers up to {}".format(
len(abundant_numbers), abundant_max
)
)
except Exception:
abundant_numbers = GetAbundantNumbersUpToN(abundant_max)
# create matrix of all abundant number sums
matrix = np.zeros((len(abundant_numbers), len(abundant_numbers)), dtype=int)
for i in range(len(abundant_numbers)):
for j in range(len(abundant_numbers)):
new_addition = abundant_numbers[i] + abundant_numbers[j]
if new_addition < abundant_max:
matrix[i, j] = new_addition
# get the uniques and sum, then take from the sum of all numbers
unique_sums = list(np.unique(matrix))
unique_sums_sum = reduce(SumOfTwoNumbers, unique_sums)
sum_of_all_numbers_to_abundant_max = reduce(SumOfTwoNumbers, range(abundant_max))
difference = sum_of_all_numbers_to_abundant_max - unique_sums_sum
print(difference)
| true
|
69c35b2065585d91bb59322b28d0664df638d254
|
harrytouche/project-euler
|
/009/main.py
| 733
| 4.21875
| 4
|
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
a + b + c = 1000
a**2 + b**2 = c**2
"""
sum_number = 1000
complete = 0
loop_max = sum_number
for a in range(1, loop_max):
for b in range(1, loop_max - a):
# c is defined once a and b are
c = loop_max - a - b
if (a ** 2 + b ** 2) == c ** 2:
print("Found! a={}, b={}, c={}".format(a, b, c))
print("Product is: {}".format(a * b * c))
complete = 1
if complete == 1:
break
if complete == 1:
break
| true
|
6a9c0f0926fa39305376a3632ef442fb4062c2c3
|
harrytouche/project-euler
|
/019/main.py
| 933
| 4.25
| 4
|
"""
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
from datetime import date
min_year = 1901
max_year = 2000
n_sundays_as_firsts = 0
for i in range(min_year, max_year + 1):
for j in range(1, 13):
current_date = date(i, j, 1)
if current_date.weekday() == 6:
n_sundays_as_firsts += 1
print(
"There were {} Sundays as first of months between the years {} and {}".format(
n_sundays_as_firsts, min_year, max_year
)
)
| true
|
7b42438ae5b38d28c48a7150b74fc91ad645a6b3
|
vonzhou/py-learn
|
/byte-python/chapter8/func_param.py
| 239
| 4.21875
| 4
|
def print_max(a,b):
if (a>b):
print a,'is bigger'
elif (a==b):
print a, 'is equal to ',b
else:
print b, 'is bigger'
print_max(34, 87)
print_max(34, 8)
print_max(87, 87)
x = 0
y = -3
print_max(x, y)
| false
|
560cfe8aacfa94fe1c35a6b33a68b61648424f3b
|
k64pony/Module7
|
/Module7.py
| 1,016
| 4.21875
| 4
|
#Assignment 1
import sys
import datetime
data = datetime.datetime.now()
print("The current datetime is: ")
print(data)
#Assignment 2
import sys
import datetime
from datetime import timedelta
dt = datetime.datetime.now()
addyears = datetime.timedelta(days=730)
minussecs = datetime.timedelta(seconds = 60)
date = dt+addyears-minussecs
print("The timedelta of current date plus two years minus 60 seconds is: ")
print(date)
#Assignment 3
import sys
import datetime
from datetime import timedelta
d = timedelta(days = 100, hours = 10, minutes = 13)
(d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)
print("The timedelta object for 100 days, 10 hours and 13 minutes is: ")
print(d)
#Assignment 4
import sys
import datetime
from datetime import date
def currentage(birthDate):
today = datetime.datetime.now()
age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day))
return age
print("My current age is: ")
print(currentage(date(1977, 12, 20)), "years old")
| false
|
1d0985e745bd74bd9b5eced8947242e0629649e0
|
NamanManocha/HeapApplications
|
/FindNumber.py
| 687
| 4.125
| 4
|
''' O(m+n)-time algorithm to determine whether a given number is stored in a given m×n Young tableau. '''
def search(list_search,element):
for i in range(0,len(list_search)):
if list_search[i][0] == element:
return 1;
elif list_search[i][0] > element:
row = i-1
break;
else:
row = i
for j in range(0,len(list_search[0])):
if list_search[row][j] == element:
return 1;
return 0;
list_search = [[1,2,3],[4,5,6],[8,9,10],[11,12,13]]
result = search(list_search,8)
if result == 0:
print("Element Not Found")
elif result == 1:
print("Element Found")
| false
|
e4eee2f6325eb055064b9f94c82eb278296e7c03
|
Parnit-Kaur/Learning_Resources
|
/Basic Arithmetic/fibonacci.py
| 237
| 4.28125
| 4
|
print("Enter the number till you want fibonacci series")
n = int(input())
a = 1
b = 1
print("The fibonacci sequence will be")
print(a)
print(b)
for i in range(2, n):
fibonacci = a + b
b = a
a = fibonacci
print(fibonacci)
| true
|
39dfeeb264d7dc50e7c7acd992e442b789dcf029
|
bnewton125/MIT-OpenCourseWare
|
/6.0001/ps4/ps4a_edited.py
| 2,539
| 4.1875
| 4
|
# Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
def permute(seq, perm):
if len(seq) < 1: # Out of letters to permute so stop recursion
return
else: # still have letters to permute through so continue recursion
if len(perm) == 0: # basically a first letter check
perm.append(seq[0]) # only permutation of the first letter are that letter
else: # for each different permutation fill
perms_copy = perm.copy() # create a copy of perms so perms can be emptied
perm.clear() # empty perms
for word in perms_copy: # for each existing word in perms fill out permutations into perms
for letters in range(len(word)+1):
if letters == 0:
perm.append(str(seq[0] + word))
elif letters == len(word)+1:
perm.append(str(word + seq[0]))
else:
perm.append(str(word[:letters] + seq[0] + word[letters:]))
permute(seq[1:], perm) # recurse with the first letter ripped out
permutations = []
permute(sequence, permutations)
return permutations
if __name__ == '__main__':
#EXAMPLE
example_input = 'cba'
print('Input:', example_input)
print('Expected Output:', ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'])
print('Actual Output:', get_permutations(example_input))
print('')
example_input = 'xyz'
print('Input:', example_input)
print('Expected Output:', ['zyx', 'yzx', 'yxz', 'zxy', 'xzy', 'xyz'])
print('Actual Output:', get_permutations(example_input))
print('')
example_input = 'mno'
print('Input:', example_input)
print('Expected Output:', ['onm', 'nom', 'nmo', 'omn', 'mon', 'mno'])
print('Actual Output:', get_permutations(example_input))
| true
|
99b08d79c104a1995e201ff2cccae06b131a6ee6
|
mareliefi/learning-python
|
/calendar.py
| 1,977
| 4.40625
| 4
|
# This is a calender keeping track of events and setting reminders for the user in an interactive way
from time import sleep,strftime
your_name = raw_input("Please enter your name: ")
calender = {}
def welcome():
print "Welcome " + your_name
print "Calender is opening"
print strftime("%A, %B, %d, %Y")
print strftime("%H:%M:%S")
sleep(1)
print "What would you like to do?"
def start_calender():
welcome()
start = True
while start == True:
user_choice = raw_input("Please enter A to Add, U to Update, V to View , D to Delete and X to Exit")
user_choice = user_choice.upper()
if user_choice =="V":
if len(calender.keys()) < 1:
print "Calender is empty"
else:
print calender
elif user_choice == "U":
date = raw_input("What date? ")
update = raw_input("Enter the update: ")
calender[date] = update
print "Update successful!"
print calender
elif user_choice == "A":
event = raw_input("Enter event: ")
date = raw_input("Enter date (MM/DD/YYYY)")
if len(date) > 10 or len(date) < 10 or int(date[6:]) < int(strftime("%Y")):
print "Invalid date was entered"
try_again = raw_input("Try Again? Y for Yes, N for No: ")
try_again = try_again.upper()
if try_again == "Y":
continue
else:
start = False
else:
calender[date] = event
print "Event was successfully added."
elif user_choice == "D":
if len(calender.keys()) < 1:
print "Calender is empty"
else:
event = raw_input("What event? ")
for date in calender.keys():
if event == calender[date]:
del calender[date]
print "Event was successfully deleted"
else:
print "Incorrect event was specified"
elif user_choice == "X":
start = False
else:
print "Invalid command was entered"
exit()
start_calender()
| true
|
23b21cec45b892ff56c982f21ec07b78d61b9c87
|
borisBelloc/onlineChallenges_Algorithms_RecruitmentTests
|
/Algorithms/sort_on_the_fly.py
| 305
| 4.1875
| 4
|
# Sort on the fly
# we ask user 3 numbers and we sort them as they arrive
lst = []
while len(lst) < 3:
value = int(input("enter one number (sort on the fly) :\n"))
i = 0
while i < len(lst) and value > lst[i]:
i += 1
lst.insert(i, value)
print("here is the sorted array {}\n".format(lst))
| true
|
95e140f15ce99d2d718b65cf751b14e7b3333684
|
mattheuslima/Projetos-Curso_Python
|
/Aulas/Aula 17.py
| 1,565
| 5.03125
| 5
|
'''Lista
Listas são declaradas através de colchetes.
Diferente das tuplas, listas são mutáveis.
Existem 2 métodos para adicionar um elemento a uma lista:
".append": Com ele você adiciona um elemento sempre ao fim da lista. Ex.: lista.append('Carro')
".insert": Com ele você consegue especificar em que posição da lista você quer adicionar tal elemento. Ex.:lista.insert(1,'Carro')
Para apagar elementos, existem 3 forma:
Comando del: Ex.: del lista[3]
método pop: Esse método geralmente é utilizado para apagar o último elemento, mas você também pode passar a posição na lista. Ex.: lista.pop(3) ou lista.pop() para eliminar o último elemento.
método remove: Esse método é utilizado para eleminar através do valor.É recomendado para quando não se sabe o índice. Ex.: lista.remove('Carro')
'''
lista=[1,2,3,15,71,17,25]
lista.sort(reverse=True)
print(lista)
lista.pop()
print(f'After pop {lista}')
lista.append(113)
lista.sort(reverse=True)
print(f'After append {lista}')
lista.insert(0,'Números inteiros:')
print(f'After insert {lista}.\n')
for c,v in enumerate(lista):
print(f'Na posição {c} eu encontrei {v}')
print('Fim da lista')
'''A linguagem python possui uma particularidade para criar uma cópia de uma lista.
Se você utilizar a lógica, listaB = listaA, Você estará estabelecendo uma ligação entre as listas e não criando uma cópia.
Se um elemento da suposta lista cópia for alterado, a lista mãe tera o elemento alterado também.
Para fazer a cópia, o comando correto seria: listaB = listaA[:]'''
| false
|
5497cec2acba334140863086e3c590a621324b2d
|
mattheuslima/Projetos-Curso_Python
|
/Exercícios/Ex.37.py
| 792
| 4.1875
| 4
|
#Escreva um programa que leia um numero inteiro qualquer e peça para escolher qual será a base de conversão: binário,octal ou hexadecimal
#Header
print('{:=^38}'.format('Desafio 37'))
print('='*5,'Conversor de base numérica','='*5)
#Survey
num=int(input('Digite um número inteiro: '))
print('''Escolha uma das bases para conversão:
[ 1 ] Converter para BINÁRIO
[ 2 ] Converter para OCTAL
[ 3 ] Converter para HEXADECIMAL''')
option=int(input('\nQual sua opção? '))
if option==1:
print('\n{} convertetido para BINÁRIO é {}'.format(num,bin(num)[2:]))
elif option==2:
print('\n{} convertido par OCTAL é {}'.format(num,oct(num)[2:]))
elif option==3:
print('\n{} convertido para HEXADECIMAL é {}'.format(num,hex(num))[2:])
else :
print('\nOpção inválida.')
| false
|
93dc0a880bf9d61481d40f0e9f49e7e2e034d8d2
|
cg342/iWriter
|
/start.py
| 1,728
| 4.21875
| 4
|
'''
https://hashedin.com/blog/how-to-convert-different-language-audio-to-text-using-python/
Step 1: Import speech_recognition as speechRecognition. #import library
Step 2: speechRecognition.Recognizer() # Initializing recognizer class in order to recognize the speech. We are using google speech recognition.
Step 3: recogniser.recognize_google(audio_text) # Converting audio transcripts into text.
Step 4: Converting specific language audio to text.
'''
import speech_recognition as sr
r = sr.Recognizer()
def getLanguage(argument):
switcher = {
1: "en-IN",
2: "hi-IN",
3: "kn-IN"
}
return switcher.get(argument, 0)
def getSelection():
try:
userInput = int(input())
if (userInput<1 or userInput>3):
print("Not an integer! Try again.")
except ValueError:
print("not an integer! Try again.")
else:
return userInput
# Reading Audio File as source
# output stored in audio_text variable
def startConvertion(path, lang = 'en-IN'):
with sr.AudioFile(path) as source:
print('Fetching File')
audio_text = r.listen(source)
try:
print('Converting audio transcripts into text ...')
text = r.recognize_google(audio_text, language = lang)
print(text)
# print("hello how are you")
except:
print('Sorry.. run again...')
# if __name__ == '__main__':
# print('Please Select Language: ')
# print('1. English')
# print('2. Chinese')
# languageSelection = getLanguage(getSelection())
# startConvertion('sample.m4a', languageSelection)
print(startConvertion('sample2.wav','en-IN'))
| true
|
f06d11254eda94677d3d723852e6b214222bd85a
|
BlissfulBlue/linux_cprogramming
|
/sample_population_deviation.py
| 1,550
| 4.4375
| 4
|
# Number values in the survey
survey = [10, 12, 6, 11, 8, 13]
# sorts numbers into ascending order and prints it out
survey.sort()
print(f"The order from lowest to highest: {survey}")
# assigns variable number of values in the list and prints
list_length = (len(survey))
print(f"There are {list_length} values in the list.")
# calculates the mean by sum of list / number of values and prints it out
mean = sum(survey) / (len(survey))
print(f"The mean is {mean}\n")
# takes each individual number, subtracts by mean, squares it, and prints it
subtract_xbar = []
for value in survey:
subtract_xbar.append(value - mean)
squared = []
for deviation in subtract_xbar:
squared.append(deviation ** 2)
print(f"Before squaring: {subtract_xbar}")
print(f"After squaring: {squared} (Worry about this part)")
print()
# adds the sum of all squared numbers and print as integer
sigma = sum(squared)
print((f"Sum of list after squaring: {sigma}"))
# divide sigma (sum of all squared values) by len(squared) (number of values in list: squared), then square root it, and print it.
import math
#################################
# uncomment for sample deviation
sample_dev = len(survey) - 1
print(f"n - 1 = {sample_dev} (To understand, look at formula)")
print()
Nminus1_divide = sigma / sample_dev
print("Answer:\n")
print(math.sqrt(Nminus1_divide))
#################################
# uncomment for population deviation
# n_divide = sigma / len(survey)
# print(math.sqrt(n_divide))
| true
|
c443f35ec994c303b74cd3a8000f5a7ed751a027
|
bhushan5890/My_new_repo
|
/My_new_repo/check_palindrome.py
| 433
| 4.28125
| 4
|
# Python code to check palindrome
def check_palindrome(ip_string):
ip_string = ip_string.replace(' ', '')
return ip_string == ip_string[::-1]
if __name__ == "__main__":
input_string = input("Enter the string to be validated-Case sensetive : ")
if check_palindrome(input_string) == True:
print(f'String {input_string} is a Palindrome')
else:
print(f'String {input_string} is not a Palindrome')
| false
|
119af8834d42cf7fae4effba7fb229b0e42983c6
|
Pratik-sys/code-and-learn
|
/Modules/sorted_random_list.py
| 620
| 4.25
| 4
|
#!/usr/bin/python3
# Get a sorted list of random integers with unique elements
# Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end.
"""
Input: num:10, start:100, end:200
Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180]
Input: num:5, start:1, end:100
Output: [37, 49, 64, 84, 95]
"""
import random
def sorted_random(num, start, end):
'''
To-do: Change a default value to the desirable value
start < end, always
'''
return sorted(random.randint(start, end) for i in range(num))
print(sorted_random(10, 1, 200))
| true
|
b2d11e2223b46cce0f39978d561dd96bead9e03c
|
Pratik-sys/code-and-learn
|
/Modules/password_gen.py
| 2,736
| 4.25
| 4
|
#!/usr/bin/python3
# Write a password generator in Python.
# Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols.
# The passwords should be random, generating a new password every time the user asks for a new password.
"""
No test cases.
This question is left open-ended as it may vary various implemention.
Using two or more different modules is allowed.
"""
import random
def generate_password(digits, low_case, up_case, symbol):
# combine the characters from the arrya that has been passed.
combine_cahr = digits + low_case + up_case + symbol
# randomly select atleast one char from each array.
rand_digit = random.choice(digits)
rand_upper_char = random.choice(low_case)
rand_lower_char = random.choice(up_case)
rand_symbol = random.choice(symbol)
# combine the each character driven from above
temp_pass = rand_digit + rand_upper_char + rand_lower_char + rand_symbol
password = temp_pass + random.choice(combine_cahr)
return (f'"{password}" is the random generated password')
print(
generate_password(
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
[
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
],
[
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"M",
"N",
"O",
"p",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
],
["@", "#", "$", "%", "=", ":", "?", ".", "/", "|", "~", ">", "*", "(", ")"],
)
)
import secrets
import string
'''
The secrets module is used for generating random numbers for managing important data such as passwords, account authentication, security tokens, and related secrets, that are cryptographically strong.
'''
def gen_password():
alphabets = string.ascii_letters + string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
password = ''.join (secrets.choice(alphabets) for i in range(10))
return password
print(f'"{gen_password()}" is the random generated password')
| true
|
7b6e3af7a399d49e8cc7979d658c3dfe7e4349cc
|
Pratik-sys/code-and-learn
|
/Recursion/Fibonacci/fibonacci_using_recursion.py
| 535
| 4.15625
| 4
|
#!/usr/bin/python3
# Write a function int fib(int n) that returns Fn. For example, if n = 0, then fib() should return 0. If n = 1, then it should return 1. For n > 1, it should return Fn-1 + Fn-2.
"""
Input: 9
Output : 34
"""
# Solution: Method 1 ( Use recursion )
def fib(n):
"""
This function returns the the fibonaaci number
"""
if n < 0:
print("we don't do that here")
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
print(fib(9))
| true
|
9cf37d2ecef5737c12ba23a5e6b99a0380c051ef
|
Pratik-sys/code-and-learn
|
/Dictionary/winner.py
| 1,350
| 4.15625
| 4
|
# Given an array of names of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidates received Max vote. If there is tie, print lexicographically smaller name.
# Check lexographically smaller/greater on wiki.
"""
Input : votes[] = {"john", "johnny", "jackie",
"johnny", "john", "jackie",
"jamie", "jamie", "john",
"johnny", "jamie", "johnny",
"john"};
Output : 'john'
We have four Candidates with name as
'John', 'Johnny', 'jamie', 'jackie'.
The candidates John and Johny get maximum votes.
Since John is alphabetically smaller, we print it.
"""
from collections import Counter
def winner(voters):
vote_name = Counter(voters)
name_vote = {}
for value in vote_name.values():
name_vote[value] = []
for key, value in vote_name.items():
name_vote[value].append(key)
winner_value = sorted(name_vote, reverse=True)[0]
winner_name = sorted(name_vote[winner_value])[0]
print(f' The winner is {winner_name}')
winner(
[
"john",
"johnny",
"jackie",
"johnny",
"john",
"jackie",
"jamie",
"jamie",
"john",
"johnny",
"jamie",
"johnny",
"john",
]
)
| true
|
73830104de32918b17b0ed1061b60a1d10a186c0
|
caronaka/ParadigmasIFTS2020
|
/CLASE2/funcionlambda.py
| 581
| 4.21875
| 4
|
#LAMBDA
# son funciones matematicas y anonimas
# no le tenes que poner nombre
# o usarla sin nombrarla
#si la funcion la vas a usar mucho, conviene nombrarla con def
#
# no funciona con funciones muy largas
# hay que reducirlas a una linea de codigo
# si requiere mas, yo no podemos usar lambda
#
# SIMPLIFICANDO
def doblar (num): #asi lo veniamos haciendo
resultado = num*2
return resultado
#
print(doblar(2))
#
def doblar(num):
return num*2
#
# #lambda num: num*2
doblar2 = lambda num: num*2
print(doblar2(2))
#LAMBDA nombredelparametro : lo que queremos devolver
| false
|
10f55cdc4a5acee3e1ece322810f64f1f30ecd25
|
RealMirage/Portfolio
|
/Python/ProjectEuler/Problem1.py
| 637
| 4.28125
| 4
|
'''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
# List comprehension method
def solve_with_lc():
numbers = range(1000)
answer = sum([x for x in numbers if x % 3 == 0 or x % 5 == 0])
print(answer)
# Simpler method
def solve_simply():
numbers = range(1000)
answer = 0
for number in numbers:
if number % 3 == 0 or number % 5 == 0:
answer = answer + number
print(answer)
if __name__ == '__main__':
solve_with_lc()
solve_simply()
| true
|
16e5b1ca44fb64f6c79bf8afeb956963ec6fa4a1
|
Danish15/TalkPythonTraining
|
/apps/03_birthday/you_try/program.py
| 1,022
| 4.34375
| 4
|
import datetime
def print_header():
print('-----------------------')
print('BIRTHDAY APP')
print('-----------------------')
print()
def get_birthday_from_user():
print('Tell us when you were born: ')
year = int(input('Year [YYYY]: '))
month = int(input('Month [MM]: '))
day = int(input('Day [DD]: '))
birthday= datetime.datetime(year, month, day)
return birthday
def compute_days_between_dates(original_date, now):
date1 = now
date2 = datetime.datetime(now.year, original_date.month, original_date.day)
dt = date1 - date2
days = int(dt.total_seconds() / 60 / 60 / 24)
return days
def print_birthday_information(days):
if days < 0:
print('your bday is in {} days!'.format(-days))
elif days > 0:
print('you had your bday already this year {} days ago'.format(days))
else:
print('happy bday!!')
def main():
print_header()
bday = get_birthday_from_user()
now = datetime.datetime.now()
number_of_days= compute_days_between_dates(bday, now)
print_birthday_information(number_of_days)
main()
| false
|
c53a436856008c3a632339f8267823e990d7dcbe
|
syudaev/lesson01
|
/lesson01_task01.py
| 1,910
| 4.21875
| 4
|
# переменные, запрос ввода чисел и строк, сохранение в переменные, вывод на экран,
# форматирование строки ( f, %, format() )
# функция проверки строковых переменных на ввод чисел, чтобы избежать ошибок при вводе
def chek_numeric(user_str):
if user_str.isdigit():
return 0
else:
try:
float(user_str)
return 1
except ValueError:
return 2
my_integer = 13
my_float = 33.2145
my_string = "Начинаем осваивать Python: "
print(f"f-строки: {my_integer:>8} {my_float:>10} {my_string}")
print("метод format(): {2} {0:>10} {1:>10} {3:>10.4f}".format(my_integer, my_float, my_string, my_integer / my_float))
print("метод оператор: %-35s %-7d %.2f" % (my_string, my_integer, my_float))
while True:
user_integer = input("Введите целое число >>>")
if chek_numeric(user_integer) == 0:
user_integer = int(user_integer)
break
else:
print("Это не целое число, повторите ввод!")
continue
while True:
user_float = input("Введите дробное число >>>")
if chek_numeric(user_float) == 1:
user_float = float(user_float)
break
else:
print("Это не число c плавающей запятой!")
continue
user_string = input("Введите строку приветствия:")
print(user_integer, user_float, user_string)
print(f'Делим целое число на число с плавающей запятой, 40 знаков: {(user_integer / user_float):.40f}')
print(f"2 знака: {user_integer} / {user_float} = {(user_integer / user_float):.2f}")
| false
|
7ec6facac795aff55fc277f331fe57fcaf63d312
|
juliusortiz/PythonTuts
|
/ListAndTuplesTutorial.py
| 1,405
| 4.28125
| 4
|
# #+INDEX - 0 1 2
# courses = ["BSIT","BSCS","BLIS","BA","ACS","BSCS","BSIT"]
#
# #Range selection
# print(courses[1:5])
#
# #Changing index value
# courses[0] = "Accountancy"
# print(courses)
#
# #Printing the length of the list
# print(len(courses))
#
# #Printing the number of duplicates from the list
# print(courses.count("BSIT"))
#
# #Adding values from the list
# courses.append("Business")
# courses.append("PE")
# courses.append("Health")
# print(courses)
#
# #Inserting index from the list
# courses.insert(1,"Family Planning")
# print(courses)
#
# #Deleting specified item from the list
# courses.remove("Accountancy")
# print(courses)
#
# #Deleting specified index from the list
# courses.pop(0)
# print(courses)
#
# #Delete default end from the list
# courses.pop()
# print(courses)
#
# #delete the whole list
# del courses
# print(courses)
#
#
# #Clear the indexes from the list
# test = ["Math", "English"]
# test.clear()
# print(test)
# #Copy lists from another lists
# listOne = ["BSIT", "BSCS", "BLIS"]
# listOne.pop()
# listTwo = listOne.copy()
# print(listTwo)
# #Combining Lists by adding
# listOne = ["BSIT","BSCS","BLIS"]
# listTwo = ["Hatdog","CheeseDog"]
# listThree = listOne + listTwo
# print(listThree)
# #Combining Lists by adding(using extend)
# listOne = ["BSIT","BSCS","BLIS"]
# listTwo = ["Hatdog","CheeseDog"]
# listOne.extend(listTwo)
# print(listOne)
| true
|
42fd81d68d74a7e10e1b86ceec1f28395faad54f
|
backfirecs/python_pratice
|
/20191207/varconvert_demo.py
| 1,300
| 4.3125
| 4
|
"""
内置函数变量类型转换
Version:1.0
Author:chaishuai
"""
# 将一个数值或者字符串转换成整数,不能转换成整数的将会报错(浮点数类型,浮点数字符串,不是数字的字符串,None,空串,空格),False=>0,true=>1
a = '123'
print(int(a))
# b = '123.00'
# print(int(b))
# c = 123.00
# print(int(c))
# d = None
# print(int(d))
e = True
print(int(e))
f = False
print(int(f))
# g = ''
# print(int(g))
# h = ' '
# print(int(h))
# 将一个字符串转换成浮点数,不能转换成浮点数的将会报错(不是数字的字符串,None,空串,空格),False=>0.0,true=>1.0
a1 = '123'
print(float(a1))
b1 = '123.00'
print(float(b1))
c1 = 123
print(float(c1))
# d1 = None
# print(float(d1))
e1 = True
print(float(e1))
f1= False
print(float(f1))
# g = ''
# print(int(g))
# h1 = ' '
# print(float(h1))
# 将指定的对象转换成字符串形式,可以指定编码,False=>'False',True=>'True',None=>'None'
a3 = 123
print(str(a3));
b3 = 123.00
print(str(b3));
c3 = None
print(str(c3));
d3 = True
print(str(d3));
f3 = False
print(str(f3));
# 将整数转换成该编码对应的字符串(一个字符)
a4 = 97
print(chr(a4));
# 将字符串(一个字符)转换成对应的编码(整数)
a5 = 'a'
print(ord(a5));
| false
|
9c0248558be0e378d8468f7424db799f676da20d
|
backfirecs/python_pratice
|
/20191211/which_day.py
| 782
| 4.34375
| 4
|
"""
计算给定的年月日是哪一天
Version:1.0
Author:chaishuai
"""
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 or (year % 3200 == 0 and year % 172800):
return True
return False
def which_day(year, month, day):
big_month = [1, 3, 5, 7, 8, 10, 12]
day_counter = 0
for x in range(1, month):
if x in big_month:
day_counter += 31
elif x == 2:
day_counter += 29 if is_leap_year(year) else 28
else:
day_counter += 30
day_counter += day
return day_counter
def main():
print(which_day(1980, 11, 28))
print(which_day(1981, 12, 31))
print(which_day(2018, 1, 1))
print(which_day(2016, 3, 1))
if __name__ == '__main__':
main()
| false
|
95829d0e11c21cbd29e53f6ad71211e4fb320bf7
|
amitsubedi353/Assignment
|
/assign2.py
| 412
| 4.21875
| 4
|
def is_Anagram(str1, str2):
n1 = len(str1)
n2 = len(str2)
if n1 != n2:
return 0
str1 = sorted(str1)
str2 = sorted(str2)
for i in range(0, n1):
if str1[i] != str2[i]:
return 0
return 1
str1 = "realmadrid"
str2 = "elarmdiard"
if is_Anagram(str1, str2):
print ("The two strings are anagram of each other")
else:
print ("The two strings are not anagram of each other")
| true
|
caacf3eb5c43161a4dd3e05156c3a85e8373b429
|
calvinsettachatgul/caty
|
/python_class/city.py
| 1,615
| 4.40625
| 4
|
class Location:
def __init__(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
# Inheritance
# Every City is a kind of Location
class City(Location):
def __init__(self, name, county, state, population, latitude, longitude):
Location.__init__(self, latitude, longitude)
self.name = name;
self.county = county;
self.state = state;
self.population = population;
# class City(Location):
# def __init__(self, name, county, state, population, latitude, longitude):
# super(self, Location).__init__(self, latitude, longitude)
# self.name = name;
# self.county = county;
# self.state = state;
# self.population = population;
SF = City("SF", "SF", "CA", 7000000, 0, 1);
print(SF.name == "SF")
print(SF.county == "SF")
print(SF.state == "CA")
print(SF.population == 7000000)
print(SF.latitude == 0)
print(SF.longitude == 1)
'''
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def Name(self):
return self.firstname + " " + self.lastname
class Employee(Person):
def __init__(self, first, last, staffnum):
Person.__init__(self,first, last) # this is like calling super of the parent
self.staffnumber = staffnum
def GetEmployee(self): # adding additional functionality -- extending the Person class
return self.Name() + ", " + self.staffnumber
x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")
print(x.Name())
print(y.GetEmployee())
'''
| false
|
4b1781ce2dd5daf4d86257ec3365995270b3b85c
|
humid1/python_learn
|
/python_study/案例代码/变量和数据格式化案例.py
| 748
| 4.125
| 4
|
# 案例
# price_str = input("请输入苹果的价格:")
# weight_str = input("请输入苹果的总量:")
# weight = float(weight_str)
# price = float(price_str)
# print(weight * price)
# 以上方式定义了多个变量 (改进方法),
# 1.节约空间,只需要为一个变量分配空间
# 2.起名字方便,不需要为中间变量起名
price = float(input("请输入苹果的价格:"))
weight = float(input("请输入苹果的总量:"))
# 格式化输出
print("苹果单价 %.02f 元/斤,购买 %.02f 斤,需要支付 %.02f 元" % (price, weight, weight * price))
# 第二种输出方式
print("苹果单价 {0:.2f} 元/斤, 购买 {1:.2f} 斤,需要支付 {2:.2f} 元".format(price, weight, weight * price))
| false
|
160ef0394e57547b4fac0d3afd7b8ef11a21d42f
|
SushanKattel/LearnBasicPython
|
/Dictionaries_example.py
| 1,023
| 4.375
| 4
|
month_names = {
"jan": "January",
1: "January",
"feb": "February",
2: "February",
"mar": "March",
3: "March",
"apr": "April",
4: "April",
"may": "May",
5: "May",
"jun": "June",
6: "June",
"jul": "July",
7: "July",
"aug": "August",
8: "August",
"sep": "September",
9: "September",
"oct": "October",
10: "October",
"nov": "November",
11: "November",
"dec": "December",
12: "December"
}
def get_work():
a= input("Press 'a' keyword for entering name in abberations and 'n' keyword if you want to input number: ")
if a == "a":
x= input("Enter the three digit abberation of english month: ")
return x
elif a == "n":
x= int(input("Enter the number of month: "))
return x
else:
print("PLEASE ENTER VALID CHARACTER! {Input in lowercase!!}")
y = get_work()
if y:
print(month_names.get(y,"Opps!! Invalid entry!!! Try giving name in lowercase or omit 0 before number."))
| true
|
b4ae05891fe87614b461f12bb04a933d48093c67
|
SaiAshish9/PythonProgramming
|
/generators/size.py
| 934
| 4.28125
| 4
|
# generator functions are a
# special kind of function that
# return a lazy iterator. These are objects
# that you can loop over like a list. However, unlike
# lists, lazy iterators do not store their conten
# Python generators are a simple way of creating iterators.
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
for char in rev_str("hello"):
print(char)
def fibonacci():
current,previous=0,1
while True:
current,previous=current+previous,current
yield current
fib=fibonacci()
# for i in range(6):
# print(next(fib))
def oddnumbers():
n=1
while True:
yield n
n+=2
def pi_series():
odds=oddnumbers()
approx=0
while True:
approx+=(4/next(odds))
yield approx
approx-=(4/next(odds))
yield approx
approx=pi_series()
for x in range(100000):
print(next(approx))
| true
|
06100aee24e1c23fa77cbd1cd43b8ef89bf01d77
|
Christopher-Caswell/holbertonschool-higher_level_programming
|
/0x0A-python-inheritance/1-my_list.py
| 495
| 4.25
| 4
|
#!/usr/bin/python3
"""
Write a class My_List that inherits from list
Public instance meth: def print_sorted(self):
that prints the list, but sorted (ascending sort)
"""
class MyList(list):
"""Top shelf, have some class"""
def __init__(self):
"""Superdot inits with parent parameters"""
super().__init__()
def print_sorted(self):
"""return the sorted list intake"""
print(sorted(self))
"""print("{}".format(self.sort)) does not work tho?"""
| true
|
9748755004c7e42dd8817a6a52bd83ff29765926
|
Christopher-Caswell/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/5-text_indentation.py
| 1,186
| 4.34375
| 4
|
#!/usr/bin/python3
"""
Print a pair of new lines between the strings
separators are . ? :
raise a flag if not a string, though
"""
def text_indentation(text):
"""Consider me noted"""
if not isinstance(text, str):
raise TypeError("text must be a string")
"""
chr(10) is a new line.
Written in ASCII to keep clean
and somewhat save space for pep8
x is a string variable used to-
-convert the old string into new
"""
i = 0
x = ""
while i in range(len(text) - 1):
if text[i] is '.':
x += text[i] + chr(10) + chr(10)
elif text[i] is '?':
x += text[i] + chr(10) + chr(10)
elif text[i] is ':':
x += text[i] + chr(10) + chr(10)
elif (text[i - 1] is '.' or
(text[i - 1] is ':') or
(text[i - 1] is '?') and
text[i] is " "):
while text[i] == " ":
i += 1
x += text[i]
elif (text[i - 1] is not '.' and
(text[i - 1] is not ':') and
(text[i - 1] is not '?')):
x += text[i]
i += 1
print("{}{}".format(x, text[-1]), end="")
| true
|
d101baa4a1ecbde443c85ea6c6f2accbf3d3ab2a
|
pankilshah412/P4E
|
/Assignment 3.2.py
| 742
| 4.375
| 4
|
#Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
try :
grade = raw_input("Enter Score: ")
g = float(grade)
except :
print "Please Enter score between 0.0 and 1.0"
quit()
if g < 0.6 and g >= 0.0:
print "F"
elif g >=0.6 and g < 0.7:
print "D"
elif g >=0.7 and g < 0.8 :
print "C"
elif g >=0.8 and g < 0.9 :
print "B"
elif g>0.9 and g<=1.0:
print "A"
else:
print "Number out of range"
| true
|
abdb72a1cd2ffd7b69580cc63730d797d4cbcc2a
|
ZombieSave/Python
|
/Урок1.2/Задача3.py
| 657
| 4.21875
| 4
|
# 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц
# (зима, весна, лето, осень). Напишите решения через list и через dict.
monthString = input("Введите месяц: ")
month = int(monthString)
seasons = {"зима": [1, 2, 12],
"весна": [3, 4, 5],
"лето": [6, 7, 8],
"осень": [9, 10, 11]}
for key in seasons.keys():
if month in seasons[key]:
print(f"Это {key}")
break
print(seasons.values())
| false
|
020749fd6c1c702e6212c5df834d5b83ae20d92f
|
bikenmoirangthem/Python
|
/reverse_string.py
| 361
| 4.59375
| 5
|
#program to reverse a string
#function to reverse a string
def reverse(s):
str = ''
for i in s:
str = i + str
return str
#getting a string from user
str = input('Enter any string : ')
#printing the original string
print('Your original string : ',str)
#printing the reverse string
print('Reverse string : ',reverse(str))
| true
|
6780b2fa26b4c1649f2787738e03ee7c042a453b
|
chetan4151/python
|
/positivelist.py
| 341
| 4.15625
| 4
|
# Write a Python program to print all positive numbers in a range.
list1=[]
n=int(input("Enter number of elements you want in list :"))
print(f"Enter {n} elements:")
for i in range(0,n):
a=int(input())
list1.append(a)
print("list1=",list1)
list2=[]
for i in range(0,n):
if list1[i]>0:
list2.append(list1[i])
print(list2)
| true
|
4229ec2c151a99ef52eec1c7841e31e2e12d8794
|
JanviChitroda24/pythonprogramming
|
/10 Days of Statistics/Day 0/Weighted Mean.py
| 1,512
| 4.28125
| 4
|
'''
Objective
In the previous challenge, we calculated a mean. In this challenge, we practice calculating a weighted mean. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, , of integers and an array, , representing the respective weights of 's elements, calculate and print the weighted mean of 's elements. Your answer should be rounded to a scale of decimal place (i.e., format).
Input Format
The first line contains an integer, , denoting the number of elements in arrays and .
The second line contains space-separated integers describing the respective elements of array .
The third line contains space-separated integers describing the respective elements of array .
Constraints
, where is the element of array .
, where is the element of array .
Output Format
Print the weighted mean on a new line. Your answer should be rounded to a scale of decimal place (i.e., format).
Sample Input
5
10 40 30 50 20
1 2 3 4 5
Sample Output
32.0
Explanation
We use the following formula to calculate the weighted mean:
And then print our result to a scale of decimal place () on a new line.
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
# import numpy as np
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
# print(round(np.average(x, weights = y), 1))
print(round(sum(map(lambda a: a[0] * a[1], zip(x,y)))/sum(y), 1))
| true
|
2a18ab3e5918b5518454ac41565769a3912d7d1f
|
JanviChitroda24/pythonprogramming
|
/Hackerrank Practice/RunnerUp.py
| 879
| 4.25
| 4
|
'''
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.
Input Format
The first line contains . The second line contains an array of integers each separated by a space.
Constraints
Output Format
Print the runner-up score.
Sample Input 0
5
2 3 6 6 5
Sample Output 0
5
Explanation 0
Given list is . The maximum score is , second maximum is . Hence, we print as the runner-up score.
'''
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
x = set(arr)
x = list(x)
x.sort(reverse=True)
print(x[1])
'''x.sort(reverse=True)
print(x);
x = list(set(x))
print(x)
#x = set(x.sort(reverse = True))
print(x[0]) #[1])'''
| true
|
eae94c125d5a7b3f733c77573111e92cc1fdb527
|
JanviChitroda24/pythonprogramming
|
/Hackerrank Practice/Mini_Max Sum.py
| 1,796
| 4.40625
| 4
|
'''
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example, . Our minimum sum is and our maximum sum is . We would print
16 24
Function Description
Complete the miniMaxSum function in the editor below. It should print two space-separated integers on one line: the minimum sum and the maximum sum of of elements.
miniMaxSum has the following parameter(s):
arr: an array of integers
Input Format
A single line of five space-separated integers.
Constraints
Output Format
Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)
Sample Input
1 2 3 4 5
Sample Output
10 14
Explanation
Our initial numbers are , , , , and . We can calculate the following sums using four of the five integers:
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
If we sum everything except , our sum is .
Hints: Beware of integer overflow! Use 64-bit Integer.
Need help to get started? Try the Solve Me First problem
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
arr.sort()
s = 0
min, max = sum(arr[:len(arr)-1]), sum(arr[1:])
print(min, max)
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
| true
|
08d15907da0916342026766888602ebb9c9c9e56
|
JanviChitroda24/pythonprogramming
|
/Hackerrank Practice/Time Conversion.py
| 1,395
| 4.15625
| 4
|
'''
Given a time in -hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
Function Description
Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.
timeConversion has the following parameter(s):
s: a string representing time in hour format
Input Format
A single string containing a time in -hour clock format (i.e.: or ), where and .
Constraints
All input times are valid
Output Format
Convert and print the given time in -hour format, where .
Sample Input 0
07:05:45PM
Sample Output 0
19:05:45
'''
#!/bin/python3
import os
import sys
#
# Complete the timeConversion function below.
#
def timeConversion(s):
#
# Write your code here.
#
time = s.split(":")
if s[-2:] == "PM":
if time[0] != "12":
time[0] = str(int(time[0])+12)
else:
if time[0] == "12":
time[0] = "00"
ntime = ':'.join(time)
return str(ntime[:-2])
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
print(s)
result = timeConversion(s)
f.write(result + '\n')
f.close()
| true
|
d908a2c337533ac0f25113b1ca7ac994247cb4ec
|
JanviChitroda24/pythonprogramming
|
/Hackerrank Practice/Lists.py
| 1,889
| 4.65625
| 5
|
```
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format
The first line contains an integer, , denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Constraints
The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
```
if __name__ == '__main__':
arr = []
for i in range(int(input())):
s = input().split()
for i in range(1, len(s)):
s[i] = int(s[i])
if s[0] == "append":
arr.append(s[1])
elif s[0] == "extend":
arr.extend(s[1:])
elif s[0] == "insert":
arr.insert(s[1],s[2])
elif s[0] == "remove":
arr.remove(s[1])
elif s[0] == "pop":
arr.pop()
elif s[0] == "index":
print(arr.index(s[1]))
elif s[0] == "count":
print(arr.count(s[1]))
elif s[0] == "sort":
arr.sort()
elif s[0] == "reverse":
arr.reverse()
elif s[0] == "print":
print(arr)
| true
|
3ce7edd59141cefc007942f7ddbd53ba0a12c8ad
|
fahimkk/automateTheBoringStuff
|
/chapter_5/birthdays.py
| 491
| 4.15625
| 4
|
birthdays = {'Alice':'April 1', 'Bob':'March 21', 'Carol':'Dec 4'}
while True:
name = input('Enter a name: (blank to Quit)\n')
if name == '':
break
if name in birthdays:
print(birthdays[name]+' is the birthday of '+name)
print()
else:
print('I dont have birthday informaton for '+name)
bday = input('What is their birthday ?\n')
birthdays[name] = bday
print('Birthday database updated')
print()
print(birthdays)
| true
|
726eca08e0049d17f4000037c283bacc627d1eb2
|
larsnohle/57
|
/21/twentyoneChallenge2.py~
| 1,239
| 4.15625
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please try again!")
return i
def main():
month_as_number = get_positive_number_input("Please enter the number of the month: ")
month_dict = {}
month_dict[1] = "January"
month_dict[2] = "February"
month_dict[3] = "March"
month_dict[4] = "April"
month_dict[5] = "May"
month_dict[6] = "June"
month_dict[7] = "July"
month_dict[8] = "August"
month_dict[9] = "September"
month_dict[10] = "October"
month_dict[11] = "November"
month_dict[12] = "December"
month_as_string = month_dict.get(month_as_number, "there is no such month!")
string_to_output = "The name of the month is %s." % month_as_string
print(string_to_output)
### MAIN ###
if __name__ == '__main__':
main()
| true
|
f6fcd47c5084c99cf3738301b304398fde52d508
|
larsnohle/57
|
/18/eighteenChallenge2.py
| 1,682
| 4.1875
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please try again!")
return i
def input_scale():
done = False
print("Press C to convert from Fahrenheit to Celsius.")
print("Press F to convert from Celsius to Fahrenheit.")
while not done:
scale = input("Your choice? ")
if scale == 'C' or scale == 'c' or scale == 'F' or scale == 'f':
scale = scale.upper()
done = True
return scale
def calculate_fahrenheit_to_celsius(f):
return (f - 32) * 5.0 / 9.0
def calculate_celsius_to_fahrenheit(c):
return (c * 9.0 / 5.0) + 32
def input_and_convert_from_celsius():
c = get_positive_number_input("Please enter the temperature in Celsius: ")
f = calculate_celsius_to_fahrenheit(c)
print("The temperature in Fahrenheit is %.1f" % f)
def input_and_convert_from_fahrenheit():
f = get_positive_number_input("Please enter the temperature in Fahrenheit: ")
c = calculate_fahrenheit_to_celsius(f)
print("The temperature in Celsius is %.1f" % c)
def main():
scale = input_scale()
if scale == "C":
input_and_convert_from_celsius()
else:
input_and_convert_from_fahrenheit()
### MAIN ###
if __name__ == '__main__':
main()
| true
|
de6c5c6492335f75b402a2d5228bcf8d25511b98
|
larsnohle/57
|
/8/eightChallenge3.py
| 921
| 4.21875
| 4
|
def get_positive_integer_input(msg):
done = False
while not done:
try:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please try again!")
return i
number_of_people = get_positive_integer_input("How many people? ")
number_of_pieces_per_pizza = get_positive_integer_input("How many pieces per pizza? ")
number_of_pieces_per_person = get_positive_integer_input("How many pieces do each person want? ")
desired_number_of_slices = number_of_people * number_of_pieces_per_person
number_of_pizzas_needed = desired_number_of_slices / number_of_pieces_per_pizza
if desired_number_of_slices % number_of_pieces_per_pizza != 0:
number_of_pizzas_needed += 1
print("%d number of pizzas are needed" % number_of_pizzas_needed)
| true
|
e42960bffe6815300320f8d19fb6ea226e6ac0cd
|
larsnohle/57
|
/24/twentyfour.py~
| 634
| 4.3125
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def is_anagram(first_string, second_string):
if len(first_string) != len(second_string):
return False
HERE
def main():
print("Enter two strings and I'll tell you if they are anagrams")
first_string = input("Enter the first string:")
second_string = input("Enter the second string:")
if is_anagram(first_string, second_string):
print("\"%s\" and \"%s\" are anagrams" % (first_string, second_string))
else:
print("\"%s\" and \"%s\" are NOT anagrams" % (first_string, second_string))
### MAIN ###
if __name__ == '__main__':
main()
| true
|
df74617e4ce1f7c9f79e8e22004f44933b140006
|
larsnohle/57
|
/34/thirtyFourChallenge1.py
| 549
| 4.21875
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
EMPLOYEES = ["John Smith", "Jackie Jackson", "Chris Jones", "Amanda Cullen", "Jeremy Goodwin"]
def main():
while len(EMPLOYEES) > 0:
print("\nThere are %d employees: " % len(EMPLOYEES))
for employee in EMPLOYEES:
print(employee)
employee_to_remove = input("Enter an employee name to remove: ")
try:
EMPLOYEES.remove(employee_to_remove)
except ValueError:
print("%s is not an employee!")
### MAIN ###
if __name__ == '__main__':
main()
| false
|
73c23d579194a4b068c24d0336e5fbd5e506ae3e
|
eric-mahasi/algorithms
|
/algorithms/linear_search.py
| 808
| 4.1875
| 4
|
"""This script demonstrates the linear search algorithm in Python 3."""
AGES = [19, 20, 13, 1, 15, 7, 11, 3, 16, 10]
def display():
"""Prints all the items in the list."""
print("The ages are: ")
for i in range(len(AGES)):
print(AGES[i])
def linear_search(array, x):
"""Sequentially check each element of the list until a match is found or
until the whole list has been searched. Time complexity of O(n).
"""
for i in range(len(AGES)):
if AGES[i] == x:
print("A student aged", x, "was found.")
return 0
else:
print("A student aged", x, "was not found.")
return -1
if __name__ == '__main__':
display()
search_key = int(input("Enter an age to search for: "))
linear_search(AGES, search_key)
| true
|
5fca17139a2fb3bcfb68acedd4ee3428735b32f6
|
eric-mahasi/algorithms
|
/algorithms/bubble_sort.py
| 895
| 4.4375
| 4
|
"""This script demonstrates the bubble sort algorithm in Python 3."""
AGES = [19, 20, 13, 1, 15, 7, 11, 3, 16, 10]
def display():
"""Prints all the items in the list."""
print("The ages are: ")
for i in range(len(AGES)):
print(AGES[i])
print("\n")
def bubble_sort(array):
"""Repeatedly step through the list, compare adjacent items and swap
them if they are in the wrong order. Time complexity of O(n^2).
Parameters
----------
array : iterable
A list of unsorted numbers
Returns
-------
array : iterable
A list of sorted numbers
"""
for i in range(len(array) - 1):
for j in range(len(array) - 1 - i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
if __name__ == '__main__':
display()
bubble_sort(AGES)
display()
| true
|
c0c1dbd89be9a529c9cb3b78e8a913d66fa6a89e
|
MirzaRaiyan/The-Most-Occuring-Number-In-a-String-Using-Regex.py
|
/Occuring.py
| 1,132
| 4.375
| 4
|
# your code goes here# Python program to
# find the most occurring element
import re
from collections import Counter
def most_occr_element(word):
# re.findall will extract all the elements
# from the string and make a list
arr = re.findall(r'[0-9] +', word)
def most_occr_element(word):
# re.findall will extract all the elements
# from the string and make a list
arr = re.findall(r'[0-9]+', word)
# to store maxm frequency
maxm = 0
# to store maxm element of most frequency
max_elem = 0
# counter will store all the number with
# their frequencies
# c = counter((55, 2), (2, 1), (3, 1), (4, 1))
c = Counter(arr)
# Store all the keys of counter in a list in
# which first would we our required element
for x in list(c.keys()):
if c[x]>= maxm:
maxm = c[x]
max_elem = int(x)
return max_elem
# Driver program
if __name__ == "__main__":
word = 'geek55of55gee4ksabc3dr2x'
print(most_occr_element(word))
| true
|
14baefcd782e3e232ccc333a7ab437c1cd3f8120
|
tinxo/Tutorias-PL-SEM1-TTI
|
/Clase #1/variables.py
| 1,288
| 4.4375
| 4
|
# Declaración de variables
# <nombreVariable> = <valor>
numeroEntero = 101
numeroDecimal = 34.2
valorBoolean = True
texto = 'Texto a guardar'
# Se pueden usar tanto comillas simples como dobles
# -------------------------
# Tipos de datos: detección y conversiones
# 1ro: Obtener el tipo de datos de una variable -- método type()
print(type(numeroEntero))
# 2do: Cada tipo tiene su método aplicable para conversión
# Pasar a tipo string --> método str()
numeroConvertido = str(numeroEntero)
print(type(numeroConvertido))
# Pasar a tipo entero --> método int()
textoConNumero = '50'
textoConvertido = int(textoConNumero)
print(type(textoConvertido))
# -------------------------
# Operadores de asignación, aritméticos y de comparación
num1 = 5
num2 = 10
# Asignación
res = num1
res += num2
print(f'Qué valor va a tener la variable? {res}')
# Aritméticos
print(f'Suma: {num1 + num2}')
print(f'Resta: {num1 - num2}')
print(f'Multiplicación: {num1 * num2}')
print(f'División: {num1 / num2}')
print(f'Módulo: {num1 % num2}')
# Comparación
print(num1 < num2) # menor que
print(num1 > num2) # mayor que
num3 = 5
print(num1 == num3) # igualdad
print(num1 != num3) # diferencia
print(num1 <= num3) # menor o igual
print(num1 >= num3) # mayor o igual
| false
|
9e675b13c7217efa27655e0950b31b8525e2bbda
|
pereiralabs/publiclab
|
/python/csv_filter_lines/ex_csv.py
| 903
| 4.125
| 4
|
#This script reads a CSV file, then return lines based on a filter
#Setting the locale
# -*- coding: utf-8 -*
#Libraries section
import csv
#List of files you want to extract rows from
file_list = ["/home/foo/Downloads/20180514.csv"]
#List of columns you want to extract from each row
included_cols = [5,2,1]
#Now let's iterate through each file on the list
for file in file_list:
#For each file:
with open(file) as csvfile:
cdrreader = csv.reader(csvfile, delimiter=',', quotechar='"')
j = 1
#For each row in a file:
for row in cdrreader:
#Checks if condition is satisfied
if row[1] == "alô":
#If it is, then the selected columns are retrieved from the row
content = list(row[x] for x in included_cols)
print(content)
j = j + 1
| true
|
b5e47b5711987b4345d86f64992ddc3709d014bf
|
tiwanacote/Pythonic-2021
|
/05-Colecciones/4-Set.py
| 517
| 4.34375
| 4
|
"""
No mantiene el orden -> no se puede indexar
-> Cada vez que imprimo veo orden diferente
Los elementos se almacenan una sola vez
Creo que desde Python 3.algo ya mantiene el orden y siempre se imprime lo mismo
"""
planetas = {"Marte","Jupiter","Venus"}
print(planetas)
print(planetas)
print("El set tiene",len(planetas),"elementos")
planetas.add("Tierra")
print(planetas)
#No puedo repetir un elemento
planetas.add("Tierra")
print(planetas)
planetas.discard("Venus")
print(planetas)
| false
|
a52b5830ce6e24ae87193c9d2b51fa4a97160959
|
yun-lai-yun-qu/patterns
|
/design-patterns/python/creational/factory_method.py
| 1,620
| 4.59375
| 5
|
#!/usr/bin/python
# -*- coding : utf-8 -*-
"""
brief:
Factory method. Use multiple factories for
multiple products
pattern:
Factory method:
Define an interface for creating an object,
but let subclasses decide which class to
instantiate.Factory Method lets a class defer
instantiation to subclasses.
AbstractProduct < = > AbstractFactory
| | | |
ProductA ProductB FactoryA(for ProductA) FactoryB(for ProductB)
"""
# AbstractProduct
class Animal:
def __init__(self):
self.boundary = 'Animal'
self.state = self.boundary
def __str__(self):
return self.state
# Product
class Lion(Animal):
def __init__(self):
super(Lion, self).__init__();
self.state = self.boundary + ' - Lion'
def __str__(self):
return self.state
class Tiger(Animal):
def __init__(self):
super(Tiger, self).__init__();
self.state = self.boundary + ' - Tiger'
def __str__(self):
return self.state
# AbstractFactory
class Factory():
def create_animal(self):
pass
# Factory
class LionFactory(Factory):
def __init__(self):
print('Initialize LionFactory.')
def create_animal(self):
return Lion()
class TigerFactory(Factory):
def __init__(self):
print('Initialize TigerFactory.')
def create_animal(self):
return Tiger()
if __name__ == '__main__':
lion_factory = LionFactory()
tiger_factory = TigerFactory()
obj1 = lion_factory.create_animal()
obj2 = tiger_factory.create_animal()
print('obj1: {0}'.format(obj1))
print('obj2: {0}'.format(obj2))
| true
|
46bde43ea1468e8b0e96c26935a4bb77baec0e7e
|
vkagwiria/thecodevillage
|
/Python Week 2/Day 1/exercise4.py
| 573
| 4.21875
| 4
|
# User Input: Ask the user to input the time of day in military time without a
# colon (1100 = 11:00 AM). Write a conditional statement so that it outputs the
# following:
# a. “Good Morning” if less than 1200
# b. “Good Afternoon” if between 1200 and 1700
# c. “Good Evening” if equal or above 1700
time=int(input("Please insert your local time here in millitary hours without spacing, a colon or hrs: "))
if(time<1200):
print("Good morning!")
elif(1700>time>=1200):
print("Good afternoon!")
elif(time>=1700):
print("Good evening!")
| true
|
bb8a0d849cd2a47df53088fee0b8c926f8654c9a
|
vkagwiria/thecodevillage
|
/Python Week 2/Day 2/exercise1.py
| 464
| 4.1875
| 4
|
# Ask the user for 3 numbers
# Calculate the sum of the three numbers
# if the values are equal then return thrice of their sum
# else, return the sum
num1=int(input("Please insert the first number here: "))
num2=int(input("Please insert the second number here: "))
num3=int(input("Please insert the third number here: "))
sum=num1+num2+num3
if(num1==num2==num3):
print(f"The sum of your numbers is {3*sum}.")
else:
print(f"The sum is {sum}.")
| true
|
85d969c057da158c9b16bd1143b78e7f1be1a990
|
vkagwiria/thecodevillage
|
/Python Week 2/Day 1/02_else_statements.py
| 1,073
| 4.5625
| 5
|
"""
Else statements
The final part of a good decision is what to do by default. Else statements are used to cater for this.
How They Work
Else conditional statements are the end all be all of the if statement. Sometimes you’re
not able to create a condition for every decision you want to make, so that’s where the
else statement is useful. The else statement will cover all other possibilities not covered
and will always run the code if the program gets to it. This means that if an elif or if
statement were to return True, then it would never run the else; however, if they all
return False, then the else clause would run no matter what every time.
Writing An Else Statement
Like an elif statement, the else clause needs to always be associated with an original
if statement. The else clause covers all other possibilities, so you don’t need to write a
condition at all; you just need to provide the keyword “else” followed by an ending
colon. Remember that an else clause will run the code inside of it if t reaches the statement.
"""
| true
|
54ebed866e5e015a47b3e2a23ff660dab7adf0af
|
vkagwiria/thecodevillage
|
/Python Week 2/Day 1/exercise2.py
| 381
| 4.28125
| 4
|
# ask the user to input a number
# check whether the number is higher or lower than 100
# print "Higher than 100" if the number is greater than 100
# print "Loweer than 100" if the number is lower than 100
num=int(input("Please insert your number here: "))
if(num>100):
print("The number is greater than 100.")
elif(num<100):
print("The number is less than 100.")
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.