blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c22167ee72352ce55dfb2b3db6108857776f6c7c
lyannjn/codeInPlaceStanford
/Assignment2/hailstones.py
829
4.5
4
""" File: hailstones.py ------------------- This is a file for the optional Hailstones problem, if you'd like to try solving it. """ def main(): while True: hailstones() def hailstones(): num = int(input("Enter a number: ")) steps = 0 while num != 1: first_num = num # Even number if num % 2 == 0: num = num // 2 print(str(first_num) + " is even, so I take half: " + str(num)) # Odd number else: num = (num * 3) + 1 print(str(first_num) + " is odd, so I make 3n + 1: " + str(num)) steps += 1 print("This process took " + str(steps) + " steps to reach 1") print("") # This provided line is required at the end of a Python file # to call the main() function. if __name__ == '__main__': main()
true
83e0cd383f22f7f9483622e7df9acf195e790103
NithinRe/slipting_current_bill
/Power_Bill.py
1,043
4.15625
4
print("----------------Electricity Bill---------------------") x = int(input("what is cost of current : ")) y = int(input("Enter Number of units used : ")) z = x/y print("Each unit is charged as : ",z) print("-----------------------------------------------------") meter1 = int(input("First floor number of units used :")) First_floor = meter1*z print("first floor bill is : ",First_floor) a = int(input("Enter Number of members in First floor :")) c = First_floor/a print("In First floor Each member should pay : ",c) print("-----------------------------------------------------") meter2 = int(input("Second floor number of units used :")) Second_floor = meter2*z print("Second floor bill is : ",Second_floor) b = int(input("Enter Number of members in Second floor :")) d = Second_floor/b print("In Second floor Each member should pay : ",d) print("-----------------------------------------------------") print("Total Bill : ",First_floor+Second_floor) print("-------------THNAK YOU-------------------------------")
true
880b3b158b1f8e2b56d01ac8e6042cbd2d4b484a
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
589
4.40625
4
#!/usr/bin/python3 """ This function will print a square equal to the size given """ def print_square(size): """ This function will raise errors if an integer is not given as well as if the value is equal or less than zero. """ if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") if isinstance(size, float) and size < 0: raise TypeError("size must be an integer") for i in range(size): for j in range(size): print("#", end="") print("")
true
ab396ea8fa83578e55ee4e24db98b4830749cc27
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_models/test_square.py
1,879
4.21875
4
#!/usr/bin/python3 """ this is the unittest file for the Base class """ import unittest from models.square import Square class SqrTest(unittest.TestCase): """ These are the unit tests for the base class """ def test_basics2(self): s = Square(1) self.assertEqual(s.width, 1) s = Square(1, 2) self.assertEqual(s.x, 2) def test_basics(self): s = Square(3, 3, 5) self.assertEqual(s.width, 3) self.assertEqual(s.height, 3) self.assertEqual(s.x, 3) self.assertEqual(s.y, 5) def test_negatives(self): """ this method tests for negative numbers in Rectangle """ with self.assertRaises(ValueError): b1 = Square(-1, 2, 3) with self.assertRaises(ValueError): b2 = Square(1, -2, 3) with self.assertRaises(ValueError): b3 = Square(1, 2, -3) def test_strings(self): """ this method tests for strings in Rectangle """ with self.assertRaises(TypeError): b1 = Square("1", 2, 3) with self.assertRaises(TypeError): b2 = Square(1, "2", 3) with self.assertRaises(TypeError): b3 = Square(1, 2, "3") def test_zero(self): """ this method tests if width and height are 0 """ with self.assertRaises(ValueError): b2 = Square(0, 2) def test_update(self): s = Square(1, 0, 0, 1) self.assertEqual(str(s), "[Square] (1) 0/0 - 1") s.update(1, 2) self.assertEqual(str(s), "[Square] (1) 0/0 - 2") s.update(1, 2, 3) self.assertEqual(str(s), "[Square] (1) 3/0 - 2") s.update(1, 2, 3, 4) self.assertEqual(str(s), "[Square] (1) 3/4 - 2") def test_area(self): s = Square(5, 5) self.assertEqual(s.area(), 25) if __name__ == '__main__': unittest.main()
true
4d3a8bef55942c0f3c4142e807f539ac5cfcda46
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
247
4.28125
4
#!/usr/bin/python3 """ This function appends a string to a file! """ def append_write(filename="", text=""): """ apppends to the end of a file then returns character count """ with open(filename, 'a') as f: return f.write(text)
true
978bad038ca358c0515806600ccd6bc92e53dfad
makpe80/Boot-camp
/7 lesson. Модуль 4. Модули и пакеты/code_examples/sphinx/ex_1.py
291
4.125
4
def say(sound:str="My")->None: """Prints what the animal's sound it. If the argument `sound` isn't passed in, the default Animal sound is used. Parameters ---------- sound : str, optional The sound the animal makes (default is My) """ print(sound)
true
0ab0a052a247fbcc29ad44ca7b05740eb65cd1f8
Taranoberoi/Practise
/List Less Than Ten.py
357
4.28125
4
# Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # write a program that prints out all the elements of the list that are less than 10. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [] # for i in a: # print("Value is ",i) # if i <= 10: # b.append(i) # else: # break # print(b)
true
463f9708d9e3cec7047f3541bc8f0b570b5b44dc
Taranoberoi/Practise
/10_LIST OVERLAP COMPREHESIONS.py
690
4.25
4
# This week’s exercise is going to be revisiting an old exercise (see Exercise 5), except require the solution in a different way. # Take two lists, say for example these two:and write a program that returns a list that contains only the elements that are # common between the lists (without duplicates). Make sure your program works on two lists of different sizes. # Write this in one line of Python using at least one list comprehension. import random a = [] b = [] c = [] for i in range(10): a.append(random.randrange(1,15)) b.append(random.randrange(1,15)) for i in b: if i in a and i not in c: c.append(i) print(a) print(b) print(c)
true
92a0429afb21d39eb64817d068b73f229a608c09
Othielgh/Cisco-python-course
/5.1.11.7 - Palindromes.py
905
4.25
4
# Your task is to write a program which: # asks the user for some text; # checks whether the entered text is a palindrome, and prints result. # Note: # assume that an empty string isn't a palindrome; # treat upper- and lower-case letters as equal; # spaces are not taken into account during the check - treat them as non-existent; # there are more than a few correct solutions - try to find more than one. def paliCheck(): sentence = input('Please enter a text to check if it\'s a palindrome: ').lower() while not sentence: sentence = input('Please enter a text to check if it\'s a palindrome: ').lower() sentence = sentence.replace(' ', '') if str(sentence) == str(sentence)[::-1]: print('It\'s a palindrome!') elif sentence == '': print('Please enter something!') else: print('This is not a palindrome!') paliCheck()
true
a0a00cec203bbaaeee83a82db647317f2db296b3
Othielgh/Cisco-python-course
/5.1.11.11 - Sudoku.py
1,186
4.3125
4
# Scenario # As you probably know, Sudoku is a number-placing puzzle played on a 9x9 board. The player has to fill the board in a very specific way: # each row of the board must contain all digits from 0 to 9 (the order doesn't matter) # each column of the board must contain all digits from 0 to 9 (again, the order doesn't matter) # each of the nine 3x3 "tiles" (we will name them "sub-squares") of the table must contain all digits from 0 to 9. # If you need more details, you can find them here. # Your task is to write a program which: # reads 9 rows of the Sudoku, each containing 9 digits (check carefully if the data entered are valid) # outputs Yes if the Sudoku is valid, and No otherwise. # Test your code using the data we've provided. import random, numpy grid = numpy.zeros(shape=(9,9)) for r in range(0, 9, 1): for c in range(0, 9, 1): while True: x = random.randint(1,9) if x not in grid[r,:] and x not in grid[:,c]: grid[r,c] = x if c == 8: print(grid[r,:]) continue continue else: break
true
fff52176408ddc67628b6c3707bc204363824ab8
greenfox-velox/oregzoltan
/week-04/day-3/09.py
476
4.125
4
# create a 300x300 canvas. # create a square drawing function that takes 1 parameter: # the square size # and draws a square of that size to the center of the canvas. # draw 3 squares with that function. from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() def draw_square(s): x = 300/2-s/2 blue_box = canvas.create_rectangle(x, x, x+s, x+s, fill='blue') draw_square(80) draw_square(44) draw_square(10) root.mainloop()
true
38bf2fa152fbe028217728b502544ce1f5732432
greenfox-velox/oregzoltan
/week-04/day-3/11.py
751
4.125
4
# create a 300x300 canvas. # create a square drawing function that takes 2 parameters: # the square size, and the fill color, # and draws a square of that size and color to the center of the canvas. # create a loop that fills the canvas with rainbow colored squares. from tkinter import * import random root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() def draw_square(size, color): x = 300/2-size/2 draw_box = canvas.create_rectangle(x, x, x+size, x+size, fill=color) for i in range(300, 1, -1): r1 = random.randrange(150, 255) r2 = random.randrange(16, 255) r3 = random.randrange(16, 150) r = '#' + str(hex(r1)[2:]) + str(hex(r2)[2:]) + str(hex(r3)[2:]) draw_square(i*10, r) root.mainloop()
true
7a9084979864dc2e1bc3a23b964d8d9790370ee5
haveano/codeacademy-python_v1
/05_Lists and Dictionaries/02_A Day at the Supermarket/13_Lets Check Out.py
1,142
4.3125
4
""" Let's Check Out! Perfect! You've done a great job with lists and dictionaries in this project. You've practiced: Using for loops with lists and dictionaries Writing functions with loops, lists, and dictionaries Updating data in response to changes in the environment (for instance, decreasing the number of bananas in stock by 1 when you sell one). Thanks for shopping at the Codecademy supermarket! Instructions Click Save & Submit Code to finish this course. """ shopping_list = ["banana", "orange", "apple"] stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } # Write your code below! def compute_bill(food): total=0 for x in food: # print x if x in stock and stock[x]>0: print "jest", stock[x], "sztuk", x total=total+prices[x] stock[x]=stock[x]-1 else: print "nie ma",x return total zakupy=["banana","gowno","kupa","apple"] print stock print compute_bill(zakupy),"$" print compute_bill(shopping_list) print stock #print stock.keys()
true
97ce0591bd0ed48a9918db96043117d016f3cc06
haveano/codeacademy-python_v1
/11_Introduction to Classes/02_Classes/08_Modifying member variables.py
1,115
4.375
4
""" Modifying member variables We can modify variables that belong to a class the same way that we initialize those member variables. This can be useful when we want to change the value a variable takes on based on something that happens inside of a class method. Instructions Inside the Car class, add a method drive_car() that sets self.condition to the string "used". Remove the call to my_car.display_car() and instead print only the condition of your car. Then drive your car by calling the drive_car() method. Finally, print the condition of your car again to see how its value changes. """ class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def display_car(self): print "This is a %s %s with %d MPG." % (self.color, self.model, self.mpg) def drive_car(self): self.condition="used" my_car = Car("DeLorean", "silver", 88) #print my_car.condition #print my_car.model #print my_car.color #print my_car.mpg print my_car.condition my_car.drive_car() print my_car.condition
true
d2b8e32208cd60547fb0ce5e786064a1d4a17906
haveano/codeacademy-python_v1
/12_File Input and Output/01_File Input and Output/05_Reading Between the Lines.py
847
4.4375
4
""" Reading Between the Lines What if we want to read from a file line by line, rather than pulling the entire file in at once. Thankfully, Python includes a readline() function that does exactly that. If you open a file and call .readline() on the file object, you'll get the first line of the file; subsequent calls to .readline() will return successive lines. Instructions Declare a new variable my_file and store the result of calling open() on the "text.txt" file in "r"ead-only mode. On three separate lines, print out the result of calling my_file.readline(). See how it gets the next line each time? Don't forget to close() your file when you're done with it!) """ my_file=open("text.txt","r") print my_file.readline() print my_file.readline() print my_file.readline() print my_file.readline() print my_file.readline() my_file.close()
true
e988e9f53a578404a3c6c4b81174c704f395f19c
haveano/codeacademy-python_v1
/10_Advanced Topics in Python/02_Introduction to Bitwise Operators/04_The bin() Function.py
1,150
4.65625
5
""" The bin() Function Excellent! The biggest hurdle you have to jump over in order to understand bitwise operators is learning how to count in base 2. Hopefully the lesson should be easier for you from here on out. There are Python functions that can aid you with bitwise operations. In order to print a number in its binary representation, you can use the bin() function. bin() takes an integer as input and returns the binary representation of that integer in a string. (Keep in mind that after using the bin function, you can no longer operate on the value like a number.) You can also represent numbers in base 8 and base 16 using the oct() and hex() functions. (We won't be dealing with those here, however.) Instructions We've provided an example of the bin function in the editor. Go ahead and use print and bin() to print out the binary representations of the numbers 2 through 5, each on its own line. """ print " ### BINy ### " print bin(1) print bin(2) print bin(3) print bin(4) print bin(5) print bin(6) print bin(7) print " ### HEXy ### " print hex(54) print " ### OCTy ### " print oct(7) print oct(9) print oct(15) print oct(17)
true
572f9b19515b5f46c03ddafedb0f93b37b13a49e
haveano/codeacademy-python_v1
/08_Loops/02_Practice Makes Perfect/03_is_int.py
1,183
4.21875
4
""" is_int An integer is just a number without a decimal part (for instance, -17, 0, and 42 are all integers, but 98.6 is not). For the purpose of this lesson, we'll also say that a number with a decimal part that is all 0s is also an integer, such as 7.0. This means that, for this lesson, you can't just test the input to see if it's of type int. If the difference between a number and that same number rounded down is greater than zero, what does that say about that particular number? Instructions Define a function is_int that takes a number x as an input. Have it return True if the number is an integer (as defined above) and False otherwise. For example: is_int(7.0) # True is_int(7.5) # False is_int(-1) # True """ import math def is_int(x): #if type(x)==int: #if math.floor(x)==x: # też działa, ale math.trunc() lub inc() jest lepsze if math.trunc(x)==x: #if int(x)==x: return True else: return False print is_int(-2.3) print is_int(-2.7) print is_int(1.9999999999999999) # HAHAHA """ print math.trunc(-2.3) print math.trunc(-2.7) print math.floor(-2.3) print math.floor(-2.7) print int(-2.9) print int(-2.1) """
true
6876089ff1413f4e3bc30adecefa91b75a59e006
haveano/codeacademy-python_v1
/07_Lists and Functions/01_Lists and Functions/11_List manipulation in functions.py
594
4.34375
4
""" List manipulation in functions You can also append or delete items of a list inside a function just as if you were manipulating the list outside a function. my_list = [1, 2, 3] my_list.append(4) print my_list # prints [1, 2, 3, 4] The example above is just a reminder of how to append items to a list. Instructions Define a function called list_extender that has one parameter lst. Inside the function, append the number 9 to lst. Then return the modified list. """ n = [3, 5, 7] # Add your function here def list_extender(lst): lst.append(9) return lst print list_extender(n)
true
15f47141d90b1e773ff194272ae57c357f3572b4
haveano/codeacademy-python_v1
/10_Advanced Topics in Python/02_Introduction to Bitwise Operators/09_This XOR That.py
1,487
4.15625
4
""" This XOR That? The XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of the two numbers are 1, but not both. a: 00101010 42 b: 00001111 15 ================ a ^ b: 00100101 37 Keep in mind that if a bit is off in both numbers, it stays off in the result. Note that XOR-ing a number with itself will always result in 0. So remember, for every given bit in a and b: 0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0 Therefore: 111 (7) ^ 1010 (10) = 1101 (13) Instructions For practice, print the result of using ^ on 0b1110 and 0b101 as a binary string. Try to do it on your own without using the ^ operator. """ #print bin(0b1110 or 0b101) # FIRST METHOD: #print bin(0b1110 ^ 0b101) # SECOND METHOD: def policz_xor (a,b): c=["0","b"] lena=len(list(str(bin(a)))) lenb=len(list(str(bin(b)))) lista=list(str(bin(a))) listb=list(str(bin(b))) lista=lista[2:] listb=listb[2:] diff=abs(lena-lenb) if lena<=lenb: lista=["0"]*diff+lista lenc=len(lista) else: listb=["0"]*diff+listb lenc=len(listb) for x in range(lenc): if (((lista[x]=="1") and (listb[x]=="1")) or ((lista[x]=="0") and (listb[x]=="0"))): c.append("0") else: c.append("1") return "".join(c) print policz_xor(0b1110,0b101) print policz_xor(0b1110,0b10110)
true
4b1a907a1f05d61a2904551c34cfc20e1a733840
haveano/codeacademy-python_v1
/08_Loops/01_Loops/13_For your lists.py
625
4.78125
5
""" For your lists Perhaps the most useful (and most common) use of for loops is to go through a list. On each iteration, the variable num will be the next value in the list. So, the first time through, it will be 7, the second time it will be 9, then 12, 54, 99, and then the loop will exit when there are no more values in the list. Instructions Write a second for loop that goes through the numbers list and prints each element squared, each on its own line. """ numbers = [7, 9, 12, 54, 99] print "This list contains: " for num in numbers: print num # Add your loop below! for x in numbers: print x*x
true
758a91bf1eefd576051c24401423f4c6578180fa
haveano/codeacademy-python_v1
/03_Conditionals and Control Flow/02_PygLatin/06_Pop Quiz.py
603
4.21875
4
""" Pop Quiz! When you finish one part of your program, it's important to test it multiple times, using a variety of inputs. Instructions Take some time to test your current code. Try some inputs that should pass and some that should fail. Enter some strings that contain non-alphabetical characters and an empty string. When you're convinced your code is ready to go, click Save & Submit to move forward! """ print 'Welcome to the Pig Latin Translator!' # Start coding here! original = raw_input("enter a word:") if len(original)>0 and original.isalpha(): print original else: print "empty"
true
6efae81bdbee61a5e960c0bce1039a31a48c3bb2
haveano/codeacademy-python_v1
/11_Introduction to Classes/01_Introduction to Classes/03_Classier Classes.py
967
4.46875
4
""" Classier Classes We'd like our classes to do more than... well, nothing, so we'll have to replace our pass with something else. You may have noticed in our example back in the first exercise that we started our class definition off with an odd-looking function: __init__(). This function is required for classes, and it's used to initialize the objects it creates. __init__() always takes at least one argument, self, that refers to the object being created. You can think of __init__() as the function that "boots up" each object the class creates. Instructions Remove the pass statement in your class definition, then go ahead and define an __init__() function for your Animal class. Pass it the argument self for now; we'll explain how this works in greater detail in the next section. Finally, put the pass into the body of the __init__() definition, since it will expect an indented block. """ class Animal(object): def __init__(self): pass
true
3c6f0c6039e2a9d52e415b7b235adda8f27bb3e6
haveano/codeacademy-python_v1
/03_Conditionals and Control Flow/02_PygLatin/01_Break It Down.py
677
4.25
4
""" Break It Down Now let's take what we've learned so far and write a Pig Latin translator. Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." So "Python" becomes "ythonpay." To write a Pig Latin translator in Python, here are the steps we'll need to take: Ask the user to input a word in English. Make sure the user entered a valid word. Convert the word from English to Pig Latin. Display the translation result. Instructions When you're ready to get coding, click Save and Submit. Since we took the time to write out the steps for our solution, you'll know what's coming next! """ raw_input("Wpisz text po andgielsku: ")
true
26c8ad332a82464bb4e423fc0f801e8f709297f0
haveano/codeacademy-python_v1
/03_Conditionals and Control Flow/02_PygLatin/09_Move it on Back.py
672
4.21875
4
""" Move it on Back Now that we have the first letter stored, we need to add both the letter and the string stored in pyg to the end of the original string. Remember how to concatenate (i.e. add) strings together? greeting = "Hello " name = "D. Y." welcome = greeting + name Instructions On a new line after where you created the first variable: Create a new variable called new_word and set it equal to the concatenation of word, first, and pyg. """ pyg = 'ay' original = raw_input('Enter a word:') if len(original) > 0 and original.isalpha(): print original word=original.lower() first=word[0] new_word=word+first+pyg else: print 'empty'
true
ed920d881c1a5fa00c6137a741e648894730e987
haveano/codeacademy-python_v1
/10_Advanced Topics in Python/01_Advanced Topics in Python/04_Building Lists.py
672
4.625
5
""" Building Lists Let's say you wanted to build a list of the numbers from 0 to 50 (inclusive). We could do this pretty easily: my_list = range(51) But what if we wanted to generate a list according to some logic—for example, a list of all the even numbers from 0 to 50? Python's answer to this is the list comprehension. List comprehensions are a powerful way to generate lists using the for/in and if keywords we've learned. Instructions Check out the list comprehension example in the editor. When you're pretty sure you know what it'll do, click Save & Submit Code to see it in action. """ evens_to_50 = [i for i in range(51) if i % 2 == 0] print evens_to_50
true
2b229803bcb9a175dac4b1b85e2b712c77adba7c
ankitandel/function.py
/4h.py
311
4.1875
4
# write a python program to print the even numbers from a given list.[1,2,3,4,5,6,7,8,9] def is_even_num(b): i=0 while i<=len(b): if i%2==0: print("even number",i,end="") else: print("odd number",i) i=i+1 b=[1,2,3,4,5,6,7,8,9] is_even_num(b)
true
21cced07ce4cf5abbcf22728b0a885585101320c
kavisha-nethmini/Hacktoberfest2020
/python codes/DoubleBasePalindrome.py
733
4.15625
4
#Problem statement: The decimal number, 585 is equal to 1001001001 in binary. #And both are palindromes. Such a number is called a double-base palindrome. #Write a function that takes a decimal number n and checks if it's binary equivalent and itself are palindromes. #The function should return True if n is a double-base palindrome or else it should return False. #Input: Integer #Output: Boolean value #Sample Input: 585 #Sample Output: True #code starts from here def check_Palindrome(n): n = str(n) rev = n[::-1] if n == rev: return True return False def isDoubleBasePalindrome(n): b = str(bin(n)[2:]) if check_Palindrome(n) and check_Palindrome(b): return True return False
true
5e94315bfe25f3afe469c6baacb18f0d123decde
piupom/Python
/tuplePersonsEsim.py
2,212
4.71875
5
# It is often convenient to bundle several pieces of data together. E.g. if the code processes information about people, then each person's information (name, age, etc.) could be bundled. This can be done in a naive manner with e.g. a tuple (also shown below), but classes provide a more convenient way. A class definition defines a new data type that can have several attributes (named pieces of data) and/or member functions. A variable whose type is a class is called an object. If x is an object, then the notation x.y refers to the attribute y (or member function) of x. # A tuple that represents a person's name, age and height. personTuple = ("John Doe", 45, 180) # A class meant for representing a person. This is a minimal class: # the body is left empty (the pass-statetement is a place-holder that # does not do anything; Python syntax does not allow a literally empty body). class Person: pass # An object of class X can be created with the notation X(parameters), # where parameters may or may not be required (depends on the class). # Python classes by default allow to "define" new attributes on-the-fly, # that is, attributes do not need to be predefined by the class definition. # Below we set values into the attributes name, age and height of personObject. personObject = Person() personObject.name = "Tom Cruise" personObject.age = 50 personObject.height = 165 personObject.weight = 75 # Printing out the type of personObject reveals that it is of type # class Person. print(type(personObject)) # One of the reasons why the naive tuple-representation of a person # is awkward: we need to remember which index corresponds to which # attribute, which is prone to accidental programming errors. # As an example, this function prints out a person's attributes. def printPersonTuple(person): print("Name is", person[0]) print("Age is", person[1]) print("Height is", person[2]) # A similar function as above, but using the Person-class. Named # attribute references are much more readable. def printPersonObject(person): print("Name is", person.name) print("Age is", person.age) print("Height is", person.height) printPersonTuple(personTuple) print() printPersonObject(personObject)
true
e8b3807b0f9d38fe7b554e73c91797fd8e13b062
piupom/Python
/classFunctionsPersonsEsim.py
1,538
4.40625
4
# Classes have also other "special" functions. One common is __str__, which defines how to represent the object in string format (e.g. what is printed out if the object is passed to the print-function). Here we transform the printPersonObject-function from above into a __str__-member function. Now Person-objects can be printed directly with print. class Person: def __init__(self, name="", age=0, height=0, weight=0): self.name = name self.age = age self.height = height self.weight = weight def bmi(self): return self.weight/((self.height/100) ** 2) # If p is a Person-object, then the string-transformation call str(p) # will result in calling this __str__ -function. The function implementation # should return a string. Here we use also string formatting to set the # number of printed decimals. # Note: the way the string is split on several lines here works because the # strings are enclosed within parentheses. def __str__(self): return ("Name is {:s}\n" "Age is {:d}\n" "Height is {:.1f}\n" "Weight is {:.1f}\n" "BMI is {:.2f}").format( self.name, self.age, self.height, self.weight, self.bmi()) tc = Person(weight=67, name="Tom Cruise", age=56, height=170) dt = Person("Donald Trump", 72, 188, 105) # These print-calls will print the strings returned by tc.__str__() and # dt.__str__(), respectively. print(tc) print() print(dt) # A side-note: the dir-function lists all attributes/functions of a class object. print(dir(dt))
true
923a822bb263814d9af788e325e228cfba233894
roblivesinottawa/intermediate_100_days
/day_twentythree/turtle_crossing/carmanager.py
1,631
4.21875
4
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 # create a class and methods to manage the movement of the cars class CarManager: def __init__(self): # create a variable to store all cars and set it to an empty list self.all_cars = [] # create a varaible that will set the starting speed of the cars self.car_speed = STARTING_MOVE_DISTANCE # this method will create cars along the y line # and set the properties for the cars def create_car(self): # create less cars random_chance = random.randint(1, 6) if random_chance == 1: new_car = Turtle("square") # this will stretch the turtle new_car.shapesize(stretch_wid=1, stretch_len=2) new_car.penup() new_car.color(random.choice(COLORS)) # define where it's going to go on the screen yrandom = random.randint(-250, 250) # cars will go to the very edge of the screen new_car.goto(300, yrandom) # then it will be added to the list of all cars self.all_cars.append(new_car) # create a new method to move all cars def move_cars(self): # FOR EACH OF THE CARS IN THE LIST for car in self.all_cars: # each car will be moved by the distance stored in the variable car.backward(self.car_speed) # create a method that will increase the speed of the cars by 10 once at the end line def level_up(self): self.car_speed += MOVE_INCREMENT
true
690574f888f0c7a65aef7402f12c56e5a928e7dd
twopiharris/230-Examples
/python/basic3/nameGame.py
533
4.25
4
""" nameGame.py illustrate basic string functions Andy Harris """ userName = input("Please tell me your name: ") print ("I will shout your name: ", userName.upper()) print ("Now all in lowercase: ", userName.lower()) print ("How about inverting the case? ", userName.swapcase()) numChars = len(userName) print ("Your name has", numChars, "characters") print ("Now I'll pronounce your name like a cartoon character:") userName = userName.upper() userName = userName.replace("R", "W") userName = userName.title() print (userName)
true
7d88f2a2dff5286c80d7fcf9a03fd70b9162f42f
twopiharris/230-Examples
/python/basic3/intDiv.py
443
4.53125
5
""" integer division explains integer division in Python 3 """ #by default, dividing integers produces a floating value print("{} / {} = {}".format(10, 3, 10 / 3)) #but sometimes you really want an integer result... #use the // to force integer division: print("{} // {} = {}".format(10, 3, 10 // 3)) #integer division is incomplete. Use modulus (%) for remainder print("{} / {} = {} remainder {}".format(10, 3, 10 // 3, 10 % 3))
true
92fc4e3107ecedca5a04673bd9b62e2c03a336e7
davidtscott/CMEECoursework
/Week2/Code/tuple.py
1,329
4.53125
5
#!/usr/bin/env python3 # Date: October 2018 """ Extracts tuples from within a tuple and outputs as seperate lines """ __appname__ = '[tuple.py]' __author__ = 'David Scott (david.scott18@imperial.ac.uk)' __version__ = '0.0.1' __license__ = "License for this code/program" birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) # Birds is a tuple of tuples of length three: latin name, common name, mass. # write a (short) script to print these on a separate line or output block by species # Hints: use the "print" command! You can use list comprehension! # ANNOTATE WHAT EVERY BLOCK OR IF NECESSARY, LINE IS DOING! # ALSO, PLEASE INCLUDE A DOCSTRING AT THE BEGINNING OF THIS FILE THAT # SAYS WHAT THE SCRIPT DOES AND WHO THE AUTHOR IS # for every tuple in object birds, print # for tuple in birds: # print(tuple) # print("") birdlist = [print(i,"\n") for i in birds] # this prints each tuple seperately, seperated by blank line as opposed to # printing entire block as would happen just used 'birds' # OR #for tuple in birds: # print(tuple[0]) # print(tuple[1]) # print(tuple[2]) # print(" ")
true
873879f49529cc6abfb81cb3258aa8fb431b1ca5
Sahana-Chandrashekar/infytq
/prg23.py
493
4.25
4
''' Write a python function to find out whether a number is divisible by the sum of its digits. If so return True,else return False. Sample Input Expected Output 42 True 66 False ''' #PF-Prac-23 def divisible_by_sum(number): temp = number s = 0 while number != 0: rem = number%10 s += rem number = number//10 if temp%s == 0: return True else: return False number=25 print(divisible_by_sum(number))
true
88ab6d0234b210119fda15fe508a7fc65d0b94ab
Brijesh739837/Mtechmmm
/arrayinput.py
242
4.125
4
from array import * arr=array('i',[]) # creates an empty array length = int(input("enter the no of students")) for i in range(length): n = int(input("enter the marks of students")) arr.append(n) for maria in arr: print(maria)
true
56dfa6e4d1b0ef316cac9de3ad21287f69d0e854
omostic21/personal-dev-repo
/guesser_game.py
1,433
4.1875
4
#I wrote this code just to play around and test my skils #Author: Omolola O. Okesanjo #Creation date: December 10, 2019 print("Welcome to the Number Guessing game!!") x = input('Press 1 to play, press 2 for instructions, press 3 to exit') x = int(x) if x == 2: print("The computer will pick a number within the specified range that you give it. Try to predict the computer's number. If you didn't get the number but you are close to getting it, the computer will give you a second try; If not, you fail!") y = input("Preass 1 to play or 3 to exit") x = int(y) if x == 3: exit if x == 1: num_range = int(input("What is the range you want to guess from?")) #To import random module import random rnumb = random.randrange(num_range) your_numb = int(input('Please type a number from 0 to ' + str(num_range))) diff = your_numb - rnumb diff = abs(diff) tolerance = int(num_range * 0.45) if diff == 0: print('Hooray!! You Win; The number was ' + str(rnumb)) elif diff <= tolerance: print("You're within range, I'll give you one last chance") last_chance = int(input()) diff2 = last_chance - rnumb if abs(diff2) == 0: print('Hooray!! You Win') else: print("Sorry, Better luck next time! " + "The number was " + str(rnumb)) else: a= "You fail!!! The number was {}" print(a.format(str(rnumb)))
true
24a0066c1f6d87c37cf15b81eb59f28c199997f8
cgarey2014/school_python_projects
/garey3/program3_3.py
1,175
4.21875
4
# Chris Garey #2417512 # This is original work by me, there are no other collaborators. # Begin Prog # Set the initial answer counter to zero # Ask the first question, count one point if correct and no points if wrong. # Ask the second question, count one point if correct and no points if wrong. # Ask the third question, count one point if correct and no points if wrong. # Calculate the total points # Sets answer counter to zero correct_answers = 0 #Starts the quiz with the first question ounces = int(input('How many ounces are in 1 measuring cup? ')) if ounces == 8: correct_answers += 1 print('Correct. Good job!') else: print('Sorry, the answer is 8') # Asks the second question flower = input('What is the state flower of Texas? ').lower() if flower == "bluebonnet": correct_answers += 1 print('Awesome! Well done.') else: print('Sorry, the answer is Bluebonnet.') # Asks the third question points = float(input('How many points does a octagon have? ')) if points == 8: correct_answers += 1 print('Nice! That is correct.') else: print('Sorry, the answer is 8') print("Good job. Your final score was: ", correct_answers)
true
44a981d0bb30cc57c6fd15ed98e02993129563cd
sprksh/quest
/recursion/backtracking/backtracking.py
1,657
4.34375
4
""" Backtracking is when you backtrack after recursion Examples in n_queens in the bottom section """ class newNode: # Construct to create a new node def __init__(self, key): self.key = key self.left = None self.right = None self.parent = None def __repr__(self): return str(self.key) def tree_sum(root): if root is None: return 0 return root.key + tree_sum(root.left) + tree_sum(root.right) # this is plain recursion def max_path_sum(root): def sub_tree_sum(node): # base case if node is None: return 0 l = sub_tree_sum(node.left) r = sub_tree_sum(node.right) return node.key + l if l > r else node.key + r max_path_sum = sub_tree_sum(root) return max_path_sum def max_sum_path(root): actual_path = [] def sub_tree_sum(node): if node is None: return 0 l = sub_tree_sum(node.left) r = sub_tree_sum(node.right) maximum = node.key + l if l > r else node.key + r actual_path.append(node.left if l > r else node.right) return maximum max_path_sum = sub_tree_sum(root) actual_path = [_ for _ in actual_path if _] actual_path.append(root) return max_path_sum, actual_path if __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.right.left.right = newNode(12) max_sum, path = max_sum_path(root) print(max_sum, path)
true
6a55c9c131b08c9afd042592d7b3b5db8cec153e
insomnia-soft/projecteuler.net
/004/004.py
831
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # def palindrome(n): m = n p = 0 while m > 0: mod = m % 10 m /= 10 p = p * 10 + mod if p == n: return True return False def main(): """ Largest palindrome product Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ nmax = 0 for i in range(100, 1000): for j in range(100, 1000): n = i * j; if palindrome(n) and n > nmax: nmax = n print nmax return 0 if __name__ == '__main__': main()
true
19f2142d863f2105fd453b35dd9832bff8ffb9e5
subash319/PythonDepth
/Practice16_Functions/Prac_16_10_count_even_odd.py
374
4.28125
4
# 10. Write a function that takes in a list of integers and returns the number of even and odd numbers from that list. def count_even_odd(list_count): even_count,odd_count = 0,0 for num in list_count: if num%2 == 0: even_count += 1 else: odd_count += 1 return even_count,odd_count print(count_even_odd(list(range(20))))
true
4410eadec793e5cfb189305a350f91052cc822e6
subash319/PythonDepth
/Practice14_List_Comprhensions/Prac_14_6_cubes_all_odd.py
292
4.53125
5
# 6. This list comprehension creates a list of cubes of all odd numbers. # # cubes = [ n**3 for n in range(5,21) if n%2!=0] # Can you write it without the if clause. cubes = [n**3 for n in range(5, 21, 2)] cubes_2 = [ n**3 for n in range(5,21) if n%2!=0] print(cubes) print(cubes_2)
true
3687ac68a5e5a98d1972ae671b90d598f2055e84
subash319/PythonDepth
/Practice17_Functions_2/Prac_17_6_kwargs.py
493
4.125
4
# def display(L, start='', end=''): # for i in L: # if i.startswith(start) and i.endswith(end): # print(i, end=' ') # # display(dir(str), 'is', 'r') # In the function definition of the function display(), # make changes such that the user is forced to send keyword arguments for the last two parameters. def display(L, *, start='', end=''): for i in L: if i.startswith(start) and i.endswith(end): print(i, end=' ') display(dir(str), start = 'is', end = 'r')
true
2b44c016feeed5be184877be0e84ba5ff8e7f38c
VishalSinghRana/Basics_Program_Python
/Squareroot_of_Number.py
284
4.34375
4
y="Y" while(y=="y" or y=="Y"): number = int(input("Enter the number")) if number < 0: print("Please Enter a postive number") else: sqrt= number**(1/2) print("The squareroot of the numebr is ",sqrt) y=input("Do you want to continue Y/N?")
true
b81bf5104838515302768a79df37c945fa7a4f5a
kcwebers/Python_Fundametnals
/fundamentals/insertion.py
2,060
4.3125
4
# Build an algorithm for insertion sort. Please watch the video here to understand how insertion sort works and implement the code. # Basically, this sort works by starting at index 1, shifting that value to the left until it is sorted relative to all values to the # left, and then moving on to the next index position and performing the same shifts until the end of the list is reached. The following # animation also shows how insertion sort is done. # Some Tips! # Don't forget to write your plan in a non-programming language first (pseudocode!) and test your base cases before you build your code. # Please refrain from checking other people's code. If your code does NOT work as intended make sure # you are writing up your plan first, # your plan solves your base case, and # your plan solves other base cases you have specified. # Sometimes if you are stuck for too long, you need to just start all over as this can be more efficient to do than dwelling on old code # with bugs that are hard to trace. def insertionSort(li): for x in range(len(li)): # loop through initial list to access each element for y in range(x + 1, len(li)): # loop through same array starting at index +1 ahead of x if(li[x] > li[y]): # if element (li[y]) is greater than the one before it (li[x], which is set to be one index behind always) tmp = li[x] # swap the smaller element with the with the original element li[x] = li[y] li[y] = tmp return li # return final array # this is the answer per online looking ... I think I am a bit confused about what an insertion sort is def insertionSort(li): for i in range(1, len(li)): # loop through array starting at the first index key = li[i] j = i - 1 # Move elements that are greater than key to one position ahead of their current position while j >= 0 and key < li[j] : li[j + 1] = li[j] j -= 1 li[j + 1] = key print(insertionSort(arr))
true
07a2b70ca25f20852834cf6b5451951ad90e4a33
psyde26/Homework1
/assignment2.py
501
4.125
4
first_line = input('Введите первую строку: ') second_line = input('Введите вторую строку: ') def length_of_lines(line1, line2): if type(line1) is not str or type(line2) is not str: return('0') elif len(line1) == len(line2): return('1') elif len(line1) > len(line2): return('2') elif len(line1) != len(line2) and line2 == ('learn'): return('3') result = length_of_lines(first_line, second_line) print(result)
true
45b08672f5802bd07e54d45df20b24c1538a2673
jxthng/cpy5python
/Practical 03/q7_display_matrix.py
383
4.4375
4
# Filename: q7_display_matrix.py # Author: Thng Jing Xiong # Created: 20130221 # Description: Program to display a 'n' by 'n' matrix # main # import random import random # define matrix def print_matrix(n): for i in range(0, n): for x in range (0, n): print(random.randint(0,1), end=" ") print(" ") x = int(input("Enter an integer: ")) print_matrix(x)
true
02f76ae07d4bb429bf6a8319cce2aba0cb80ef58
jxthng/cpy5python
/compute_bmi.py
634
4.59375
5
# Filename: compute_bmi.py # Author: Thng Jing Xiong # Created: 20130121 # Modified: 20130121 # Description: Program to get user weight and height and # calculate body mass index (BMI) # main # prompt and get weight weight = int(input("Enter weight in kg:")) # prompt and get height height = float(input("Enter height in m:")) # calculate bmi bmi = weight / (height * height) # display result print ("BMI={0:.2f}".format(bmi)) # determine health risk if bmi >=27.50: print("High Risk!!!") elif 23.5 <= bmi <27.5: print ("Moderate risk!!") elif 18.5 <= bmi <23: print ("Healthy! :D") else: print ("Malnutrition :(")
true
3c144e821443e44da6317169ecdc9992134a34fc
DevJ5/Automate_The_Boring_Stuff
/Dictionary.py
1,184
4.28125
4
import pprint pizzas = { "cheese": 9, "pepperoni": 10, "vegetable": 11, "buffalo chicken": 12 } for topping, price in pizzas.items(): print(f"Pizza with {topping}, costs {price}.") print("Pizza with {0}, costs {1}.".format(topping, price)) # There is no order in dictionaries. print('cheese' in pizzas) # True print('ham' not in pizzas) # True # print(pizzas['ham']) # KeyError # Solution: if 'ham' in pizzas: print(pizzas['ham']) # Alternative solution: print(pizzas.get('ham', "doesnt exist")) # There is also a setdefault method on dictionaries message = '''It was a bright cold day in April when I parked my car.''' count = {} for character in message.upper(): count.setdefault(character, 0) count[character] +=1 pprint.pprint(count) # Shows the dictionary in a readable format. text = pprint.pformat(count) # Returns a string value of this output format print(text) print(pizzas.values()) # Returns a listlike datatype (dict_values) list(pizzas.values()) # Returns list of values list(pizzas.keys()) # Returns list of keys list(pizzas.items()) # Returns list of tuples for key in pizzas.keys(): print(key)
true
0bb5501ebf856a20a70f2ec604495f21e10a4b0c
MachFour/info1110-2019
/week3/W13B/integer_test.py
399
4.25
4
number = int(input("Integer: ")) is_even = number%2 == 0 is_odd = not is_even is_within_range = 20 <= number <= 200 is_negative = number < 0 if is_even and is_within_range: print("{} passes the test.".format(number)) # Else if number is odd and negative elif is_odd and is_negative: print("{} passes the test.".format(number)) else: print("{} does not pass the test.".format(number))
true
bf86e2e9ac26825248273684b72b95427cc26328
MachFour/info1110-2019
/week6/W13B/exceptions.py
778
4.25
4
def divide(a, b): if not a.isdigit() or not b.isdigit(): raise ValueError("a or b are not numbers.") if float(b) == 0: # IF my b is equal to 0 # Raise a more meaningful exception raise ZeroDivisionError("Zero Division Error: Value of a was {} and value of b was {}".format(a,b)) return float(a)/float(b) while True: a = input("Numerator: ") b = input("Denominator: ") try: x = divide(a,b) except ZeroDivisionError as err: print("Catching Zero Divsion Error \n {}".format(err)) raise Exception("The user is dumb") except ValueError as err: print("Catching Value Error \n {}".format(err)) continue finally: print("Try putting in different numbers again")
true
da7b7caea279a8444cd63c43cabe65240ca21b57
Jyun-Neng/LeetCode_Python
/104-maximum-depth-of-binary-tree.py
1,301
4.21875
4
""" Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3. """ import collections # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 queue = collections.deque([]) queue.append([root, 1]) # BFS while queue: node, depth = queue.popleft() if node.left: queue.append([node.left, depth + 1]) if node.right: queue.append([node.right, depth + 1]) return depth if __name__ == "__main__": vals = [3, 9, 20, None, None, 15, 7] root = TreeNode(vals[0]) node = root node.left = TreeNode(vals[1]) node.right = TreeNode(vals[2]) node = node.right node.left = TreeNode(vals[5]) node.right = TreeNode(vals[6]) print(Solution().maxDepth(root))
true
6e784b269099a926400bc136e6810610a96a88ed
Jyun-Neng/LeetCode_Python
/729-my-calendar-I.py
2,328
4.125
4
""" Implement a MyCalendar class to store your events. A new event can be added if adding the event will not cause a double booking. Your class will have the method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end. A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.) For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar. Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end) Note: The number of calls to MyCalendar.book per test case will be at most 1000. In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9]. Example: MyCalendar(); MyCalendar.book(10, 20); // returns true MyCalendar.book(15, 25); // returns false MyCalendar.book(20, 30); // returns true Explanation: The first event can be booked. The second can't because time 15 is already booked by another event. The third event can be booked, as the first event takes every time less than 20, but not including 20. """ class TreeNode: def __init__(self, s, e): self.start, self.end = s, e self.left = None self.right = None class MyCalendar: def __init__(self): self.root = None def book(self, start: 'int', end: 'int') -> 'bool': new_node = TreeNode(start, end) if not self.root: self.root = new_node return True node = self.root # binary search tree while node: if new_node.end <= node.start: if not node.left: node.left = new_node return True node = node.left elif new_node.start >= node.end: if not node.right: node.right = new_node return True node = node.right else: return False if __name__ == "__main__": obj = MyCalendar() print(obj.book(10, 20)) print(obj.book(15, 25)) print(obj.book(5, 10))
true
4038b6ca7e62b6bd3b5ba7ef3cf01de2d3e8ee84
rishabh2811/Must-Know-Programming-Codes
/Series/Geometric.py
751
4.3125
4
# Geometric.py """ Geometric takes the first number firstElem, the ratio and the number of elements Num, and returns a list containing "Num" numbers in the Geometric series. Pre-Conditions - firstElem should be an Number. - ratio should be an Number. - Num should be an integer >=1. Geometric(firstElem=7,ratio = 9,Num = 5) --> Standard function call Output --> Num numbers are returned in series starting from firstElem with geometric value ratio Example: Geometric(1,1,2) returns --> [1,1] Geometric(2,2,5) returns --> [2,4,8,16,32] """ def Geometric(firstElem, ratio, Num): return [firstElem * (ratio ** i) for i in range(Num)] if __name__ == '__main__': print(Geometric(1, 1, 2)) print(Geometric(2, 2, 5))
true
24eb50260ff182ad58f58665b2bbbe609a713f6b
manansharma18/BigJ
/listAddDelete.py
1,280
4.34375
4
def main(): menuDictionary = {'breakfast':[],'lunch':[], 'dinner':[]} print(menuDictionary) choiceOfMenu = '' while choiceOfMenu != 'q': choiceOfMenu = input('Enter the category (enter q to exit) ') if choiceOfMenu in menuDictionary: addOrDelete= input('Do you want to list, add or delete ') if addOrDelete =='add': addItem = input('Enter the item you want to add ') if addItem not in menuDictionary[choiceOfMenu]: menuDictionary[choiceOfMenu].append(addItem) print("Item added sucessfully") else: print('Item already added in list') elif addOrDelete =='delete': deleteItem = input('Enter the item you want to delete ') if deleteItem in menuDictionary[choiceOfMenu]: menuDictionary[choiceOfMenu].remove(deleteItem) print(menuDictionary) else: print('Item is not in list') else: print('entered choice is not available, try again') else: print('entered category is not available, try again') if __name__ == "__main__": main()
true
0ab1712df48bd99d3e5c744138caaea015ca12e1
Rupam-Shil/30_days_of_competative_python
/Day29.py
496
4.1875
4
'''write a python program to takes the user for a distance(in meters) and the time was taken(as three numbers: hours, minutes and seconds) and display the speed in miles per hour.''' distance = float(input("Please inter the distance in meter:")) hour, min, sec = [int(i) for i in input("Please enter the time taken in hh/mm/ss order:").split()] hour = hour + (min /60) + (sec/3600) mile = distance * 0.000621371 speed = mile / hour print("THe speed of the car is {:.5f}m/hr".format(speed))
true
48ded77911e4f9e63e254d4cc5265e02f8f593e1
BrimCap/BoredomBot
/day.py
1,010
4.3125
4
import datetime import calendar def calc_day(day : str, next = False): """ Returns a datetime for the next or coming day that is coming. Params: day : str The day you want to search for. Must be in [ "monday" "tuesday" "wednesday" "thursday" "friday" "saturday" "sunday" ] next : bool If true, returns the next day (skips the first one) Defaults to False if not passed in Returns: A datetime.date of the day """ delta = 8 if next else 1 date = datetime.date.today() + datetime.timedelta(days = delta) for _, i in enumerate(range(7)): date += datetime.timedelta(days = 0 if i == 0 else 1) if calendar.day_name[date.weekday()].lower() == day.lower(): return date if __name__ == "__main__": print(calc_day('thursday', True))
true
ad1ae0039c48c95c13268cfd96241e93a858d57b
papri-entropy/pyplus
/class7/exercise4c.py
710
4.15625
4
#!/usr/bin/env python """ 4c. Use the findall() method to find all occurrences of "zones-security". For each of these security zones, print out the security zone name ("zones-security-zonename", the text of that element). """ from pprint import pprint from lxml import etree with open("show_security_zones.xml") as f: xml_str = f.read().strip() xml_data = etree.fromstring(xml_str) print("Finding all occurrences of 'zones-security'") xml_zon_sec_all = xml_data.findall(".//zones-security") print(xml_zon_sec_all) print("Prining the zone names of each sec zones:") for zone in xml_zon_sec_all: for ele in zone: if ele.tag == "zones-security-zonename": print(ele.text)
true
e0e0d097adba29f9673331887f6527caa5b3d2ad
fr3d3rico/python-machine-learning-course
/study/linear-regression/test4.py
2,734
4.53125
5
# https://www.w3schools.com/python/python_ml_polynomial_regression.asp # polynomial regression import matplotlib.pyplot as plt x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22] y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100] plt.scatter(x, y) plt.show() import numpy as np import matplotlib.pyplot as plt x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22] y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100] mymodel = np.poly1d(np.polyfit(x, y, 3)) myline = np.linspace(1, 22, 100) plt.scatter(x, y) plt.plot(myline, mymodel(myline), c='r') plt.show() """ R-Squared It is important to know how well the relationship between the values of the x- and y-axis is, if there are no relationship the polynomial regression can not be used to predict anything. The relationship is measured with a value called the r-squared. The r-squared value ranges from 0 to 1, where 0 means no relationship, and 1 means 100% related. Python and the Sklearn module will compute this value for you, all you have to do is feed it with the x and y arrays: """ from sklearn.metrics import r2_score print(r2_score(y, mymodel(x))) """ Predict Future Values Now we can use the information we have gathered to predict future values. Example: Let us try to predict the speed of a car that passes the tollbooth at around 17 P.M: To do so, we need the same mymodel array from the example above: mymodel = numpy.poly1d(numpy.polyfit(x, y, 3)) """ import numpy as np from sklearn.metrics import r2_score x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22] y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100] mymodel = np.poly1d(np.polyfit(x,y,3)) speed = mymodel(17) print(speed) """ Bad Fit? Let us create an example where polynomial regression would not be the best method to predict future values. Example These values for the x- and y-axis should result in a very bad fit for polynomial regression: import numpy import matplotlib.pyplot as plt x = [89,43,36,36,95,10,66,34,38,20,26,29,48,64,6,5,36,66,72,40] y = [21,46,3,35,67,95,53,72,58,10,26,34,90,33,38,20,56,2,47,15] mymodel = numpy.poly1d(numpy.polyfit(x, y, 3)) myline = numpy.linspace(2, 95, 100) plt.scatter(x, y) plt.plot(myline, mymodel(myline)) plt.show() And the r-squared value? Example You should get a very low r-squared value. import numpy from sklearn.metrics import r2_score x = [89,43,36,36,95,10,66,34,38,20,26,29,48,64,6,5,36,66,72,40] y = [21,46,3,35,67,95,53,72,58,10,26,34,90,33,38,20,56,2,47,15] mymodel = numpy.poly1d(numpy.polyfit(x, y, 3)) print(r2_score(y, mymodel(x))) The result: 0.00995 indicates a very bad relationship, and tells us that this data set is not suitable for polynomial regression. """
true
02e08da64766c262406de320027d2d53b5e3dfa2
Fanniek/intro_DI_github
/lambda.py
1,305
4.53125
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 26 19:20:40 2019 @author: fannieklein """ #Exercise 1: mylist =[" hello"," itsme ","heyy "," i love python "] mylist = list(map(lambda s: s.strip(), mylist)) #print(mylist) #Explanattion of Exercise 1: #This function should use map function --> map applies to every element. First we build: #map(lambda s: s.strip(), mylist) --> The map applies to every element of the list, # s --> every string: I want to STRIP every string in my list # --> then the argument is that I want this done inside mylist # returning this will be an object. We need to set the map object to a list, therefor add # list(map(lambda s: s.strip(), mylist)) #Exercise 2: people = {"eyal":20, "JOHN":10, "PaBlo":23, "reX":11} legal_people = {k.lower():v for k, v in people.items() if v > 18} #print(legal_people) #Exercise 3: marks = [("John",46), ("Ethan",22), ("Sean",60)] marks.sort(key = lambda t: t[1]) #print(marks) #Cope one list to a new list without a whole yadyada function my_list = [3,2,43455,6,23,456546567] my_list_2 = [x for x in my_list] #print(my_list_2) string = "This is a string" rev_s = " ".join([w[::-1] for w in string.split(" ")]) #print(rev_s) ## joining a list --> need to know every word, to know every word we need split it
true
8ad71cb6e4e52fc454528ad87e4ecf657a6e406f
userddssilva/ESTCMP064-oficina-de-desenvolvimento-de-software-1
/distances/minkowski.py
513
4.125
4
def minkowski(ratings_1, ratings_2, r): """Computes the Minkowski distance. Both ratings_1 and rating_2 are dictionaries of the form {'The Strokes: 3.0, 'Slightlyt Stoopid: 2.5} """ distance = 0 commonRatings = False for key in ratings_1: if key in ratings_2: distance += pow(abs(ratings_1[key] - ratings_2[key]), r) commonRatings = True if commonRatings: return pow(distance, 1/r) else: return 0 # Indicates no ratings in common
true
9ad2e6f1e44f976b5a34b08705420da4ee5598b5
nihal-wadhwa/Computer-Science-1
/Labs/Lab07/top_10_years.py
2,524
4.21875
4
""" CSCI-141 Week 9: Dictionaries & Dataclasses Lab: 07-BabyNames Author: RIT CS This is the third program that computes the top 10 female and top 10 male baby names over a range of years. The program requires two command line arguments, the start year, followed by the end year. Assuming the working directory is set to the project's data/ directory when run: $ python3 top_10_years 1880 2018 TOP 10 BABY NAMES OF 1880-2018 RANK FEMALE NAME MALE NAME 1 Mary James 2 Elizabeth John 3 Patricia Robert 4 Jennifer Michael 5 Linda William 6 Barbara David 7 Margaret Joseph 8 Susan Richard 9 Dorothy Charles 10 Sarah Thomas """ import names_util # get_most_popular_name_year, START_YEAR, END_YEAR import sys # argv, stderr.write # constants for the printed table RANK = 'RANK' FEMALE_NAME = 'FEMALE NAME' MALE_NAME = 'MALE NAME' def main(): """ The main program reads the command line, calls the function to compute and return the results, and then prints out the results. """ # verify the command line contains the arguments if len(sys.argv) != 3: sys.stderr.write('Usage: python3 top_10_years.py start-year end-year') else: # convert the start and end year from command line strings to integers start_year, end_year = int(sys.argv[1]), int(sys.argv[2]) # verify start year is less than or equal to the end year if start_year > end_year: sys.std.write('Start year must be less than or equal to end year') # verify both years fall within the valid range for the data elif start_year < names_util.START_YEAR or end_year > names_util.END_YEAR: sys.stderr.write('Year must be between ' + str(names_util.START_YEAR) + ' and ' + str(names_util.END_YEAR)) else: # call names_util.get_top_years and print the results top_year = names_util.get_top_years(start_year, end_year) print(f'TOP 10 BABY NAMES OF {start_year}-{end_year}') print(f'{RANK:<10}{FEMALE_NAME:<20}{MALE_NAME:<20}') rank = 1 for female, male in zip(top_year.females, top_year.males): print(f'{rank:<10}{female:<20}{male:<20}') rank += 1 if __name__ == '__main__': main()
true
6f2539ffb11dc17d1f277f6cbe7e7ed2b10377a1
loyti/GitHubRepoAssingment
/Python/pythonPlay/bikePlay.py
1,065
4.15625
4
class Bike(object): def __init__ (price,maxSpeed,miles): self.price = "$Really$ Expen$ive" self.maxSpeed = maxSpeed self.miles = 0 def displayInfo(self): print "A little about your Bike: $Price: {}, {} max kph & {} miles traveled".format(str(self.price), int(self.maxSpeed), str(self.miles)) retrun self def ride(self): self.miles += 10 print "You just went on a 10 mile journey" retrun self def reverse(self): self.miles -= 5 print "Backing up 5 miles in reverse is quite interesting You have gone {} miles ".format(self.miles) return self def noNeg(self): if (self.miles < 0): self.miles = 0 print "You backed up off a cliff and were saved just in time but the bike is gone :( Here is a new one :)" return self bike1 = Bike(99.99, 12) bike1.drive() bike1.drive() bike1.drive() bike1.reverse() bike1.displayInfo() bike2 = Bike(139.99, 20) bike2.drive() bike2.drive() bike2.reverse() bike2.reverse() bike2.displayInfo()
true
9bcc9a4088f6081d67388d517bc7d0ef80154e3e
securepadawan/Coding-Projects
/Converstation with a Computer/first_program_week2.py
2,283
4.125
4
print('Halt!! I am the Knight of First Python Program!. He or she who would open my program must answer these questions!') Ready = input('Are you ready?').lower() if Ready.startswith('y'): print('Great, what is your name?') # ask for their name else: print('Run me again when you are ready!') exit() myName = input() if myName.lower() == 'jamie martin': print('Well hello, Professor Martin! I hope you enjoy Month Python puns!') # special greeting for Professor. elif myName.lower() == 'ian ince': print('All Hail The Creator!') #special greetings for Creator else: print('Nice to meet you, ' + myName + '!') print('What is your quest? (degree program at Champlain College?)') # ask for their degree degree = input() if degree == 'Cybersecurity': print('My creator as well!') elif degree == "i don't know": print("Don't me get the Black Knight. He's invincible and may bleed on you.") #insert pun here else: print('I bet a lot of people are interested in ' + degree) print('What is your favorite color?') # ask for their favorite color color = input () if color.lower () == 'green': print('Speaking of green.... Bring me..... A Shrubbery!') else: print(color + ' is a nice color') print('How many kids do you have?') #ask if have kids kid = input () if kid == '0': print("Don't be a DINK! (double income no kids). Kids makes life interesting! This means you only have " + str(int(kid)+1) + ' or ' + str(int(kid)+2) + " (if you have a spouse) in your immediate family.") exit() if kid == '1': print('Nice! Does your child also enjoy the color ' + color + '?') #ask if kid have like same color else: print('Nice! Does any of your ' + kid + ' children enjoy the color ' + color + '?') likecolor = input () if likecolor.startswith('y'): print('Great! You have something in common in your family of ' + str(int(kid)+1) + ' or ' + str(int(kid)+2) + ' (if you have a spouse).') #add parent and kid's age else: print('Well that stinks! I hope your family of ' + str(int(kid)+1) + ' or ' + str(int(kid)+2) + ' (if you have a spouse) have something else in common.' ) print('I will now ride off in the sunset with my coconuts. Now for something completely different. Goodbye!')
true
f4f8dfb4f59a722fd628f0634654aca2ba592a5e
NguyenLeVo/cs50
/Python/House_Roster/2020-04-27 import.py
1,569
4.1875
4
# Program to import data from a CSV spreadsheet from cs50 import SQL from csv import reader, DictReader from sys import argv # Create database open(f"students.db", "w").close() db = SQL("sqlite:///students.db") # Create tables db.execute("CREATE TABLE Students (first TEXT, middle TEXT, last TEXT, house TEXT, birth NUMERIC)") # Check for arguments (import.py, character.csv) if len(argv) != 2: print("Usage: python import.py character.csv") exit() # Open CSV file by command line argument and read it with open(argv[1]) as database: # Read it into memory as a list database_reader = reader(database) for row in database_reader: # Populate the house and birth year data = [None] * 5 data[3] = row[1] data[4] = row[2] # For each row, parse name # Use split method to split name into first, middle, and last names # Insert each student into the student table in students.db # db.execute to insert a row into the table name = row[0].split() if len(name) == 3: data[0] = name[0] data[1] = name[1] data[2] = name[2] db.execute("INSERT INTO Students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", data[0], data[1], data[2], data[3], data[4]) elif len(name) == 2: data[0] = name[0] data[2] = name[1] db.execute("INSERT INTO Students (first, last, house, birth) VALUES(?, ?, ?, ?)", data[0], data[2], data[3], data[4])
true
7bab4b14a82a9e79dd6dd2ebc52f6a1c315d9176
JASTYN/30dayspyquiz
/exam/spaces.py
253
4.1875
4
""" Write a loop that counts the number of words in a string """ space = ' ' count = 0 sentence = input("Enter a sentence: ") for letter in sentence: if letter == space: count = count + 1 print(f'Your sentence has {count + 1} words')
true
d29b0a47e7fe7df6a7906e8c96e7e43492c8ccd9
JASTYN/30dayspyquiz
/exam/hey/finalav.py
980
4.1875
4
def getNumberList(filename): f = open(filename,'r') #opening the file line = f.readline() #reading the file line by line numbers = line.split(',') #The split() method splits a string into a list. numberList = [] #An array to store the list for i in numbers: numberList.append(int(i)) return numberList def getAverage(numbers): sum = 0 #for storage of the sum of the numbers in the file counter = 0 #for cointing numbers present in the file for i in numbers: sum = sum + i counter = counter + 1 average = sum/counter # Getting the average return average def main(): #user input filename = input("Enter filename : ") #getting numbers from the required file numbers = getNumberList(filename) #get the average from the numbers list average = getAverage(numbers) #display the average print(average) if __name__ == "__main__": main()
true
2e4e0012235649961b56e64101e1b417ef98738e
hemanthkumar25/MyProjects
/Python/InsertionSort.py
409
4.21875
4
def insertionSort(list): for index in range(1,len(list)): currentvalue = list[index] position = index while position > 0 and list[position-1]>currentvalue: list[position] = list[position -1] position = position -1 list[position] = currentvalue list = [1,9,87,646,2,57,5] insertionSort(list) print list
true
a72bec9020e351bc3ef6e30d72aa3202021f2eab
severinkrystyan/CIS2348-Fall-2020
/Homework 4/14.11 zylab_Krystyan Severin_CIS2348.py
790
4.125
4
"""Name: Krystyan Severin PSID: 1916594""" def selection_sort_descend_trace(integers): for number in range(len(integers)): # Sets first number of iteration as largest number largest = number for i in range(number+1, len(integers)): # Checks for number in list that is larger than the number initially set if integers[i] > integers[largest]: largest = i # Sets the largest number found to be first element integers[number], integers[largest] = integers[largest], integers[number] if number != len(integers)-1: print(*integers, '') if __name__ == '__main__': numbers = input().split() integer_list = [int(number) for number in numbers] selection_sort_descend_trace(integer_list)
true
fbeaf00fea7890184e40e34f3e403b2121f6b289
BriannaRice/Final_Project
/Final_Project.py
1,201
4.125
4
''' I already started before I knew that they all had to go together so some of it makes sense the rest doesn't ''' # 3/11/19 Final Project # Brianna Rice print('Pick a number between 1 and 30', "\n") magic_number = 3 guess = int(input('Enter a number:', )) while guess != magic_number: print('Guess again', "\n") guess = int(input('Enter a number:')) print('Now that you got the number I have another task for you.', "\n") # I'm getting them to guess the numb while True: Mystery = int(input("Enter number: ")) if Mystery > 100: print("Nope to big of a number sorry", "\n") elif Mystery < 20: print("No lager number", "\n") else: print("Good choice", "\n") break print('Ok your next task is .... ', "\n") # I am hoping I can attach this code so it can work with my for loop, functions and so on. def print_multiple_times(string, times): for i in range(times): print(string) print_multiple_times('money', 5) scan = str('Im hungry') def print_something(): scan_van = str('This is confusing') print('\r\n',scan_van) print('\r\n', scan) print_something() for i in range(1,3): for j in range(7,10): print(i,j)
true
858fd9f1634b03d69550a3202c2f12a7295d568b
hutbe/python_space
/8-Decorators/decorators.py
1,017
4.34375
4
# Decorator # Using a wrap function to add extra functions to a function def my_decorator(fun): def wrap_fun(): print(f"==== Function: {fun.__name__}") fun() return wrap_fun @my_decorator def say_hi(): print(f"Hello everyone, nice to be here!") say_hi() @my_decorator def generator_even_odd(): result_list = ["even" if num % 2 == 0 else "odd" for num in range(10)] print(result_list) generator_even_odd() # Decorator Pattern def new_decorator(fun): def wrap_fun(*args, **kwargs): print(f"==== Function: {fun.__name__}") fun(*args, **kwargs) return wrap_fun @new_decorator def say_something(words, emoji = ":)"): print(words, emoji) say_something("A bomb is coming!!!!!!") # Another example from time import time def performance(fn): def wrapper(*args, **kwargs): t1 = time() result = fn(*args, **kwargs) t2 = time() print(f"This function took: {t2 - t1}s") return result return wrapper @performance @new_decorator def caculate(): for i in range(10000): i*5 caculate()
true
9a6cd4518c1bb000496a8aef48336b7b5179f809
hutbe/python_space
/13-FileIO/read_file.py
1,054
4.34375
4
test_file = open('Test.txt') print("File read object:") print(test_file) print("Read file first time") print(test_file.read()) # The point will move to the end of file print("Read file second time") test_file.seek(0) # move the point back to the head of file print(test_file.read()) print("Read file third time") print(test_file.read()) # nothing will print here test_file.seek(0) print(test_file.readline()) # read file line by line print(test_file.readline()) print(" ======== readlines =======") test_file.seek(0) file_list = test_file.readlines() print(file_list) print(" ======= end =========") test_file.close() # close the file # The standard way to open a file # Do not need seek with as handle file opening and closing print(" ======== open file with as First =======") with open('Test.txt') as file_object: print(file_object.read()) print(" ======= end =========") print(" ======== open file with as Second =======") with open('Test.txt') as file_object: print(file_object.readlines()) print(" ======= end =========")
true
ed8e8f7646b93809bf53f84dc4654ecc61ffbac7
Omkar2702/python_project
/Guess_the_number.py
887
4.21875
4
Hidden_number = 24 print("Welcome to the Guess The Number Game!!") for i in range(1, 6): print("Enter Guess", int(i), ": ") userInput = int(input()) if userInput == Hidden_number: print("Voila! you've guessed it right,", userInput, "is the hidden number!") print("Congratulations!!!!! You took", i, "guesses to win the game!") break elif 0 < userInput < 24: if 20 < userInput < 24: print("You are very close to get it right! Guess a higher number now!") else: print("You've guessed it very less buddy!") else: if 24 < userInput < 28: print("You are very close to get it right! Guess a lower number now!") else: print("You've gone too far away!") print("You are left with ", (5-i), "guesses") print("GAME OVER!") print("The Hidden_number was: ", Hidden_number)
true
7fbdcfad250a949cb0575167c87d212f376e4d98
vaish28/Python-Programming
/JOC-Python/NLP_Stylometry/punct_tokenizer.py
405
4.125
4
# -*- coding: utf-8 -*- """ Punctuation tokenizer """ #Tokenizes a text into a sequence of alphabetic and non-alphabetic characters. #splits all punctuations into separate tokens from nltk.tokenize import WordPunctTokenizer text="Hey @airvistara , not #flyinghigher these days we heard? #StayingParkedStayingSafe #LetsIndiGo laugh/cry" tokens=WordPunctTokenizer().tokenize(text) print(tokens)
true
0290746b9b476109ea203930c5ccaaf2ec98bf31
qwatro1111/common
/tests/tests.py
1,917
4.125
4
import unittest from math import sqrt from homework import Rectangle class Test(unittest.TestCase): def setUp(self): self.width, self.height = 4, 6 self.rectangle = Rectangle(self.width, self.height) def test_1_rectangle_perimeter(self): cheack = (self.width+self.height)*2 result = self.rectangle.get_rectangle_perimeter() self.assertEqual(cheack, result) def test_2_rectangle_square(self): cheack = self.width*self.height result = self.rectangle.get_rectangle_square() self.assertEqual(cheack, result) def test_3_sum_of_corners_valid(self): cheack = 4*90 result = self.rectangle.get_sum_of_corners(4) self.assertEqual(cheack, result) def test_4_sum_of_corners_invalid(self): with self.assertRaises(ValueError): self.rectangle.get_sum_of_corners(6) def test_5_sum_of_corners_invalid(self): with self.assertRaises(ValueError): self.rectangle.get_sum_of_corners(0) def test_6_rectangle_diagonal(self): cheack = sqrt(self.width**2 + self.height**2) result = self.rectangle.get_rectangle_diagonal() self.assertEqual(cheack, result) def test_7_radius_of_circumscribed_circle(self): cheack = self.rectangle.get_rectangle_diagonal() / 2 result = self.rectangle.get_radius_of_circumscribed_circle() self.assertEqual(cheack, result) def test_8_radius_of_inscribed_circle(self): rectangle = Rectangle(width=1, height=1) cheack = rectangle.get_rectangle_diagonal() / 2 * sqrt(2) result = rectangle.get_radius_of_inscribed_circle() self.assertEqual(cheack, result) def test_9_radius_of_inscribed_circle(self): with self.assertRaises(ValueError): return self.rectangle.get_radius_of_inscribed_circle() if __name__ == '__main__': unittest.main()
true
8c44895f64d1161588c25e339ff6b23c82d8290e
KhaledAchech/Problem_Solving
/CodeForces/Easy/File Name.py
2,425
4.375
4
""" You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed. Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx". You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by 1. For example, if you delete the character in the position 2 from the string "exxxii", then the resulting string is "exxii". Input The first line contains integer n (3≤n≤100) — the length of the file name. The second line contains a string of length n consisting of lowercase Latin letters only — the file name. Output Print the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. If initially the file name dost not contain a forbidden substring "xxx", print 0. """ #inputs n = int(input()) s = input() #initializing x : x_counter and i : iteration_counter x = 0 i = 0 #specific case so we don't loop for unecessary reasons #i ve noticed that if the string is containing only x's #then x will be n(length of the string 's') - 2 if 'x'*n == s : x = n - 2 #another specification where if there s no 'xxx' in the whole string #then we ll go ahead and give x the 0 value :) elif s.count('xxx') == 0: x = 0 else: #the actual work start here :) #the loop will go on until there is no more 'xxx' in s while s.count('xxx') != 0: #each new time the loop will go on i will be initialized i = 0 while i!=len(s): #sub will hold every 3 characters of the string sub = s[i:i+3] #now sub will be compared to 'xxx' if they are equal #then we ll need to leave one 'x' behind and increment the x value :) if sub == 'xxx': s = s[i+1:n] x += 1 #then reinitialize i as the length of s has changed i = 0 else: #else we ll just increment i to get another sub in the next loop :) i += 1 #printing the result :) print(x)
true
33290292667e0df5ef32c562b2320933446a118e
KhaledAchech/Problem_Solving
/CodeForces/Easy/Helpful Maths.py
1,112
4.21875
4
""" Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3. You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum. Input The first line contains a non-empty string s — the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long. Output Print the new sum that Xenia can count. """ #input s = input() #spliting the string by '+' so we can sort it l = sorted(s.split('+')) #result new_s = '+'.join(l) print(new_s)
true
afebc658717b8f3badb5ee990c9d9e48ef32bc0e
makyca/Hacker-Rank
/Power-Mod_Power.py
286
4.25
4
#Task #You are given three integers: a, b, and m, respectively. Print two lines. #The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). a = int(raw_input()) b = int(raw_input()) m = int(raw_input()) print pow(a,b) print pow(a,b,m)
true
e0f20d297d8816da124a9f4e8a41a23e680e95b7
makyca/Hacker-Rank
/Sets-Symmetric_Difference.py
719
4.28125
4
#Task #Given 2 sets of integers, M and N, print their symmetric difference in ascending order. The term symmetric difference indicates #those values that exist in either M or N but do not exist in both. #Input Format #The first line of input contains an integer, M. #The second line contains M space-separated integers. #The third line contains an integer, N. #The fourth line contains N space-separated integers. #Output Format #Output the symmetric difference integers in ascending order, one per line. Memova = int(raw_input()) m = set(map(int, raw_input().split(' '))) Nemova = int(raw_input()) n = set(map(int, raw_input().split(' '))) mix1 = n.symmetric_difference(m) for x in sorted(list(mix1)): print x
true
8f6a0b68353c38fad53150c779444b96abc1b8e5
levi-terry/CSCI136
/hw_28JAN/bool_exercise.py
1,284
4.15625
4
# Author: LDT # Date: 27JAN2019 # Title: bool_exercise.py # Purpose: This program is comprised of several functions. # The any() function evaluates an array of booleans and # returns True if any boolean is True. The all() function # evaluates an array of booleans and returns True if all # are True. # Function to evaluate if any values in an array are true def any(booleanArray): for i in booleanArray: if i: return True else: return False # Function to evaluate if all values in an array are true def all(booleanArray): flag = True for i in booleanArray: if not i: flag = False return flag # Code Testing if __name__ == "__main__": trueArray = [True, True, True, True] tfArray = [True, False, True, False] falseArray = [False, False, False, False] print("This should return True: ", end='') print(any(trueArray)) print("This should return True: ", end='') print(any(tfArray)) print("This should return False: ", end='') print(any(falseArray)) print("This should return True: ", end='') print(all(trueArray)) print("This should return False: ", end='') print(all(tfArray)) print("This should return False: ", end='') print(all(falseArray))
true
1c73961f953b4686742f415bc9aaf2fe389f8d14
levi-terry/CSCI136
/hw_30JAN/recursion_begin.py
1,860
4.15625
4
# Author: LDT # Date: 27JAN2019 # Title: recursion_begin.py # Purpose: This program implements two functions. # The first function accepts an int array as a parameter # and returns the sum of the array using recursion. The # second function validates nested parentheses oriented # correctly, such as (), (()()), and so on using recursion # Int sum w/recursion function def int_sum(array): if len(array) == 0: return 0 else: return array[0] + int_sum(array[1:]) # Parentheses function recursion def parentheses_nesting(string): # FIXME: Add the code, what to return? pass # Code testing if __name__ == "__main__": # Test int_sum function intArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] intArray2 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] print("Testing int_sum function on first array...") print("Results should read 55:") print(int_sum(intArray)) if int_sum(intArray) == 55: print("Success!") else: print("Need to fix int_sum function...") print("Testing int_sum function on second array...") print("Results should read 145") print(int_sum(intArray2)) if int_sum(intArray2) == 145: print("Success!") else: print("Need to fix int_sum function...") # Test parentheses_nesting function paren1 = "()" # Good paren2 = "()()" # Good paren3 = "(()())" # Good paren4 = "((()()()))" # Good paren5 = ")(" # Bad paren6 = "(()))())" # Bad print("Testing parentheses_nesting function...") print("Results TBD") # FIXME: Figure out what results should look like after writing code print(parentheses_nesting(paren1)) print(parentheses_nesting(paren2)) print(parentheses_nesting(paren3)) print(parentheses_nesting(paren4)) print(parentheses_nesting(paren5)) print(parentheses_nesting(paren6))
true
7868d39dfc5a0e63481d605c23d303303c851bb9
levi-terry/CSCI136
/hw_28JAN/three_true.py
912
4.34375
4
# Author: LDT # Date: 27JAN2019 # Title: three_true.py # Purpose: This program implements a function which returns # True if 1 or 3 of the 3 boolean arguments are True. # Function to perform the checking of 3 booleans def three_true(a, b, c): if a: if b: if c: return True else: return False elif c: return False else: return True elif b: if c: return False else: return True elif c: return True else: return False # Testing Code if __name__ == "__main__": t = True f = False print(three_true(t, t, t)) print(three_true(t, t, f)) print(three_true(t, f, t)) print(three_true(t, f, f)) print(three_true(f, t, t)) print(three_true(f, t, f)) print(three_true(f, f, t)) print(three_true(f, f, f))
true
66afd8353ae48aa03ac42674765b59b18884d19a
wjwainwright/ASTP720
/HW1/rootFind.py
2,848
4.28125
4
# -*- coding: utf-8 -*- def bisect(func,a,b,threshold=0.0001): """ Bisect root finding method Args: func: Input function that takes a single variable i.e. f(x) whose root you want to find a: lower bound of the range of your initial guess where the root is an element of [a,b] b: upper bound of the range of your initial guess where the root is an element of [a,b] threshold: degree of accuracy you want in your root such that |f(root)| < threshold Returns: If an even number (including zero) of roots is located between the points a and b, then the function returns nothing and prints accordingly. Otherwise, the function returns a float c where f(c) is within the threshold of zero. """ c = (a+b)/2 count = 0 while(True): if func(a) < 0 and func(b) < 0 : print("Both f(a) and f(b) are negative. Try again, buddy") return 0,0 elif func(a) > 0 and func(b) > 0 : print("Both f(a) and f(b) are positive. Try again, buddy") return 0,0 else: if func(a)*func(c) < 0 : b = float(c) else: a = float(c) c = (a+b)/2 count += 1 if(abs(func(c)) < threshold): return c,count def newton(func,funcPrime,pos,threshold=0.0001): """ Newton root finding method Args: func: Input function that takes a single variable i.e. f(x) whose root you want to find funcPrime: Input function for the analytical derivative of the same function f(x) pos: initial guess for an x value that is ideally somewhat close to the root threshold: degree of accuracy you want in your root such that |f(root)| < threshold Returns: Returns a float c where f(c) is within the threshold of zero. """ count = 0 while(abs(func(pos)) > threshold): pos = pos - func(pos)/funcPrime(pos) count += 1 return pos,count def secant(func,a,b,threshold=0.0001): """ Secant root finding method Args: func: Input function that takes a single variable i.e. f(x) whose root you want to find a: lower bound of the range of your initial guess where the root is an element of [a,b] b: upper bound of the range of your initial guess where the root is an element of [a,b] threshold: degree of accuracy you want in your root such that |f(root)| < threshold Returns: Returns a float c where f(c) is within the threshold of zero. """ count = 0 while(abs(func(b)) > threshold): temp = float(b) b = b - func(b) * ( (b-a)/(func(b)-func(a)) ) a = float(temp) count += 1 return b,count
true
fe0e8af3b6d088f25a8726e32abe1ab08c03b8c3
vickyjeptoo/DataScience
/VickyPython/lesson3a.py
381
4.1875
4
#looping - repeat a task n-times # 2 types :for,while, #modcom.co.ke/datascience counter = 1 while counter<=3: print('Do Something',counter) age=int(input('Your age?')) counter=counter+1 #update counter # using while loop print from 10 to 1 number=11 while number>1: number=number-1 print(number) #print -20 to -1 x=-21 while x<-1: x=x+1 print(x)
true
e9a0af2257266fa452fddf4b79e1939784bca493
vickyjeptoo/DataScience
/VickyPython/multiplication table.py
204
4.21875
4
number = int(input("Enter a number to generate multiplication table: ")) # use for loop to iterate 10 times for i in range(1, 13): print(number, 'x', i, '=', number * i) #print a triangle of stars
true
32bdec09e8dc8ef94efd14ff0ab50b7585fdda7d
vickyjeptoo/DataScience
/VickyPython/lesson5.py
1,511
4.25
4
#functions #BMI def body_mass_index(): weight=float(input('Enter your weight:')) height=float(input('Enter your height:')) answer=weight/height**2 print("Your BMI is:",answer) #body_mass_index() #functions with parameters #base&height are called parameters #these parameters are unknown,we provide them during function call def area(base,height): #base = 50 #height =5 answer=0.5*base*height print('Your area is:',answer) area(base=50,height=5) #function to calculate electricity bill #Units is a parameter def electricity(units): if units<=50: print('pay',units*3.40) elif units>=50 and units<=100: print('pay',units*4) elif units>=100 and units<=200: print('pay',units*4.50) else: print('pay',units*5.20) #value=float(input('What are your units')) electricity(units=444) #parameters vs arguments #parameters are defined in the function i.e def function(param1,param2,....) #arguments are provided during function call to fit the defined parameters. #write a function to convert kshs to any other currency(USD,EURO,YEN,RAND) def convert_money(KES): print(KES*0.0096,'USD') print(KES*0.0087,'EURO') print(KES*1.05 ,'YEN') print(KES*0.14,'RAND') value=float(input('Enter amount you wish to convert:')) convert_money(KES=value) #OOP-Object Oriented Programming #create a function that check if a password has a Capital,Number,Symbol,not less than 8 letters. #hint:ifs,re(regular expression) #test :qweRT#123
true
a4322a82e093af0b6a1a4acdfcbb5540b7084db5
PragmaticMates/python-pragmatic
/python_pragmatic/classes.py
675
4.25
4
def get_subclasses(classes, level=0): """ Return the list of all subclasses given class (or list of classes) has. Inspired by this question: http://stackoverflow.com/questions/3862310/how-can-i-find-all-subclasses-of-a-given-class-in-python Thanks to: http://codeblogging.net/blogs/1/14/ """ # for convenience, only one class can can be accepted as argument # converting to list if this is the case if not isinstance(classes, list): classes = [classes] if level < len(classes): classes += classes[level].__subclasses__() return get_subclasses(classes, level+1) else: return classes
true
b09b2657f56cb03fae84b598ce256753b6eb4571
prashant523580/python-tutorials
/conditions/neg_pos.py
336
4.4375
4
#user input a number ui = input("enter a number: ") ui = float(ui) #converting it to a floating point number #if the number is greater then zero # output positive if ui > 0: print("positive number") #if the number is less then zero #output negative elif ui < 0: print("negative number") #in all other case else: print("zero ")
true
6d8d75053d9d281db48f32327598b55e1010ee78
deepak1214/CompetitiveCode
/InterviewBit_problems/Sorting/Hotel Booking/solution.py
1,298
4.34375
4
''' - A hotel manager has to process N advance bookings of rooms for the next season. His hotel has C rooms. Bookings contain a list A of arrival date and a list B of departure date. He wants to find out whether there are enough rooms in the hotel to satisfy the demand. - Creating a function hotel which will take 3 arguments as arrive, depart and K - First we will sort both the list arrive and depart - Then we will traverse the list arrive and check for the index elements at i+K that the element in arrive is less than depart i.e. arrive date is less than depart date - If arrive date is less than depart date then there are no rooms and returning False - But if no arrive date is less than depart date then there are enough rooms for N bookings and hence returning True ''' def hotel(arrive, depart, K): arrive.sort() depart.sort() for i in range(len(arrive)): if i+K<len(arrive) and arrive[i+K]<depart[i]: return False return True if __name__=="__main__": A=[ 13, 14, 36, 19, 44, 1, 45, 4, 48, 23, 32, 16, 37, 44, 47, 28, 8, 47, 4, 31, 25, 48, 49, 12, 7, 8 ] B=[ 28, 27, 61, 34, 73, 18, 50, 5, 86, 28, 34, 32, 75, 45, 68, 65, 35, 91, 13, 76, 60, 90, 67, 22, 51, 53 ] C=23 result=hotel(A,B,C) print(result)
true
4eb966b642158fd2266ae747d4cd6fcf694acfe2
deepak1214/CompetitiveCode
/LeetCode_problems/Invert Binary Tree/invert_binary_Tree.py
1,436
4.125
4
from collections import deque class TreeNode: def __init__(self,val): self.val = val self.left = None self.right = None def insert(root,node): if root is None: root = node else: if root.val < node.val: if root.right is None: root.right = node else: insert(root.right, node) else: if root.left is None: root.left = node else: insert(root.left, node) def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) # invert of binary tree means left elemtns goes to right and right element goes to left # this is the most simple problem but sometimes confused when they see it first time # so here is the solution def invertTree(root): if root is None: return 0 # invert the elements simple swapping root.left , root.right = root.right , root.left # left Invert root.left = invertTree(root.left) # right invert root.right = invertTree(root.right) return root root = TreeNode(5) insert(root , TreeNode(3)) insert(root , TreeNode(8)) insert(root , TreeNode(2)) insert(root , TreeNode(4)) insert(root , TreeNode(7)) insert(root , TreeNode(9)) inorder(root) print('Inverted') inorder(invertTree(root))
true
d4cc2c4c13be0e76bb0b78f50f32dacef61b63ee
deepak1214/CompetitiveCode
/Hackerrank_problems/counting_valleys/solution.py
1,605
4.125
4
# Importing the required Libraries import math import os import random import re import sys # Fuction For Counting the Valleys Traversed. Takes the number of steps(n) and The path(s[D/U]). Returns the Number. def countingValleys(n, s): count = 0 number_of_valleys = 0 # Initialized Variables count and number_of_valleys with 0. for i in range(n): # Looping the steps traversed by the no. of steps given. if(s[i] == 'U'): # Check if the Step equal to 'U' Then Count Incremented by 1 count += 1 if(count == 0): # Check if After certain steps The counter reaches to 0, Means a valleys is trversed. number_of_valleys += 1 # Hence increment the number_of_valleys by one. elif(s[i] == 'D'): # Check if the Step equal to 'U' Then Count Incremented by 1 count -= 1 return(number_of_valleys) # Returning the number of valleys traversed. # Check if the main is there and then run the main program. if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) # Taking the input from user. The number of steps in the hike. s = input() # A single string of Steps characters that describe the path (D/U). result = countingValleys(n, s) # Calling the countingvalleys function, Return the number of valleys traversed fptr.write(str(result) + '\n') # Writing/Printing the Result fptr.close() # Closing the Program
true
26614f5cbe266818c5f34b536b9f921c922a18d2
WSMathias/crypto-cli-trader
/innum.py
2,012
4.5625
5
""" This file contains functions to process user input. """ # return integer user input class Input: """ This class provides methods to process user input """ def get_int(self, message='Enter your number: ', default=0, warning=''): """ Accepts only integers """ hasInputNumbers = False while hasInputNumbers==False: try: # try to convert user input into a integer number userInput = input(message) if userInput is '': if default == 0: message = message+'\r' continue else: return default userInput = int(userInput) hasInputNumbers=True return userInput except ValueError: # if it gives a ValueError, return to line 2! print("[!] invalid input try again") # return floating point user input def get_float(self, message='Enter your number: ', default=0,warning=''): """ Accepts integer and floating point numbers """ hasInputNumbers = False while hasInputNumbers==False: try: # try to convert user input into a floating number userInput = input(message) if userInput is '': if default == 0: continue else: return default userInput = float(userInput) hasInputNumbers=True return userInput except KeyboardInterrupt : raise except ValueError: # if it gives a ValueError, return to line 2! print("[!] invalid input try again") def get_coin(self, message='Enter Coin symbol : ', default='', warning=''): """ Accepts Coin Symbol """ return input(message) #TODO: Logic need to be implimented
true
20191d04dad06de1f7b191ed7538828580eac557
jeremycross/Python-Notes
/Learning_Python_JoeMarini/Ch2/variables_start.py
609
4.46875
4
# # Example file for variables # # Declare a variable and initialize it f=0 # print(f) # # # re-declaring the variable works # f="abc" # print(f) # # # ERROR: variables of different types cannot be combined # print("this is a string" + str(123)) # Global vs. local variables in functions def someFunction(): global f #tells program that we are using f found as a global f="def" print(f) print(f) #prints f = 0 someFunction() #changes and prints f print(f) #prints new value of f del f #deletes the definition of a variable that was previously declared print(f) #f is no longer defined here
true
6ec438602e86c1eeebbab11746d4445b84e0187a
jeremycross/Python-Notes
/Essential_Training_BillWeinman/Chap02/hello.py
365
4.34375
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ x = 42 print('Hello, World. %d' % x) #you can use ''' for strings for '"' for strings, either works # above line is legacy from python 2 and is deprecated print('Hello, world. {}'.format(x)) # format is a function of the string object print(f'Hello, world. {x}') # f-string here call format function
true
9fbd24524c7fbeec9a79c7f6a2ecdc1d6992ab08
Crewcop/pcc-exercises
/chapter_three_final.py
822
4.21875
4
# 3-8 # list of locations destinations = ['london', 'madrid', 'brisbane', 'sydney', 'melbourne'] print(destinations) # print the list alphabetically without modifying it print('\nHere is the sorted list : ') print(sorted(destinations)) # print the original order print('\nHere is the original list still :') print(destinations) # print the list in reverse alpha order print('\nHere is the sorted list in reverse : ') print(sorted(destinations, reverse=True)) print(destinations,'\n') # use reverse to change the order destinations.reverse() print(destinations, '\n') # reverse it back destinations.reverse() print(destinations, '\n') # sort the list alphabetically permanently destinations.sort() print(destinations, '\n') # use sort() to reverse the order destinations.sort(reverse=True) print(destinations, '\n')
true
8b93a72a07be2865330628e84d8255718bf838d0
aakash19222/Pis1
/p.py
351
4.1875
4
def rotate(s, direction, k): """ This function takes a string, rotation direction and count as parameters and returns a string rotated in the defined direction count times. """ k = k%len(s) if direction == 'right': r = s[-k:] + s[:len(s)-k] elif direction == 'left': r = s[k:] + s[:k] else: r = "" print("Invalid direction") return r
true
c8c3de51f3c5828ac8ce280924f83c7d8474b3c0
PrinceCuet77/Python
/Extra topic/lambda_expression.py
824
4.3125
4
# Example : 01 def add(a, b) : return a + b add2 = lambda a, b : a + b # 'function_name' = lambda 'parameters' : 'return_type' print(add(4, 5)) print(add2(4, 5)) # Example : 02 def multiply(a, b) : return a * b multiply2 = lambda a, b : a * b print(multiply(4, 5)) print(multiply2(4, 5)) # Calling function and lambda print(add) print(add2) print(multiply) print(multiply2) # Example : 03 # Cheching a number is even or not is_even = lambda a : a % 2 == 0 print() print(is_even(2)) print(is_even(3)) # Example : 04 # Printing the last character of the string last_char = lambda s : s[-1] print(last_char('Prince')) print() # Example : 05 # Lambda expression with if else condition checking = lambda a : True if a > 5 else False print(checking(3)) print(checking(6)) print()
true
bd802c4bae44b75a820c70349a5eab4221bac821
PrinceCuet77/Python
/Tuple/tuple.py
1,323
4.3125
4
example = ('one', 'two', 'three', 'one') # Support below functions print(example.count('one')) print(example.index('one')) print(len(example)) print(example[:2]) # Function returning tuple def func(int1, int2) : add = int1 + int2 mul = int1 * int2 return add, mul print(func(2, 3)) # Returning tuple add, mul = func(4, 5) # Unpacking tuple two variable print(add) print(mul) # Looping into tuple mixed = (1, 2.0, 'three') for i in mixed : # Using for loop print(i, end = ' ') print() i = 0 while i < len(mixed) : # Using while loop print(mixed[i]) i += 1 # Tuple with one element one = (1) word = ('word') print(type(one)) print(type(word)) one1 = (1,) word1 = ('word',) print(type(one1)) print(type(word1)) # Tuple without paranthesis num = 'one', 'two', 'three' num1 = 1, 2, 3 print(type(num)) print(type(num1)) # Tuple unpacking st = ('prince', 23) name, age = st # Unpacking print(name) print(age) # List inside tuple value = (1, 2, ['three', 'four']) value[2].pop() value[2].append('five') print(value) # range(), tuple(), max(), min(), sum() functions t = tuple(range(1, 6)) print(max(t)) print(min(t)) print(sum(t))
true
553c0af65afd7d80a9ebfca8a1bc80f1ab660726
PrinceCuet77/Python
/List/list_comprehension.py
1,520
4.28125
4
# List comprehension # With the help of list comprehension, we can create a list in one line # Make a list of square from 1 to 10 sq = [i**2 for i in range(1, 11)] print(sq) # Create a list of negative number from 1 to 10 neg = [-i for i in range(1, 11)] print(neg) # Make a list where store the first character from the other list which consists of strings name = ['Rezoan', 'Shakil', 'Prince'] new_list = [ch[0] for ch in name] print(new_list) # Make a list where store the reverse string from other list which consists of strings name = ['Rezoan', 'shakil', 'Prince'] l = [ch[::-1] for ch in name] print(l) # List comprehensive with if statement # Make a list where store only even numbers from 1 to 10 l = [i for i in range(1, 11) if i % 2 == 0] print(l) l2 = [i for i in range(1, 11) if i & 1 == 0] print(l2) # Make a list where store only int or float variable in the form of string from the other list which consists all data types def make_list(l) : return [str(i) for i in l if (type(i) == int or type(i) == float)] l = [True, False, (1, 2, 3), [4, 5], {4, 5}, {3:3}, 1, 'string', 4.4] new_l = make_list(l) print(new_l) # List comprehensive with if else statement # Make a list where store odd numbers as negative and even numbers as square of even numbers l = [i**2 if (i & 1 == 0) else -i for i in range(1, 11)] print(l) l2 = [i**2 if (i % 2 == 0) else -1 for i in range(1, 11)] print(l2) # Nested list # Using list comprehension mat = [[i for i in range(1, 4)] for i in range(3)] print(mat)
true
712f46fc65f3c6d3c8ca8154748f9a942c6781f2
cnaseeb/Pythonify
/queue.py
815
4.125
4
#!/usr/bin/python class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items ==[] #further conditions implementation needed def enqueue(self, item): return self.items.insert(0, item) #further checks needed if queue already contains items def dequeue(self): return self.items.pop() def size(self): return len(self.items) #instantiate the queue object q = Queue() # check the size of the queue q.size() #Insert items into the queue q.enqueue('test1') q.enqueue('item2') q.enqueue('Ams') q.enqueue('CPH') #check the size again q.size() #check if teh queue is empty or not q.isEmpty() #delete or dequeue an item q.dequeue() #check teh size after the deletion of an item q.size()
true
2d7308d13f713b7c98492c3a8aa0a95a2aad0903
charliepoker/pythonJourney
/simple_calculator.py
876
4.25
4
def add(x,y): return x + y def Subraction(x,y): return x - y def Multiplication(x,y): return x * y def Division(x,y): return x / y operation = input(''' Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division ''') num_1 = float(input('Enter your first number: ')) num_2 = float(input('Enter your second number: ')) if operation == '+': print('{} + {} = '.format(num_1,num_2)) print(num_1 + num_2) elif operation == '-': print('{} - {} = ' .format(num_1, num_2)) print(num_1 - num_2) elif operation == '*': print('{} * {} = ' .format(num_1, num_2)) print(num_1 * num_2) elif operation == '/': print('{} / {} = '.format(num_1, num_2)) print(num_1 / num_2) else: print('You selected an invalid operator, please run the program again.')
true