blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9d30c4e827acb72d6b13932a5d3c8667b6669c96 | gergokutu/cs50-python | /try.py | 912 | 4.28125 | 4 | text = input("Your text: ")
# pay attention > f (format string)
print(f"You typed: {text}")
print("You typed: {text}")
# order counts > cough()
def cough():
print("Cough")
for i in range(3):
cough()
# say no to write anything after the ?s
# named argument > end
# then use print() to write a new line
for i in range(4):
print("?", end="")
print()
# same with different syntax
print("?" * 4)
for i in [0, 1, 2]:
print('!')
for i in range(3):
print("*")
print("#\n" * 3, end="")
number = int(input("Type a number: "))
if number > 4:
print("Greater than 4")
elif number < 4:
print("Smaller than 4")
else:
print("Equal to 4")
# while True:
# print("True is true...")
i = 0
while i < 4:
# print("Lol" + "and I=" + str(i))
print("Lol", "and I=", i)
i += 1
# list
listOfNums = [0, 1, 2, 3, 4]
print(listOfNums[:1])
print(listOfNums[:2])
print(listOfNums[2:4])
| false |
5151cfe22c6ba893660c49ba006b512c77a74e6b | Suryashish14/Suryashish-Programs | /SpecialCalculator 1.py | 2,115 | 4.25 | 4 | print('::::::::::::::::::::::::::: MENU ::::::::::::::::::::::::::::::::::')
print('Press 1 To Check For Armstrong Number')
print('Press 2 To Check For Duck Number')
print('Press 3 To Check For Perfect Number')
print('\t\t\t\t Instructions')
print('''1.Provide Only Positive Numbers
2.For Using The Menu Use Only 1,2,3''')
a=int(input('Enter Your Choice From The Above Menu:'))
if a==1 or a==2 or a==3:
print(':::::::::::: WELCOME ::::::::::::::::::::')
if a==1:
b=int(input('Enter A Number:'))
numcopy1=b
add=0
if b>0:
while numcopy1>0:
part=int(numcopy1%10)
add+=part**3
numcopy1//=10
if add==b:
print('Its an Armstrong Number')
else:
print('Its Not An Armstrong Number')
else:
print('Invalid Input!Provide Any Positive Integer')
if a==2:
c=int(input('Enter Any Positive Number:'))
numcopy2=c
flag=0
if c>0:
while numcopy2>0:
rem=int(numcopy2%10)
numcopy2//=10
if rem==0:
flag+=1
break
if flag>0:
print(c,'is a Duck Number')
else:
print(c,'is Not a Duck Number')
else:
print('Invalid Input!Please Provide Any Positive Integer')
if a==3:
d=int(input('Enter Any Positive Integer:'))
numcopy3=d
factors=0
if d>0:
for i in range(1,numcopy3):
if numcopy3%i==0:
factors+=i
if factors==d:
print('It is a Perfect Number')
else:
print('It is Not A a Perfect Number')
else:
print('invalid Input!Please Enter A Positive Number')
else:
print('Invalid Input!Please Follow The Instructions')
print('\n')
print('''Thank You For Using This Program..
It Has Developed By Suryashish Guha ''')
| true |
459ad480d62c540f80f0160af4fe6d59478cea54 | wear99/Python_Study | /类和实例/类和实例.py | 1,860 | 4.15625 | 4 | # 类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,
# 每个对象都拥有相同的方法,但各自的数据可能不同。
# 首先要定义类,指定从哪继承
class 学生(object):
# 也可以定义类的属性,这样实例就会自动具备这个属性
性别='女'
# 定义类的实例有什么属性,定义了之后,再生成实例的时候就必须传入这些参数
def __init__(self, 姓名, 学号, 成绩):
self.姓名 = 姓名
self.学号 = 学号
self.成绩 = 成绩
# 数据封装,直接在类里面定义好获得属性的函数,不用外界再调用print.
# 这些封装数据的函数是和Student类本身是关联起来的,我们称之为类的方法
def 打印成绩(self):
print('%s,%d'% (self.姓名,self.成绩))
# 根据学生这个类,建立了sun这个实例.
sun = 学生('孙', 36, 100)
liu = 学生('刘', 33, 99)
# 调用了sun这个实例里 姓名/学号/成绩 的属性
print(sun.姓名)
print(sun.学号)
print(sun.成绩)
# 实例虽然没有 性别这个属性,但类有
print(sun.性别)
# 调用了sun这个实例里面打印成绩这个函数(也叫方法),后面要加()
sun.打印成绩()
'''
小结
类是创建实例的模板,而实例则是一个一个具体的对象,各个实例拥有的数据都互相独立,互不影响;
方法就是与实例绑定的函数,和普通函数不同,方法可以直接访问实例的数据;
通过在实例上调用方法,我们就直接操作了对象内部的数据,但无需知道方法内部的实现细节。
和静态语言不同,Python允许对实例变量绑定任何数据,也就是说,对于两个实例变量,虽然它们都是
同一个类的不同实例,但拥有的变量名称都可能不同.
''' | false |
3ec8b2046e343d9ef8422f4f83640ad579aa342b | u101022119/NTHU10220PHYS290000 | /student/101022105/fibonacci_rec.py | 327 | 4.1875 | 4 | n=float(raw_input("Put n here."))
def fibonacci_rec(n):
if n==1:
return 1
if n>1:
return n+fibonacci_rec(n-1)
else:
return 0
if fibonacci_rec(n)>0:
print fibonacci_rec(n)
elif n<0 or type(n)!=int or type(n)!=str:
print 'Error, the n given should positive and should be an integer.'
| false |
ab74efe5f6803502cf971679fdce57ebbab0f609 | u101022119/NTHU10220PHYS290000 | /student/101022171/hw1/satellite.py | 366 | 4.25 | 4 | #File: satellite.py
#HW1_EX5_Altitude_of_a_satellite
#Due: 3/25/2014
#Author: 101022171
import math
G = 6.67 * 10**-11
M = 5.97 * 10**24
R = 6417.0
t = float( input('Enter the period T of the satellite in seconds. >:'))
h = ((G*M*t**2)/(4*math.pi**2))**(1.0/3) - R
print "The satellite is about %.2f km above the Earths surface with period %.1fs." % (h, t)
| false |
034c084055637a5c567c8c6b25e6ccd6c25a302e | u101022119/NTHU10220PHYS290000 | /student/100021216/myclass.py | 734 | 4.125 | 4 | import copy
import math
class point(object):
'''Represents a point in 2-D space.'''
class rectangle(object):
"""
Represents a rectangle.
attributes: width, height, corner.
"""
a=point()
a.x=0.0
a.y=0.0
b=point()
b.x=3.0
b.y=4.0
box=rectangle()
box.width=100.0
box.height=200.0
box.corner=point()
box.corner.x=0.0
box.corner.y=0.0
def print_point(p):
print '(%g,%g)' % (p.x,p.y)
def distance_between_points(a,b):
distance=math.sqrt((a.x-b.x)**2+(a.y-b.y)**2)
return distance
def move_rectangle(rect,dx,dy):
rect.corner.x += dx
rect.corner.y += dy
def move_rectangle_1(rect,dx,dy):
global newbox
newbox=copy.deepcopy(rect)
newbox.corner.x += dx
newbox.corner.y += dy
| true |
73a465b867ac3d51f2319dabc02c8581084e6cf7 | u101022119/NTHU10220PHYS290000 | /student/100022223/is_triangle.py | 207 | 4.125 | 4 | def is_triangle(a,b,c):
if (a+b)>c and(a+c)>b and(b+c)>a:
print 'Yes'
else:
print 'No'
x=float(raw_input('x:'))
y=float(raw_input('y:'))
z=float(raw_input('z:'))
is_triangle(x,y,z)
| false |
b411dacd5547dc23c890717b6be2f31f01c0ed59 | u101022119/NTHU10220PHYS290000 | /student/101022139/convert polar.py | 289 | 4.28125 | 4 | import math
x=float(raw_input('enter the value of the x coordinate:'))
y=float(raw_input('enter the value of the y coordinate:'))
r=math.sqrt(x**2+y**2)
theta=math.atan(y/x)*180/math.pi
print 'the corresponding polar coordinates (r,theta) is:','(',r,',',theta,')','theta given in degrees'
| false |
8a6188201bbbb2991472cac385ad33da1197df12 | u101022119/NTHU10220PHYS290000 | /student/101022122/hw1/fibonacci series.py | 580 | 4.1875 | 4 |
n=input('enter the fibonacci number:')
def fi(n):
if n<0:
pass
elif not isinstance(n,int):
pass
else:
if n==1:
return 1
elif n==2:
return 1
else:
return fi(n-1)+fi(n-2)
def print_fi(n):
f1=1
f2=1
if n<0:
print 'fibonacci number cannot be negative'
elif not isinstance(n,int):
print 'fibonacci number need to be integer'
elif n==1:
print '1'
else:
while f1<=fi(n):
print f1,''
f1,f2=f2,f1+f2
fi(n)
print_fi(n)
| false |
a856fb36597912de35ac0cbce90aadb781d63599 | bria051/Game | /Tic_tac_toe/choose.py | 345 | 4.21875 | 4 | def choosing():
print("Choose O or X to play the Game:")
while (True):
user = input()
if (user == 'O'):
computer = 'X'
break
elif (user == 'X'):
computer = 'O'
break
else:
print("You chose the wrong one. Choose again")
return user,computer
| true |
881c561f1e8ca930a70a4c7a35be7df48b8bbc04 | jiuash/python-lessons-cny | /code-exercises-etc/section_04_(lists)/ajm.lists01_attendees.20170218.py | 983 | 4.125 | 4 | ##things = []
##print things
attendees = ['Alison', 'Belen', 'Rebecca', 'Nura']
#print attendees
print attendees[0]
##name = 'Alison'
##print name[0]
print attendees[1:3]
print attendees[:3]
#print attendees[4]
#print len(attendees)
number_of_attendees = len(attendees)
print number_of_attendees
attendees.append("Andrea")
print attendees
##print "\n\n\n"
## oh by the way, our list can contain a mix of strings and numbers!
##attendees.append(4)
##print attendees
## change the first peron's name to be spelled wrong
##print attendees[0]
##attendees[0] = "Allison"
##print attendees
attendees.insert(2, "Samantha")
print attendees
#### a list of numbers! just to see it a different way ####
attendees_ages = []
print attendees_ages
print len(attendees_ages)
attendees_ages.append(28)
print attendees_ages
print len(attendees_ages)
attendees_ages.append(27)
print attendees_ages
print len(attendees_ages)
attendees_ages[0] = attendees_ages[0] + 1
print attendees_ages
| true |
495f7f47477d142d149095c3c84906575ab22bdd | Austin306/Python-Assessment | /prob2.py | 704 | 4.3125 | 4 | def comparator( tupleElem ) :
'''This function returns last element of tuple'''
return tupleElem[1]
def main():
'''This function takes the tuple as input and sorts it'''
final_list = []
lines = input('Enter the list of tuples separated by , : ')
for tup in lines.split('),('):#This For Loop is used to obtian the tuble from entered list
tup = tup.replace(')','').replace('(','')
final_list.append(tuple(tup.split(',')))
print('The Entered List of tuples is: ')
print(final_list)#Display unsorted list
final_list.sort(key=lambda elem: elem[1])#Sort the tuples based on last element
print('The Sorted List of Tuples is')
print(final_list)
main()
| true |
3e0ddfa7513c609ecbc2c87604767f846ea6d1b8 | karanchavan26/math-operation-using-python | /Quadratic_Equation.py | 475 | 4.125 | 4 | #FINDING THE ROOT OF ax^2+bx+c=0
import cmath
a=int(input('ENTER coeffient of x^2 : '))
b=int(input('ENTER coeffient of x : '))
c=int(input('ENTER coeffient of 1 : '))
''' To find the value of x following is the formula,
x=( -b +ro- sqrt(b^2 - 4ac))/(2*a)
'''
# (b^2 - 4ac)
z=(b*b)-(4*a*c)
# sqrt(b^2 - 4ac)
z1= cmath.sqrt(z)
#( -b +ro- sqrt(b^2 - 4ac))/(2*a)
root1=((-b+z1)/(2*a))
root2=((-b-z1)/(2*a))
#printing the roots
print(root1,root2)
| false |
bcf6cc01615591b36df9c3822ae51821c684d6ff | nicholaskarlson/Object-Oriented-Programming-in-Python | /off day.py | 2,170 | 4.125 | 4 | # creating a class of my class.
class Science:
form ="c"
num_student=0
def __init__(self,name,college_num,fav_sub):
self.name=name
self.college_num=college_num
self.fav_sub=fav_sub
Science.num_student+=1
def introduce(self):
print(f"Hey! I am {self.name}.My form is {self.form} and college number is {self.college_num}. I like {self.fav_sub} most.")
def change_sub(self,sub):
self.fav_sub=sub
print("My favourite subject is {} now!".format(self.fav_sub))
@classmethod
def change_form(emp,form):
emp.form=form
print("Science C is now become Science {} ".format(emp.form))
@staticmethod
def school_day(day):
if day.weekday==5 or day.weekday==6:
return False
else:
return True
def __add__(self,other):
return self.college_num+other.college_num
def __len__(self):
return len(self.name)
@property
def print_name(self):
print(self.name)
@print_name.setter
def print_name(self,name):
self.name=name
print(self.name)
@print_name.deleter
def print_name(self):
self.name=None
class Hater_mkj(Science):
def __init__(self,name,college_num,fav_sub,hate):
super().__init__(name,college_num,fav_sub)
self.hate=hate
def prove(self):
if self.hate:
print("MKJ is the worst teacher in the world. Piss on you!")
else:
print("I think MKJ and ME both are foolish :(")
student1=Science("Shawki",5130,"Math")
student2=Science("Hasnine",5150,"Chemistry")
student3=Science("Arko",5162,"Math")
student4=Science("Mahidul",5139,"Physics")
student5=Science("Abir",5169,"eating")
student6=Hater_mkj("Anonymus",0000,"not chemistry",False)
student1.introduce()
student2.introduce()
student5.introduce()
print()
student3.change_sub("Physics")
print(student1.form)
print(student2.form)
print(Science.form)
student6.introduce()
student6.prove()
print(student1+student2)
print(len(student1))
student1.print_name
student1.print_name="New_name"
del student1.print_name
student1.print_name | true |
83871c85a545012e93680ba23a0e61caf02e40a4 | dapazjunior/ifpi-ads-algoritmos2020 | /Iteracoes/Fabio_03/f3_q14_maior_quadrado.py | 205 | 4.125 | 4 | def main():
n = int(input('Digite um número: '))
num = 0
while (num ** 2) <= n:
maior_quadrado = num ** 2
num += 1
print(f'Maior quadrado: ', maior_quadrado)
main() | false |
537a10b2964afb6cbecdce161536769f24eb410f | sokuro/PythonBFH | /03_Exercises/Stings/06_SplitStringDelimiter.py | 278 | 4.28125 | 4 | """
split a string on the last occurrence of the delimiter
"""
str_input = input('Enter a String: ')
# create a list from the string
temp_list = list(str_input)
int_input = int(input('Enter a Number of split Characters: '))
print(str(temp_list).rsplit(',', int_input))
| true |
3fc66aa0b3bde5ee6a7d3bafdeb6bab46f0c926e | sokuro/PythonBFH | /01_Fundamentals/Strings/Exercises/04_IsString.py | 344 | 4.40625 | 4 | """
get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.
"""
def IsString(str):
if len(str) >= 2 and str[:2] == 'Is':
return str
else:
return 'Is' + str
print(IsString("Testing"))
print(IsString("IsTesting"))
| true |
c8c32cfec48b1307d4b5156bbe8881d0303063d0 | sokuro/PythonBFH | /01_Fundamentals/Lists/Lists.py | 477 | 4.125 | 4 | """
* Lists are MUTABLE ordered sequence of items
* Lists may be of different type
* [] brackets
* Expressions separated by a comma
"""
list1 = [1, 2.14, 'test']
list2 = [42]
list3 = [] # empty list
list4 = list() # empty list
# ERROR
# list5 = list(1, 2, 3)
# Solving
list6 = list((1, 2, 3)) # List out of the Tuple
print(list1) # >> [1, 2.14, 'test']
print(list2) # >> [42]
print(list3) # >> []
print(list4) # >> []
print(list6) # >> [1, 2, 3]
| true |
286f659c944c2744440dcdf9b3ffba55d4e4b1c1 | sokuro/PythonBFH | /01_Fundamentals/Sort/01_Sort.py | 414 | 4.21875 | 4 | """
sort(...)
L.sort(key=None, reverse=False)
"""
# List of Names
names = ["Karol", "Rebeca", "Daniel", "Michael", "Patrik", "Richard"]
# sort alphabetically
names.sort()
print(names)
# sort reversed
names.sort(reverse=True)
print(names)
# Tuple of Names
names_tuple = ("Karol", "Rebeca", "Daniel", "Michael", "Patrik", "Richard")
# names_tuple.sort() # ERROR: Tuples are not mutable!
| true |
4e8ad1365031a9051b83c439396cea43aa5b6d3a | igorgabrig/AprendizadoPython---curso-em-video | /Mundo03/desafios/Desafios Funcao/desafio104.py | 522 | 4.1875 | 4 | # Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante
# 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico.
# Ex: n = leiaInt('Digite um n: ')
def leiaInt(msg):
while True:
num = str(input(msg))
if num.isnumeric():
numero = int(num)
return numero
else:
print("Digite um valor válido")
n = leiaInt('Digite um numero: ')
print(f'Você acbou de digitar o numero {n}') | false |
da46590dcb44a879d75f9ebe34eeb043545760c8 | nithin-kumar/urban-waffle | /LucidProgramming/paranthesis_balance_stack.py | 551 | 4.15625 | 4 | from stack import Stack
def is_balanced(expression):
stack = Stack()
for item in expression:
if item in ['(', '[', '{']:
stack.push(item)
else:
if is_matching_paranthesis(stack.peek(), item):
stack.pop()
else:
return False
if not stack.is_empty():
return False
return True
def is_matching_paranthesis(p1, p2):
if p1 == '(' and p2 == ')':
return True
elif p1 == '[' and p2 == ']':
return True
elif p1 == '{' and p2 == '}':
return True
return False
if __name__ == '__main__':
print is_balanced("()[]{{(())}")
| true |
abcbb6f7a02de5de2d19df7a96a2fa018d2d1985 | nithin-kumar/urban-waffle | /InterviewCake/max_product_3.py | 699 | 4.125 | 4 | import math
def highest_product_of_3(list_of_ints):
# Calculate the highest product of three numbers
if len(list_of_ints) < 3:
raise Exception
return
window = [list_of_ints[0], list_of_ints[1], list_of_ints[2]]
min_number = min(window)
min_index = window.index(min_number)
prod = reduce(lambda x, y: x*y, window)
for i in range(3, len(list_of_ints)):
if list_of_ints[i] > min_number:
window[min_index] = list_of_ints[i]
min_number = min(window)
min_index = window.index(min_number)
prod = max(prod, reduce(lambda x, y: x*y, window))
return prod
print highest_product_of_3([-10, 1, 3, 2, -10]) | true |
a8798d0623136431334ef7e791b6b5cd2a81e187 | nachobh/python_calculator | /main.py | 1,064 | 4.1875 | 4 | def compute(number1, operation, number2):
if is_number(number1) and "+-*/^".__contains__(operation) and is_number(number2):
result = 0
if operation == "+":
result = float(number1) + float(number2)
elif operation == "-":
result = float(number1) - float(number2)
elif operation == "*":
result = float(number1) * float(number2)
elif operation == "/":
result = float(number1) / float(number2)
elif operation == "^":
result = pow(float(number1), float(number2))
print(number1 + " " + operation + " " + number2 + " = " + format(result, ".2f"))
else:
print("Error, some character is not ok")
def is_number(string):
try:
float(string)
return True
except ValueError:
return False
if __name__ == '__main__':
input_a = input("First number? ")
input_b = input("Operation (+, -, /, *, ^)? ")
input_c = input("Second number? ")
compute(input_a, input_b, input_c)
| true |
0a217be052ad34e326b15008bf02dcf4a54fa27b | gilgameshzzz/learn | /day4-循环和分支/04-while循环.py | 738 | 4.25 | 4 | # while 循环
"""
while 条件语句:
循环体
while :关键字
条件语句:结果是True,或者False
循环体:重复执行的代码段
执行过程:判断条件语句是否为True,如果为True就执行循环体,执行完循环体在判断条件语句是否True,
如果为True,再次执行循环体,直到条件语句的值为False,循环结束,直接执行其他语句。
注意:如果条件语句的结果一直都是True,就会造成死循环。在循环体中要有可以让循环结束的操作。
Python 中没有do-while循环
"""
# 使用while循环计算1+2+。。+100
x=1;a=0
while x<=100:
a+=x
x+=1
print(a)
# 练习:计算2+4+6+。。+100
a=0;b=2
while b<=100:
a+=b
b+=2
print(a)
| false |
a045cd2a100ac535a1ce498f282c9c0b9fb5a80f | gilgameshzzz/learn | /day7Python管理系统/03-函数参数.py | 1,394 | 4.46875 | 4 | """
参数的作用:从函数的外面给函数传值
"""
# 1、位置参数
"""
传参数的时候,实参按顺序给形参赋值
"""
# 2、关键字参数
"""
调用函数的时候:
函数名(参数=值)
"""
def func1(a, b, c):
print(a, b, c)
func1(10, 20, 30)
func1(b=20, a=10, c=30)
# 说明:位置参数和关键字参数可以混着来
# 3、参数的默认值
"""Python中函数的参数可以设置默认值,有默认值的
参数必须放在参数列表的最后
调用参数有默认值的函数,有默认值的参数可以传参也可以不传参
"""
def func2 (a, b, c=100):
print(a, b, c)
func2(10, 20, 30)
func2(10, 20)
# 4、参数个数不定
# 函数参数的个数不确定的时候,就在声明函数的时候,
# 形参的前面加一个*,将形参变成一个元组。
# 调用函数的时候,这个参数会将对应的实参作为元组的元素保存起来
"""写一个函数,求多个数的和"""
def my_sum(*numbers):
print(numbers)
sum1 = 0
for item in numbers:
sum1 += item
print(sum1)
my_sum(10, 20, 33, 42)
# 注意:参数个数不定,可以是形参中的一部分是不定的
# 个数不确定的参数要放到参数的最后
def func1(char, *numbers):
print(char, numbers)
func1('a', 10, 20, 39)
# 参数个数不定,也可以不传参数,但对应的值是一个空的元组
func1('asd') | false |
5531f81e5a293246c451eec8e6dff1bb005b1b5d | gilgameshzzz/learn | /day6Python字典/day6-字典/dict/04-集合.py | 2,419 | 4.25 | 4 | """__author__ = 余婷"""
"""
集合(set)也是一种容器类型的数据类型(序列);数据放在{}中,多个之间只用逗号隔开:{1, 2, 'a'}
集合是无序的(不能通过索引取取值), 可变(可以增删改), 元素不能重复
集合可以进行数学中集合相关的操作:判断是否包含,求交集、并集、差集、补集
"""
# 1.怎么声明集合
"""a.声明一个变量,赋一个集合值"""
set0 = set() # 创建一个空的集合
set1 = {1, 2, 3, 2, 2}
print(set1, type(set1))
"""b.将其他的数据转换成集合"""
set2 = set('abc1233h') # 将其他数据转换成集合,自带一个去重的功能
print(set2)
set3 = set([12, 'abc', 'hh', 32, 12, 'abcn'])
print(set3)
print(list(set3))
# 2.增删改查
"""a.查:遍历
注意:集合没有办法单独获取某一个元素
"""
for item in set2:
print(item)
"""b.增"""
# 集合.add(元素): 在指定的集合中添加指定的元素
set1 = {1, 2, 3}
set1.add(100)
print(set1)
# 集合1.update(集合2):将集合2中的元素添加到集合1中,自动去重
set1.update({'abc', 'ss'})
print(set1)
"""c.删"""
# 集合.remove(元素): 在指定的集合中删除指定的元素
set1.remove('ss')
print(set1)
# pop删除是随机删除一个
set1.pop()
print(set1)
# 3.判断是否包含
"""
集合1 >= 集合2 -- 判断集合1中是否包含集合2(判断集合2中的所有的元素是否都在集合1中)
集合1 <= 集合2 -- 判断集合2中是否包含集合1
"""
print({1, 2, 3, 4} >= {1, 4}) # True
print({1, 2, 3, 4} <= {1, 2}) # False
# 4.数学的集合运算
"""求并集: | """
print({1, 2, 3} | {2, 3, 4, 5})
"""求交集: &"""
print({1, 2, 3} & {2, 3, 4, 5})
"""求差集: -"""
print({1, 2, 3} - {2, 3, 4, 5})
"""求补集: ^"""
print({1, 2, 3} ^ {2, 3, 4, 5})
# 5.其他方法
"""clear:清空集合"""
set1.clear()
print(set1, type(set1))
"""len:获取集合中元素的个数"""
print(len(set1))
# 1.写一个程序
"""
a.用一个变量来保存一个班级的学生信息,学生信息包括:姓名、学号、成绩(英语、体育、美术、数学)、年龄
b.给这个班级添加学生
c.根据姓名查看班级里的某个学生的信息
d.根据姓名删除一个指定的学生信息
e.查看班级的所有的学生信息
f.求指定的学生平均成绩
"""
# 2.尝试着写学生管理系统
set1 = {'abc', 'a', 1, 2}
set1.pop()
print(set1)
| false |
c64ba5ea1bb599384e763e95e123b638aa5e3733 | gilgameshzzz/learn | /day5Python/03-列表.py | 1,642 | 4.1875 | 4 | """
列表、字典、元组、集合都是序列,都是容器类型的数据类型
列表(list):用来存储多个数据的一种数据类型。里面存储的单个数据,叫元素
特点1、有序的 2、可变的(可变指容器中的内容的个数和值可变)
3、元素可以是任何类型的数据
列表的值:用[]将列表中的元素括起来,多个元素之间用逗号隔开。[] -->空列表
"""
# 1、怎么声明一个列表
"""1、声明一个变量,赋一个列表值"""
list1 = []
print(type(list1))
"""2、将其他的数据类型转换成列表"""
list2 = list('police')
print(list2)
list3 = list(i*2 for i in range(10))
print(list3)
# 2、获取列表元素
# 列表中的每一个元素都对应一个下标:0~列表长度-1或-1~-列表长度
# a、获取单个元素:列表名[下标]
"""下标不能越界,会报IndexError"""
names = ['BMw', 'Audi', 'yuri', 'joe']
# b、获取部分元素(切片)
"""
列表名[起始下标:结束下标]:获取从起始下标开始,到结束下标前所有元素,结果是一个列表
列表名[起始下标:结束下标:步进]
起始下标和结束下标都可以缺省,
起始下标缺省如果步进为正,就从第一个开始取,如果步进是负数,就从最后一个开始取到结束下标
结束下标缺省,步进为正,获取到最后一个元素,步进是负数,从起始下标往前取到第一个元素
"""
print(names[:1:-1])
print(names[1::-1])
print(names[::-1])
print(names[:1])
print(names[1:])
print(names[:])
# 3、获取列表的长度(获取列表元素的个数)
"""
len(列表)
""" | false |
1f5d440084e02fe88bce3a547e56a7c0a83f5e29 | gilgameshzzz/learn | /day12Python面向对象/day12-面向对象基础/object/05-对象属性的增删改查.py | 2,608 | 4.5 | 4 | """__author__ = 余婷"""
class Dog:
"""狗类"""
def __init__(self, age=0, color='yellow'):
self.age = age
self.color = color
if __name__ == '__main__':
dog1 = Dog(3,'white')
# 1.查(获取属性)
"""
方法一:对象.属性 (如果属性不存在,会报错)
方法二:对象.__getattribute__(属性名) 和 getattr(对象, 属性名, 默认值)
"""
print(dog1.age, dog1.color)
print(dog1.__getattribute__('age'))
print(getattr(dog1, 'age'))
# 如果设置了default的值,那么当属性不存在的时候不会报错,并且返回默认值
print(getattr(dog1, 'abc', '无名氏'))
# 2.改(修改属性的值)
"""
方法一: 对象.属性 = 新值
方法二:对象.__setattr__(属性名,新值) 和 setattr(对象,属性名,新值)
"""
dog1.age = 4
print(dog1.age)
dog1.__setattr__('color', 'black')
print(dog1.color)
setattr(dog1, 'color', 'blue')
print(dog1.color)
# 3.增加(增加对象属性)
"""
对象.属性 = 值(属性不存在)
注意:属性是添加给对象的,而不是类的
"""
dog1.name = '大黄'
print(dog1.name)
dog1.__setattr__('type', '哈士奇')
print(dog1.type)
setattr(dog1,'sex', '公')
print(dog1.sex)
# dog2 = Dog()
# print(dog2.name)
# 4.删(删除对象的属性)
"""
方法一: del 对象.属性
注意:删除属性也是删的具体某个对象的属性。不会影响这个类的其他对象
"""
# del dog1.age
# print(dog1.age) # AttributeError: 'Dog' object has no attribute 'age'
# dog1.__delattr__('age')
# print(dog1.age) # AttributeError: 'Dog' object has no attribute 'age'
delattr(dog1, 'color')
# print(dog1.color) # 'Dog' object has no attribute 'color'
"""
练习:声明一个学生类,拥有属性:姓名、性别、年龄。方法:学习
1.声明学生类的对象,声明的时候就给姓名、性别和年龄赋值
2.通过三种方式分别获取姓名、性别和年龄,并且打印
3.给学生对象添加一个属性,电话
4.修改学生的年龄
5.删除学生的性别
"""
class Student:
def __init__(self, name='', age=0, sex=''):
self.name = name
self.sex = sex
self.age = age
def study(self):
print('%s学习' % self.name)
stu1 = Student('小明', 30, '男')
print(stu1.name)
print(stu1.__getattribute__('age'))
print(getattr(stu1, 'sex'))
stu1.tel = '123333'
stu1.age = 35
del stu1.sex
stu1.study()
| false |
86485d9d6f8634e1e1b7cba487180bb6f86441d1 | Mixiz/python_study | /lesson_3/task_2.py | 1,099 | 4.5 | 4 | # Запросим у пользователя данные и передадим их в функцию как именованные аргументы. Вывод в одну строку
def print_user_data(name, surname, birth_place, birth_date, email, phone_number):
print(f'Пользователь {name} {surname} родился {birth_date} в населенном пункте {birth_place}. '
f'Вы можете написать ему письмо на {email} или позвонить по номеру {phone_number}')
name = input("Введите имя\n")
surname = input("Введите фамилию\n")
birth_place = input("Введите место рождения\n")
birth_date = input("Введите дату рождения\n")
email = input("Введите email\n")
phone_number = input("Введите номер телефона\n")
print_user_data(name=name,
surname=surname,
birth_place=birth_place,
birth_date=birth_date,
email=email,
phone_number=phone_number)
| false |
b10dfdb063283012974f58deb9f5baf5711570bf | skhortiuk/python_course | /lab_5/main_3.py | 803 | 4.1875 | 4 | #! /usr/bin/python3
# -*-coding: utf-8-*-
import random
def human_win(human_move_id, computer_move_id):
if human_move_id == computer_move_id:
return "Draw"
elif human_move_id == 0 and computer_move_id == 2:
return "YOU WIN!!!!!!!"
elif human_move_id > computer_move_id and human_move_id != 2:
return "YOU WIN!!!!!!!"
else:
return "YOU LOSE!!!!!!"
moves = ["Rock", "Paper", "Scissors"]
while True:
print('*****NEW GAME*****')
human_move = moves[
(int(input("Your move hoose one & press enter:\n1. Rock\n2. Paper\n3. Scissors\nYour choose: ")) - 1)]
computer_move = moves[random.randrange(0, 3)]
print(human_move + " VS " + computer_move)
print(human_win(moves.index(human_move), moves.index(computer_move)), end='\n\n\n')
| false |
2b9d4c7bd4d01cd5c5547dd5b0bd45a206afe19f | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-2020/part01-e16_transform/src/transform.py | 393 | 4.125 | 4 | #!/usr/bin/env python3
def transform(s1, s2):
#convert to list of integers
s1_int = map(int, s1.split())
s2_int = map(int, s2.split())
#multiplicate elements and add to one list
zipped = zip(s1_int, s2_int)
L = []
for i in zipped:
L.append(i[0]*i[1])
return L
def main():
print(transform("1 5 3", "2 6 -1"))
if __name__ == "__main__":
main()
| false |
324a22534f107a044d7b9d7b40bfd1fd19624df3 | nopomi/hy-data-analysis-python-2019 | /hy-data-analysis-with-python-2020/part01-e13_reverse_dictionary/src/reverse_dictionary.py | 462 | 4.375 | 4 | #!/usr/bin/env python3
def reverse_dictionary(d):
reversed = {}
for key in d.keys():
for fin in d[key]:
if fin in reversed.keys():
reversed[fin].append(key)
else:
reversed[fin] = [key]
return reversed
def main():
d={'move': ['liikuttaa'], 'hide': ['piilottaa', 'salata'], 'six': ['kuusi'], 'fir': ['kuusi']}
print(reverse_dictionary(d))
if __name__ == "__main__":
main()
| false |
17f8beb9bb16ad49e62d0f4637d99862c3169bc5 | YiddishKop/python_simple_study | /OO/interface_absmethods_overriding.py | 2,335 | 4.3125 | 4 | """
python 想使用接口或是抽象类, 要比 java 多做一些工作,
需要引入 abc 包中的 ABCMeta 函数和 abstractmethod 标签
"""
# [知识点]
# 想使用接口/抽象类等定义,必须引入这个包
from abc import ABCMeta, abstractmethod
# Interface
class Shape(object):
# [知识点]
# 当你希望把这个类声明为接口or抽象类,并且其中的两个函数必须被
# 子类实现的时候,就必须在该类中
# 1. 声明 __metaclass__ 字段为 ABCMeta
# 2. 抽象函数头添加 @abstractmethod 标签
__metaclass__ = ABCMeta
@abstractmethod
def area(self): pass
@abstractmethod
def perimeter(self):pass
s=Shape() # tutorial 中说这里会报错,但是却没有
print(s.area()) # None
# implement interface Shape
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
# [知识点]
# __init__ 函数相当于构造函数, 我们一般希望当我们构建
# 子类对象的时候, 也会构造父类对象, 所以我们如此书写:
# 必须在每一个 __init__ 函数定义中调用 super().__init__()
# 并且将子类类名作为参数传递其中
super(Rectangle, self).__init__()
def area(self):
print("using rectangle area method")
return self.width * self.height
def perimeter(self):
print("using rectangle perimiter method")
return 2*(self.width + self.height)
rect = Rectangle(5, 7) # 创建一个 Rectangle 对象
print(rect)
print(rect.area()) # 35
print(rect.perimeter()) # 24
# extends class Rectangle
class Square(Rectangle):
def __init__(self, side_length):
self.side_length = side_length
super(Square, self).__init__(side_length, side_length)
def area(self):
print("using square area method")
return self.side_length ** 2
def perimeter(self):
print("using square perimeter method")
return 4 * self.side_length
square = Square(12)
print(square)
print("side lenth = {length} , and square area = {area}".format(length = square.side_length, area = square.area()))
print("side lenth = {length} , and square perimiter = {perimeter}".format(length = square.side_length, perimeter = square.perimeter()))
| false |
a1b1b2983bf4721f26de6b1cf85468509703bc46 | SjorsVanGelderen/Graduation | /python_3/features/classes.py | 1,010 | 4.125 | 4 | """Classes example
Copyright 2016, Sjors van Gelderen
"""
from enum import Enum
# Enumeration for different book editions
class Edition(Enum):
hardcover = 0
paperback = 1
# Simple class for a book
class Book:
def __init__(self, _title, _author, _edition):
self.title = _title
self.author = _author
self.edition = _edition
print("Created book {} by {} as {}".format(self.title, self.author, self.edition))
# Simple class for an E-reader
class E_Reader:
def __init__(self, _model, _brand, _books):
self.model = _model
self.brand = _brand
self.books = _books
print("Created E-reader {} by {} containing {}".format(self.model, self.brand, self.books))
# Main program logic
def program():
kindle = E_Reader("Kindle", "Amazon", [Book("1984", "George Orwell", Edition.hardcover)])
kobo = E_Reader("Aura", "Kobo", [
Book("Dune", "Frank Herbert", Edition.hardcover),
Book("Rama", "Arthur Clarke", Edition.paperback)
])
program()
| true |
23c0d628cf4eb3c0b347c149a1c90e89eb159866 | BohdanHamulets/LearnPython3 | /ThinkPython/newfile1.py | 2,816 | 4.125 | 4 | #!/usr/bin/env python3
import time
import turtle
# some_text = input("What fo you want to print?\n")
def print_user(some_text):
if len(some_text) > 0:
print(">>> ", some_text)
else:
pass
# print_user(some_text)
def my_get_time():
seconds = time.time()
days = 60 * 60 * 24
days_since_epoch = seconds // days
rest_time = seconds % days
rest_time_hours = rest_time / (60 * 60)
_hours = rest_time_hours // 1
_minutes = rest_time_hours % 1
print(days_since_epoch, " days have past after 1 Jan 1970", _hours, "HOURS", _minutes, "MINUTES")
# my_get_time()
# a = input("Ready to check if you can get a triangle? Please input side a\n")
# b = input("Please input side b\n")
# c = input("Please input side c\n")
def triangle(a, b, c):
if a > b + c or b > a + c or c > b + a:
print("Nope, you cannot")
else:
print("Yes you can!")
# triangle(a, b, c)
def book_rec(n, s):
if n == 0:
print(s)
else:
print(n, s)
book_rec(n - 1, n + s)
# book_rec(3, 0)
def draw(t, length, n):
if n == 0:
turtle.mainloop()
return
angle = 50
t.fd(length * n)
t.lt(angle)
draw(t, length, n - 1)
t.rt(2 * angle)
draw(t, length, n - 1)
t.lt(angle)
t.bk(length * n)
bodja = turtle.Turtle()
# draw(bodja, 15, 3)
def return_function(x):
if x < 0:
return -x
if x > 0:
return x
# print(return_function(-5))
def zadacha(x, y):
if x > y:
return 1
if x < y:
return -1
else:
return 0
#print(zadacha(6, 5))
# квадрат гіпотенузи дорівнює сумі квадратів катедів
# 5 ** 2 == 4 ** 2 + 3 ** 2
def hypotunyza(a, b):
#kvadrat_a = a ** 2
#kvadrat_b = b ** 2
#result = kvadrat_b + kvadrat_a
return b ** 2 + a ** 2
# print(hypotunyza(7, 3))
def is_divisible( x , y ):
return x % y == 0
# bla = is_divisible(3,3)
# print(bla)
# print("AAAAA")
# print(is_divisible(3,4))
def break_func(x):
while x < 10:
print("Doing smth, wail . . . ", x)
x += 1
if x == 9:
break
print("We just breaked")
print("Smth else")
#break_func(1)
def advanced_wait(param):
#if param > 3:
#print("We found it")
while param <= 4:
print("We're looking for it")
param += 1
if param >= 4:
print("It's bigger than 4")
continue
print("Is this like else or what?")
# advanced_wait(1)
def blaa():
listt = []
for x in range(3):
print(x)
listt.append(x)
return listt
print("bla")
# blaa()
def b(z):
prod = a(z, z)
print(z, prod)
return prod
def a (x, y):
x = x + 1
return x * y
b(5) | false |
6a33fc24a8ebcbae955ef6e91e6cd5f6d918596c | ankit1765/Hangman-and-other-fundamental-programs | /HIghScores.py | 700 | 4.15625 | 4 | #This program asks is a high score displayer.
#It asks the user how many entries they would like to input
#and how many top scores it should display
scores = []
numentries = int(raw_input("How many entries would you like to Enter? "))
numtop = int(raw_input("How many top scores would you like to display? "))
count = 1
while count <= numentries:
name = raw_input("\nEnter the name: ")
score = int(raw_input("Enter their scrore: "))
entry = score, name
scores.append(entry)
count += 1
scores.sort(reverse=True)
scores = scores[0:numtop]
print"\t\t\tTOP", numtop, "\tSCORES\n"
print "\t\t\tPLAYER\tSCORE"
for entries in scores:
s, p = entries
print "\t\t\t",p,"\t",s
| true |
c838d8701727936b9b7134468b879573e9fd3cd3 | solandmedotru/Python_Tutorials | /useless_trivia.py | 942 | 4.15625 | 4 | # Программа бесполезные факты
#
name = input("Привет. Как тебя зовут? ")
age = int(input("Сколько тебе лет? "))
weight = int(input("И последний вопрос. Сколько ты весишь в кг? "))
print("\nЕсли бы маленький ребенок захотел привлечь твое внимание.")
print("Он произнес бы твое имя так: " + name * 5)
seconds = age * 365 * 24 * 60 * 60
print("\nТвой возаст - свыше", seconds, "секунд")
moon_weigth = weight / 6
print("\nЗнаете ли вы, что на Луне вы весили бы всего", moon_weigth, "кг?")
sun_weigth = weight * 27.1
print("А вот на Солнце, вы бы весили", sun_weigth, "кг. (Но увы, не долго... )")
print("\a")
input("\nНажмите на клавишу Enter, чтобы выйти.")
| false |
94fcc18a0b3265087ebbfb6e224c898e95364a9d | acmachado14/ListasCCF110 | /Lista10/06.py | 1,714 | 4.25 | 4 | #6. Faça um programa que funciona como uma agenda telefônica. A agenda deve
#ser guardada em uma lista com o seguinte formato: [[‘Ana’, ‘99999-1234’], [‘Bia’,
#‘99999-5678’]]. (Não utilize esses dados. Isso é só um exemplo da estrutura. Leia
#todos os dados do teclado). O programa deve ter um menu que tenha as seguintes
#opções:
#(a) Adicionar telefones na agenda -- isso deve ser feito de forma que ela se
#mantenha sempre ordenada
#(b) Procurar um telefone -- o usuário informa um nome e o programa mostra o
#número do telefone, ou diz que não está na agenda
#A busca deve ser inteligente: deve parar assim que encontrar um nome maior do
#que o nome que está sendo buscado, ao invés de percorrer a lista sempre até o final
#para concluir que um nome não está na agenda.
agenda = [[0 for j in range(2)] for i in range(10)]
cont = 0
while True:
print("--------------------O QUE DESEJA FAZER?---------------------")
print("--------------- 1) Para adicionar um contato----------------")
print("--------------- 2) Para buscar um Telefone------------------")
print("------------------- 3) Parar a execução---------------------")
N = int(input())
if N == 3:
print("SAINDO...")
break
elif N == 1:
nome, telefone = input("DIGITE: NOME TELEFONE: ").split()
agenda[cont][0] = nome
agenda[cont][1] = telefone
print("INSERIDO COM SUCESSO")
elif N ==2:
s = input("DIGITE O NOME A SER PESQUISADO: ")
for i in range(len(agenda)):
if s == agenda[i][0]:
print("TELEFONE")
print(agenda[i][1])
else:
print("OPÇÃO INVÁLIDA")
cont += 1 | false |
0ee0d2873e2aec1ab8e74319127281ac81eb79c6 | Arween/PythonMIT-lessons | /Lecture-test/lect2_t2.py | 753 | 4.25 | 4 | outstandingBalance = float(raw_input("Enter the outstanding balance on your credit card: "));
interestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: "));
monthlyPayment = 0;
monthlyInterestRate = interestRate/12;
balance = outstandingBalance;
while balance > 0:
monthlyPayment += 10;
balance = outstandingBalance;
numMonths = 0;
while numMonths < 12 and balance > 0:
numMonths += 1;
interest = monthlyInterestRate * balance;
balance -= monthlyPayment;
balance += interest;
balance = round(balance, 2);
print "RESULT";
print "Monthly payment to pay off debt in 1 year: ", monthlyPayment;
print "Number of months need: ", numMonths;
print "Balance: ", balance; | true |
7cf7a34d09d0a5889a577850391ebf14d486d535 | ImwaterP/learn-Python | /Python note/元组.py | 323 | 4.1875 | 4 | """
元组:
特点:元组内元素无法修改,以圆括号括起来
"""
location = (1,2,3)
print(location)
location[0] = 10
print(location)
#重新创建新元组,覆盖旧元组即可
location = (10, 2, 3)
print(location)
#遍历元组内所有元素
for i in location:
print(i)
| false |
646d6816429c5dac188fd8693ffb4406aa57e752 | aamartinez25/effective-system | /cpu.py | 1,482 | 4.1875 | 4 | #
#Author: Adrian Martinez
#Description: takes a few inputs on CPU specs and organizes them accordingly
#
#
cpu_ghz = float(input('Enter CPU gigahertz:\n')) #input for CPU specs
cpu_core = int(input('Enter CPU core count:\n'))
cpu_hyper = input('Enter CPU hyperthreading (True or False):\n')
print()
if cpu_core >= 20:
print('That is a high-performance CPU.')
exit(0)
if (cpu_hyper == "True") or (cpu_hyper == 'true'): #setting bool for hyperthreading spec
cpu_hyper = True
elif (cpu_hyper == 'False') or (cpu_hyper == 'false'):
cpu_hyper = False
else:
print('Please enter True or False for hyperthreading')
exit(0)
if cpu_hyper: #CPUs with hyperthreading
if (cpu_ghz >= 2.7) and (cpu_core >= 6):
print ('That is a high-performance CPU.')
exit(0)
elif (cpu_ghz >= 2.4) and (cpu_core >= 4):
print('That is a medium-performance CPU.')
exit(0)
elif (cpu_ghz >= 1.9) and (cpu_core >= 2):
print('That is a low-performance CPU.')
exit(0)
else: #CPUs without hyperthreading
if (cpu_ghz >= 3.2) and (cpu_core >= 8):
print('That is a high-performance CPU.')
exit(0)
elif (cpu_ghz >= 2.8) and (cpu_core >= 6):
print('That is a medium-performance CPU.')
exit(0)
elif (cpu_ghz >= 2.4) and (cpu_core >= 2):
print('That is a low-performance CPU.')
exit(0)
# everything else
print('That CPU could use an upgrade.') | true |
9a576e7335c48f855798d6c1e42d8be4da138fd5 | niksanand1717/TCS-434 | /03 feb/solution_2.py | 499 | 4.15625 | 4 | num1 = eval(input("Enter the first number: "))
num2 = eval(input("Enter the second number: "))
count1, count2 = 0, 0
print("\n\nNumbers divisible by both 3 and 5")
for num in range(num1, num2+1):
if num%3 == 0 and num%5 == 0:
print(num)
count1+= 1
print("Total numbers of numbers:",count1)
print("\n\nNumbers divisible by 3 or 5")
for num in range(num1, num2+1):
if num%3 == 0 or num%5 == 0:
print(num)
count2+=1
print("Total numbers of numbers:",count2) | true |
360b2dba16714f2e2fee62d85537d49faefab8c1 | niksanand1717/TCS-434 | /28 april/fourth.py | 292 | 4.34375 | 4 | """Input a string and return all the words starting with vowels"""
import re
pattern = '^[aeiou]'
str1 = input("enter string: ")
print("Following are the words in entered string starting with vowel: ", end=' ')
[print(word, end=' ') for word in str1.split(" ") if re.match(pattern, word)] | true |
e3c9452a5563afe71101af97ced7f3834d042b83 | niksanand1717/TCS-434 | /28 april/first.py | 276 | 4.5 | 4 | """Print all the words from a string having length of 3"""
import re
pattern = '(...)$'
input_data = input("input string: ")
print("Following are the words which have length 3: ")
for words in input_data.split(" "):
if re.match(pattern, words): print(words, end=" ")
| true |
04680654bc17937b0d8f2939891f622784a66a56 | farmani60/coding_practice | /topic5_sorting/InsertionSortPart1.py | 340 | 4.15625 | 4 | # Description:
# https://www.hackerrank.com/challenges/insertionsort1/problem?h_r=internal-search
def insertionSort1(arr):
for i in range(len(arr)):
if arr[i] > arr[-1]:
temp = arr[i]
arr[i] = arr[-1]
arr[-1] = temp
input_list = [2, 4, 6, 8, 3]
insertionSort1(input_list)
print(input_list)
| false |
d448f3cebeff50b9eb66a2d1749d703c7a4f635e | farmani60/coding_practice | /topic10_bigO/log_n.py | 1,147 | 4.15625 | 4 | """
Logarithmic time complexities usually apply to algorithms
that divide problems in half every time.
If we implement (Algorithm A) going through all the elements
in an array, it will take a running time of O(n). We can try
using the fact that the collection is already sorted.
Later, we can divide in half as we look for the element in
question. O(log(n))
"""
def binarySearch(arr, element, offest=0):
middle = len(arr) // 2
current = arr[middle]
if current == element:
return middle + offest
elif element > current:
right = arr[middle:]
return binarySearch(right, element, offest+middle)
else:
left = arr[:middle]
return binarySearch(left, element, offest)
arr = [1, 3, 5, 6, 8, 9, 10, 13, 15]
print(binarySearch(arr, 1))
def binarySearch(arr, element, offset=0):
middle = len(arr) // 2
current = arr[middle]
if element == current:
return middle + offset
elif element > current:
right = arr[middle:]
return binarySearch(right, element, offset+middle)
else:
left = arr[:middle]
return binarySearch(left, element, offset) | true |
0f8fe20a3d49ce95591f9d9c46dd57d17e007866 | nomatterhowyoutry/GeekPython | /HT_1/Task6.py | 263 | 4.28125 | 4 | # 6. Write a script to check whether a specified value is contained in a group of values.
# Test Data :
# 3 -> [1, 5, 8, 3] : True
# -1 -> (1, 5, 8, 3) : False
list = [1, 5, 8, 3]
tuple = tuple(list)
print(3 in list)
print(-1 in tuple) | true |
96819f1bdd9469451af6089d77a9c6a979709856 | vanTrant/py4e | /ex3_try_exec/script.py | 361 | 4.1875 | 4 | # hours = input('Enter Hours: ')
# rate = input('Enter Rate: ')
try:
hours = float(input('Enter Hours: '))
rate = float(input('Enter Rate: '))
except:
print('Please enter a valid number')
quit()
if hours > 40:
overtime_pay = (hours - 40) * (rate * 1.5)
pay = 40 * rate + overtime_pay
else:
pay = hours * rate
print('Pay: ', pay)
| true |
d5b0514e7c3e53f7f1bf6ec53717c79f81325591 | yevgenybulochnik/lp3thw | /ex03/drill1.py | 859 | 4.375 | 4 | # Simple print statement that prints a string
print("I will count my chickens:")
# Prints a string then divides 30 by 6 then adds 25
print("Hens", 25 + 30 / 6)
# Prints a string then gives you the remainder of 75/3 or 3 and subtracts from 100
print("Roosters", 100 - 25 * 3 % 4)
print("Now I will count the eggs:")
# 4/2 remainder = 0, total adds up to 6.75
print(3 + 2 + 1 - 5 + 4 % 2 -1 / 4 + 6)
# Prints a string
print("Is it true that 3 + 2 < 5 - 7?")
# false statement
print(3 + 2 < 5 - 7)
# string plus result of 3 add 2
print("What is 3 + 2?", 3 + 2)
# string plus result of 5 subtract 7
print("What is 5 - 7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
# Returns true
print("Is it greater?", 5 > -2)
# Returns true
print("Is it greater or equal?", 5 >= -2)
# Returns false
print("Is it less or equal?", 5 <= -2)
| true |
8905a8a1c3bd892fef8604ff4e1c8741c730654a | PaulSweeney89/squareroot | /sqrt_test.py | 830 | 4.3125 | 4 | # defining a fuction to calculate the square root of a positive real number
# using Newton's method (ALTERNATIVE)
while True:
A = float(input("Please input positive value "))
if A > 0:
break
else:
print(A, " is a negative value")
continue
def sqrt(A):
x = 1
for n in range(0, 10): # using a for loop with 10 iterations
f1 = (x * x - A)
f2 = 2 * x
x = (x - (f1 / f2))
n = n + 1
if f1 == 0:
break
return (x)
ans = sqrt(A)
print("The square root of ", A , "is ", ans)
| true |
0ad794722abfb826b414f7d7eeb51f6b59293c5f | ljsauer/DS-From-Scratch | /Notes/Chapter 4.py | 1,188 | 4.375 | 4 | """Linear Algebra:
the branch of math that deals with vector spaces
"""
#
# Vectors - objects that can be added together to form new vectors,
# and that can be multiplied by scalars; points in some
# finite-dimensional space
from typing import List
Vector = List[float]
height_weight_age = [70, # inches
170, # pounds
40] # years
grades = [95, # exam 1
80, # exam 2
75, # exam 3
62] # exam 4
# Python lists *aren't* vectors, so we need to build our own tools
# Zip the vectors together and use list comprehension to perform
# arithmetic operations on them:
def add(v: Vector, w: Vector) -> Vector:
"""Adds corresponding elements"""
assert len(v) == len(w), "vectors must be the same length"
return [v_i + w_i for v_i, w_i in zip(v, w)]
assert add([1, 2, 3], [4, 5, 6]) == [5, 7, 9]
def subtract(v: Vector, w: Vector) -> Vector:
"""Subtracts corresponding elements"""
assert len(v) == len(w), "vectors must be the same length"
return [v_i - w_i for v_i, w_i in zip(v, w)]
assert subtract([5, 7, 9], [4, 5, 6]) == [1, 2, 3]
| true |
6b997548a37e7a761a789a4b44df67cfa69651d8 | blainekuhn/Python | /Reverse_text.py | 255 | 4.15625 | 4 | def reverse(text):
word = [text]
new_word = ""
count = len(text) - 1
for letter in text:
word.insert(0, letter)
for a in range(len(word) - 1):
new_word = new_word + word[a]
return new_word
print reverse("This is my text to reverse")
| true |
494d979b41757904cbcc0e9f10a6adfb0d5132f2 | Gopi3998/UPPERCASE-AND-LOWERCASE | /Uppercase and Lowercase...py | 527 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print('Starting the program for count the upper and lower case'.center(80,'*'))
sample = input('enter string: ')
uppercase = 0
lowercase = 0
for ch in sample:
if str .isupper(ch):
uppercase+=1
elif str.islower(ch):
lowercase+=1
print('No of uppercase character..',uppercase)
print('No of lowercase character..',lowercase)
print("THE END".center(80,'*'))
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
| true |
6e9034990271d7ed4549663f9d537dd7ac8f6a86 | Veletronic/Farmville | /Sheep_class.py | 1,217 | 4.125 | 4 | from Animal import *
class Sheep(Animal): #Cow inherits from Animal
"""A sheep"""
#Constructor
def __init__(self):
#Call the parent class constructor with default value
#Growth rate =1; food requirement = 3; water requirement = 3
super().__init__(1,3,3)
self._type = "Sheep" #basic sub-class
#Overrides growth method for subclasses
def grow(self,food,water):
if food>= self._food_req and water >= self.water_req:
if self._status == "infant" and water > self._water_req:
self._growth += self._growth_r8
elif self._status == "Young" and water >self._water_req:
self._growth += self._growth_r8 * 1.25
else:
self._growth += self._growth_r8
#Increments days
self._days_growing += 1
#Status update
self._update_status()
def main():
#Creates sheep
sheep_animal = Sheep()
print(sheep_animal.report())
#manually grows
manual_grow(sheep_animal)
print(sheep_animal.report())
if __name__ == "__main__":
main()
| true |
14025dd27c8f83cf0fed8b4cfea0c76badea0319 | sarahovey/AnalysisOfAlgos | /hw1/mergesort.py | 1,995 | 4.15625 | 4 | #Sort
#Merge Sort
def merge_sort(numbers):
#Divide the list into halves recursively
if len(numbers) > 1:
#get midpoint of list
mid = len(numbers)/2
left = numbers[:mid]
right = numbers[mid:]
merge_sort(left)
merge_sort(right)
#index variables
i = 0 #left half
j = 0 #right half
k = 0 #final numbersay
#Sorting
#Make sure that the index falls in the bounds of the respective halves
while i < len(left) and j < len(right):
if left[i] < right[j]:
numbers[k] = left[i]
#increment
i=i+1
else:
numbers[k] = right[j]
j += 1
k +=1
#Merging
while i < len(left):
numbers[k] = left[i]
i += 1
k += 1
while j < len(right):
numbers[k] = right[j]
j += 1
k += 1
#Reading from file
with open('data.txt', 'r') as fIn:
count =1
line = fIn.readline()
while line:
#Get the first number
#numbersIn = fIn.readline()
numbersIn = line
toSort = numbersIn[0]
int(toSort)
print("Numbers to sort:")
print toSort
#get the remaining numbers into a list as integers
numStrIn = numbersIn[1:]
#print (numStr)
numbers = [int(s) for s in numStrIn.split()]
print("Unsorted values:")
print(numStrIn)
#Call function
merge_sort(numbers)
#Write to file
with open('merge.out', 'a') as fOut:
#format sorted values for writing
numStrOut = ' '.join(str(e) for e in numbers)
fOut.write("%s\n" % (numStrOut))
print("Sorted values:")
print(numStrOut)
line = fIn.readline()
count +=1
| true |
2ad2891489db9ee7ddfd36acf02fbf71eac598bf | codeaudit/tutorial | /exercises/exercise01.py | 1,863 | 4.125 | 4 | # The goal of this exercise is to show how to run simple tasks in parallel.
#
# EXERCISE: This script is too slow, and the computation is embarrassingly
# parallel. Use Ray to execute the functions in parallel to speed it up.
#
# NOTE: This exercise should work even if you have only one core on your
# machine because the function that we're parallelizing is just sleeping.
# However, in general you would not expect a larger speedup than the number of
# cores on the machine.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ray
import time
if __name__ == "__main__":
# Start Ray. By default, Ray does not schedule more tasks concurrently than
# there are CPUs. This example requires four tasks to run concurrently, so we
# tell Ray that there are four CPUs. Usually this is not done and Ray
# computes the number of CPUs using psutil.cpu_count(). The argument
# redirect_output=True just hides some logging.
ray.init(num_cpus=4, redirect_output=True)
# This function is a proxy for a more interesting and computationally
# intensive function.
def slow_function(i):
time.sleep(1)
return i
# Sleep a little to improve the accuracy of the timing measurements below.
time.sleep(2.0)
start_time = time.time()
# This loop is too slow. The calls to slow_function should happen in
# parallel.
results = []
for i in range(4):
results.append(slow_function(i))
end_time = time.time()
duration = end_time - start_time
assert results == [0, 1, 2, 3]
assert duration < 1.1, ("The loop took {} seconds. This is too slow."
.format(duration))
assert duration > 1, ("The loop took {} seconds. This is too fast."
.format(duration))
print("Success! The example took {} seconds.".format(duration))
| true |
cf3480dca530bcedcb764f2cb0655914d004a409 | Abhishek-kr7/Basic-Python-Programming | /09_Functions_in_python.py | 1,759 | 4.375 | 4 | def hello():
"""This function will print the Hello Message when called"""
print('Hey there! Hello')
# hello()
def hello_user(user):
'''This function will take a parameter or name and will print hello with
the parameter/name'''
print("Hello",user, "How are you")
hello_user('abhi')
print(help(hello_user))
def mycountry(country='India'):
"""This function will print the country name which has been passed as parameter
If Nothing passed, then default value as 'India' will be Printed"""
print('My country is :' ,country)
mycountry('America')
mycountry()
def myfood(food):
"""This function will take list as input will print all the items"""
for item in food:
print('You can have ' + item)
fruits = ['Apple','Banana','Cherry']
myfruits = tuple(fruits)
print(myfruits)
myfood(myfruits)
def multipliers(x):
return x**5
print(multipliers(5))
import math
def sphereVol(r):
"""This function will take a parameter as r and calculate Volume of Sphere with that r value"""
return 4/3 * math.pi * r**3
# print(sphereVol(3))
# print(help(sphereVol))
def tri_area(b,h):
"""This Function will take 2 parameter as base and height and will return the area of triangle"""
return 0.5 * b * h
# print(tri_area(3,5))
def centi(feet=0, inch=0):
"""This function will take feet/inch or both
1 feet = 12 inches
1 inch = 2.54 cm
and will convert into centimeter
This function parameter have 0 as default value assigned"""
feet_to_cm = feet * 12 * 2.54
inch_to_cm = inch * 2.54
return feet_to_cm + inch_to_cm
print(centi(5))
print(centi(feet = 5))
print(centi(inch = 10))
print(centi(inch = 10, feet = 5))
def g(y, x = 0,):
print(x + y)
print(g(4,5))
print(g(x = 5))
| true |
5fc1530a3fb637127abf517484c0e96f3940fdd4 | Axl11475581/Projects-Folder | /Python Exercises/Python Basics/Practical Exercise.py | 2,256 | 4.53125 | 5 | # 7 Exercise to practice the previous topics viewed 1
price_product_1 = input("What is the price of the product 1?: \n ")
quantity_product_1 = input("How many of the product 1 will you buy?: \n ")
price_product_2 = input("What is the price of the product 2?: \n ")
quantity_product_2 = input("How many of the product 2 will you buy?: \n ")
price_product_3 = input("What is the price of the product 3?: \n ")
quantity_product_3 = input("How many of the product 3 will you buy?: \n ")
result_product_1 = float(price_product_1)*float(quantity_product_1)
result_product_2 = float(price_product_2)*float(quantity_product_2)
result_product_3 = float(price_product_2)*float(quantity_product_3)
result = result_product_1+result_product_2+result_product_3
print("Your final price is: \n" + str(result))
# Exercise to practice the previous topics viewed 2
name_1 = input("Write your name: \n")
name_2 = input("Write your name: \n")
name_3 = input("Write your name: \n")
slices_in_pizza = input("How many slices had the pizza?: \n")
pizza_price = input("How much did the pizza cost? \n")
percentage_ate_by_person_1 = input(name_1 + "How many slices did you ate?: \n")
percentage_ate_by_person_2 = input(name_2 + "How many slices did you ate?: \n")
percentage_ate_by_person_3 = input(name_3 + "How many slices did you ate?: \n")
number_of_slices_ate_by_person_1 = float(percentage_ate_by_person_1)*float(slices_in_pizza)
number_of_slices_ate_by_person_2 = float(percentage_ate_by_person_2)*float(slices_in_pizza)
number_of_slices_ate_by_person_3 = float(percentage_ate_by_person_3)*float(slices_in_pizza)
price_paid_by_name_1 = float(percentage_ate_by_person_1)*float(pizza_price)
price_paid_by_name_2 = float(percentage_ate_by_person_2)*float(pizza_price)
price_paid_by_name_3 = float(percentage_ate_by_person_3)*float(pizza_price)
print(name_1 + " have ate " + str(number_of_slices_ate_by_person_1) + " of slices, and paid " + str(price_paid_by_name_1) + "$ for the meal")
print(name_2 + " have ate " + str(number_of_slices_ate_by_person_2) + " of slices, and paid " + str(price_paid_by_name_2) + "$ for the meal")
print(name_3 + " have ate " + str(number_of_slices_ate_by_person_3) + " of slices, and paid " + str(price_paid_by_name_3) + "$ for the meal") | true |
b8f090d72c4065c18bfd430e24ce11254b369fee | boluocat/core-python-programming | /Fiboacci.py | 1,147 | 4.4375 | 4 | '''递归 recursion
'''
def Fibonacci_recursion(n):
if n == 0:
return 0
elif n ==1:
return 1
else:
return Fibonacci_recursion(n-1)+Fibonacci_recursion(n-2)
'''迭代 iteration
前一个数字+当前数值=下一个数值
'''
def Fibonacci_interation(n):
if n ==0 :
return 0
elif n == 1:
return 1
else:
now = 1
pre = 0
for j in range(2,n+1):
next = pre + now
pre = now
now = next
return next
sp = 0
ep = 10
Fibonacci_recursion_list = []
Fibonacci_interation_list = []
while sp <= ep:
fibonacci_recursion = Fibonacci_recursion(sp)
fibonacci_interation = Fibonacci_interation(sp)
sp += 1
Fibonacci_recursion_list.append(fibonacci_recursion)
print('----------------------------------->')
print('sp = {}, Fibonacci = {}'.format(sp,fibonacci_recursion))
Fibonacci_interation_list.append(fibonacci_interation)
print('sp = {}, Fibonacci = {}'.format(sp,fibonacci_interation))
print(Fibonacci_recursion_list)
print(Fibonacci_interation_list) | false |
770dfec0ac2a38cd1d55cd33087dde8caf87db28 | ikamesh/Algorithms | /inputs.py | 1,314 | 4.375 | 4 | import random
"""This is file for generating input list for algorithms"""
#input method1 -- filling list with try-except
def infinite_num_list():
print("""
Press enter after each input.
Press 'x' to when done...!
""")
num_list = []
while True:
num = input("Enter num to fill the list : ")
if type(num) == 'int':
num_list.append(num)
elif num.lower() == "x":
break
else:
pass
return num_list
# input method2 -- filling element with for loop
def finite_num_list():
num_of_element = int(input("\nHow many elements do you have..? : "))
print(f"Enter {num_of_element} elements :")
num_list = []
for _ in range(num_of_element):
num_list.append(int(input()))
return num_list
# Input Method3 -- Generating num with random
def random_num_list_generator():
num_of_element = int(input("\nHow many num in list you want to generate : "))
num_list = []
for _ in range(num_of_element):
num_list.append(random.randint(0, num_of_element))
if input("\nDo you want to print the list (Y/N): ").lower() == "y":
print("\n", num_list)
return num_list
if __name__ == "__main__":
infinite_num_list()
finite_num_list()
random_num_list_generator()
| true |
7504bbb277af091a8b5b4bd1230ea416f169a5b3 | uit-inf-1400-2021/uit-inf-1400-2021.github.io | /lectures/oop-02-03-oo-concepts/code/extending.py | 1,281 | 4.375 | 4 | #!/usr/bin/env python3
"""
Based on code from the OOP book.
"""
class ContactList(list):
def search(self, name):
'''Return all contacts that contain the search value
in their name.'''
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacts = ContactList() # class level / shared
def __init__(self, name, email):
self.name = name
self.email = email
self.all_contacts.append(self)
def __str__(self):
return "({}, {}, {})".format(super().__str__(), self.name, self.email)
def __repr__(self):
return "({}, {}, {})".format(super().__repr__(), self.name, self.email)
t = ContactList([
Contact("foo", "foo@bar.com"),
Contact("foo2", "foo2@bar.com"),
])
t2 = ContactList()
print("t : ", t.search("foo2"))
print("t2 : ", t.search("foo2"))
print(Contact.all_contacts)
class Friend(Contact):
def __init__(self, name, email, phone):
self.name = name
self.email = email
self.phone = phone
class Friend(Contact):
def __init__(self, name, email, phone):
super().__init__(name, email)
self.phone = phone
| true |
d0fec4e684b774cbc4b07cce6c7d7bacfa6681ca | shortma1/Coyote | /day6.py | 615 | 4.25 | 4 | # # functions
# print("Hello") # print() is a function
# num_char = len("Hello") # len() is also a function
# print(num_char)
# def my_function(): # def defines function, my_function() is the name of the function, and : finished the function definition
# print("Hello")
# print("Bye")
# my_function() # to call the function, otherwise it will not run
# Defining Functions
# def my_function():
# #Do this
# #Then do this
# Then Call the function
# my_function()
# While Loops
# while something is True
# do something
number = 6
while number > 0:
print(f"Number is: {number}")
number -= 1
| true |
d2748867ecdaa65218c7ffecaf74fbaec0149789 | Vitaee/Python-Basic-Projects-5 | /BinarytoHexadecimal.py | 1,387 | 4.34375 | 4 | print("Welcome to the Binary/Hexadecimal Converter App\n")
a = int(input("Compute binary and hexadecimal values up to the following decimal number: "))
decimal = list(range(1, a+1)) #a+1 dedik çünkü range fonksiyonu son sayıyı almıyor.
binary = []
hexadecimal = []
for i in decimal: #for döngüsü oluşturarak decimal binary ve hexadecimal değerleri listelere atadık.
binary.append(bin(i))
hexadecimal.append(hex(i))
print("Generating lists.. complete!\n")
print("Using slices, we will now show a portion of each list")
b = int(input("What decimal number would you like to start at: "))
c = int(input("What decimal number would you like to stop at: "))
print("\nDecimal values from", b, "to", c,":")
for i in decimal[b-1:c]: #list slice kullanarak değerlei girilen aralıklarda yazdırmış olduk
print(i)
print("\nBinary values from",b, "to", c,":")
for i in binary[b-1:c]:
print(i)
print("\nHexadecimal values from", b, "to", c,":")
for i in hexadecimal[b-1:c]:
print(i)
input("\nPress Enter to see al values from 1 to " + str(a))
print("Decimal----Binary----Hexadecimal")
print("-------------------------------------")
for e,f,g in zip(decimal, binary, hexadecimal): #ve ilk başta girdiğimiz değeri mesela 40, 40 a kadar olan decimal , binary, hexadecimal değerleri yazdırdık.
print(str(e) + "----" + str(f) + "-----" + str(g))
| false |
a08f76a2e3ccc91b0e0ebae2c191fd09f7c43063 | piluvr/Python | /max.py | 233 | 4.125 | 4 | # your code goes here
nums =[]
input1 = int(input("Enter a number: "))
input2 = int(input("Enter a number: "))
input3 = int(input("Enter a number: "))
nums.append(input1)
nums.append(input2)
nums.append(input3)
print(str(max(nums)))
| true |
d8c92e58919689ff644004479aad9cbae61218e2 | shanjiang1994/LeetCode_for_DataScience | /Solutions/Array/88.Merge Sorted Array.py | 2,809 | 4.34375 | 4 |
'''
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Constraints:
-10^9 <= nums1[i], nums2[i] <= 10^9
nums1.length == m + n
nums2.length == n
'''
# Runtime: 32 ms, faster than 94.10% of Python3 online submissions for Merge Sorted Array.
# Memory Usage: 13.8 MB, less than 53.32% of Python3 online submissions for Merge Sorted Array.
nums1 = [1,2,3,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
def merge(nums1,m,nums2,n):
while m>0 and n>0: #incase the position are stepped to 0
if nums2[n-1]>=nums1[m-1]:
nums1[m+n-1]=nums2[n-1]
n-=1
else: #nums1[m-1]>=nums2[n-1]
nums1[m+n-1],nums1[m-1]= nums1[m-1],nums1[m+n-1] #it's okay we just let nums1[m+n-1] = nums1[m-1]
m-=1
# corner case
if m==0 and n>0:
nums1[:n] = nums2[:n]
print(nums1)
# call the function
merge(nums1,m,nums2,n)
########################################################
# Methodology: #
# - two pointer #
# - start from the end to the front #
########################################################
# [1,2,3,0,0,0]
# [2,5,6]
# Normal case:
# --------------------------------------------
# while m>0 and n>0:
# if nums1[m-1]<=nums2[n-1]?
# nums1[1,2,3,0,0,0]
# ↑(m-1)
# nums2[2,5,6]
# ↑(n-1)
# answer is True
# Then we let nums1[m+n-1]=nums2[n-1], and n = n-1
# nums1[1,2,3,0,0,6]
# ↑(m-1)
# nums2[2,5,6]
# ↑(n-1)
# so on and so forth until:
# else nums1[m-1]>nums2[n-1]
# nums1[1,2,3,0,5,6]
# (m-1)↑ ↑(m+n-1)
# nums2[2,5,6]
# ↑(n-1) = 0 # n still > 0
# move nums1[m-1] to the place nums1[m+n-1] and move m forward = m-1
# nums1[1,2,0,3,5,6]
# ↑(m-1)
# nums2[2,5,6]
# ↑(n-1) = 0
# # here is the previous loop we get:
# nums1[1,2,2,3,5,6]
# now n is zero, break the loop
# Other cases that we need to concern
# --------------------------------------------
# [1,2,3,0,0,0]
# 3
# [2,5,6]
# 3
# --------------------------------------------
# [0,0,0,0,0]
# 0
# [1,2,3,4,5]
# 5
# --------------------------------------------
# so we need add this :
# if m==0 and n>0:
# nums1[:n] = nums2[:n] | true |
92b23cdfa9a34ba5230c0353dbc1958a63a38658 | Skryvvara/DS1-Soullevel-Calculator | /soullevelcalc.py | 1,287 | 4.1875 | 4 | # returns cost of the given level
# when level = 12 the returned cost is from level 11 -> 12
def get_level_cost(level: int) -> int:
return int(round((0.02 * pow(level, 3)) + (3.06 * pow(level, 2)) + (105.6 * level) - 895, 0))
# returns the amount of possible levelups
# takes the current level and the amount of held souls
# a boolean can be given as last parameter to supress print statement
def get_possible_ups(currentLevel: int, souls: int, silent: bool = False) -> int:
level: int = currentLevel + 1
cost: int = get_level_cost(level)
ups: int = 0
while (souls >= cost):
if (silent == False):
print(f"Cost from level {level-1} to {level}: {cost} Souls.")
souls -= cost
level += 1
ups += 1
cost = get_level_cost(level)
return ups
# takes the current level and amount of souls from user input
# then prints the amount of possible level ups
def start():
try:
print("Enter your starting level.")
currentLevel: int = int(input("> "))
print("Enter the amount of souls you have.")
souls: int = int(input("> "))
ups: int = get_possible_ups(currentLevel, souls)
print(ups)
except:
print("Something happened :c, try entering real numbers.")
start()
| true |
cf79d548cfb65bb4ea3073cd0d1723981cea1400 | sydoruk89/math_series | /math_series/series.py | 1,177 | 4.1875 | 4 | def fibonacci(n):
"""
The function return the nth value in the fibonacci series.
Args:
n (int): integer
"""
if n >= 0:
if n < 2:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
else:
return 'Please provide a positive number'
def lucas(n):
"""
The function return the nth value in the lucas series.
Args:
n (int): integer
"""
if n >= 0:
if n == 0:
return 2
elif n == 1:
return n
else:
return lucas(n - 1) + lucas(n - 2)
else:
return 'Please provide a positive number'
def sum_series(n, prev = 0, next = 1):
"""
Calling this function with no optional parameters will produce numbers from the fibonacci series.
Args:
n (int): integer
prev (int, optional): [description]. Defaults to 0.
next (int, optional): [description]. Defaults to 1.
"""
if n >= 0 and prev >= 0 and next >= 0:
for i in range(n):
prev, next = next, prev + next
return prev
else:
return 'Please provide a positive number'
| true |
94e9bebee541b227fee0713a50ef389e0089f1bf | anshdholakia/Python_Projects | /setters and property_decorators.py | 1,179 | 4.21875 | 4 | class Employee:
def __init__(self,fname,lname):
self.fname=fname
self.lname=lname
# self.email=f"{self.fname}.{self.lname}@gamil.com"
def explain(self):
return f" This Employee is {self.fname} {self.lname}"
@property
def email(self):
if self.fname==None or self.lname== None:
return ("Email is not set")
return f"{self.fname}.{self.lname}@gamil.com" #To print hiro after changing fname that was Ansh, Setters are used.
@email.setter # How to set that when an email is typed, the fname and lname change automatically with respect to the email
def email(self,string):
print("Setting now...")
names=string.split("@")[0]
self.fname=names.string.split(".")[0]
self.lname=names.string.split(".")[1]
@email.deleter
def email(self):
self.fname= None
self.lname= None
Ansh= Employee("Ansh","Dholakia")
Lewis= Employee("Harry","Lewis")
print(Ansh.email)
Ansh.fname="Hiro"
# print(Ansh.email) # * It wont print Hiro instead of Ansh as the email is already initialised when made an object
# print(Ansh.fname)
del Ansh.email
print(Ansh.email) | false |
45521599af6d990c059840b0f1b70c9d3c482c6f | anshdholakia/Python_Projects | /map_filter.py | 1,387 | 4.21875 | 4 | # numbers=["1","2","3"]
#
# # for i in range(len(numbers)): # not suitable every-time to use a for loop
# # numbers[i]=int(numbers[i])
#
# # using a map function
# numbers=list(map(int,numbers))
#
#
# numbers[2]=numbers[2]+5
#
# print(numbers[2])
# def sq(a):
# return a*a
# num=[1,2,124,4,5,5,123,23,3,53]
# square=list(map(sq, num))
# print(square)
#
#
#
# num=[1,2,124,4,5,5,123,23,3,53]
# square=list(map(lambda x:x*x, num))
# print(square)
# def square(a):
# return a*a
#
# def cube(a):
# return a*a*a
#
# function=[square,cube]
#
# for i in range(6): #[0,6)
# func=list(map(lambda x:x(i),function ))
# print(func)
######################################## FILTER ########################################################
#FILTER FUNCTION
# It makes a list of elements on which the given function is true
# list_1=[1,2,3,4,5,6,7,8,9]
# def is_greater_5(num):
# return num>5
#
# # gr_than_5=filter(is_greater_5,list_1) this will give you a filter variable
# # print(gr_than_5)
# gr_than_5=list(filter(is_greater_5,list_1))
# print(gr_than_5)
######################################## REDUCE #############################################################3
from functools import reduce
list1=[1,2,3,4] # how to add all the numbers in the list
num=reduce(lambda x,i:x+i, list1)
print(num)
| true |
6c465540793c7d032822d027ff5e58837b8fcf31 | lovaraju987/Python | /learning concepts and practising/basics/sep,end,flash.py | 443 | 4.15625 | 4 | ''' sep, end, flash'''
print('slfhs',2,'shalds',end = ' ') # by default print statement ends with \n(newline).so, this 'end' is used to change to ending of the print statement when we required it
print('sfjsaa',3,'hissa')
print('sfjsaa',2,'hissa',sep = ' ') # by default multiple statemnets in one print without any space. so the 'sep' seperates the multiple statements in print with given string by ou
print('sfjsaa',3,'hissa',sep = ' ')
| true |
5733608db00de58d07cd64754e9592302e8e7dd6 | badri-venkat/Computational-Geometry-Algorithms | /PolygonHelper.py | 849 | 4.21875 | 4 | def inputPolygon(numberOfPoints):
polygonArray = []
print(
"Enter the points in cyclic order. Each point is represented by space-separated coordinates."
)
i=0
while i<numberOfPoints + 1:
x, y = map(int, input().split())
polygonArray.append(tuple([x, y]))
i+=1
if isValidPolygon(numberOfPoints, polygonArray):
polygonArray.pop()
return polygonArray
else:
return None
def printPolygon(polygonArray):
for count, point in enumerate(polygonArray):
print(count + 1, " ", point)
def isValidPolygon(numberOfPoints, polygonArray):
if numberOfPoints < 3 or polygonArray[0] != polygonArray[numberOfPoints]:
print("The 2D object is not a Polygon.")
return False
else:
print("The 2D object is a Polygon.")
return True
| true |
e01e7b007f7041fccc232fc3e9ab9ecacb44dec4 | kradical/ProjectEuler | /p9.py | 467 | 4.15625 | 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.
def test():
for a in range(1, 333):
for b in range(1000-a):
c = 1000-b-a
if a**2 + b**2 == c**2:
print(a*b*c)
return
if __name__ == "__main__":
test() | true |
732c172fbce4e4cac32875feb880b5e1c6ac59f4 | CucchiettiNicola/PythonProgramsCucchietti | /Compiti-Sistemi/Es32/Es32.py | 1,475 | 4.75 | 5 | the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quartiers']
# this first kind of for-loop goes trough a list
for number in the_count:
print(f"This is count {number}")
# same as above
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# also we can go trough mixed lists too
# notice we have to use {} since we don't know what's in it
for i in change:
print(f"I got {i}")
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counte
for i in range(0,6):
print(f"Adding {i} to the list")
# append is a function that lists understand
elements.append(i)
# this print out element values
print("Elements -> {}".format(elements))
# now we can print them out too
for i in elements:
print(f"Element was: {i}")
# Study Drills
# 1. Take a look at how you used range. Look up the range function to understand it.
# > range() function create a list of numbers from the first to the second.
# For example: range(2, 5) -> [2,3,4] (5 it's not included)
# 2. Could you have avoided that for-loop entirely on line 22 and just assigned range(0,6) directly
# to elements ?
# > elements = range(0,6)
# 3. Find the Python documentation on lists and read about them. What other operations can you do
# to lists besides append ?
# > clear, copy, extend, index, insert, pop, remove, reverse, sort
| true |
b0dfa1327acc7c44cf0c80db63aa3a2afb2dc23f | Gauravsahadev/Udemy-Python3-BootCamp-Practice-Problems | /Dictionary/two_lists.py | 201 | 4.21875 | 4 | list1 = ["CA", "NJ", "RI"]
list2 = ["California", "New Jersey", "Rhode Island"]
answer={list1[i]:list2[i] for i in range(3)}
print(answer)
#method second
answer2=dict(zip(list1,list2))
print(answer2) | false |
272d6b26253dfb3573be18709097920d1dbb07ab | cb-kali/Python | /Day13.py | 1,021 | 4.1875 | 4 | '''
Introduction to python class:
Class --> it's like a blueprint of codedesing.
class
method --> A function writen inside a class is called a method.
attributes --> a variable writen inside a class is called an attributes.
Introduction of a class/object
'''
# req:-
'''
You have to create a class, it should your name as an input, it should your name as an input, it should great you as well at the end
'''
class Greet: # create name
'''Creating a greet class for greeting an user '''
def create_name(self,name):
self.name = name
def display_name(self):
print(self.name)
def greet_user(self):
print(f'Hello, good to you are again in training class {self.name}')
'''
Object is the key... any thing you wanted to touch inside a class number other option
'''
# Object creation
superman = Greet()
superman.create_name('chetan')
superman.display_name()
superman.greet_user()
# OOPs concept --> object
# New object
a = Greet()
a.create_name('Anu')
a.display_name()
a.greet_user()
| true |
e4063d8bc9fa4a3a89eb99209c699aa2c667b722 | GibsonCool/python_Basis | /ptythonProject/python_basis/knowledgePoint/1.list_tuple_dict_set.py | 734 | 4.34375 | 4 | """ list 一个可变的有序表 """
listSimple = ['a', 'b', 'c']
print(listSimple)
print(listSimple[2])
print(listSimple[-2])
# print(listSimple[3]) # 会奔溃,越界
listSimple.append("sss")
print(listSimple)
listSimple.insert(2, "555")
print(listSimple)
""" tuple 一个不可变的有序表"""
tupleSimple = (1,) # 为了避免歧义定义只有一个元素的tuple时候需要在末尾加个逗号
print(tupleSimple)
tupleSimple
""" dict """
d = {'name': "cxx", 'age': 25, 'city': "shenzheng"}
print(d['name'])
print(d['age'])
d['age'] = 55
print(d['age'])
d['sorce'] = 100
print(d)
""" set """
setSimple = set(listSimple)
print(setSimple)
setSimple2 = set(['a', 'a', 2, 3, 4, 4])
print(setSimple2)
print(abs(-11))
| false |
5107df9089c13654010da7dc262f5812d84fd508 | GibsonCool/python_Basis | /ptythonProject/python_basis/knowledgePoint/13.浅拷贝、深拷贝.py | 944 | 4.34375 | 4 | """
==:比较的是值
is:比较的是地址值
"""
a = [11, 22, 33]
b = [11, 22, 33]
print(id(a))
print(id(b))
print(a == b)
print(a is b)
print("__________________________________________________________________________________")
"""
浅拷贝(copy.copy()):正常的赋值操作,只拷贝地址值或者叫内存引用,如果有多层只拷贝第一层,如果第一层是不可变比如元组,那么一层都不拷贝直接复制
深拷贝(copy.deepcopy()):直接拷贝值(地址值指向的内容)
"""
c = a
print(id(c))
print(c == a)
print(c is a)
import copy
d = copy.deepcopy(a)
print(id(d))
print(d == a)
print(d is a)
print("~~~~~~~~~~~~~~~~~~~~~~~~~")
c = [a, b]
print(id(c))
print(c)
e = copy.copy(c)
print(id(e))
print(e)
a.append(99)
print(c)
print(e)
print("~~~~~~~~~~~~~~~~~~~~~~~~~")
c = (a, b)
print(id(c))
print(c)
e = copy.copy(c)
print(id(e))
print(e)
a.append(99)
print(c)
print(e)
| false |
29e91abac0e3e1202cd2fef2f4666bfe681dc9be | robert0525/Python- | /hello.py | 393 | 4.1875 | 4 | first_name = input("What's is your first name? ")
print("Hello", first_name)
if first_name == "Robert":
print(first_name, "is learning Python")
elif first_name == "Maxi":
print(first_name, " is learning with fellow students in the Comunity! Me too!")
else:
print("You should totally learn Python, {}!".format(first_name))
print("Have a greate day {}!".format(first_name))
| true |
a8cb384dc0440a3f8ae962d3c543af8e179fa9cd | riteshelias/UMC | /ProgramFlow/guessgame.py | 1,734 | 4.125 | 4 | import random
answer = random.randint(1, 10)
print(answer)
tries = 1
print()
print("Lets play a guessing game, you can exit by pressing 0")
guess = int(input("try count - {}. Please enter a number between 1 and 10: ".format(tries)))
while guess != answer:
if guess == 0:
print("Bye, have a nice day!")
break
if tries == 5:
print("You have reached your guess limit. Bye!")
break
tries += 1
guess = int(input("try count - {}. Please enter a number between 1 and 10: ".format(tries)))
else:
if tries == 1:
print("Wow, correct guess at the first time!")
else:
tries += 1
print("You took {} tries to guess right!".format(tries))
# if guess == answer:
# print("Woah! You got that right at the first go!")
# else:
# if guess < answer:
# print("Please guess a higher number")
# else:
# print("Please guess a lower number")
# guess = int(input("Try again: "))
# if guess == answer:
# print("You get it finally")
# else:
# print("Oops! Still wrong!")
# if guess != answer:
# if guess < answer:
# print("Please guess a higher number")
# else:
# print("Please guess a lower number")
# guess = int(input("Guess again: "))
# if guess == answer:
# print("You finally got it")
# else:
# print("Sorry, you still didn't get it")
# else:
# print("Woah! You got it right the first time")
# if guess < 1 or guess > 10:
# print("The entered number is not in the requested range")
# elif guess < answer:
# print("Please guess a higher number")
# elif guess > answer:
# print("Please guess a lower number")
# else:
# print("You guessed right!")
| true |
16f595b7e1ff1b8b22ab8ba1221d96448a03d15e | daniel10012/python-onsite | /week_01/03_basics_variables/07_conversion.py | 526 | 4.375 | 4 | '''
Celsius to Fahrenheit:
Write the necessary code to read a degree in Celsius from the console
then convert it to fahrenheit and print it to the console.
F = C * 1.8 + 32
Output should read like - "27.4 degrees celsius = 81.32 degrees fahrenheit"
NOTE: if you get an error, look up what input() returns!
'''
def fahrenheit(c):
f = int(c*1.8 + 32)
return f
c = int(input("Degrees Celcius:"))
print(f"{c} degrees celcius = {fahrenheit(c)} degrees fahrenheit") | true |
9e6b89661cd68140884634d1a7978e4afc899e98 | daniel10012/python-onsite | /week_02/11_inheritance/01_class_attributes.py | 910 | 4.40625 | 4 |
'''
Flush out the classes below with the following:
- Add inheritance so that Class1 is inherited by Class2 and Class2 is inherited by Class3.
- Follow the directions in each class to complete the functionality.
'''
class Class1:
def __init__(self, x):
self.x = x
# define an __init__() method that sets an attribute x
class Class2(Class1):
def __init__(self, x, y):
super().__init__(x)
self.y = y
# define an __init__() method that sets an attribute y and calls the __init__() method of its parent
class Class3(Class2):
def __init__(self, x, y,z):
super().__init__(x,y)
self.z = z
# define an __init__() method that sets an attribute z and calls the __init__() method of its parent
# create an object of each class and print each of its attributes
obj1 = Class1(3)
obj2 = Class2(4, 5)
obj3 = Class3(7, 9, 8)
print(obj3.y) | true |
fe26c3fa3494717d2cb65c234594323fae19a5f0 | daniel10012/python-onsite | /week_04/intro_apis/01_countries.py | 1,117 | 4.375 | 4 | '''
Use the countries API https://restcountries.eu/ to fetch information
on your home country and the country you're currently in.
In your python program, parse and compare the data of the two responses:
* Which country has the larger population?
* How much does the are of the two countries differ?
* Print the native name of both countries, as well as their capitals
'''
import requests
url1 = "https://restcountries.eu/rest/v2/name/france?fullText=true"
url2 ="https://restcountries.eu/rest/v2/name/germany?fullText=true"
r1 = requests.get(url1).json()
r2 = requests.get(url2).json()
country1 = r1[0]["name"]
country2 = r2[0]["name"]
population1 = r1[0]["population"]
population2 = r2[0]["population"]
area1 = r1[0]["area"]
area2 = r2[0]["area"]
if population1 > population2:
print(f"{country1} is more populous than {country2}")
else:
print(f"{country2} is more populous than {country1}")
print(f"the difference in area is {abs(population2-population1)} sq km")
print(f"{r1[0]['nativeName']} has for capital {r1[0]['capital']}")
print(f"{r2[0]['nativeName']} has for capital {r2[0]['capital']}") | true |
06774114cb67d9626933f4f3d752b8beb4f9f2b2 | daniel10012/python-onsite | /week_03/01_files/04_rename_doc.py | 1,156 | 4.125 | 4 | '''
Write a function called sed that takes as arguments a pattern string,
a replacement string, and two filenames; it should read the first file
and write the contents into the second file (creating it if necessary).
If the pattern string appears anywhere in the file, it should be
replaced with the replacement string.
If an error occurs while opening, reading, writing or closing files,
your program should catch the exception, print an error message,
and exit.
Solution: http://thinkpython2.com/code/sed.py.
Source: Read through the "Files" chapter in Think Python 2e:
http://greenteapress.com/thinkpython2/html/thinkpython2015.html
'''
def sed(pattern_string, replacement_string, file1,file2):
try:
with open(file1,"r") as fin:
content = fin.readlines()
except FileNotFoundError:
print(f"{file1} doesn't exist")
try:
with open(file2, "w") as fout:
for line in content:
new_line = line.replace(pattern_string,replacement_string)
fout.write(new_line)
except UnboundLocalError:
pass
sed("strings", "Notstrings", "words3.txt", "wordss3.txt")
| true |
cd99f695faa50653c2ca9488547a528059c94d62 | daniel10012/python-onsite | /week_02/06_tuples/01_make_tuples.py | 502 | 4.34375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
my_list = [5,3,32,1,3,9,5,3,2,2,5]
my_list.sort()
if len(my_list) % 2 != 0:
my_list.append(0)
#
print(my_list)
pairs = [(my_list[i], my_list[i+1]) for i in range(0,len(my_list),2)]
print(pairs)
for i in pairs:
print(i)
| true |
fd1561a9a0a9c1cf29c24efbf299c0e3e135fa19 | balaramhub1/Python_Test | /Tuple/Tuple_03.py | 668 | 4.125 | 4 | '''
Created on Jul 17, 2014
@author: HOME
The script is to see the function of T.index[x] and T.count(x) methods of Tuple
'''
list1=['hello','balaram']
color = ("red","green","blue",list1)
fruit =(5,"lemon",8,"berry",color,"grapes","cherry")
numtup=(4,6,3,2,5,23,3,2,4,2,3,5)
print("Elements of List1 are : ",list1)
print("Elements of tuple 'color' are : ",color)
print("Elements of tuple 'fruit' are : ",fruit)
print("Index value of 'hello' is : ",fruit[4][3][0].index('hello'))
print("Index value of 'blue' is : ",fruit[4].index('blue'))
print("count of '3' in numtup is : ",numtup.count(3))
print("Index of '3' in numtup is : ",numtup.index(3))
| true |
bd2ca872c954096e50e818e402969a3bc9a1ff8b | balaramhub1/Python_Test | /Math/math_03.py | 394 | 4.125 | 4 | '''
Created on Jun 14, 2020
Usage of Random module
@author: beherb2
'''
import random
print(random.random())
# Choose a random number from a list
l=[1,2,3,4,5,6]
print(random.choice(l))
# generate a random number between a range
print(random.randint(10,100))
# end number is not included
print(random.randrange(10,100))
# generate a floating random number
print(random.uniform(10,20))
| true |
9b1e5b1a994bc633e8eabe5131f79db0bbfd2c21 | jage6277/Portfolio | /Discrete Structures/Unsorted to Sorted List.py | 1,559 | 4.21875 | 4 | # This function takes two sorted lists and merges them into one sorted list
# Input: L1,L2 - Two sorted lists
# Output: L - One sorted list
def merge(L1,L2):
L = [] # Array where the sorted list will be stored
while len(L1) != 0 and len(L2) != 0:
# While L1 and L2 are both nonempty
if L1[0] < L2[0]:
# If L1 contains the 1st smaller element, remove element and add to end of L
print(L1[0],end="")
print('<', end = "")
print(L2[0], end = "")
print()
L.append(L1[0])
L1.remove(L1[0])
else:
# If L2 contains the 1st smaller element, remove element and add to end of L
print(L2[0], end = "")
print('<', end = "")
print(L1[0], end = "")
print()
L.append(L2[0])
L2.remove(L2[0])
while len(L1) != 0:
L.append(L1[0])
L1.remove(L1[0])
while len(L2) != 0:
L.append(L2[0])
L2.remove(L2[0])
return L
# This function takes an unordered list and transforms it to an ordered list
# Input: An unordered list
# Returns: A ordered list (ascending)
def mergeSort(L):
if len(L) > 1:
# Check if the size of the list is greater than 1
m = len(L) // 2 # m = floor(n/2)
L1 = L[:m] # L1 = a1, a2, ..., am
L2 = L[m:]# L2 = am+1, am+2, ..., an
L = merge(mergeSort(L1), mergeSort(L2))
return L
print(mergeSort([1, 3, 2, 7, 12, 14, 5, 9])) | true |
8364b704a8261dc3ffc774e747dfd430550cc587 | jarmer7043/Functions_Parameters-Global_Variables | /diceRoller.py | 1,748 | 4.21875 | 4 | #Dice rolling program
#Aim is to roll a 6 or roll a number twice in a row
import random
import time
s1 = "- - - - -\n| |\n| O |\n| |\n- - - - -\n" #the dice prints
s2 = "- - - - -\n| O |\n| |\n| O |\n- - - - -\n"
s3 = "- - - - -\n| O |\n| O |\n| O |\n- - - - -\n"
s4 = "- - - - -\n| O O |\n| |\n| O O |\n- - - - -\n"
s5 = "- - - - -\n| O O |\n| O |\n| O O |\n- - - - -\n"
s6 = "- - - - -\n| O O |\n| O O |\n| O O |\n- - - - -\n"
def roll(): #rolling a random number
print("rolling.....\n")
roll = random.randint(1,6)
return roll
def show_dice(roll): #what that roll equates to - dice print
if roll == 1:
print(s1)
elif roll == 2:
print(s2)
elif roll == 3:
print(s3)
elif roll == 4:
print(s4)
elif roll == 5:
print(s5)
elif roll == 6:
print(s6)
def Until6(roll,show_dice):
ask = input("Would you like to roll the dice? (y/n)")#give the user an option not to roll
if ask == "y":
myroll = roll()
while myroll != 6: #if the roll isn't 6, keep going until it is
time.sleep(1)
show_dice(myroll)
else:
print(":(")
def UntilTwice(roll,show_dice):
ask = input("Would you like to roll the dice? (y/n)")#give the user an option not to roll
if ask == "y":
myroll1 = 0 #creating both variables
myroll2 = 1
while myroll1 != myroll2: #while both rolls are different
myroll1 = roll() #roll until both rolls are the same
show_dice(myroll1)
time.sleep(1)
myroll2 = roll()
show_dice(myroll2)
time.sleep(1)
else:
print(":(")
| false |
f74a9179d69a3f625a19a7688a9ff452c2b2b651 | samahmood1/Python-Basic | /for_challenge2.py | 854 | 4.375 | 4 | #!/usr/bin/env python3
farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]},
{"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]},
{"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}]
animals = ["cats", "chickens", "cows", "llamas", "pigs", "sheep"]
def animals_in_farm(animal_list):
global animals
return [a for a in animal_list if a in animals]
NE_animals = animals_in_farm(farms[0]["agriculture"])
print(f'Animal in NE farm {NE_animals}')
farm_name = input("Choose a farm (NE Farm, W Farm, or SE Farm)>> ")
for farm in farms:
if farm["name"] == farm_name:
print(f'Plant and animals raised in {farm_name} are {farm["agriculture"]}')
print(f'Animals raised in {farm_name} are {animals_in_farm(farm["agriculture"])}')
| false |
9ca92b5f121723702b7901dfa4d2d3f86885b077 | rnagle/pycar | /project1/step_2_complete.py | 810 | 4.25 | 4 | # Import built-in python modules we'll want to access csv files and download files
import csv
import urllib
# We're going to download a csv file...
# What should we name it?
file_name = "banklist.csv"
# Use urllib.urlretrieve() to download the csv file from a url and save it to a directory
# The csv link can be found at https://www.fdic.gov/bank/individual/failed/banklist.html
target_file = urllib.urlretrieve("http://www.fdic.gov/bank/individual/failed/banklist.csv", file_name)
# Open the csv file
with open(file_name, "rb") as file:
# Use python's csv reader to access the contents
# and create an object that represents the data
csv_data = csv.reader(file)
# Loop through each row of the csv...
for row in csv_data:
# and print the row to the terminal
print row
| true |
2f00505d175bd72b047b898d367fc9a201b9c0e8 | vivekbhadra/python_samples | /count_prime.py | 684 | 4.125 | 4 | '''
COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
count_primes(100) --> 25
By convention, 0 and 1 are not prime.
'''
"""
Spyder Editor
This is a temporary script file.
"""
def isprime(num):
flag = True
for n in range(2, (num // 2) + 1):
if num % n == 0:
flag = False
if flag:
print('{} is prime'.format(num))
return flag
def count_primes(num):
count = 0
for n in range(1, num):
if isprime(n):
count += 1
return count
def main():
print(count_primes(100))
if __name__ == '__main__':
main()
| true |
559e6721d46d0156427efb46a07815d8852c85d8 | jfxugithub/python | /面向对象的高级编程/staticmethod.py | 475 | 4.15625 | 4 | """
静态方法定义:
通过修饰器staticmethod来进行修饰,可以不用传参数,第一参数默认为cls
加载时机:随着类的加载而加载
"""
class Student:
address = "太阳系"
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod #修饰静态方法
def get_address():
return Student.address
print(Student.get_address()) #不需要声明对象而直接调用方法
| false |
717f322356962fb6fd13819bdeb5f133f56a0553 | Mathtzt/Python | /collections/src/Collections-pt1/aula2.2.py | 1,502 | 4.34375 | 4 | ##Esse arquivo foi criado para o estudo das Coleções no python em especial as listas e tuplas.
from abc import ABCMeta, abstractmethod, ABC
class Conta(metaclass=ABCMeta):
def __init__(self, codigo):
self._codigo = codigo
self._saldo = 0
def deposita(self, valor):
self._saldo += valor
@abstractmethod
def passa_o_mes(self):
pass
def __str__(self):
return "[>>Codigo {} saldo {}<<]".format(self._codigo, self._saldo)
class ContaCorrente(Conta):
def passa_o_mes(self):
self._saldo -= 2
class ContaPoupanca(Conta):
def passa_o_mes(self):
self._saldo *= 1.01
self._saldo -= 3
class ContaInvestimento(Conta):
pass
### Testes
if (__name__ == "__main__"):
## 1
print("\nTeste 1")
conta1 = ContaCorrente(1)
conta1.deposita(1000)
conta1.passa_o_mes()
print(conta1)
## 2
print("\nTeste 2")
conta2 = ContaPoupanca(2)
conta2.deposita(1000)
conta2.passa_o_mes()
print(conta2)
## 3 - Utilizando o polimorfismo com a listas
print("\nTeste 3")
conta1 = ContaCorrente(1)
conta1.deposita(1000)
conta2 = ContaPoupanca(2)
conta2.deposita(1000)
contas = [conta1, conta2]
for conta in contas:
conta.passa_o_mes() #duck typing
print(conta)
## 4 - Forçando um metodo abstrato. Objetivo é dar um erro mostrando que é necessário implementar o método passa_o_mes
print("\nTeste 4")
ContaInvestimento() | false |
3c043341d16e6c27c947230779d248f00b72a6c6 | glennpantaleon/python2.7 | /doughnutJoe.py | 2,197 | 4.4375 | 4 | '''
A program designed for the purpose of selling coffee and donuts.
The coffee and donut shop only sells one flavor of coffee and donuts at a fixed price.
Each cup of coffee cost seventy seven cents and each donut cost sixty four cents.
This program will imediately be activated upon a business.
\/\/\/\\/\/\/\
DOUGHNUT JOE
\/\/\/\\/\/\/\
__ cups of coffee: $__.__
__ doughnuts: $__.__
tax: $__.__
Amount Owed: $_____
Thank you for purchasing local.
'''
import os
tax_rate = 0.0846
coffee_cost = 0.77
donut_cost = 0.64
def getOrder ():
'''Retrives the customer's order.'''
number_of_donuts = raw_input("How many donuts would you like to order? ")
donut = int(number_of_donuts)
number_of_coffee = raw_input("How many cups of coffee do you want? ")
coffee = int(number_of_coffee)
return donut,coffee
def calcAmount (donut,coffee):
'''Calculates the total amount of money paid for the coffee and donuts.'''
total_cost_of_donuts = donut * donut_cost
total_cost_of_coffee = coffee * coffee_cost
bill_before_tax = total_cost_of_donuts + total_cost_of_coffee
total_tax = bill_before_tax * tax_rate
total_cost = bill_before_tax + total_tax
return total_cost_of_donuts,total_cost_of_coffee,bill_before_tax,total_tax,total_cost
def presentBill (total_cost_of_donuts,total_cost_of_coffee,bill_before_tax,total_tax,total_cost,donut,coffee):
'''Presents the bill after the calculations are done.'''
print "/\/\/\/\/\/\/\/\/\/\\"
print " DOUGHNUT JOE "
print "/\/\/\/\/\/\/\/\/\/\\"
print str(coffee) + " cups of coffee: $" + str (total_cost_of_coffee)
print str(donut) + " doughnuts: $" + str (total_cost_of_donuts)
print "Tax: $" + str (total_tax)
print "Amount Owed: $" + str (total_cost)
print '''
Thank you for buying
'''
def main():
donut,coffee = getOrder ()
total_cost_of_donuts,total_cost_of_coffee,bill_before_tax,total_tax,total_cost = calcAmount (donut,coffee)
presentBill (total_cost_of_donuts,total_cost_of_coffee,bill_before_tax,total_tax,total_cost,donut,coffee)
os.system ("pause")
main()
| true |
7f7d73dd0b2be68187d745c8a3893d52a587a2e3 | erickclasen/PMLC | /xor/xor_nn_single_layer.py | 1,571 | 4.21875 | 4 | import numpy as np
# sigmoid function
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
print("XOR: With a hidden layer and the non-linear activation function on the output layer.")
print("Fails!")
'''
2 inputs 1 output
l0 is the input layer values, aka X
l1 is the hidden layer values
syn0 synapse 0 is the weight matrix for the output layer
b0 is the bias for the output layer.
X is the input matrix of features.
Y is the target to be learned.
'''
# input dataset
X = np.array([ [0,0],
[0,1],
[1,0],
[1,1] ])
# output dataset
y = np.array([[0,1,1,0]]).T
# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(1)
# How wide are the layers, how many neurons per layer?
input_layer = 2
output_layer = 1
# initialize weights randomly with mean 0
# syn0 weights for input layer with input_layers to output_layers dimension
syn0 = 2*np.random.random((input_layer,output_layer)) - 1
# One output_layer bias
b0 = 2.0*np.random.random((1,output_layer)) - 1
for iter in range(10000):
# forward propagation
l0 = X
l1 = nonlin(np.dot(l0,syn0) + b0)
# how much did we miss?
l1_error = y - l1
# multiply how much we missed by the
# slope of the sigmoid at the values in l2
l1_delta = l1_error * nonlin(l1,True)
# update weights and biases
syn0 += np.dot(l0.T,l1_delta)
b0 += np.sum(l1_delta,axis=0,keepdims=True)
print("Output After Training:")
print(l1)
| true |
71716899604df84cc40aa5650cad8dc91df5c05c | shouvikbj/IBM-Data-Science-and-Machine-Learning-Course-Practice-Files | /Python Basics for Data Science/loops.py | 532 | 4.34375 | 4 | num = 2
# for loop in a range
for i in range(0, num):
print(i + 1)
for i in range(num):
print(i + 1)
# for loop in case of tuples
names = ("amrita", "pori", "shouvik", "moni")
for name in names:
print(name)
# for loop in case of lists
names = ["amrita", "pori", "shouvik", "moni"]
for name in names:
print(name)
# for loop in case of dictionaries
names = {
"name_1": "amrita",
"name_2": "pori",
"name_3": "shouvik",
"name_4": "moni"
}
for key, name in names.items():
print(f"{key} : {name}") | true |
a2318f87b16e2a7ddbb2a2a14fea964e69923972 | MichalKotecki/DataCiphering | /ModularInverse/ModularInverse.py | 1,517 | 4.1875 | 4 | # Title: Modular Inverse in Python
# Author: Michał Kotecki
# Date: 5/09/2020
# Description:
# This algorithm is used to find S in (a * S) mod b = 1, given that a and b are known.
# This kind of problem is called 'Prime Factorization'.
class TableRow:
def __init__(self, q, r, s):
self.q = q
self.r = r
self.s = s
def __str__(self) -> str:
return f"q: {self.q}, r: {self.r}, s: {self.s} \n"
def __repr__(self) -> str:
return f"q: {self.q}, r: {self.r}, s: {self.s} \n"
def modularInverse(a, b):
correctPositions = lambda a, b: (a, b, 1, 0) if a > b else (b, a, 0, 1)
r0, r1, s0, s1 = correctPositions(a,b)
table = []
table.append(TableRow(0,r0,s0))
table.append(TableRow(0,r1,s1))
while True:
# calculating current row
q = int(table[-2].r / table[-1].r)
r = table[-2].r - (q * table[-1].r)
s = table[-2].s - (q * table[-1].s)
table.append(TableRow(q,r,s))
if r == 1:
# print(table)
return s if s > 0 else s + b
elif r == 0:
# print(table)
return -1
if __name__ == '__main__':
print("Modular Inverse Algorithm")
print("This is used to find S in (a * S) mod b = 1 given that a and b are known.")
print("Enter a:")
a = int(input())
print("Enter b:")
b = int(input())
filterResult = lambda num: f"The solution is {num}." if num > 0 else "There is no solution."
print(filterResult(modularInverse(a, b))) | false |
c1649abbfeea25a8b318f96a8dfe086a1d8a1a40 | cyphar/ncss | /2014/w2/q4complex.py | 1,806 | 4.1875 | 4 | #!/usr/bin/env python3
# Enter your code for "Mysterious Dates" here.
# THIS WAS MY INITAL SOLUTION.
# IT DOES NOT PASS THE TEST CASES.
# However, the reason I added this is because this code will take any date
# format (not just the given ones) and brute-force the first non-ambiguous
# representation. It is (in my opinion) a more "complete" solution.
import re
import itertools
PATTERN = r"(\d+).(\d+).(\d+)"
MONTHS = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
DAY = 0
MONTH = 1
YEAR = 2
def is_month(part):
return 0 < part <= 12
def is_day(part, month):
return 12 < part <= MONTHS[month]
def is_year(part, month):
return MONTHS[month] < part <= 9999
def brute_force_order(date):
for fmt in itertools.permutations([DAY, MONTH, YEAR], 3):
fmt = list(fmt)
day = date[fmt.index(DAY)]
month = date[fmt.index(MONTH)]
year = date[fmt.index(YEAR)]
if not is_month(month) or not is_day(day, month) or not is_year(year, month):
continue
return [fmt.index(DAY), fmt.index(MONTH), fmt.index(YEAR)]
return None
def ambiguity_order(dates):
for date in dates:
order = brute_force_order(date)
if order:
break
else:
return None
fmt = {
"day": order[DAY],
"month": order[MONTH],
"year": order[YEAR],
}
return fmt
def main():
with open("ambiguous-dates.txt") as f:
data = f.read()
dates = re.findall(PATTERN, data)
if not dates:
return
dates = [tuple(int(p) for p in d) for d in dates]
order = ambiguity_order(dates)
# No order found.
if not order:
print("No unambiguous dates found")
return
for date in dates:
day = date[order["day"]]
month = date[order["month"]]
year = date[order["year"]]
print("%.4d-%.2d-%.2d" % (year, month, day))
if __name__ == "__main__":
main()
| true |
954ecbf16326abddafe9b391a88fabe0393cc50e | dhwani910/w18c-fizzbuzz | /app.py | 409 | 4.125 | 4 | numbers = [10, 22, 27, 30, 29, 18, 21, 1, 28, 20, 18, 5, 19, 9, 11, 22, 15, 20, 0, 6, 12, 7, 17]
def fizzbuzz(number):
if(number % 3 == 0 and number % 5 == 0):
print("fizzbuzz")
elif(number % 3 ==0):
print("fizz")
elif(number % 5 == 0):
print("buzz")
else:
print("something went wrong")
for number in numbers:
fizzbuzz(number)
| false |
76c2a205292169daea9e1c5c085dea4525992e94 | javedbaloch4/python-programs | /01-Basics/015-print-formatting.py | 490 | 4.125 | 4 | #!C:/python/python
print("Content-type: text/html\n\n")
s = "string"
x = 123
# print ("Place my variable here: %s" %s) # Prints the string and also convert this into string
# print("Floating point number: %0.3f" %1335) # Prints the following floating number .3 is decimal point
# print("Convert into string %r" %x) # %r / %s convert into string
# print("First: %s Second: %s Third: %s" %('Hi','Hello',3))
print("First: {x} Second: {y} Third: {x}" .format(x='Interested', y= 'Hi'))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.