blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
8ff5973935a0e39f686eb0fa6b28a16ae7c3f0ff
victorrgouvea/URI-Problems
/Prova 2/2803.py
427
4.15625
4
norte = ['roraima', 'acre', 'amapa', 'amazonas', 'para', 'rondonia', 'tocantins'] #Vetor com todos os estados da região norte estado = input() #Entrada do nome do estado em questão if estado in norte: #Daqui para baixo, verfico se o estado da entrada está ou não na lista de estados do norte, e então imprimo a mensagem baseada nesse verificação print("Regiao Norte") else: print("Outra regiao")
false
7122dd20fb1d3b60bce4eef29dccd9592f929c0e
Bhaktibj/Python_Programs
/FunctionalPrograms/TwoDList.py
409
4.1875
4
# program to print the two dimensional array or list rows = int(input("Enter row size \n")) col = int(input("Enter column size \n")) two_d_array = [[0 for i in range(col)] for j in range(rows)] print("Enter the Elements of the list") for i in range(rows): for j in range(col): # loop for creating the list elements during run time tow_d_array[i][j] = int(input()) print(two_d_array)
true
c0ac922bc8a5db10aaa890df7cc44831999648ee
Bhaktibj/Python_Programs
/ObjectOrientedProgramming/Regular_Expression_2.py
2,046
4.5
4
""" Regular Expression Demonstration I/P -> read in the Message Logic -> Use Regex to do the following Replace <<name>> by first name of the user ( assume you are the user) replace <<full name>> by user full name.replace any occurance of mobile number that should be in format 91-xxxxxxxxxx by your contact number. replace any date in the format XX/XX/XXXX by current date. O/P -> Print the Modified Message. """ import re # re is python module import datetime class RegularExpression: def regex_function(self): string = " Hello <<user-name>>,we have your full name as <<full-name>> in our system." first_name = input("Enter your first name: ") string_one = re.sub("<<user-name>>", first_name,string) # sub method is used to replace the text. full_name = input("Enter your full name: ") string_two = re.sub("<<full-name>>", full_name,string_one) # print(string_two,"\n") try: contact_string = "Your contact number is 91-xxxxxxxxxx." mobil_number = int(input("Enter Your Mobile Number: ")) new_mobile_num = str(mobil_number) new_string = re.sub("xxxxxxxxxx", new_mobile_num, contact_string) # print(new_string, "\n") except ValueError: print("Enter the data in number\n") date_string = "please, let us know in case of any clarification Thank you BridgeLabs,on <<Today>>-XX/XX/XXXX. " date = datetime.date.today() # date.today is display the today date replace_date = str(date) day = date.strftime("%A") # this method is used to display the day in full name . day1 = re.sub("<<Today>>", day, date_string) bridge_lab = re.sub("XX/XX/XXXX", replace_date, day1) # print(bridge_lab, "\n") print("Complete String") print(string_two , new_string) print(bridge_lab) object1 = RegularExpression() if __name__ == '__main__': try: object1.regex_function() except UnboundLocalError: print("try again by entering the valid data")
true
cca2236947de8ab6d44a9336a1bd80eb26dc7533
hexinyu1900/LearnPython
/face to/07 在初始化方法内部添加属性.py
566
4.1875
4
# 定义类模板 class cat: def __init__(self): """初始化方法""" print("1.__init__初始化方法主要用来初始化数据") # 在类的内部添加属性 self.属性名 = 属性初始值 self.name = "汤姆猫" print("2.初始化方法在使用类模板创建对象时自动调用") def eat(self): print("---%s eat fish---" % self.name) # 使用类模板创建对象 tom = cat() # 在类的外部访问属性 对象名.属性名 print(tom.name) # 在类的外部调用 对象名.方法名() tom.eat()
false
8423408fd2e86fa0aedd018599c52aaae2f52555
hexinyu1900/LearnPython
/ifProject/05 函数.py
775
4.15625
4
# # 定义函数 # def say_hello(): # ''' # 一个函数的文档注释 # :return: # ''' # print("你好") # print("hello") # print("hi") # # 调用函数 # say_hello() # # 查看注释 # help(say_hello) # def sum_2_num(): # ''' # 当前函数实现两个数字求和功能 # :return: # ''' # num1 = int(input("请输入第一个加数:")) # num2 = int(input("请输入第二个加数:")) # sum = num1+num2 # print("%d + %d = %d" % (num1, num2, sum)) # # sum_2_num() def sum_2_num(num1, num2): ''' 当前函数实现两个数字求和功能 :return: ''' sum = num1 + num2 print("%d + %d = %d" % (num1, num2, sum)) return sum sumaa = sum_2_num(20, 50) print("----result:", sumaa)
false
72e1619506c35ee77ad2d5a9644b274668402ab6
MULI506/robolab-group138
/src/planettest.py
2,201
4.21875
4
#!/usr/bin/env python3 import unittest from planet import Direction, Planet class ExampleTestPlanet(unittest.TestCase): def setUp(self): """ Instantiates the planet data structure and fills it with paths example planet: +--+ | | +-0,3------+ | | 0,2-----2,2 (target) | / +-0,1 / | | / +-0,0-1,0 | (start) """ # set your data structure self.planet = Planet() # add the paths self.planet.add_path(((0, 0), Direction.NORTH), ((0, 1), Direction.SOUTH), 1) self.planet.add_path(((0, 1), Direction.WEST), ((0, 0), Direction.WEST), 1) def test_target_not_reachable_with_loop(self): # does the shortest path algorithm loop infinitely? # there is no shortest path self.assertIsNone(self.planet.shortest_path((0, 0), (1, 2))) class YourFirstTestPlanet(unittest.TestCase): def setUp(self): """ Instantiates the planet data structure and fills it with paths MODEL YOUR TEST PLANET HERE (if you'd like): """ # set your data structure self.planet = Planet() # ADD YOUR PATHS HERE: # self.planet.add_path(...) def test_integrity(self): # were all paths added correctly to the planet # check if add_path() works by using get_paths() self.fail('implement me!') def test_empty_planet(self): self.fail('implement me!') def test_target_not_reachable(self): self.fail('implement me!') def test_shortest_path(self): # at least 2 possible paths self.fail('implement me!') def test_same_length(self): # at least 2 possible paths with the same weight self.fail('implement me!') def test_shortest_path_with_loop(self): # does the shortest path algorithm loop infinitely? # there is a shortest path self.fail('implement me!') def test_target_not_reachable_with_loop(self): # there is no shortest path self.fail('implement me!') if __name__ == "__main__": unittest.main()
true
756902115eeed0bad858fb363067449062257dd4
rcollins22/ClassNotes
/python_notes/python_101/exceptions/try.py
937
4.28125
4
""" Create a program that asks for a number between 10 - 101. If the user enters anything that is not a number, or is less than 10 or greater than 101 throw some sort of insult. If the number is 42 print a very positive message. If the number is -1 disregaurd the first point and print a message about being a smart person. Any other print a message that includes the number given. """ num = int(input("Hello, please input a number between 10 and 101\n")) try: num==int(num) ## TESTS IF THE INPUT IS A NUMBER ### except ValueError: ### ALLOWS ME TO HANDLE THE DIFFERENT VALUES ### Print("Are you dumb?\n") num = int(input("Please Try Again")) while num < 10 or num > 101: print("Dude, C'mon") num = int(input("Please Try Again")) if num == -1: print("Good Job Smarty pants") exit() elif num == 42: print("You're Awesome!") exit() print(num) #####
true
2693155dbc621f2cdea55edd058315076698760f
rcollins22/ClassNotes
/python_notes/python_102/nested_list/exercise_102e.py
2,265
4.25
4
""" 1. Sum the Numbers Create a list of numbers, print their sum. """ list=[4,5,7,8] print(sum(list)) #------------------------------------------------------------------------------------------------------------ """ 2. Largest Number Create a list of numbers, print the largest of the numbers. """ list=[4,8,6,5] list.sort() print(list[-1]) #------------------------------------------------------------------------------------------------------------ """ 3. Smallest Number Create a list of numbers, print the smallest of the numbers. """ list=[4,8,6,5] list.sort() print(list[:1]) #------------------------------------------------------------------------------------------------------------ """ Even Numbers Create a list of numbers, print each number in the list that is even. """ list=[4,8,6,5] for even in list: if even % 2 == 0: print(even) #------------------------------------------------------------------------------------------------------------ """ Positive Numbers Create a list of numbers, print each number in the list that is greater than zero. """ list=[-5,15,2,-7,-3,8] for good in list: if good>0: print(good) #------------------------------------------------------------------------------------------------------------ """ Positive Numbers II Create a list of numbers, create a new list which contains every number in the given list which is positive. """ list=[-5,15,2,-7,-3,8] pos=[] for good in list: if good>0: pos.append(good) print(pos) #------------------------------------------------------------------------------------------------------------ """ Multiply a list Create a list of numbers, and a single factor (also a number), create a new list consisting of each of the numbers in the first list multiplied by the factor. Print this list. """ list=[5,8,4,6,9] factor=5 new_list=[] for mtpl in list: final = factor*mtpl new_list.append(final) print(new_list) #------------------------------------------------------------------------------------------------------------ """ Reverse a String Given a string, print the string reversed. """ string='rashad' print(string[::-1]) #------------------------------------------------------------------------------------------------------------
true
256393dec17201283f58836e9553e3f185e435bc
kabmkb/Python-DeepLearning
/ICP1/Sourcecode/Python_to_Pythons.py
292
4.4375
4
String = input('Please enter a sentence:') #Taking any string as a input which contains python word A = String print(A) #Printing sentence as it is print(A.replace('python', 'pythons')) #Replacing every python word with pythons
true
068e312bc131cb72a88917868eefe34e335e2a2b
saichaitu92/chaitanya
/asspg3.py
269
4.25
4
print ("length of triangle sides ") x=float(input("x: ")) y=float(input("y: ")) z=float(input("z: ")) if x==y and y==z and x==z: print("equilateral triangle") elif x==y or y==z or z==x: print("isosceles triangle") else: print("scalen triangle")
false
f1f49e8a89c307e11a8f5790e72aa2f7b507d525
samdhuse/Courses
/dateprinter.py
441
4.28125
4
def main(): date = input("Enter date mm/dd/yyyy") print(date_printer(date)) def date_printer(date): months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] month_list = months[int(date[0])] date_list = date.split("/") date_format = month_list + " " + date_list[1] +', ' + date_list[2] return date_format main()
false
715a937efda25ca533b1595ee195e7de09122093
mrmuli/Toy-problems
/python/multiples_of_3_and_5/multiples-of-3-and-5.py
465
4.34375
4
# Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # what to do: # Find the sum of all the multiples of 3 or 5 below 1000. def multiples(): #total = [None]*1000 total = range(1000) count3 = 0 count5 = 0 sumT = 0 for x in total: if x%3 == 0: count3 += x elif x%5 == 0: count5 += x sumT = count3 + count5 print(sumT) multiples()
true
efcbdeb7ac347d1f4763f48e152487c95c43dcb6
VasudevJaiswal/Python-2500--Quistions
/01/10.py
409
4.21875
4
# Find the Perimeter of a Rectangle print("Create a function that takes length and width and finds the perimeter of a rectangle.") def peri_area(): H = int(input("Enter Your Height : ")) W = int(input("Enter Your Width : ")) A = (H+W)*2 print("total area of Perimeter of a rectangle - ",A) peri_area() # Program not closed emmidately input("Please Click to Enter to End the Program ")
true
fc6844026112a6748c8936b3a72bf193ca292469
VasudevJaiswal/Python-2500--Quistions
/01/18.py
917
4.375
4
# The Farm Problem print('''In this challenge, a farmer is asking you to tell him how many legs can be counted among all his animals. The farmer breeds three species: chickens = 2 legs cows = 4 legs pigs = 4 legs The farmer has counted his animals and he gives you a subtotal for each species. You have to implement a function that returns the total number of legs of all the animals. Examples ''') def legs_count(chick,cows,pigs): # chick = int(input("Enter Number of Chickens : ")) chick_tot = chick*2 # cows = int(input("Enter Number of Cows : ")) cows_tot = cows*4 # pigs = int(input("Enter Number of Pigs : ")) pigs_tot = pigs*4 # Total of Animals legs total = chick_tot+cows_tot+pigs_tot print("Total No. of All animals legs : ",str(total)) return total legs_count(1,1,1) # Program not closed emmidately input("Please Click to Enter to End the Program ")
true
2c8a4b3ce20f90a309c7177db06e293b8705f5ad
sdanil-ops/poc-learning-cases
/stepik/stepik-7.3.8.py
317
4.15625
4
# Copyright (c) 2021. by Danil Smirnov # zabanen.nu@ya.ru # input is natural number n. write program that computes n! number = int(input()) def factorial(num): if num == 0: return 1 factorial = 1 i = 0 while i < num: i += 1 factorial *= i return factorial print(factorial(number))
false
be50118001325be10780073be6d094e461b2b827
LeonardoRossetti/Python
/simple-exercises/tuples.py
1,822
4.4375
4
from random import randint # IMPORTANT: Tuples are immutable. However, we can delete a Tuple from memory using: del(tuple) # Tuples can accept different data. E.g. ('Leo', 25, 'M', 72.10) heroes = ('Wonder Woman', 'Spider Man', 'Batman', 'Iron Man') realNames = 'Diana Prince', 'Peter Parker', 'Bruce Wayne', 'Tony Stark' # it is also a tuple mix = heroes + realNames print('-=' * 20) print('READING') print('-' * 20) for hero in heroes: print(hero) for cont in range(0, len(mix)): print(mix[cont]) for pos, name in enumerate(mix): print(f'I would like to see {name} on position {pos}.') # Python 3.6+ print(f'First five names are {mix[0:5]}') print(f'Last five names are {mix[-5:]}') print('\n\n', end='-=' * 20) print('\nSearching for letters into words') print('-' * 20) for hero in heroes: print(f'\nOn the name {hero} we have ', end='') for letter in hero: if letter.lower() in 'aeiou': print(f'{letter}', end=' ') print('\n\n', end='-=' * 20) print('\nSorting') print('-' * 20) print(sorted(mix)) # It becomes a list when sorting print('\n\n', end='-=' * 20) print('\nFinding the index') print('-' * 20) print(mix.index('Batman')) print(mix.index('Batman', 2)) # Start searching on position 2 for hero, name in zip(heroes, realNames): print(f'{hero :.<30} is actually ', end='') print(f'{name:>5.15}') numbers = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10)) print('The sorted numbers are: ', end='') for n in numbers: print(f'{n} ', end='') print(f'\nThe biggest value is {max(numbers)}') print(f'The smallest value is {min(numbers)}') if 9 in numbers: print(f'The value 9 appeared {numbers.count(9)} times. The first one was on position {numbers.index(9)}') else: print('The value 9 does not appear in the tuple')
true
40d93f57326bfb4e0245a91125e06557c3559241
Pumala/python_loop_exercises
/multiplication_table.py
227
4.34375
4
print "Multiplication Table" # Print the multiplication table from numbers 1 - 10. for num in range(1, 11): for num2 in range(1, 11): product = num * num2 print str(num) + " x " + str(num2) + " =", product
true
914596c8ba96c89482d378d564558a3973864e20
flinteller/unit_four
/d3_unit_four_warmups.py
226
4.28125
4
grade = int(input("What grade are you in?")) if grade >= 9 and grade <= 12: print("You are in upper school") elif grade >= 6 and grade <= 8: print("You are in middle school") else: print("You are in lower school")
true
ac872342e8a87436a32b0d5079952f21a06e5a68
cayybh1314/lect06
/which_day_v2.0.py
1,679
4.25
4
""" 作者:zqc 版本:v2.0 日期:12/05/2019 功能:输入某年某月某日,判断这一天是这一年的第几天? 2.0增加功能:用列表替换元组 """ import datetime def is_leap_year(year): """ 判断是否为闰年 是:返回true 否:返回false """ #这样写逻辑没问题,但是不好, #if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): # return True #else: # return False #改写以上代码 #定义变量 is_leap = False if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): is_leap = True else: return is_leap def main(): """ 主函数 """ #从外部输入数据,并转换为时间格式。 input_str = input("请输入日期(yyyy/mm/dd):") input_date = datetime.datetime.strptime(input_str,'%Y/%m/%d') print(input_date) #获取 输入时间的 年,月,日 year = input_date.year month = input_date.month day = input_date.day print(year,month,day) #计算之前月份天数的总和以及当前月份天数,例如今天是3月4好,就是 1月+2月+4天 #此处不用元组,改用list(列表) #days_in_month_tup = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) days_in_month_list = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) if is_leap_year(year): days_in_month_list[1] = 29 #print(days_in_month_tup[:month-1]) days = sum(days_in_month_list[:month-1]) + day print("这是第{}天!".format(days)) if __name__ == '__main__': main() #下一课,使用集合替代list。
false
32186bed03bae139f0137cfd1e499a36cd02c18a
DarkJoney/python_examples
/hillel3/chess.py
916
4.1875
4
"""Шахматный конь ходит буквой “Г” — на две клетки по вертикали в любом направлении и на одну клетку по горизонтали, или наоборот. Даны две различные клетки шахматной доски, определите, может ли конь попасть с первой клетки на вторую одним ходом.""" print(" 12345678") print("1 _X_X_X_X\n2 X_X_X_X_\n3 _X_X_X_X\n4 X_X_X_X_\n5 _X_X_X_X\n6 X_X_X_X_\n7 _X_X_X_X\n8 X_X_X_X_") print("\nInput the horse's move coordinates:") x1 = int(input("x1:")) y1 = int(input("y1:")) x2 = int(input("x2:")) y2 = int(input("y2:")) if (x1 - 2 == x2 or x1 + 2 == x2) and (y1 - 1 == y2 or y1 + 1 == y2): print('YES') elif (x1 - 1 == x2 or x1 + 1 == x2) and (y1 - 2 == y2 or y1 + 2 == y2): print('YES') else: print('NO')
false
d700546444f995d0c0c686261f01448646a00519
DarkJoney/python_examples
/hillel8/years.py
436
4.1875
4
"""2. Написать функцию `is_year_leap`, принимающую 1 аргумент — год, и возвращающую True, если год високосный, и False иначе.""" def is_year_leap(year): check = True if year % 4 != 0 or (year % 100 == 0 and year % 400 != 0): check = False return check x = int(input("Please enter the year to check:")) out = is_year_leap(x) print(out)
false
db8c47bb9cab582dacdd749a29e7dafc675fcd8e
DarkJoney/python_examples
/hillel9/shiftv2.py
1,336
4.4375
4
"""10. Написать функцию, циклически сдвигающую целое число на N разрядов вправо или влево, в зависимости от третьего параметра функции. Функция должна принимать три параметра: в первом параметре передаётся число для сдвига, второй параметр задаёт количество разрядов для сдвига (по умолчанию сдвиг на 1 разряд), 3-й булевский параметр з адаёт направление сдвига (по умолчанию влево (False)).""" def shiftfun(value, times, shift): data = list(map(int, str(value))) for i in range(times): if shift == True: data.insert(0, data.pop()) elif shift == False: data.insert(len(data), data.pop(0)) shiftout = ''.join(map(str, data)) return shiftout a = int(input("Enter the value to shift: ")) b = int(input("How much times do you want to shift?")) direction = input("in what direction? left/right:" ) if direction == "left": direction = False elif direction == "right": direction = True else: print("Wrong direction!") out = shiftfun(a, b, direction) print(out)
false
23f0384b21d8fa5ba2c05fdcf717ccc9c8506bd3
ale-fante/python
/tuples.py
1,454
4.59375
5
# A tuple is a collection which is ordered and unchangeable. # In Python tuples are written with round brackets. thistuple = ("apple", "banana", "cherry") print(thistuple) thistuple = ("apple", "banana", "cherry") print(thistuple[1]) # Once a tuple is created, you cannot change its values. Tuples are unchangeable. thistuple = ("apple", "banana", "cherry") for x in thistuple: print(x) thistuple = ("apple", "banana", "cherry") if "orange" in thistuple: print("Yes, 'apple' is in the fruits tuple") else: print("Nope, not here") thistuple = ("apple", "banana", "cherry") print(len(thistuple)) thistuple = ("apple", "banana", "cherry") del thistuple print("Tuple deleted!") # the tuple() constructor can be used to make a tuple thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets print(thistuple) # return the number of times the value 5 appears in the tuple thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5, 5, 5, 5, 5) x = thistuple.count(5) print(x) # usage: tuple.count(value) # parameter: value - required. The item to search for # Search for the first occurrence of the value 8 and return its index thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5) x = thistuple.index(8) print(x) # usage: tuple.index(value) # parameter: value - required. The item to search for fruits = {"apple", "banana", "cherry", "watermelon"} more_fruits = ["orange", "mango", "grapes", "pears"] fruits.update(more_fruits) print fruits
true
c7eb1495467a870cc5f2101d2c4dd31988dc1338
Pankaj1729/Python-Learning
/Exercise17.py
595
4.125
4
def common_element_in_list(l1,l2): list3=[] for i in l1: for j in l2: if i==j: list3.append(i) return list3 list1=[] list2=[] m=int(input("enter number of element you want in list1 :")) print("enter element in list1") for i in range(m): list1.append(int(input())) print("list1 is :",list1) n=int(input("enter number of element you want in list2 :")) print("enter element in list2") for i in range(n): list2.append(int(input())) print("list2 is :",list2) print("common element in list1 and list2 are :",common_element_in_list(list1,list2))
false
168f4f392a43d49f05869b237f327d7511abb728
silvisharma/Hacktoberfest2021_beginner
/fact_silvisharma.py
239
4.15625
4
class Factorial: def fact(self,n): f = 1 for i in range(1, n + 1): f = f * i return f n = int(input("Enter a number:")) obj=Factorial() f=obj.fact(n) print("The factorial of",n,"is",f)
true
55fac6437f660920feb2117c855bc479a1820a11
eduardogomezvidela/Summer-Intro
/9 Strings/remove_vowels.py
221
4.40625
4
#This program removes the vowels from a string word = input ("Word: ") vowels = "aAeEiIoOuU" new_word="" for each_char in word: if each_char not in vowels: new_word = new_word + each_char print (new_word)
true
a9c3d45538abcb85d089db719e933b481bc69d8b
eduardogomezvidela/Summer-Intro
/6 Functions/excersises/6.py
582
4.3125
4
#Use the drawsquare function we wrote in this chapter in a program to draw the image shown below. #Assume each side is 20 units. (Hint: notice that the turtle has already moved away from the ending point of the last square when the program ends.) #5 squares size 20 import turtle import draw_square screen=turtle.Screen() screen.bgcolor("lightgreen") alex=turtle.Turtle() alex.color("hotpink") alex.pensize(3) alex.speed(5) for i in range(5): draw_square.draw_square(alex,20) alex.up() alex.forward(40) alex.down() screen.exitonclick()
true
20d051e6b6d60e904ea8944894d987a24a1959c8
eduardogomezvidela/Summer-Intro
/6 Functions/excersises/17 draw_sprite.py
616
4.125
4
#Write a function called drawSprite that will draw a sprite. #The function will need parameters for the turtle, the number of legs, and the length of the legs. #Invoke the function to create a sprite with 15 legs of length 120. import turtle screen=turtle.Screen() screen.bgcolor("black") alex=turtle.Turtle() alex.color("white") def draw_sprite(turtle, length, legs): alex.pensize(25) alex.dot() alex.pensize(4) turtle.left(90) for i in range(legs): turtle.right(360/legs) turtle.forward(length) turtle.forward(-length) draw_sprite(alex,120,15) screen.exitonclick()
true
0d942e8cc62c4203d01d0d727b3f85e1d8d4fcba
eduardogomezvidela/Summer-Intro
/9 Strings/more_strings.py
1,114
4.1875
4
colors = "red,yellow,green" print(colors[0:3]) #Prints red y = (colors[4:10]) #Prints yellow print(y) print(colors[:5]) print(colors[5:]) print(len(colors)) print(colors[len(colors)-1]) #Prints last letter in string print(colors[:]) #Will print everything print(ord("a")) print(ord("A")) print("------------------------------------------------") a = "zero" if a < "zebra": print("Your word", a, "comes before zebra") elif a > "zebra": print("Your word " + a + " comes after zebra") else: print("Your word is zebra") a = "apple" if a < "zebra": print("Your word", a, "comes before zebra") elif a > "zebra": print("Your word " + a + " comes after zebra") else: print("Your word is zebra") print("------------------------------------------------") print ("apple" > "Apple") print ("zebra" < "apple") print("------------------------------------------------") b ="ball" h="h"+(b[1:]) print(h) print("------------------------------------------------") for x in "Hello world!": print(x) hello = "Hello world" for y in range( len(hello)-1,-1,-1): print (hello[y])
true
c44c66689c349af0fa0698598a3f2500e3943e63
eduardogomezvidela/Summer-Intro
/4 Turtles/Exercises/4.py
416
4.1875
4
#Assume you have a list of numbers 12, 10, 32, 3, 66, 17, 42, 99, 20 #Write a loop that prints each of the numbers on a new line. #Write a loop that prints each number and its square on a new line. #Save & RunShow FeedbackShow CodeShow CodeLensCode Coach for i in (12, 10, 32, 3, 66, 17, 42, 99, 20): print(i) print("####################") for i in (12, 10, 32, 3, 66, 17, 42, 99, 20): print(i, " ",i^2)
true
5dc7a2312ae9b64fb58273ff8995a23d105b523f
eduardogomezvidela/Summer-Intro
/6 Functions/excersises/11.py
425
4.125
4
#Write a non-fruitful function drawEquitriangle(someturtle, somesize) which calls #drawPoly from the previous question to have its turtle draw a equilateral triangle. import turtle import draw_poly screen=turtle.Screen() screen.bgcolor("black") alex=turtle.Turtle() alex.color("white") alex.pensize(3) def equi_triangle(turtle,size): draw_poly.draw_poly(turtle,3,size) equi_triangle(alex,120) screen.exitonclick()
true
ffcb375ffb52151fd1129404a5c6694999b7058d
rahul9852-dot/Python-From-Scratch
/Basic Python/Practise_problem/nthmultiple_fibonacci.py
354
4.15625
4
# given two integer n and k.find position the n\'th multiple of k in the fibonacci. def findposition(k,n): f1=0 f2=1 i=2 while i!=0: f3=f1+f2 f1=f2 f2=f3 if f2%k==0: return n*i i+=1 return n=5 k=4 print("Position of n\'th multiple of k in" "fibonacci Series is",findposition(n,k))
false
599f1035745804bddbdff675694a0aff36302e82
k-kondo-s/eight-queen
/models/model.py
2,697
4.3125
4
from abc import ABCMeta, abstractmethod from typing import List, Tuple, Union class Queen(): pass class Board(): def __init__(self, n: int) -> None: """ Args: n (int): length of the chess board """ self.n: int = n self.board: List[List[Union[None, Queen]]] = None # initialize self.reset_board() def reset_board(self) -> None: """initialize board """ # make n-chess board as a 2-dementional list self.board = [[None for _ in range(self.n)] for _ in range(self.n)] def has_queen(self, at: Tuple[int, int]) -> bool: """get value according to the coodinate Args: at (Tuple[int, int]): location (row, column) Returns: (bool): True if queen exists at the given place, else return False """ row, column = at if self.board[row][column] is not None: return True return False def set_queen(self, at: Tuple[int, int]) -> None: """Set Queen onto the board Args: at (Tuple[int, int]): the place on the board where the queen is placed (row, column) """ row_at, column_at = at self.board[row_at][column_at] = Queen() def remove_queen(self, at: Tuple[int, int]) -> None: """Remove Queen from the given place Args: at (Tuple[int, int]): the place where a queen will be removed from (row, column) """ row_at, column_at = at self.board[row_at][column_at] = None def print(self) -> None: """Print the current state of the queens on the board """ # insert a new line anyway print() # symbol of Queen on the board Q = 'Q' # maximum length of numbers as str max_len = len(str(self.n)) # seperator sep = '-'.join(['-'.center(max_len, '-') for _ in range(self.n + 1)]) + '-' # print the top row top_row_list = [' '.center(max_len, ' ')] for i in range(self.n): top_row_list.append(str(i).center(max_len, ' ')) top_row = '|'.join(top_row_list) + '|' print(top_row) print(sep) # print the board state for i in range(self.n): row_list = [str(i).center(max_len, ' ')] for j in self.board[i]: s = ' '.center(max_len, ' ') if j is None else Q.center(max_len, ' ') row_list.append(s) row = '|'.join(row_list) + '|' print(row) print(sep) class Engine(metaclass=ABCMeta): @abstractmethod def solve(self) -> List[Board]: pass
true
3e255c8a9846304b2e163e96983ecb0c4132f52d
G-laukon/py-training
/.github/arc.py
799
4.3125
4
def arc(number,length,angle): """绘出花朵图案。三个输入参数分别决定瓣数,瓣长,瓣幅。ps:(10,100,200)效果不错。""" import math angle_arc = 2*math.pi*(angle/360) r = length/(2*math.sin(angle_arc/2)) arc_length = angle_arc* r n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle/2) / n polyline(number,n, step_length, step_angle,angle) def polyline(number,n,step_length,step_angle,angle): import turtle t = turtle.Turtle() for i in range(number): for i in range(n): t.fd(step_length) t.lt(step_angle) t.rt(angle/2) for i in range(n): t.backward(step_length) t.lt(step_angle) t.lt(360/number-angle/2)
false
0cf287accb342a6dd70c91adc88dd084528251b5
ben18-meet/meet201617YL1cs-mod4
/rectangle.py
2,250
4.375
4
import turtle class Rectangle : def __init__(self,length,height): """ Initialize new rectangle instance. :param length: length of rectangle (horizontal dimension). Must be >= 0. Otherwise, set to 0. :param length: height of rectangle (vertical dimension). Must be >= 0. Otherwise, set to 0. """ if length>=0 : self.length=length else : self.length=0 if height>=0 : self.height=height else : self.height=0 self.turtle=turtle.clone() #Make a new turtle object just for this instance so that drawings can be cleared. turtle.speed(0) #Make turtle move as fast as possible. self.has_been_drawn=False #Keep track of whether shape has been drawn. def set_length(self,new_length): """ Change the length of the rectangle. :param new_length: length (horizontal dimension) of rectangle. Must be >= 0. Otherwise, no change is made. """ if new_length>=0 : self.length=new_length if self.has_been_drawn : #Only redraw rectangle; don't make new drawing. self.draw_shape() def set_height(self,new_height): """ Change the height of the rectangle. :param new_height: height (vertical dimension) of rectangle. Must be >= 0. Otherwise, no change is made. """ if new_height>=0 : self.height=new_height if self.has_been_drawn : #Only redraw rectangle; don't make new drawing. self.draw_shape() def get_area(self): """ Calculate the area of the shape """ return self.length*self.height def draw_shape(self): """ Draw the shape, starting at 0,0. If any old drawings exist, remove them. """ self.turtle.clear() #Remove old drawings (if they exist) self.turtle.penup() self.turtle.goto(0,0) self.turtle.pendown() self.turtle.goto(self.length,0) self.turtle.goto(self.length,self.height) self.turtle.goto(0,self.height) self.turtle.goto(0,0) self.turtle.penup() self.has_been_drawn=True
true
0e122be8382a6f79cdb8dbb7126e59e67475a39d
kozeyandrey/LearningPython
/Ch3/calendars_start.py
1,517
4.3125
4
import calendar # create a plain text calendar c = calendar.TextCalendar(calendar.SUNDAY) # THe Sunday will be as a first day str = c.formatmonth(2016, 1, 0, 0) # Last two values are indentations values (width, height) print str # create an HTML formatted calendar hc = calendar.HTMLCalendar(calendar.SUNDAY) # THe Sunday will be as a first day str = hc.formatmonth(2016, 1) print str # loop over the days of a month # zeroes mean that the day of the week is in an overlapping month for i in c.itermonthdays(2016, 8): print i # The Calendar module provides useful utilities for the given locale. # such as the names of days and months in both full and abbreviated forms for name in calendar.month_name: print name for day in calendar.day_name: print day # Calculate days based on a rule: For example, consider # a team meeting on the Friday of every month. # To figure out what days thay would be for each month, # we can use this script: for m in range(1, 13): # returns an array of weeks that represent the month cal = calendar.monthcalendar(2016, m) # The first Friday has to be within the first two weeks weekone = cal[0] weektwo = cal[1] # calendar.FRIDAY - return index of Friday in the week. It's 4. if weekone[calendar.FRIDAY] != 0: meetday = weekone[calendar.FRIDAY] else: # if the first friday isn't in the first week, it must be in the second meetday = weektwo[calendar. FRIDAY] # %10 - it's mean insert 10 space before string print "%10s %3d" % (calendar.month_name[m], meetday)
true
1e618057ca04b88309b86d63df1fb576aabdbb73
EmilPisarev/-9
/9.3.py
498
4.25
4
s = [ 3 , 'hello' , 7 , 4 , 'привет' , 4 , 3 , - 1 ] print ( s [ 2 ]) # выводит третий элемент print ( s [ - 2 ]) # вывод предпоследний элемент print ( s [ 0 : 5 ]) # выводит первые пять элементов print ( s [: - 2 ]) # вывод вывод всю строку кроме последних двух символов print ( s [:: 2 ]) # выводит все элементы с четными индексами
false
612c9b4b9f1fa7b55a8f686a94d4c0fdd602d807
99004302-nikhilhr/Daily-Practice-258088
/ifelse/check_no.py
606
4.21875
4
#Constraint in-order to check the number complex it must have input end with "h" n=input() if n.isalpha(): print("String") elif n.isdecimal(): n=int(n) if n==0: print("Zero") else: print("Real") elif n.endswith("h"): n=n.replace("h","") if n.isalnum(): print("Complex") if "+" in n or "-" in n: for i in n: if i=="+": n=n.replace("+","") break if i=="-": n=n.replace("-","") break if n.isalnum(): print("Complex") else: print("Float")
false
ec0c4cb232ede74d1dfdc16b73214dc53fc57395
kaiopomini/PythonExercisesCursoEmVideo
/ex018.py
414
4.25
4
'''Exercício Python 018: Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.''' from math import cos, sin, tan, radians a = float(input('Enter with a angle: ')) ar = radians(a) print('the cosine of {} is {:.2f}'.format(a, cos(ar))) print('the sine of {} is {:.2f}'.format(a, sin(ar))) print('the tangent of {} is {:.2f}'.format(a, tan(ar)))
false
3edfef38e016da32b5f622a3f10f4ca22aa854ac
kaiopomini/PythonExercisesCursoEmVideo
/ex099.py
572
4.34375
4
'''Exercício Python 099: Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior.''' def maior(* num): print('#'*50) if len(num) > 0: for i in range(0, len(num)): print(f'{num[i]} ', end='') print(f'Foram informados {len(num)} valores ao todo.') if len(num) > 0: print(f'O maior valor informado foi {max(num)}') maior(1, 2, 45, 34, 44, 474, 1, -2, 31) maior(5, 55, 14, 98) maior() maior(5)
false
9abb591ea2f22552a270e56f2453b15833fdcfd8
kaiopomini/PythonExercisesCursoEmVideo
/ex100.py
786
4.1875
4
'''Exercício Python 100: Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores pares sorteados pela função anterior.''' from random import randint from time import sleep def sorteia(lst): print('Sorteando os valores da lista: ', end='') for i in range(0, 5): lst.append(randint(0, 999)) sleep(0.5) print(f'{lst[i]} ', end='') print('Pronto!') def somaPar(lst): soma = 0 for i in lst: if i % 2 == 0: soma += i print(f'Somando os valores PARES de {lst} temos {soma}') numeros = list() sorteia(numeros) somaPar(numeros)
false
170d78c160363d56150798b7c4116fa573bede65
kaiopomini/PythonExercisesCursoEmVideo
/ex098.py
931
4.34375
4
''' Exercício Python 098: Faça um programa que tenha uma função chamada contador(), que receba três parâmetros: início, fim e passo. Seu programa tem que realizar três contagens através da função criada: a) de 1 até 10, de 1 em 1 b) de 10 até 0, de 2 em 2 c) uma contagem personalizada ''' from time import sleep def contador(i, f, p): if p == 0: p = 1 if p < 0: p = (-p) print('#' * 50) print(f'Contagem de {i} até {f} de {p} em {p}:') if i <= f: while i <= f: print(f'{i} ', end='') sleep(0.3) i += p else: while i >= f: print(f'{i} ', end='') sleep(0.3) i -= p print('FIM!') contador(1, 10, 1) contador(10, 0, 2) print('#'*50) print('Agora é sua vez de personalizar a contagem!') a = int(input('Inicio: ')) b = int(input('Fim: ')) c = int(input('Passo: ')) contador(a, b, c)
false
b3dd45aa328a2ffd07f6443aecfb5ec509ef4e71
kaiopomini/PythonExercisesCursoEmVideo
/ex087.py
1,145
4.21875
4
''' Exercício Python 087: Aprimore o desafio anterior, mostrando no final: A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha. ''' somaPar = somaC3 = maiorS = 0 matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'Informe o numero da posição [{l+1}],[{c+1}]: ')) print('=-'*20) maiorS = matriz[1][0] # atribui o valor da posição 1,0 para comparar se os demais são maiores for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') # Print a tabela if matriz[l][c] % 2 == 0: # identifica os numeros pares somaPar += matriz[l][c] if c == 2: # identifica a coluna 3 somaC3 += matriz[l][c] if l == 1 and matriz[l][c] > maiorS: # identifica a linha 2 e testa se a posição da matriz é maior que a var maiorS maiorS = matriz[l][c] print() print('=-'*20) print(f'Soma da coluna 3 é {somaC3}') print(f'Soma dos numeros pares é {somaPar}') print(f'O maior valor da segunda linha é {maiorS}')
false
1902660743d024c580dcb6b43a238e4359da49ec
kaiopomini/PythonExercisesCursoEmVideo
/ex008.py
273
4.21875
4
'''Exercício Python 008: Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.''' n1 = float(input('Enter the measurement in meters: ')) print('The value informed is: \n {:.0f}cm \n {:.0f}mm'.format((n1*100), (n1*1000)))
false
b93f61e24969c9a6ef4619cb1ceb9ee0faf59e8f
ModeConfusion/how-to-python-code
/challenges/how-to-check-key-in-dictionary/check-key-2.py
776
4.28125
4
# link to the challenge: https://therenegadecoder.com/code/how-to-check-if-a-key-exists-in-a-dictionary-in-python/#challenge # Solution by: jrg94 dictionary = { "fire": "combustion or burning, in which substances combine chemically with oxygen from the air and typically give out bright light, heat, and smoke.", "wood": "the hard fibrous material that forms the main substance of the trunk or branches of a tree or shrub, used for fuel or timber.", "glass": "a hard, brittle substance, typically transparent or translucent, made by fusing sand with soda, lime, and sometimes other ingredients and cooling rapidly. It is used to make windows, drinking containers, and other articles." } key = input("Enter a key here: ") print(dictionary.get(key.lower()))
true
18d6bf7016c41f34436fff943a7dc30ece439b9f
janewjy/Leetcode
/ImplementQueueusingStacks.py
1,847
4.21875
4
class Queue(object): def __init__(self): """ initialize your data structure here. """ self.stackin = [] self.stackout = [] def push(self, x): """ :type x: int :rtype: nothing """ self.stackin.append(x) def pop(self): """ :rtype: nothing """ self.move() self.stackout.pop() def peek(self): """ :rtype: int """ self.move() return self.stackout[-1] def empty(self): """ :rtype: bool """ return (not self.stackin) and (not self.stackout) def move(self): if not self.stackout: while self.stackin: self.stackout.append(self.stackin.pop()) x = Queue() x.push(3) x.push(4) x.push(6) print x.empty(),x.peek(),x.stackin,x.stackout # 1-31 class Queue(object): def __init__(self): """ initialize your data structure here. """ self.stack1 = [] self.stack2 = [] def push(self, x): """ :type x: int :rtype: nothing """ self.stack1.append(x) def pop(self): """ :rtype: nothing """ if not self.empty(): self.peek() self.stack2.pop() def peek(self): """ :rtype: int """ if not self.empty(): if self.stack2: return self.stack2[-1] else: while self.stack1: self.stack2.append(self.stack1.pop()) return self.stack2[-1] def empty(self): """ :rtype: bool """ return not self.stack1 and not self.stack2
false
75303c67647277d16aee98e2e3f77fa96887b6bf
sonalishintre/The-Knowledge-House-prework-repo
/TKH_Prework/assignment_3.py
984
4.65625
5
#Assignment 3 #Name comparison: #With your newfound skills we are going to add one new thing -- the len function. #The len function will tell you the length of the string: len("hello") #5 name = "joe" len(name) # 3 Create a script that loops through a list of names, comparing the length of each name to the length of all other names in the list finally printing out only the largest name names_list = ["bob","jimmy","max b", "bernie", "jordan", "future hendrix"] #hint it should look something like this: #longest_name = '' empty string as placeholder #for name in names_list : #if len(name)>longest_name: #do something maybe reassign the longest name variable #else: #do another thing #print longest_name names_list = ["bob","jimmy","max b", "bernie", "jordan", "future hendrix"] longest_name = '' for name in names_list: if len(name) > len(longest_name): longest_name = name else: print(longest_name) print(longest_name) #output: #jimmy #bernie #future hendrix
true
ed9c9b75b35b565458b5561ae1176d3f984ad887
weifo/interview_preps
/basic/level1/fac.py
429
4.28125
4
# question # Write a program which can compute the factorial of a given number. def facnum(): try: receive_num=int(input()) if receive_num<=0: raise ValueError('This num should be positive') else: result=1 for num in range(2,receive_num+1): result*=num print(result) except Exception as e: print(e) facnum()
true
6ea357d1c0b7b00f4da220bd084cb088d7477dab
MarkusHiersche89/SmartNinja
/Python-Grundlagen/_uebung/Tag 2/hue_2_2.py
2,117
4.3125
4
""" Homework 2.2: FizzBuzz User enters a number between 1 and 100 FizzBuzz program starts to count to that number (it prints them in the Terminal). In case the number is divisible with 3, it prints "fizz" instead of the number. If the number is divisible with 5, it prints "buzz". If it's divisible with both 3 and 5, it prints "fizzbuzz". Example: Select a number between 1 and 100 16 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 A tip for this project: How to find a division remainder If a division remainder is 0, that means some number is divisible with another (without remainder). Example: print(15 % 5) print(15 % 4) 15 is divisible with 5, so the remainder is 0. But 15 is not divisible with 4, so the remainder is not 0. When you finish, paste your code on GitHub Gist and share it on the SmartNinja forum. === === === Hausaufgabe 2.2: FizzBuzz Der Benutzer gibt eine Zahl zwischen 1 und 100 ein Das FizzBuzz-Programm beginnt, bis zu dieser Nummer zu zählen (es druckt sie im Terminal aus). Falls die Zahl durch 3 teilbar ist, wird anstelle der Zahl "fizz" ausgegeben. Wenn die Zahl durch 5 teilbar ist, wird "Buzz" ausgegeben. Wenn es mit 3 und 5 teilbar ist, wird "fizzbuzz" gedruckt. Beispiel: Wählen Sie eine Zahl zwischen 1 und 100 16 1 2 Sprudel 4 summen Sprudel 7 8 Sprudel summen 11 Sprudel 13 14 Fizzbuzz 16 Ein Tipp für dieses Projekt: So finden Sie einen Teilungsrest Wenn ein Teilungsrest 0 ist, bedeutet dies, dass eine Zahl mit einer anderen teilbar ist (ohne Rest). Beispiel: Drucken (15% 5) Drucken (15% 4) 15 ist mit 5 teilbar, also ist der Rest 0. Aber 15 ist nicht mit 4 teilbar, also ist der Rest nicht 0. Wenn Sie fertig sind, fügen Sie Ihren Code in GitHub Gist ein und teilen Sie ihn im SmartNinja-Forum. """ ende = int(input("Endzahl: ")) for i in range(1, ende): if (i % 3 == 0 and i % 5 == 0): # Methematisch gesehen könnte man auch mit "i % 15 == 0" abfragen... print("fizzbuzz") elif(i % 3 == 0): print("fizz") elif(i % 5 == 0): print("buzz") else: print(i) print("Programmende erreicht")
true
4333624216e816b06e7743d12df20a3466423af1
MarkusHiersche89/SmartNinja
/Python-Grundlagen/_uebung/Tag 3/hue_3_1.py
1,267
4.34375
4
""" CSV files are the ones that end with .csv. They are very common for spreadsheets. CSV means "comma-separated values". This means that values in the file are separated with a comma: ,. You can create a CSV file the same way as you created a TXT file, except that you'd use .csv instead of .txt at the end of the file. Let's take a look at how a CSV file may look like: Name,Age,Gender Tina,23,female Jakob,35,male Barbara,44,female If you would import this CSV file in a spreadsheet (like Excel), you'd see a table with three columns (Name, Age, Gender). But you can also process this file with Python. So your task is to create a Python program, that will go through this CSV file and print the following text in the Terminal: Tina is female and 23 years old. Jakob is male and 35 years old. Barbara is female and 44 years old. Hint: You will also need a string method called split(). ;) When you complete the homework, store it on GitHub and share the link to it on Slack. """ counter = 0 lineList = [] with open("person.csv", "r") as item: for line in item: if counter > 0: line = line.rstrip("\n") line = line.split(",") print(line[0] + " is " + line[2] + " and " + line[1] + " years old.") counter += 1
true
6ccb2c612c9280a848460093200569c46e7a0563
namntran/7001ICT_python3
/workshops/04/marks.py
300
4.1875
4
# marks.py # indefinite loops # read marks until negative numbers n = 0 total = 0.0 mark = float(input("Enter a mark: ")) while mark >= 0.0: n += 1 total += mark mark = float(input("Enter a mark: ")) print("The number of marks: ", n) if n > 0: print("The average mark is: ", total/ n)
true
df5c9e59ddfd77df8d7da3aba3408b773b4e6ccf
HelalChow/Pyhton-Basics
/Classwork/12/12-13-17.py
805
4.21875
4
def main(): file_name = input("Please enter a filename: ") line_num_str = (input("Please enter the line number you want: ")) try: line_num = int(line_num_str) in_file = open(file_name, "r") line = get_line_number(in_file, line_num) in_file.close() print(line) except ValueError: print(line_num, "must be an integer") except FileNotFoundError: print(file_name, "not found") except Exception: print(line_num, "is am invalid line number") return line def get_line_number(file, line_num): lines_list = file.readlines() if(line_num > len(lines_list)) or (line_num < 0): raise Exception(str(line_num) + " is a inavild line number") return lines_list[line_num-1] main()
true
d7146586f56f05371f3452a9838a47c825238714
Calleuz/python10
/Othercode/script1.py
637
4.15625
4
from tkinter import * window = Tk() def calc (): num1 = float(e1_value.get()) num2 = float(e2_value.get()) multi = num1*num2 #res = "The result of the multiplication is: " + num1*num2 #print(res) t1.insert(END, res) b1 = Button(window, text = "Calculate", command = calc) b1.grid(row = 0, column = 0) e1_value = StringVar() e1 = Entry(window, textvariable = e1_value) e1.grid(row = 0, column = 1) e2_value = StringVar() e2 = Entry(window, textvariable = e2_value) e2.grid(row = 0, column = 2) t1 = Text(window, height = 1, width = 10) #Height är i cells t1.grid(row = 0, column = 3) window.mainloop()
true
b127e06f8d9279453d981f86933228fa59696698
yuvrajmetrani2/codingstudies
/bubble sort.py
1,477
4.21875
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 22 23:36:49 2020 @author: Krishna """ def bubble_sort(arr, increasing = True): ''' Parameters ---------- arr : List List of numeric values. increasing : Bool, optional Sorting increasing or decreasing. The default is True. Returns ------- arr : TYPE list DESCRIPTION - Sorted array. itercount : integer DESCRIPTION - The number of cycles of loop the algorithm took to sort.. ''' itercount = 0 while True: corrected = False for i in range(0, len(arr)-1): #check for each pair of array items if(increasing): if (arr[i] > arr[i+1]): arr[i],arr[i+1] = arr[i+1], arr[i] corrected = True else: if (arr[i] < arr[i+1]): arr[i],arr[i+1] = arr[i+1], arr[i] corrected = True if corrected: itercount +=1 if not corrected: return arr, itercount def swap_arrayitems(a,b): a,b = b,a return a,b sortedarry , iterations = (bubble_sort([8,2,3,4,5,6])) print(iterations, " -> " , sortedarry) print (bubble_sort([9,3,0,6,-4,5,1], True)) #print (bubble_sort([a, z, g,b,c,e,o,f])) print(bubble_sort([2,4,1])) print(bubble_sort([2,4,1],False))
true
b37bf900985850c168ca34c0c9410f92b6e39cc6
avivrm/beginpython
/Include/assigment1/Assign10.py
730
4.21875
4
# Write a program that accepts a sequence of whitespace separated words as input # and prints the words after removing all duplicate words and sorting them alphanumerically. # Suppose the following input is supplied to the program: # hello world and practice makes perfect and hello world again # Then, the output should be: # again and hello makes perfect practice world # HInt : In case of input data being supplied to the question, it should be assumed to be a console input. # We use set container to remove duplicated data automatically and then use sorted() to sort the data. string = input('Enter the line : ') arr = string.split(" ") arr.sort() removedDup = sorted(set(arr)) for val in removedDup: print(val, end=" ")
true
9793730e35a9c5b64bff7bf7ccdff989321f2d7b
avivrm/beginpython
/Include/assigment1/Assign7.py
838
4.15625
4
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. # The element value in the i-th row and j-th column of the array should be i*j. # Note: i=0,1.., X-1; j=0,1,¡¬Y-1. # Example # Suppose the following inputs are given to the program: # 3,5 # Then, the output of the program should be: # [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] # Hint : In case of input data being supplied to the question, # it should be assumed to be a console input in a comma-separated form. transposed = [] row = int(input('Enter the row : ')) column = int(input('Enter the column : ')) for i in range(row): # the following 3 lines implement the nested listcomp transposed_row = [] for j in range(column): transposed_row.append(i*j) transposed.append(transposed_row) print(transposed)
true
733c465639201de198a71f922df35b05967ae0d7
avivrm/beginpython
/Include/assigment1/Assign2.py
496
4.4375
4
#Write a program which can compute the factorial of a given numbers. #The results should be printed in a comma-separated sequence on a single line. #Suppose the following input is supplied to the program: #8 #Then, the output should be: #40320 # #hint : In case of input data being supplied to the question, it should be assumed to be a console input def fact(num): fact = 1 for i in range(1, num + 1): fact = fact * i print("The factorial of 8 is : ", fact, end="") fact(8)
true
099fc005d3bc11b53d596ba984222fe77912777e
llcawthorne/old-python-learning-play
/scripts/exceptions.py
2,979
4.25
4
#!/usr/bin/env python3 import sys def this_fails(): x = 1 / 0 def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero attempted!") else: print("result is", result) finally: print("executing finally clause") # Three user-defined exceptions class Error(Exception): """Base class for exceptions in this module.""" pass class InputError(Error): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """ def __init__(self, expression, message): self.expression = expression self.message = message class TransitionError(Error): """Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """ def __init__(self,previous, next, message): self.previous = previous self.next = next self.message = message class B(Exception): pass class C(B): pass class D(C): pass # begin excecution here # The following prints B, C, D. If the except clauses were reversed, # it would print B, B, B. Because D is a C, and C is a B. B does not # match except D:, but D matches except B: for c in [B, C, D]: try: raise c() except D: print("D") except C: print("C") except B: print("B") while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again...") try: f = open('myfile.txt', 'w') f.write("{0}\n".format(x)) f.write("{0}\n".format(x+1)) f.write("{0}\n".format(x+10)) except IOError as err: print("I/O error: {0}".format(err)) finally: # finally works well for releasing real-world resources # ie. files, network connections, etc f.close() try: this_fails() except ZeroDivisionError as err: print("Handling run-time error:", err) divide(5,2) divide(5,0) try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as err: print("I/O error: {0}".format(err)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) # Raise re-raises the unhandled exception raise else: f.seek(0) print("myfile.txt has", len(f.readlines()), "lines") finally: f.close() print("The first value in myfile is:", s) print("A handled user defined exception:") try: raise TransitionError('gas','solid',"gas to solid not allowed!") except TransitionError as err: print("Transition Error: ", err.message) print("An unhandled user defined exception:") raise InputError("cin >> joe", "Joe not defined!")
true
d3a50db177db8f32125491e7eab76e97d76085dd
llcawthorne/old-python-learning-play
/scripts/looping.py
1,121
4.3125
4
#!/usr/bin/env python3 # Various looping techniques are displayed # When looping through a dictionary, the key and corresponding value # can be retrieved at the same time using the items() method knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.items(): print(k, v) # When looping through a sequence, the position index and corresponding # value can be retrieved at the same time using the enumerate() function for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v) # To loop over two or more sequences at the same time, the entries can # be paired with the zip() function questions = ['name', 'quest', 'favorite color'] answers = ['lancelot', 'the holy grail', 'blue'] for q, a in zip(questions, answers): print('What is your {0}? It is {1}.'.format(q, a)) # To loop over a sequence in reverse, use the reversed() function for i in reversed(range(1, 10, 2)): # 9-1 in steps of 2 print(i) # To loop over a sequence in sorted order, use the sorted() function basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for f in sorted(set(basket)): print(f)
true
1c5a98d6e9a995146023aad74ff58a42b8c29c95
llcawthorne/old-python-learning-play
/LearningPython/prime_test.py
341
4.125
4
#!/usr/bin/env python3 def isprime(y): try: y = int(y) except: y = 0 if y < 2: print('Test invalid for inputs under 2!') return x = 2 while x <= y // 2: if y % x == 0: print(y, 'has factor', x) break x += 1 else: print(y, 'is prime')
true
d15daeb0f21ae4eb44f9392b8b44451f882f8b8f
llcawthorne/old-python-learning-play
/ProjectEuler/Problem009_2.py
658
4.28125
4
#!/usr/bin/env python3 """Project Euler Problem 009 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^(2) + b^(2) = c^(2) For example, 3^(2) + 4^(2) = 9 + 16 = 25 = 5^(2). There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ triplets = [(a, b, c) for a in range(1,1000) for b in range(1,1000) for c in range(1,1000) if a + b + c == 1000] thetriplet = [ tuple for tuple in triplets if tuple[0]**2 + tuple[1]**2 == tuple[2]**2] print("The triplet is",thetriplet[0]) print("The product is",thetriplet[0][0]*thetriplet[0][1]*thetriplet[0][2])
false
fb6255b4cdb6c9811f296150c14a31b8a7b65182
Avstrian/SoftUni-Python-Advanced
/Error_Handling/1-Numbers_Dictionary.py
769
4.21875
4
numbers_dictionary = {} line = input() while not line == "Search": num_as_digit = input() try: int(num_as_digit) except ValueError: print("The variable number must be an integer") else: numbers_dictionary[line] = num_as_digit line = input() command = input() while not command == "Remove": try: print(numbers_dictionary[command]) except KeyError: print("Number does not exist in dictionary") command = input() num_to_remove = input() while not num_to_remove == "End": try: numbers_dictionary.pop(num_to_remove) except KeyError: print("Number does not exist in dictionary") num_to_remove = input() print(numbers_dictionary)
true
b211db3958a1c989c7f15497e0b4b57652976c4d
sawaseemgit/AppsUsingLists
/groceryListApp.py
952
4.4375
4
import datetime time = datetime.datetime.now() print('Welcome to the Grocery List App') print(f'Current Date and Time: {time.month}/{time.day}\t{time.hour}:{time.minute}') grocery = ['Cheese','Meat'] for i in range(3): item = input('Add item to grocery list: ') grocery.append(item.title()) print(f'Here is your grocery list:', grocery) grocery.sort() print(f'Here is your grocery list:', grocery) print('Simulating grocery shopping...\n') print('Current grocery list:', len(grocery), ' items') while len(grocery) >2: removeItem = input('What food item did you just buy: ').title() grocery.remove(removeItem) print(f'Removing {removeItem} from the list\n') print(f'Current grocery list: {len(grocery)} items') print(grocery) print(f'Sorry, we are out of {grocery[1]}.') grocery.pop() item = input('What item would you like instead? ').title() grocery.insert(0, item) print('Here is what remains in your grocery list:', grocery)
true
cea8f7f19a51b182fdf8024014c004efce78fd6d
sptan1/class
/python/python102/medium/multiply_vector.py
416
4.125
4
list1 = [] list2 = [] list3 = [] num = int(input("Enter the length of lists : ")) for i in range(1,num+1): number=int(input("Enter a number for first list: ")) list1.append(number) for j in range(1,num+1): number=int(input("Enter a number for second list: ")) list2.append(number) for k in range(1,num+1): m = list1[k-1] * list2[k-1] list3.append(m) print(list1, "x" , list2 , "=", list3)
false
0c30e8cff0f3d836b37ab788e0f23f47528a9083
sptan1/class
/python/python102/large/matrix_multiply.py
756
4.21875
4
list1 = [] list2 = [] list3 = [] #num = int(input("Enter the length of lists : ")) n = 2 m = 2 for i in range(n): temp = [] for j in range(m): number=int(input("Enter a number for [{}, {}] in the first matrix: ".format(i,j))) temp.append(number) list1.append(temp) for i in range(n): temp = [] for j in range(m): number=int(input("Enter a number for [{}, {}] in the second matrix: ".format(i,j))) temp.append(number) list2.append(temp) for i in range(n): temp = [] for j in range(m): x = list1[i][j] * list2[i][j] temp.append(x) list3.append(temp) print("The first matrix is : ") for row in list1 : print(row) print("The second matrix is : ") for row in list2 : print(row) print("Result is : ") for row in list3 : print(row)
false
a9a4e22c3583d557e0cef9c57bbe2b2ce08a41aa
sptan1/class
/python/python102/medium/matrix_addition2.py
1,038
4.15625
4
list1 = [] list2 = [] list3 = [] #num = int(input("Enter the length of lists : ")) n = int(input("Please enter the number of rows : ")) m = int(input("Please enter the number of columns : ")) for i in range(n): temp = [] for j in range(m): number=int(input("Enter a number for [{}, {}] in the first matrix: ".format(i,j))) temp.append(number) list1.append(temp) for i in range(n): temp = [] for j in range(m): number=int(input("Enter a number for [{}, {}] in the second matrix: ".format(i,j))) temp.append(number) list2.append(temp) for i in range(n): temp = [] for j in range(m): x = list1[i][j] + list2[i][j] temp.append(x) list3.append(temp) print("The first matrix is : ") for row in range(n): for col in range(m): print(list1[row][col], end= " ") print() print("The second matrix is : ") for row in range(n): for col in range(m): print(list2[row][col], end = " ") print() print("The result of addition is : ") for row in range(n): for col in range(m): print(list3[row][col], end = " ") print()
false
392bbc7da9105ece04a3d71783947f1be5a61b76
G00364778/52960_Multi_Paradigm_Programming
/assignment_2/08_print_array.py
519
4.21875
4
# 8. Print an array Given an array of integers prints all # the elements one per line. This is a little bit different # as there is no need for a ’return’ statement just to print # and recurse. def stepArr(arr): if len(arr)== 1: #if the array length reached length one only print and return print(arr[0]) else: #otherwise print and iterate print(arr[0]) stepArr(arr[1:]) if __name__ == '__main__': # input values to list arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] stepArr(arr)
true
b113f0eabc2d57cf8ce3fab6acbd5424961b4288
simonfuller3/fuller_simon_python
/RPSGame.py
1,593
4.25
4
# import random package so that we can generate random numbers from random import randint # choices is an array => a contaienr that can hold multiple items # arrays are 0-nased -> the first item is 0, the second is 1, etc choices =["Rock", "Paper", "Scissors"] player = False # make the compputer choose a weapon from the choices at random computer_choice = choices[randint(0,2)] # print the choice to the terminal window print("computer chooses: ", computer_choice) # set up our loop while player is False: # set player to True by making a selection print("choose your weapon!") player = input("Rock, Paper or Scissors?") print(player, "\n") # check for a tie = choices are the same if player == computer_choice: print("Tie! You live to shoot again") # check to see if the computer choice beats our choice or not elif player == "Rock": if computer_choice == "Paper": # computer won. crap!! print("You Lose! paper covers rock") else: # we win! such winning print("You Win!", player, "smashes", computer_choice) elif player == "paper": if computer_choice == "Scissors": print("You Lose!", computer_choice, "cut", player) else: print("You Won! Would ya just look at it", player, "covers", computer_choice) elif player == "scissors": if computer_choice == "rock": print("You Lose!", computer_choice, "smashes", player) else: print("you win!", player, "Cut", computer_choice) elif player == "quit": exit() else: print("check your spelling.. thats not a valid choice\n") player = False computer_choice = choices[randint(0, 2)]
true
b97a719af977ecd19b100cec7b85da8dd0044751
wints/lpthw-exercises
/ex19_lpthw.py
1,516
4.25
4
# defines function with cheese_count and boxes_of_crackers arguments def cheese_and_crackers(cheese_count, boxes_of_crackers): # prints cheese_count in string print "You have %d cheeses!" % cheese_count # prints boxes_of_crackers in string print "You have %d boxes of crackers!" % boxes_of_crackers # prints string print "Man that's enough for a party!" # prints string plus newline print "Get a blanket.\n" # prints string print "We can just give the function numbers directly:" # calls function with args of 20 and 30 cheese_and_crackers(20, 30) # prints string print "OR, we can use variables from our script:" # assigns variable amount_of_cheese amount_of_cheese = 10 # assigns variable amount_of_crackers amount_of_crackers = 50 # calls function with newly assigned vars as arguments cheese_and_crackers(amount_of_cheese, amount_of_crackers) # prints string print "OR, we can use variables from our script:" # assigns variable amount_of_cheese amount_of_cheese = 100 # assigns variable amount_of_crackers amount_of_crackers = 37 # calls function with newly assigned vars as arguments cheese_and_crackers(amount_of_cheese, amount_of_crackers) #prints string print "We can even do math inside too:" # calls function with simple arithmetic as arguments cheese_and_crackers(10 + 20, 5 + 6) # prints string print "And we can combine the two, variables and math:" # calls function with sums of variables and integers for arguments cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
true
dad8daf507a1ad64fe7b24c981e91f8676a0c8ce
wints/lpthw-exercises
/ex31_study.py
1,643
4.1875
4
print "It's been a long week, but luckily, you have a three-day weekend coming up." print "How would you like to spend it?" print "1. By the beach." print "2. Off in nature." print "3. In a charming city." destination = raw_input("Enter 1, 2, or 3: ") if destination == "1": print "OK, let's get you to a beach." print "Would you rather see Spain or Croatia?" beach = raw_input("Spain or Croatia: ") if beach == "Spain": print "OK, just booked you a flight and hotel for San Sebastian!" elif beach == "Croatia": print "Great, you're going to Susak! Get to the airport!" else: print "OK, someone else will need to help you get to %s." % beach elif destination == "2": print "Ah, good choice. I love nature." print "Would you rather visit Cinque Terre or Mont Blanc?" nature = raw_input("Cinque Terre or Mont Blanc: ") if nature == "Cinque Terre": print "I love that hike from Monterosso to Riomaggiore." elif nature == "Mont Blanc": print "Some of the grandest vistas this side of the Thames. Yodel-ay-hee-hoooo!" else: print "OK, someone else will need to help you get to %s." % nature elif destination == "3": print "A hefty dose of old-world charm, coming right up!" print "Would you rather visit Prague or Amsterdam?" city = raw_input("Prague or Amsterdam:") if city == "Prague": print "Be sure to try the beer at the Strahov Monatic Brewery!" elif city == "Amsterdam": print "Rent a boat, tour the canals, and hey-ey-ey-ey...eat ribs every day." else: print "OK, someone else will need to help you get to %s." % city else: print "Well, it sure would be nice to relax in Berlin too, wouldn't it?"
true
2cde4b13d732748bbcfe614d87ca3025e5918cda
wints/lpthw-exercises
/ex7_lpthw.py
1,683
4.21875
4
<<<<<<< HEAD # prints string print "Mary had a little lamb." # prints string, inserts string variable print "Its fleece was white as %s." % 'snow' # prints string print "And everywhere that Mary went." # prints 10 . in succession print "." * 10 # what'd that do? # assigns variable end1 = "C" # assigns variable end2 = "h" # assigns variable end3 = "e" # assigns variable end4 = "e" # assigns variable end5 = "s" # assigns variable end6 = "e" # assigns variable end7 = "B" # assigns variable end8 = "u" # assigns variable end9 = "r" # assigns variable end10 = "g" # assigns variable end11 = "e" # assigns variable end12 = "r" # watch the comment at the end. try removing it to see what happens: 'Burger' prints on a new line # concatenates strings (variables) to spell Cheese Burger print end1 + end2 + end3 + end4 + end5 + end6, print end7 + end8 + end9 + end10 + end11 + end12 ======= # print string print "Mary had a little lamb." # print string print "Its fleece was white as %s." % 'snow' # print string print "And everywhere that Mary went." # print string of one period ten times consecutively print "." * 10 # what'd that do? # defines variables end1 through end12 end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # watch that comma at the end. try removing it to see what happens. # Removing it breaks Cheese Burger onto 2 lines # print variables end1 through end6 print end1 + end2 + end3 + end4 + end5 + end6, # print variables end7 through end12 on the same line print end7 + end8 + end9 + end10 + end11 + end12 >>>>>>> 5e39aee329f96af716a2e0fba84872881cd73540
true
a310b75597d76c882ac0d69fb3805970bd358850
huntercollegehighschool/srs2pythonbasicsf21-eaindra-naing
/part2.py
615
4.1875
4
""" Define a function diamond that takes a single integer input size. The function then prints (doesn't have to return) a hollow diamond made of asterisks. Hint: <string>.center(2*size - 1) may be helpful in your code (for center aligning) Examples of what should appear: diamond(4) --> * * * * * * * * * * * * diamond(5) --> * * * * * * * * * * * * * * * * * * * * * * * * """ def diamond(size): pass # delete this when you start writing your code
true
4da1e2d1bd6acd3d43d3dee33c76ab9cecc864af
architlatkar27/python-lab
/script_input_a_number.py
326
4.21875
4
#Write a script that asks a user for a number. The script adds 3 to that number. #Then multiplies the result by 2, subtracts 4, subtracts twice the original number, adds 3, then prints the result. num=int(input("enter a number ")) org=num num+=3 num*=2 num-=4 num-=2*org num+=3 print("result of this circus = {}".format(num))
true
160354f8afb1c59a40e6c62ea9e6a94c5f138123
JcesarIA/learning-python
/EXCursoEmVideo/ex041.py
506
4.15625
4
from datetime import datetime Nascimento = int(input('Insira a data do seu nascimento: ')) idade = datetime.today().year - Nascimento if idade <= 9: print(f'Com {idade} Anos sua categoria é Mirim. ') elif idade <= 14: print(f'Com {idade} Anos sua categoria é Infantil. ') elif idade <= 19: print(f'Com {idade} Anos sua categoria é Júnior ') elif idade <= 25: print(f'Com {idade} Anos sua categoria é Sênior ') elif idade > 25: print(f'Com {idade} Anos sua categoria é Master ')
false
755d9daa8dfdc81cafd1ac2ee1f33bbca1fdd2a2
boyer-code/pynet_ansible
/Coursera-UMich/http_template.py
2,866
4.1875
4
def integer_check(user_supplied_number): #this is a function to ensure that the user is actually entering a number while True: try: user_supplied_number = int(user_supplied_number) if user_supplied_number > 0: return user_supplied_number else: print 'that will not work' user_supplied_number = raw_input('please enter a valid integer ') continue except: print 'that will not work' user_supplied_number = raw_input('please enter a valid integer ') continue def server_names_and_ips_loop(server_variable): #this function will ask users for server names and IPs, then add them to a list...we'll later read from the list to create our pools serverList = [] #reset the list that we update in the loop...this allows us to reuse the function with fresh lists per DC while server_variable > 0: #print server_variable serverName = raw_input('What is the server name? ') serverIP = raw_input('What is the server IP? ') serverName = str(serverName) serverIP = str(serverIP) serverList.append(serverName) serverList.append(serverIP) server_variable -= 1 #print serverList #print serverIPList return serverList #appID = raw_input('What is your app ID? ') #appID = integer_check(appID) #print 'AppID is',appID #path = raw_input('What is your probe path? ') #print 'path is',path backend80Port = raw_input('What is your backend 80 port? ') #backend80Port = integer_check(backend80Port) #print '80 redirects to',backend80Port #backend443Port = raw_input('What is your backend 443 port? ') #backend443Port = integer_check(backend443Port) #print '443 redirects to',backend443Port pdc1ServerCount = raw_input('How many PDC1 servers do you have? ') pdc1ServerCount = integer_check(pdc1ServerCount) #pdc3ServerCount = raw_input('How many PDC3 servers do you have? ') #pdc3ServerCount = integer_check(pdc3ServerCount) serverListPDC1 = [] #serverListPDC3 = [] appName = raw_input('What is your application name? ') #appFQDN = raw_input('What is your FQDN? ') #vip1 = raw_input('What is your first VIP? ') #vip2 = raw_input('What is your second VIP? ') serverListPDC1 = server_names_and_ips_loop(pdc1ServerCount) #serverListPDC3 = server_names_and_ips_loop(pdc3ServerCount) #print 'modify ltm profile',appName,'-ssl-profile something I don\'t remember without looking at my notes' #modify the below to add the servers to the pools once we write the for/while loops to get input for each server name print 'create ltm pool '+appName+'-'+backend80Port+'-pool members add '+serverListPDC1[0]+':'+backend80Port+' { address ',serverListPDC1[1],' } ',serverListPDC1[2],'\b:',backend80Port,'\b\{ address',serverListPDC1[3],'\}'
true
16f10e5bdfb9f78be84538d01cf631df5f0d1f2e
mongoz/itstep
/lesson7/palindrom.py
233
4.125
4
num = int(input("Enter a number:")) temp = num rev = 0 while num > 0: dig = num % 10 rev = rev*10 + dig num = num//10 if temp == rev: print("The number is palindrome!") else: print("Not a palindrome!")
true
c77712457a0e60261d5ad2ed79e8c88c6f4efced
JorgeCastillo97/Python
/Working with Lists and Dictionaries.py
2,309
4.125
4
names=["Adam","Alex","Mariah","Martin","Spencer"] for n in names: print(n) print("\n\n") webster={ "Cartoon Network" : "A TV Channel for kids.", "Blark" : "The sound a dog makes.", "Carpet" : "Goes on the floor.", "Dab" : "A small amount." } for w in webster: print(webster[w]) print("\n\n") a=[1,2,3,4,5,6,7,8,9,10] for b in a: if b%2==0: print(b) print("\n\n") def redOnes ( subset ): count=0 for color in subset: if color=="Red": count=count+1 return count subset=["Red","Blue","Yellow","Black","White","Red","Gold","Cyan","Red","Orange"] subset.append("Black") subset[0]="Red" print("Colors:\n") print(subset) last_3=subset[8:len(subset)] print("The last three elements are: %s" %last_3) print("Gold is in position: %d" %subset.index("Gold")) subset.insert(subset.index("Gold"), "Deleted") print(subset[6]) print("\nRed ones found:\n%d"%redOnes(subset)) print("\n\n") for letter in "Programming in Python": if letter=="i": print(letter) print("\n\n") prices = { "banana":4, "apple":2, "orange":1.5, "pear":3 } stock = { "banana":6, "apple":0, "orange":32, "pear":15 } for fruit in prices: print(fruit) print("Price: %s" %prices[fruit]) print("Stock: %s" %stock[fruit]) total=0 for key in prices: total=total+(prices[key]*stock[key]) print("\nTotal: %d\n" %total) start_list=[10,50,30,20,40] squared_list=[] for number in start_list: squared_list.append(number**2) print("Original list:") print(start_list) squared_list.sort() print("Squared list:") print(squared_list) print("\n") choices=['pizza','burguer','pasta','salad', 'milkshake'] print("\n") for index, item in enumerate(choices): print((index+1), item) print("\n") list_a=[3, 9, 17, 15, 19] list_b=[2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90] for a,b in zip(list_a,list_b): if a>b: print(a) else: print(b) print("\n") fruits = ['banana', 'apple', 'orange', 'carrot', 'pear', 'grape'] print("You have...") for f in fruits: if f == 'carrot': print ('A carrot is not a fruit!') break print ('A', f) #the "else" statement is not executed because of the "Break" inside the for loop else: print ('A fine selection of fruits!')
false
a97862f48a407a67591aef40fda7ccb7b659cf8c
hugodepaula/linguagens-de-programacao
/exemplos/clp-aula-17-funcional-python/hof.py
2,048
4.25
4
# -*- coding: utf-8 -*- """ hof.py: funcões de ordem superior @author: Prof. Hugo de Paula @contact: hugo@pucminas.br """ # Recebe uma função como parâmetro e avalia esta função def avaliar(f, x): return f(x) # retorna uma função # note que retorna result, e não result() def linear(a, b): def funcao(x): return a*x + b return funcao # não é result() minhaFuncaoLinear = linear(-2, 5) # faz a função -2x + 5 print("minhaFuncaoLinear = linear(-2, 5)\nminhaFuncaoLinear(2) = {}" .format(minhaFuncaoLinear(2))) #avalia a função no ponto 8 print("linear(4, 3)(8) = {}" .format(linear(4, 3)(8))) print("\n--------------------------------------\n") def composicaoVal(f, g, x): return f(g(x)) def composicaoFun(f, g): def h(x): return f(g(x)) return h # -2 (3x + 4) + 5 = -6x -8 + 5 = -6x - 3 print("novaFun composicaoFun(linear(-2, 5), linear(3, 4)) = ") novaFun = composicaoFun(linear(-2, 5), linear(3, 4)) print(novaFun(4)) print((lambda x, y : composicaoFun(x, y)) (linear(-2, 5), linear(3, 4))(4)) print("\n--------------------------------------\n") # retorna o máximo de dois valores def maxVal(x, y): if (x > y): return x else: return y # retorna o máximo de duas funções num ponto def maxFunVal(f, g, x): return maxVal(f(x), g(x)) print("maxFunVal(linear(3, 6), linear(5, -8), 10) = {0}" .format(maxFunVal(linear(3, 6), linear(5, -8), 10))) # f(x) = 3x10 + 6 = 36 g(x)= 5x10 -8 = 42 f = lambda x: x + 2 g = lambda x: 6 print("maxFunVal(lambda x: x + 2, lambda x: 6, 3) = {0}" .format(maxFunVal(f, g, 3))) # retorna o máximo de dois valores def maxFun(f, g): def funcaoMax(x): return maxVal(f(x), g(x)) return funcaoMax funcaoMaxima = maxFun(linear(2, 4), linear(3, -2)) print("maxFun(linear(2, 4), linear(3, -2)) (3) = {0}" .format(funcaoMaxima(3))) print("[funcaoMaxima(x) for x in range(1,10)] = ") print([funcaoMaxima(x) for x in range(1,10)])
false
6b6da31225845fa1319f0e98e6016b14135e643e
hieuvanvoW04/Python
/Assignment 1/Imperial to Metric Conversion.py
930
4.21875
4
""" Name..: Hieu NGuyen, Student ID....: W0424530 """ _AUTHOR_ = "Hieu Nguyen <W0424530@nscc.ca>" #1. Print program name #2. Input tons, stones, pounds and ounces amount #3. Convert amount into kilos #4. Convert rest amount to grams #5. Print Result def main(): #Input print("Imperial to Metric Conversion") tons=float(input("\nEnter number of tons: ")) Stones=float(input("Enter number of stone: ")) pounds=float(input("Enter number of pounds: ")) ounces=float(input("Enter number of ounces: ")) #Process totalOunces=tons*35840+Stones*224+pounds*16+ounces totalKilos=totalOunces/35.274 metricTons=int(totalKilos/1000) kilo=int(totalKilos-metricTons*1000) gram=float(((totalKilos-kilo-metricTons*1000)*1000)) #Output print("\nThe metric weight is {0}".format(metricTons)+" metric tons, {0}".format(kilo)+" kilos, and {0:.1f}".format(gram)+ " grams") if __name__== "__main__": main()
false
fc8bce489b3be53d040b3ae5f082c74e3362a3a5
hieuvanvoW04/Python
/In Class/301018 whileloop.py
859
4.125
4
def whileloop(): input_is_valid=False while(not input_is_valid): # Ask for input maybe_num=input("Please enter 4 number ") # kk=maybe_num.replace(".","") # kk.isnumeric # try float # not float # Check is it valid if(maybe_num.isnumeric()): # Set input_is_valid input_is_valid=True else: num=int(maybe_num) print(num) function # def getValidNum(num_to_check): # nc=num_to_check.replace(".","") # while(not num_to_check.isnumeric): # num_to_check=input("Not a number. Please try again.") # nc=num_to_check.replace(".","") # else: # num_to_check=int(num_to_check) # return(num_to_check) # first_int=input("Give me first #") # first_int=getValidNum(first_int) whileloop()
true
da0413366d76330a055942c15cb39c4e6b3161cc
cjwood032/CSC1570
/CSC1570/property_tax_Wood.py
1,236
4.375
4
# property_tax_Wood # This program will calculate the property tax of a property # Programmer: Christopher Wood # date 2/20/18 # file name property_tax_Wood.py # pseudocode #define the functions assessment and taxing #Get the actual value of the property #Calculate the assessed value, 60% of the actual value #calculate the propery tax, for each $100 of the actual value add .72 #display the assessed value and the property tax def main(): assessed=assessment(percent=.6) #set the values for the percent and the cost for tax taxing(assessed,tax_cost=.72) def assessment(percent): actual = float(input("enter the actual value of the property:")) # get the actual value of the property assessed = percent * actual # calculate the assessed value print("Assessed value: $",end='')# display the assessed value print(format(assessed, ",.2f"), "\n") # display the assessed value return assessed def taxing(assessed,tax_cost): tax = (assessed // 100) * tax_cost # calculate the property tax, for each $100 of the assessed print("Property Tax: $",end='') # display the property tax print(format(tax, ",.2f")) # display the property tax return tax main() #run the main function
true
d0327449d0afc053c8777acd9d7ed1949fda8e78
cjwood032/CSC1570
/CSC1570/paint_job_estimator_Wood.py
2,479
4.59375
5
# paint_job_estimator_Wood # This program will calculate the cost of painting a wall # Programmer: Christopher Wood # date 2/20/18 # file name paint_job_estimator_Wood.py # pseudocode #user inputs the area of the wall #divide the area of the wall by 112, rounding up to get the gallons of paint #user inputs the price per gallon #multiply the gallons of paint by 8 to get the number of hours worked #multiply the gallons of paint by the price of a single gallon paint for the paint cost #display the total hours of labor required for the paint job #multiply the hours worked by 35 for the labor costs #the total cost will be the paint charges plus labor charges #display the gallons of paint, paint charges, labor charges, and total cost to the user def main(): area=float(input("How much wall will be painted (in square feet)?")) #user inputs the area of the wall gal=gallons(area)#run the gallons function paint_cost=Paint_cost(gal)#display the number of gallons of paint required hours=gal*8 #multiply the gallons of paint by 8 to get the number of hours worked print("hours of labor:", hours) # display the number of hours of labor required labor_cost=Labor_cost(hours) # run the labor function total_cost=paint_cost+labor_cost #The total cost will be the paint charges plus the labor charges print("Total charges: $", end='') #Display the total cost to the user print(format(total_cost,",.2f")) #Display the total cost to the user def gallons(area): gal=area/112#divide the area by 112 if gal != area// 112 or area//112 == 0: # if there is a remainder, add 1 more number of gallons required gal += 1 gal=int(gal)#Make sure there's no remainder return gal def Paint_cost(gal): paint_price = float(input("What is the price per gallon for paint?")) #user inputs the price for gallon print("Gallons of paint:", gal) #display the price per unit paint_cost = gal * paint_price #multiply the gallons of paint by the price per gallon of the paint to get total paint cost print("paint charges: $",end='') #display the paint charges print(format(paint_cost,",.2f")) return paint_cost def Labor_cost(hours): labor_cost=hours*35#multiply the hours worked by 35 for the labor costs print("Labor charges: $",end='')#display the labor cost print(format(labor_cost,",.2f"))#display the labor cost return labor_cost main() #run the main function.
true
ba6cc860b098f26539724664c8ef0f4eaf46ba37
nullx5/Learning-the-Syntax-python
/ejemplo_funcion_varios_valores_salida.py
615
4.1875
4
 def calculo_multiple(a, b): sum = a + b res = a - b mul = a * b return(sum, res, mul, a / b, a ** b) def main(): print("Introduce los dos valores sobre los que se harán los cálculos:") num1 = eval(input("número 1: ")) num2 = eval(input("número 2: ")) suma, resta, multiplicacion, division, potencia = calculo_multiple(num1,num2) print("La suma es: ", suma) print("La resta es: ", resta) print("La multiplicación es: ", multiplicacion) print("La división es: ", division) print("La potencia es: ", potencia) main()
false
6d4f9d08d3c77204b344f6b57e6fb338f8ef8492
sunggeunkim/datastructure
/array/majorityElement.py
1,690
4.3125
4
''' reference: http://www.geeksforgeeks.org/majority-element/ A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). Write a function which takes an array and returns the majority element (if it exists), otherwise returns NONE as follows: Moore’s Voting Algorithm This is a two step process. 1. The first step gives the element that may be majority element in the array. If there is a majority element in an array, then this step will definitely return majority element, otherwise it will return any other element. 2. Check if the element obtained from above step is majority element. This step is necessary as we are not always sure that element return by first step is majority element. 1. Finding a Candidate: The algorithm for first phase that works in O(n) is known as Moore’s Voting Algorithm. Basic idea of the algorithm is if we cancel out each occurrence of an element e with all the other elements that are different from e then e will exist till end if it is a majority element. 2. Check if the element obtained in step 1 is majority ''' def findCandidate(A): maj_index = 0 count = 1 for i in range(len(A)): if A[maj_index] == A[i]: count += 1 else: count -= 1 if count == 0: maj_index = i count = 1 return A[maj_index] # Function to check if the candidate occurs more than n/2 times def isMajority(A, cand): count = 0 for i in range(len(A)): if A[i] == cand: count += 1 if count > len(A)/2: return True else: return False
true
81aa295b94d3000e9632c93d6a3f1f154692b022
sunggeunkim/datastructure
/tree/BT2DLL.py
679
4.125
4
# convert binary tree to doubly linked list # root is the root of the tree # head is the head of the linked list prev = None def BT2DLL(root, head): #base case if root == None: return prev = None # traverse to the left BT2DLL(root.left, head) # if we are at the left most node # set the head to the root if prev is None if prev == None: head = root # if prev is not pointing to None # create a double link to prev and root else: root.left = prev prev.right = root # prev is pointing to the root prev = root # do the same thing above to the right subtree. BT2DLL(root.right, head)
true
6974fee675205df729a3adc9a6d4a883af888988
sunggeunkim/datastructure
/array/permutations.py
953
4.125
4
''' Write a function that returns all permutations of a given list. permutations({1, 2, 3}) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] ''' def swap(a, i, j): temp = a[i] a[i] = a[j] a[j] = temp def string_permutations(s): results = [] string_permutation("", s, results) return results def string_permutation(prefix, suffix, results): if len(suffix) == 0: results.append(prefix) else: for i in range(0, len(suffix)): string_permutation(prefix + suffix[i], suffix[:i] + suffix[i+1:], results) def list_permutations(a, start, results): if start >= len(a): results.append(list(a)) else: for i in range(start, len(a)): swap(a, start, i) list_permutations(a, start+1, results) swap(a, start, i) a = "abc" print(string_permutations(a)) a = [1, 2, 3] results = [] list_permutations(a, 0, results) print(results)
true
3b7fd50d019a5949bba8c51f2f0f382324d15aed
thebobak/ProjectEuler
/test.py
1,049
4.28125
4
from math import sqrt #GLOBALS FALSE = 0 TRUE = 1 #List and count of all prime numbers primes = [2,3,5,7,11,13,17,19,29,31] count = len(primes) primes_to_seek = 15 x = 32 while (count < primes_to_seek): print "now testing %s" % x xs = str(x) lastdigit = xs[-1] xroot = sqrt(x) #Check the last digit of the number #if last digit is 0,2,4,5,6,8, move on to next number if (lastdigit == "0" or lastdigit == "2" or lastdigit == "4" or lastdigit == "5" or lastdigit == "6" or lastdigit == "8"): print "%s is NOT prime (last digit)" % x x+=1 # check if sqrt is an INT, skip number if it is elif (isinstance(xroot, int) == TRUE): print "%s is NOT prime (has root)" % x x+=1 else: flag = TRUE i = 2 while (i < int(xroot)): if (x%i == 0): flag = FALSE i+=1 if (flag == TRUE): primes.append(x) count = len(primes) print "Prime Found: %s" % x x+=1 elif (flag == FALSE): print "%s is NOT prime (division test)" % x x+=1 print "The list of Primes is:" print primes print "The End"
true
7dbcc5402c7550bcdfbe78411820ce4a4b4747fe
pritamkashyap/ds-practice
/Linked-List-implementation/linked_list.py
1,671
4.15625
4
class Node(object): next=None def __init__(self,data): self.data=data class Linked_List(object): size=0 def __init__(self): self.head=None def push_beg(self,data): self.size=self.size+1 newNode=Node(data) if self.head is None: self.head=newNode else: newNode.next=self.head self.head=newNode def push_end(self,data): self.size=self.size+1 newNode=Node(data) temp=self.head; while(temp.next): temp=temp.next temp.next=newNode newNode.next=None def remove(self,data): self.size=self.size-1 if self.root is None: print("list is already empty") elif self.root.data == data: print("Deleting.. ",data) else: temp = self.root while(temp.next.data != data): temp = temp.next print("Deleting ..",data) temp.next = temp.next.next def traverse(self): temp2=self.head while(temp2 is not None): print(temp2.data) temp2=temp2.next list=Linked_List() ans="n" print("<---**** Linked List Implementation ****--->") while(ans=="n"): print("1. Insert an element at begning") print("2. Insert an element at the end") print("3. Remove an element") print("4. Display all elements") print("5. size of the linked list") choice=int(input()) if(choice ==1): data=input("Enter the item") list.push_beg(data) elif(choice==2): data=input("Enter the item") list.push_end(data) elif(choice==3): data=input("Enter the element to be removed") list.remove(data) elif(choice==4): print("Elements are : ") list.traverse() elif(choice==5): print("Size of Linked List : ",list.size) else: print("Invalid Option") ans=raw_input("Quit(y/n)")
true
2a2a08a7646016dc26f7906138ec5950949f31cc
snowingsc/module02-python
/main.py
212
4.25
4
weight = 90 height = 56 BMI = 703*weight/(height**2) print(f"BMI is {BMI}") if BMI < 18.5: print("underweight") elif BMI < 25.0: print("normal") elif BMI < 30.0: print("overweight") else: print("obese")
false
b962ec294a5ca5806569a898f1c4b77edba8b679
Hex4Bin/python_data_structures
/3_stack/linkedstack.py
939
4.28125
4
from linkedlist import LinkedList class LinkedStack: """ This class is a stack wrapper around a LinkedList. This means that methods like `add_to_list_start` should now be called `push`, for example. """ def __init__(self): self.__linked_list = LinkedList() def push(self, node): """ Same as LinkedList's add_start_to_list method. """ self.__linked_list.add_start_to_list(node) def pop(self): """ Same as LinkedList's remove_start_from_list method. """ return self.__linked_list.remove_start_from_list() def find(self, text): """ Same as LinkedList's find method. """ return self.__linked_list.find(text) def print_details(self): """ Same as LinkedList's print_list method. """ self.__linked_list.print_list() def __len__(self): """ Same as LinkedList's size method. """ return self.__linked_list.size()
true
66ff95b4c31b77b1cf2dcae7a7a38c31e370e589
kevindooley/pands-problem-set
/datetimesolution.py
601
4.3125
4
#Kevin Dooley 08 Mar 19 #A program that outputs todays date and time #Expressed in the format “Monday, January 10th 2019 at 1:15pm” #datetime module allows representation of date and time #shortened datetime to dt to reduce number of characters import datetime as dt #strftime allows user to return date in string format #import datetime module, within that use sub section datetime and then sub section strftime #%A = Day of week, %B = Month, %d = day of month, %Y = year, %I = hour, %M = minute, %p = AM/PM today = dt.datetime.strftime(dt.datetime.now(), "%A, %B %dth %Y at %I:%M%p") print (today)
true
dfa1fab027cf5b4d0bc7b5820e9fae3f4ad25561
techuy/Python
/Bootcamp/Datatype_DataStructure/list.py
731
4.375
4
# list is like array but it's dynamic because we can store any datatype my_list = ["String",1,5.0] mylist = ["zero","one","two"] print(mylist[0]) #concate list print(mylist+my_list) # change mylist[0]="ONEEEE" print(mylist) # append is like "push" add the end of the list mylist.append("four") print(mylist) #remove element from the list mylist.pop() pop_list = mylist.pop() print(mylist) print(pop_list) # we can remove the element base on the index mylist.pop(1) print(mylist) #sort and reverse new_list = ['a','v','d','b','f'] numlist = [1,3,5,2,10,8,12] numlist.sort() new_list.sort() print(numlist) print(new_list) numlist.reverse() new_list.reverse() print(numlist) print(new_list)
true
80a2d8eb1dee3046acc40ccbda3806ec9df7c574
techuy/Python
/KIT bootcamp project/week01/ex/06_odd_even.py
390
4.21875
4
con = True while (con): userIn = input("Enter a Number:") if(userIn != 'EXIT'): try: userIn = int(userIn) if(userIn%2==0): print(f"{userIn} is EVEN") else: print(f"{userIn} is ODD") except Exception: if userIn != '': print(f"{userIn} is not a valid number") elif userIn=='EXIT': break
false
f9ac7fe33bccade672df53fcfaa5e7432ad33e97
alvas-education-foundation/Alsten_Tauro
/coding_solutions/DAY73(05-08-2020)/pangram.py
254
4.125
4
from string import ascii_lowercase as asc_lower def check(s): return set(asc_lower) - set(s.lower()) == set([]) strng=str("Enter string:") if(check(strng)==True): print("The string is a pangram") else: print("The string isn't a pangram")
true
47ca461f588e5d55099077a93eee0019d38ae1b0
lsm4446/study_python
/Kwonhee/파이썬 데이터 분석 입문/database/2db_insert_rows.py
1,199
4.3125
4
#!/usr/bin/env python3 import csv import sqlite3 import sys # Path to and name of a CSV input file input_file = "D:\Kwonhee\OneDrive\Github\study_python\Kwonhee\파이썬 데이터 분석 입문\database\supplier_data.csv" # Create an in-memory SQLite3 database # Create a table called Suppliers with five attributes con = sqlite3.connect('Suppliers.db') c = con.cursor() create_table = """CREATE TABLE IF NOT EXISTS Suppliers (Supplier_Name VARCHAR(20), Invoice_Number VARCHAR(20), Part_Number VARCHAR(20), Cost FLOAT, Purchase_Date DATE);""" con.execute(create_table) con.commit() # Read the CSV file # Insert the data into the Suppliers table file_reader = csv.reader(open(input_file, 'r'), delimiter=',') header = next(file_reader, None) for row in file_reader: data = [] for column_index in range(len(header)): data.append(row[column_index]) print(data) c.execute("INSERT INTO Suppliers VALUES (?, ?, ?, ?, ?);", data) con.commit() # Query the Suppliers table output = c.execute("SELECT * FROM Suppliers") rows = output.fetchall() for row in rows: output = [] for column_index in range(len(row)): output.append(str(row[column_index])) print('output:', output)
true
bb915fb8c0f0940dce4a655133618e48247ecbfd
ankiyang/Scripts.Fundamental.Little
/Fundamentals/triangle.py
752
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' 判断三个数值是否可以构成三角形 ''' while True: s = raw_input("Please input 3 integers to combine a triangle(enter q to quit):") S = s.split(',') if s == 'q': break else: a = int(S[0]) b = int(S[1]) c = int(S[2]) if a+b > c and a+c > b and b+c > a: if a == b and b == c: print "It's a regular triangle." else: if a == b or b == c or a == c: print "It's an isosceles triangle." else: print "It's a normal triangle." else: print "sorry, the 3 numbers cannot combine a triangle." print 'The end'
true
e19b6b684cb44fe6419a9a02611eeb37e867da49
aseafamily/Coding
/Emily/FunctionsDay24/brokenhidingdata/MoreHotdogsandTriangles.py
2,858
4.1875
4
class Triangle: def __init__(self, width, height, side1, side2, side3): self.width = width self.height = height self.side1 = side1 self.side2 = side2 self.side3 = side3 def getArea(self): area = self.width * self.height / 2.0 return area def getPeri(self): perimeter = self.side1 + self.side2 + self.side3 return perimeter class Square: def __init__(self, size): self.size = size def getArea(self): area = self.size * self.size return area def getPeri(self): perimeter = self.size * 4 return perimeter class Circle: def __init__(self, radius): self.radius = radius def getArea(self): area = self.radius * self.radius * 3.14 return area def getCircum(self): circumference = self.radius * 2 * 3.14 return circumference class Rectangle: def __init__(self, length, height): self.length = length self.height = height def getArea(self): area = self.length * self.height return area def getPeri(self): perimeter = self.length + self.length + self.height + self.height return perimeter thewidthft = float(input('What is the width of the triangle?')) theheightft = float(input('What is the height of the triangle')) side1ft = float(input('What is the length of the first side of the triangle?')) side2ft = float(input('What is the length of the second side of the triangle?')) side3ft = float(input('What is the length of the third side of the triangle?')) myTriangle = Triangle(thewidthft, theheightft, side1ft, side2ft, side3ft) thesidefs = float(input("What is the length of one of the square's sides?")) mySquare = Square(thesidefs) theradiusfc = float(input('What is the radius of the circle?')) myCircle = Circle(theradiusfc) thelengthfr = float(input('What is the height of the rectangle?')) theheightfr = float(input('What is the length of the rectangle?')) myRectangle = Rectangle(thelengthfr, theheightfr) areaOfTriangle = myTriangle.getArea() areaOfSquare = mySquare.getArea() areaofCircle = myCircle.getArea() areaofRectangle = myRectangle.getArea() periofTriangle = myTriangle.getPeri() periofSquare = mySquare.getPeri() circumofCircle = myCircle.getCircum() periofRectangle = myRectangle.getPeri() print('The area of the triangle is ' + str(areaOfTriangle)) print('The perimeter of the triangle is ' + str(periofTriangle)) print('The area of the square is ' + str(areaOfSquare)) print('The perimeter of the square is ' + str(periofSquare)) print('The area of the circle is', str(areaofCircle)) print('The circumference of the circle is ' + str(circumofCircle)) print('The area of the rectangle is ' + str(areaofRectangle)) print('The perimeter of the rectangle is ' + str(periofRectangle))
true
f027804adf068d093c9c18460d810024f7b62395
aseafamily/Coding
/andrew/new.py
452
4.15625
4
age = float(input("Enter your age: ")) grade = int(input("Enter your grade: ")) if age >= 8 and grade >= 3: print("You can play the game") else: print("Sorry you can not play the game.") #answer = float(input("Enter a number from 1 to 15: ")) #if answer >= 10: # print("You got at least 10!") #elif answer >= 5: # print("You got at least 5!") #elif answer >= 3: # print("You got at least 3!") #else: # print("You got less then 3.")
true
70966d29e4dc21c1d49129d22ae971ed0eec6de7
aseafamily/Coding
/Emily/OOProjects/RandomPygamePro.py
1,308
4.15625
4
from time import sleep import pygame pygame.init() print('Welcome to Stopwatch & Timer!') which = input('''Would you like to set a stopwatch or a timer?(s/t) ''') if which == 't': long = input('Alright, would you like to set a timer in seconds, minutes, or hours?(seconds/minutes/hours)') thetime = int(input('Okay, how long would you like the timer to be? Put it in your earlier preferred units.')) print('Okay then! One more thing, a white screen with a red circle will pop up when your timer is up.') if long == 'seconds': thetime = thetime elif long == 'minutes': thetime = thetime*60 elif long == 'hours': thetime = thetime*60*60 else: print("Sorry, that isn't an option.") for i in range(thetime, 0, -1): print(i) sleep(1) screen = pygame.display.set_mode([600, 600]) screen.fill([255,255,255]) pygame.draw.circle(screen, (255,0,0),[300,300],150,0) pygame.display.flip() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() elif which == 's': stopwatchfy = input('Alright, Stopwatch starting! Type stop when you want to stop the stopwatch.') else: print('Sorry, that is not an option!')
true
9d6bb6d2d9cece154e91ff4e9d5061aabcb1cfc0
Eduardo-Gonz/InClassGit
/divisors.py
278
4.1875
4
def find_divisors(num): divisors = [] for i in range(1, num + 1): if(num % i == 0): divisors.append(i) print(divisors) def input_number(): num = input("Enter number you want to find divisors of: ") find_divisors(num) input_number()
true