blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d88926237a6b9aadabe227420130ae0a8c617524
Code-Institute-Solutions/directory-based
/03-test_driven_development/asserts.py
441
4.28125
4
def is_even(number): return number % 2 == 0 def even_numbers_of_evens(numbers): evens = sum([1 for n in numbers if is_even(n)]) return False if evens == 0 else is_even(evens) assert even_numbers_of_evens([]) == False, "No numbers" assert even_numbers_of_evens([2, 4]) == True, "Two even numbers" assert even_numbers_of_evens([2]) == False, "One even number" assert even_numbers_of_evens([1, 3, 9]) == False, "No even numbers"
false
559618c6a03eb8547eed2891b4ac7ed038e92b3b
KhadijaAbbasi/python-program-to-take-input-from-user-and-add-into-tuple
/tuple.py
244
4.15625
4
tuple_items = () total_items = int(input("Enter the total number of items: ")) for i in range(total_items): user_input = int(input("Enter a number: ")) tuple_items += (user_input,) print(f"Items added to tuple are {tuple_items}")
true
4472c1ba6c824fb9021d05ef985d4394cc6a61f9
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/7_collections/practise/pr_3.py
1,452
4.59375
5
# # # Buffet: A buffet-style restaurant offers only five basic foods. Think of five simple foods, and store them in a tuple. # # Use a for loop to print each food the restaurant offers. # Try to modify one of the items, and make sure that Python rejects the change. # The restaurant changes its menu, replacing two of the items with different foods. # Add a block of code that rewrites the tuple, and then use a for loop to print each of the items on the revised menu. # Use slicing for get last two items of foods. # Use slicing for get every second item of food. # Reverse your food order. # # Done buffet_style = ('meat', 'fish', 'potatoes', 'pizza', 'dessert') for dishes in buffet_style: print(f'{dishes}') ######################################################## # Try to modify # buffet_style[1] = ('sea fish') # print(buffet_style) ######################################################### # changes menu new_menu = list(buffet_style) new_menu[0] = 'chicken', 'makarones' print(tuple(new_menu)) ######################################################### # rewrites the tuple buffet_style = new_menu print('New menu', buffet_style) for menu in buffet_style: print('New menu Done', menu) ######################################################### # Use slicing print(buffet_style[-2:]) ######################################################### # Reverse your food order print(buffet_style[::-1])
true
1944dfdcadc11363e212ae18c4703f0fdf0e6e85
YuriiKhomych/ITEA-BC
/Vlad_Hytun/8_files/HW/HW81_Hytun.py
1,509
4.59375
5
# 1. According to Wikipedia, a semordnilap is a word or phrase that spells # a different word or phrase backwards. ("Semordnilap" is itself # "palindromes" spelled backwards.) # Write a semordnilap recogniser that accepts a file name (pointing to a list of words) # from the program arguments and finds # and prints all pairs of words that are semordnilaps to the screen. # For example, if "stressed" and "desserts" is part of the word list, the # the output should include the pair "stressed desserts". Note, by the way, # that each pair by itself forms a palindrome! import codecs import re filename = 'polindrome frases.txt' def semordnilap(filename): with codecs.open(filename, 'r', encoding='utf-8') as file_obj: cashe_data = file_obj.readlines() # print(cashe_data) with codecs.open(f'{filename}_check.', 'w+', encoding='utf-8') as file_obj2: # print(cashe_data) # print(cashe_data2) for line in cashe_data: if line.strip().replace(' ', '').lower()[:len(line.strip().replace(' ', ''))//2] !=\ line.strip().replace(' ', '').lower()[:len(line.strip().replace(' ', ''))//2:-1]: # print(f'{line.rstrip()} --- It is NOT semordnilap!') file_obj2.writelines(f'{line.rstrip()} --- It is NOT semordnilap!\n') else: # print(f'{line.rstrip()} --- It is semordnilap!') file_obj2.writelines(f'{line.rstrip()} --- It is semordnilap!\n') semordnilap(filename)
true
0d5c313729151e7a85b242ac9c962fde609e3ddf
YuriiKhomych/ITEA-BC
/Vlad_Hytun/5_functions/practise/P52-Hytun_Vlad.py
330
4.1875
4
# 2. Define a function that computes the length of a # given list or string. (It is true that Python has # the len() function built in, but writing it yourself # is nevertheless a good exercise.) def my_len(str): count_symbol = 0 for i in str: count_symbol += 1 return count_symbol print(my_len('djfkdflk'))
true
7182a3fc269c6e81fff77f6a66921c7469c6746b
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/7_collections/HW/hw_6.py
726
4.34375
4
# # # Pets: Make several dictionaries, where the name of each dictionary is the name of a pet. # # In each dictionary, include the kind of animal and the owner’s name. # Store these dictionaries in a list called pets. # Next, loop through your list and as you do print everything you know about each pet. # # DONE chappy = { 'name': 'Chappy', 'kind': 'robot', 'owners': 'Sophi', } tom = { 'name': 'Tom', 'kind': 'yard cat', 'owners': 'Lina', } keks = { 'name': 'Keks', 'kind': 'toyteryer', 'owners': 'Sveta', } pets = [chappy, tom, keks] for pet in pets: print(f'We know about {pet["name"]}') for key, value in pet.items(): print(f'{key} : {value}')
true
71c997605a5578583cd9de46f7bdbe283dd99ff4
YuriiKhomych/ITEA-BC
/Sergey_Naumchick/5_functions/05_PR_03.py
411
4.1875
4
'''3. Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.''' VOLVED = 'aeiouy' my_input = "" while len(my_input) != 1: my_input = input("please input only one symbol: ") def my_func(func): if func in VOLVED: return True else: return False if (my_func(my_input))==True: print("True") else: print("False")
true
fdce28c8eb106cdcc1f205ac12a2f813a893aaeb
YuriiKhomych/ITEA-BC
/Patenko_Victoria/3_conditions/homework3.1.py
2,979
4.25
4
my_fav_brand = ["toyota", "audi", "land rover"] my_fav_model = ["camry", "r8", "range rover"] my_fav_color = ["blue", "black", "gray"] price = 3000 brand: "str" = input("Brand of your car is: ") if brand not in my_fav_brand: print("Got it!") else: print("Good choice!") price_1 = price + 100 model = input("Model of your car is: ") if model not in my_fav_model: print("As you wish") else: print("Good choice!") price_2 = price_1 + 100 color = input("Color of your car is: ") if color not in my_fav_color: print("OK") else: print("Good choice!") price_3 = price_2 + 100 try: year = int(input("Year of your car is: ")) except ValueError as error: print("Try again") year = int(input("Year of your car is: ")) except Exception as error: print(error) else: print("Good but let's try a bit older one") finally: year = year - 1 print("Year of your car is: ", year) price_4 = price_3 + 100 try: engine_volume = float(input("Engine volume of your car is: ")) except Exeption as error: print(error) engine_volume = int(input("Engine volume of your car is: ")) else: engine_volume = engine_volume + 0.1 print("Maybe a bit more?") print("Engine volume of your car is: ", engine_volume) price_5 = price_4 + 100 odometer = int(input("Odometer of your car is: ")) if odometer < 1000: print("Did you even use it?") if odometer > 50000: print("Wow! Such a traveler!") if odometer >= 100000: print("Don't know when to stop, huh?") price_6 = price_5 + 100 phone_number = int(input("Your phone number: ")) print("Great! We'll call you!") end_price = price_6 + 100 print("Let's sum up!") print("Brand of your car is: ", brand) print("Model of your car is: ", model) print("Color of your car is: ", color) print("Year of your car is: ", year) print("Engine volume of your car is: ", engine_volume) print("Odometer of your car is: ", odometer) print("Price of the car is: ", end_price) total_rating = [ ] if brand == "toyota": if model in my_fav_model and year == 2012: total_rating.append("Exellent choice!") elif model in my_fav_model and year <= 2012: total_rating.append("Try somthing new") elif model not in my_fav_model and year <= 2012: total_rating.append("Would you like to change model?") elif model not in my_fav_model and year >= 2012: total_rating.append("Not bad") elif model in my_fav_model and year >= 2012: total_rating.append("Ha! We are on the same page!") else: total_rating.append("Could be better") elif brand in my_fav_brand: if model in my_fav_model and color in my_fav_color: total_rating.append("Great choice!") if model in my_fav_model and color not in my_fav_color: total_rating.append("Well, that's nice too") else: total_rating.append("You could do better") else: total_rating.append("We sure have different taste") print("Total rating: ", total_rating)
true
80ef3072710719831cc6968b4d049e964b94faa4
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/7_collections/HW/hw_2.py
1,823
4.375
4
# # # My Pizzas, Your Pizzas: Make a copy of the list of pizzas, and call it friend_pizzas. # Then, do the following: # # Add a new pizza to the original list. ########## Done # Add a different pizza to the list friend_pizzas. ######### Done # Prove that you have two separate lists. # # Print the message, My favorite pizzas are:, and then use a for # loop to print the first list. ## Done # # Print the message, My friend’s favorite pizzas are:, and then use a # for loop to print the second list. Make sure each new pizza is stored # in the appropriate list. # # Done, maybe friend_pizzas = { 'mix': 'all we have will be on your pizza', 'paperoni': 'paperoni, cheese, hot souse and tomatos', 'diablo': 'Salami, tomato sauce, sweet pepper and chilli', } pizzas = { 'mix': 'all we have will be on your pizza', 'paperoni': 'paperoni, cheese, hot souse and tomatos', 'diablo': 'Salami, tomato sauce, sweet pepper and chilli', } pizzas['four friends'] = 'Tomato sauce, mozzarella, bacon, hunting sausages, bogarsky pepper' friend_pizzas['BBQ'] = 'BBQ sauce, mozzarella cheese, bacon, hunting sausages, smoked chicken' print('Pizza friend_pizzas', friend_pizzas) print('Pizza pizzas', pizzas) for pizza in pizzas: # favorite = input('Enter favorite pizzas: ').lower() # if favorite in pizzas: print(f'My friend’s favorite pizzas are - {pizza.title()}, ' f'the ingredients is {pizzas[pizza]}.') # break # else: # print('Sorry ))') for pizza in friend_pizzas: # favorite = input('Enter favorite pizzas my friends: ').lower() # if favorite in friend_pizzas: print(f'My favorite is - {pizza.title()} pizza, ' f'the ingredients is {friend_pizzas[pizza]}.') # break # else: # print('Sorry ))')
true
14e5cd2b86f8e1df5ac05d69416b2a2455e3b47b
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/7_collections/practise/pr_1.py
1,296
4.65625
5
# # # Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza # names in a list, and then use a for loop to print the name of each pizza. # # Modify your for loop to print a sentence using the name of the pizza # instead of printing just the name of the pizza. For each pizza you should # have one line of output containing a simple statement like: I like pepperoni pizza. # Add a line at the end of your program, outside the for loop, that states # how much you like pizza. The output should consist of three or more lines # about the kinds of pizza you like and then an additional sentence, such as I really love pizza! # # pizzas = { # 'vegetariana': 'Sous, royal cheese, tomatoes, corn, broccoli, green peppers, oregano', # 'margherita': 'mozzarella cheese, fresh basil, salt and olive oil', # 'diablo': 'Salami, tomato sauce, sweet pepper and chilli', # } # # vegetariana = 'Sous, royal cheese, tomatoes, corn, broccoli, green peppers, oregano' # margherita = 'mozzarella cheese, fresh basil, salt and olive oil' # diablo = 'Salami, tomato sauce, sweet pepper and chilli' favorite_pizza = ['vegetariana', 'margherita', 'diablo'] for pizz in favorite_pizza: print(pizz) print(f'Im so much love {favorite_pizza[2]} pizza')
true
2e6fe0e1de69caccd003f1de0d9e2d43562d254b
YuriiKhomych/ITEA-BC
/Oksana_Yeroshenko/6_strings/6_strings_practise_yeroshenko_4.py
628
4.21875
4
my_string = "AV is largest Analytics community of India" # 4. Return first word from string. # result: `AV` my_string.split(' ')[0] # 5. Return last word from string. # result: `India` my_string.split(' ')[-1] # 6. Get two symbols of each word in string # result: `['AV', 'is', 'la', 'An', 'co', 'of', 'In']` my_string = "AV is largest Analytics community of India" my_string_sep = my_string.split(' ') new_string = [] for item in my_string_sep: j = item[0:2] new_string.append(j) print(new_string) my_string2 = 'Amit 34-3456 12-05-2007, XYZ 56-4532 11-11-2011, ABC 67-8945 12-01-2009' # 7. Get date from string
true
85f79e9a11264fbecf65e7c7e41e7cf36bfdc7bc
YuriiKhomych/ITEA-BC
/Nemchynov_Artur/5_functions/Practise#5.1.py
475
4.125
4
# . Define a function `max()` that takes two numbers as arguments # and returns the largest of them. Use the if-then-else construct # available in Python. (It is true that Python has the `max()` function # built in, but writing it yourself is nevertheless a good exercise.)""" def max_in_list(lst): max = 0 for n in lst: if n > max: max = n return max print(max_in_list([2,3,4,5,6,7,8,8,9,10])) print(max_in_list([38,2,3,4])) print(max_in_list([9,2,3,4,28]))
true
598d6b24b64826bff334de88948e23abe3e01762
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/9_functional_programming/HW9/hw_1.py
1,292
4.46875
4
# The third person singular verb form in English is distinguished by the suffix # -s, which is added to the stem of the infinitive form: run -> runs. A simple # set of rules can be given as follows: # If the verb ends in y, remove it and add ies If the verb ends in o, ch, s, sh, # x or z, add es By default just add s Your task in this exercise is to define a # function make_3sg_form() which given a verb in infinitive form returns its third # person singular form. Test your function with words like try, brush, run and fix. # Note however that the rules must be regarded as heuristic, in the sense that you # must not expect them to work for all cases. Tip: Check out the string method endswith(). # DOne + test # my_file = 'text_file/test.txt' def singular(my_file): text = open(my_file) words = text.read().lower().split() text.close() sing_word = [] for word in words: len_word = len(word) if word.endswith('y'): sing_word.append(str(word)[:(len_word-1)] + 'ies') elif word.endswith(('o', 's', 'x', 'z')): sing_word.append(str(word)[:(len_word - 1)] + 'es') elif word.endswith(('ch', 'sh')): sing_word.append(str(word)[:(len_word - 2)] + 'es') return sing_word # print(singular(my_file))
true
29b9026eeaf7d582b512ded6d6deb8ee3cf4da6d
YuriiKhomych/ITEA-BC
/Andrii_Bakhmach/4_iterations/4_3_exercise.py
303
4.15625
4
#Write a Python program that accepts a sequence of lines (blank line to terminate) as input #and prints the lines as output (all characters in lower case). our_line = input("please, input you text: ") if our_line is None: print("input your text once more") else: print(our_line.lower())
true
a3d0bef46700b4471601bc766aaf75d7e1c64cf7
YuriiKhomych/ITEA-BC
/Vlad_Hytun/7_collections/practise/P75_Hytun.py
804
4.90625
5
# 5. Rivers: # Make a dictionary containing three major rivers and the country each river runs through. # One key-value pair might be `'nile': 'egypt'`. # * Use a loop to print a sentence about each river, such as The Nile runs through Egypt. # * Use a loop to print the name of each river included in the dictionary. # * Use a loop to print the name of each country included in the dictionary. rivers_in_country = { 'Dnipro': 'Ukraine', 'Nile': 'Egypt', 'Dynai': 'Romain', } for river, country in rivers_in_country.items(): print(f'The {river} run through {country}') for river in rivers_in_country.keys(): print(f'The {river} included in rivers_in_country dict') for country in rivers_in_country.values(): print(f'The {country} included in rivers_in_country dict')
true
76cdeb563c3329f18ce11051aa902ca2a18f6bf7
YuriiKhomych/ITEA-BC
/Oksana_Yeroshenko/6_strings/6_strings_practise_yeroshenko_3.py
585
4.28125
4
# 3. Define a function `overlapping()` that takes two lists and # returns True if they have at least one member in common, # False otherwise. You may use your `is_member()` function, # or the in operator, but for the sake of the exercise, # you should (also) write it using two nested for-loops. a = (1, "a", "b", "c", 3, "x", "y", "z") b = (2, "f", "g", "h", 4, "o", "p", "q") c = (5, "i", "j", "k", 1, "s", "m", "o") def overlapping(x,y): for item_x in x: for item_y in y: if item_x == item_y: return True return False overlapping(a,b)
true
fb85dfcc07245c05844294fc7bd12ff25175d642
YuriiKhomych/ITEA-BC
/Andrii_Bakhmach/5_functions/HW/5_5_exercise.py
488
4.15625
4
#Write a function `is_member()` that takes a value #i.e. a number, string, etc) x and a list of values a, #and returns True if x is a member of a, False otherwise. #(Note that this is exactly what the `in` operator does, but #for the sake of the exercise you should pretend Python #id not have this operator.) def is_member(): list_a = input("Input a list of values: ").split() x = input("Input a number: ") if x in list_a: return True else: return False
true
26673a4cb7762f89c06e0bb5dab3387415aabb75
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/4_iterations/practise2.py
338
4.25
4
# Write a Python program to count the number of even # and odd numbers from a series of numbers. number = int(input('Make your choice number: ')) even = 0 odd = 0 for i in range(number): if i % 2 == 0: even += 1 elif i % 2 != 0: odd += 1 print(f'The odd numbers is {odd}') print(f'The even numbers is {even}')
true
94cfe965059c1be0c455f78f4dd83c2b8df387f7
YuriiKhomych/ITEA-BC
/Vlad_Hytun/7_collections/hw/HW74_Hytun.py
632
4.1875
4
# # Dictionary # 4. Favorite Numbers: # * Use a dictionary to store people’s favorite numbers. # * Think of five names, and use them as keys in your dictionary. # * Think of a favorite number for each person, and store each as a value in your dictionary. # * Print each person’s name and their favorite number. # * For even more fun, poll a few friends and get some actual data for your program. favorite_numbers_dict = { "Vlad": "13", "Ksu": "26", "Katya": "15", "Den": "27", "Dad": "01", } for name, number in favorite_numbers_dict.items(): print(f'One {name} like {number}')
true
84c50cc665fa7f67d2bbe261ce6c657a6adf8da1
YuriiKhomych/ITEA-BC
/Andrii_Ravlyk/7_collections/practise/pr4_person.py
440
4.21875
4
'''4. Person: * Use a dictionary to store information about a person you know. * Store their first name, last name, age, and the city in which they live. * You should have keys such as first_name, last_name, age, and city. * Print each piece of information stored in your dictionary.''' my_dict = {"first_name":"Anna", "last name":"Lee", "age":"21", "city":"Kyiv"} for key in my_dict.keys(): print (f'{my_dict[key]}')
true
73bb85c2b0ddb1b71fd7d9495dee92ff2afa1a22
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/9_functional_programming/HW9/hw_2.py
1,325
4.375
4
# In English, the present participle is formed by adding the suffix -ing # to the infinite form: go -> going. A simple set of heuristic rules can # be given as follows: If the verb ends in e, drop the e and add ing # (if not exception: be, see, flee, knee, etc.) # If the verb ends in ie, change ie to y and add ing For words consisting of consonant-vowel-consonant, # double the final letter before adding ing By default just add ing Your task in # this exercise is to define a function make_ing_form() which given a verb in # infinitive form returns its present participle form. # Test your function with words such as lie, see, move and hug. # However, you must not expect such simple rules to work for all cases. # Done + test from hw_3 import my_timer # my_file = 'text_file/test.txt' my_excaption = 'be, see, flee, knee' @my_timer def participle(my_file): text = open(my_file) words = text.read().lower().split() text.close() part_word = [] for word in words: len_word = len(word) if word not in my_excaption: if word.endswith('ie'): part_word.append(str(word)[:(len_word - 2)] + 'y' + 'ing') elif word.endswith('e'): part_word.append(str(word)[:(len_word - 1)] + 'ing') return part_word # print(participle(my_file))
true
3f2566abf3dc5144058177b9ed8ec52799b9fd87
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/4_iterations/practise1.py
224
4.1875
4
# Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. # Note : Use 'continue' statement. # Expected Output : 0 1 2 4 5 for i in range(0, 6): if i == 3: continue print(i, end=", ")
true
2edb0b06caf01ff2ec134e1f8589b12ecc867fe6
YuriiKhomych/ITEA-BC
/Sergey_Naumchick/7_Collections/PR/PR_07_05.py
710
4.90625
5
'''5. Rivers: Make a dictionary containing three major rivers and the country each river runs through. One key-value pair might be `'nile': 'egypt'`. * Use a loop to print a sentence about each river, such as The Nile runs through Egypt. * Use a loop to print the name of each river included in the dictionary. * Use a loop to print the name of each country included in the dictionary.''' dict_rivers = {"Nile": "Egipt", "Don": "Ukraine", "Syrdarya": "Tajikistan"} for country, river in dict_rivers.items(): print(f"The {country} runs throught {river}") print() for key_river in dict_rivers.keys(): print(key_river) print() for river, country in dict_rivers.items(): print(country)
true
e6bc0f5408a6c4bcccf6c5ab27cf8539c595d08a
shailesh/angle_btwn_hrs_min
/angle_btw_hrs_min.py
713
4.15625
4
def calcAngle(hour,minute): # validating the inputs here if (hour < 0 or minute < 0 or hour > 12 or minute > 60): print('Wrong input') if (hour == 12): hour = 0 if (minute == 60): minute = 0 # Calculating the angles moved by hour and minute hands with reference to 12:00 hour_angle, minute_angle = 0.5 * (hour * 60 + minute), 6 * minute # finding the difference between two angles abs_angle = abs(hour_angle - minute_angle) # Returning the smaller angle of two possible angles (min or max will not make much diff or no diff) angle = min(360 - abs_angle, abs_angle) return angle # driver program hour = 6 minute = 15 print('Angle ', calcAngle(hour,minute))
true
0021e305037992731bdc891d8d6bf4bd35d227bd
vwang0/causal_inference
/misc/pi_MC_simulation.py
737
4.15625
4
''' Monte Carlo Simulation: pi N: total number of darts random.random() gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0 which is also known as a semi-open range). random.uniform(a, b) gives you a random floating point number in the range [a, b], (where rounding may end up giving you b). random.random() generates a random float uniformly in the semi-open range [0.0, 1.0) random.uniform() generates a random float uniformly in the range [0.0, 1.0]. ''' import random def simu_pi(N): inside = 0 for i in range(N): x = random.uniform(0,1) y = random.uniform(0,1) if (x**2+y**2)<=1: inside +=1 pi = 4*inside/N return pi
true
f391340953675e637a74ca5ac0473961f4e69b38
yukikokurashima/Python-Practice
/Python3.2.py
542
4.1875
4
def calc_average(scores): return sum(scores) / 5 def determine_grade(score): if 90 <= score <= 100: result = "A" elif 80 <= score <= 89: result = "B" elif 70 <= score <= 79: result = "C" elif 60 <= score <= 69: result = "D" else: result = "F" return result scores = [] for _ in range(5): score = int(input("Please enter five test scores: ")) print("Letter Grade is:", determine_grade(score)) scores.append(score) avg = calc_average(scores) print("Average test scores:", avg, "Letter Grade is:", determine_grade(avg))
true
89bbd5a5b7c05eaa471954f562d33d8bf04024ba
EstevamPonte/Python-Basico
/PythonExercicios/mundo2/ex038.py
332
4.125
4
primeiro = int(input('digite um valor: ')) segundo = int(input('digite um valor: ')) if segundo > primeiro: print('o numero {} é maior que o numero {}'.format(segundo, primeiro)) elif primeiro > segundo: print('o numero {} é maior que o numero {}'.format(primeiro, segundo)) else: print('Os dois numeros sao iguails')
false
435b42c6946277df30947069bdf071ff21c60448
yaksas443/SimplyPython
/days.py
415
4.34375
4
# Source: Understanding Computer Applications with BlueJ - X # Accept number of days and display the result after converting it into number of years, number of months and the remaining number of days days = int(raw_input("Enter number of days : ")) years = days / 365 rem = days % 365 months = rem / 30 rem = rem % 30 print "\nYears: " + str(years) print "\nMonths: " + str(months) print "\nDays: " + str(rem)
true
b659ec2d05bbcc676a3a9eed647941edddb48601
yaksas443/SimplyPython
/sumfactorial.py
443
4.21875
4
# Source: https://adriann.github.io/programming_problems.html # Write a program that asks the user for a number n and prints the sum of the numbers 1 to n # To convert str to int use int() # to concatenate int to str, first convert it to str def sumFactorial(number): count = 0 sum=0 for count in range(0,number): sum = sum + count return sum num = raw_input ("Please enter a number: ") print "Sum: " + str(sumFactorial(int(num)))
true
87fd6a86c8de17dbbcdedc073a6c5c7c4b19d396
mariavarley/PythonExercises
/pyweek2.py
428
4.15625
4
#!/usr/bin/python num = int(input("Please Enter a number\n")) check = int(input("Please Enter a number to divide with\n")) if num%4 == 0: print("The number is divisible by 4") elif num%2 == 0: print("The number is an even number") else: print("The number is an odd number") if num%check == 0: print("The number, {0} divides into {1} evenly".format(check, num)) else: print("These numbers do not divide evenly")
true
bca3a78b6ee4b68f4efc0ca71186e9299121bd90
Sav1ors/labs
/Bubble_Sort.py
384
4.15625
4
def bubbleSort(list): for passnum in range(len(list)-1,0,-1): for i in range(passnum): if list[i]>list[i+1]: temp = list[i] list[i] = list[i+1] list[i+1] = temp list = [] for i in range(int(input('Enter the number of list items\n'))): list.append(int(input('Input elements\n'))) bubbleSort(list) print(list)
true
611c5db0bf4ee59131fc59b83842c7dc433fb444
mekhrimary/python3
/factorial.py
1,417
4.25
4
# Вычисление факториала числа 100 различными методами # Метод 1: рекурсия def recursive_factorial(n): if n == 0: return 1 else: return n * recursive_factorial(n - 1) print(f'Метод 1 (рекурсия) для числа 100: {recursive_factorial(100)}') # Метод 2: итерация + рекурсия def iterative_and_recursive_factorial(n): def calculate_factorial(counter, factorial): if counter == 1: return factorial else: return calculate_factorial(counter - 1, counter * factorial) return calculate_factorial(n, 1) print(f'Метод 2 (интерация + рекурсия) для числа 100: {iterative_and_recursive_factorial(100)}') # Метод 3: итерация (цикл while) def iterative_factorial_while(n): factorial = 1 counter = 1 while counter <= n: factorial *= counter counter += 1 return factorial print(f'Метод 3 (итерация-while) для числа 100: {iterative_factorial_while(100)}') # Метод 4: итерация (цикл for) def iterative_factorial_for(n): factorial = 1 for value in range(1, n + 1): factorial *= value return factorial print(f'Метод 4 (итерация-for) для числа 100: {iterative_factorial_for(100)}')
false
bfba95ff46cc7730d8736d352b900c4dd89d00c4
mekhrimary/python3
/countdown.py
1,121
4.15625
4
# Recursive function as a countdown def main(): """Run main function.""" number = get_number() while number == 0: number = get_number() print('\nStart:') countdown(number) def get_number() -> int: """Input and check a number from 1 to 100.""" try: num = int(input('Enter a positive integer from 1 to 100: ')) # if num is not in range 1-100, it will be reassignment = 0 if num <= 0: print('Wrong value (your number <= 0), try again.') num = 0 elif num > 100: print('Wrong value (your number > 100), try again.') num = 0 except ValueError: # if exeption, num will be assignment = 0 print('Wrong value (not a number), try again.') num = 0 finally: # return num (num = 0 if not in range or exception) return num def countdown(n: int) -> None: """Run recursive function.""" if n == 1: print('1\nDone!') else: print(n) countdown(n - 1) if __name__ == '__main__': main()
true
fadc2a22e5db5f8b2887067699ee05c721328e7c
mekhrimary/python3
/lettersstatsemma.py
1,818
4.125
4
# Use string.punctuation for other symbols (!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~) import string def main() -> None: '''Run the main function-driver.''' print('This program analyzes the use of letters in a passage') print('from "Emma" by Jane Austen:\n') print('Emma Woodhouse, handsome, clever, and rich, with a comfortable home') print('and happy disposition, seemed to unite some of the best blessings of') print('existence; and had lived nearly twenty-one years in the world with') print('very little to distress or vex her [and so on]...') # 1. Get a dictionary of text sentences. text = input_text() # 2. Analyze sentences and return a dictionary of lettes's usage. stats = count_letters(text) # 3. Print statistics print_stats(stats) def input_text() -> list: '''Open file and return a text.''' file_text = list() with open('fromEmma.txt', 'r') as fin: for line in fin: file_text.append(line.strip()) return file_text def count_letters(phrases: list) -> dict: '''Counts a usage of every letter and return as a dictionary.''' usage = dict() punkts = string.punctuation + string.whitespace for sentence in phrases: for symbol in sentence: if symbol not in punkts: if symbol not in usage: usage[symbol.lower()] = 1 else: usage[symbol.lower()] += 1 return usage def print_stats(usage: dict) -> None: '''Print statistics sorted by letters.''' letters = sorted(list(usage.keys())) print('\nStatistics (letters in alphabetical order):') for letter in letters: print(f'\t{letter}: {usage[letter]:3d} times') if __name__ == '__main__': main()
true
6ee057f17a4b7b82142808545a47ae6b5d0cc2bf
leonlinsx/ABP-code
/Python-projects/crackle_pop.py
682
4.3125
4
''' recurse application Write a program that prints out the numbers 1 to 100 (inclusive). If the number is divisible by 3, print Crackle instead of the number. If it's divisible by 5, print Pop. If it's divisible by both 3 and 5, print CracklePop. You can use any language. ''' class CracklePop: def __init__(self): pass def main(self): # from 1 to 100 (inclusive) for i in range(1, 101): # handle the both case first if i % 3 == 0 and i % 5 == 0: print("CracklePop") elif i % 3 == 0: print("Crackle") elif i % 5 == 0: print("Pop") else: print(i) return None crackle_pop = CracklePop() crackle_pop.main()
true
6982b7b8cf932a3c9e59e5909c3dfd6d1d6716d0
Ayush-1211/Python
/Advanced OOP/9. Polymorphism.py
1,130
4.46875
4
''' Polymorphism: Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. In inheritance, the child class inherits the methods from the parent class. ''' class User: def sign_in(self): print('Logged In!!') def attack(self): print('Do nothing!!') class Wizard(User): def __init__(self,name,power): self.name = name self.power = power def attack(self): User.attack(self) print(f'{self.name} attacking with {self.power}% of power.') class Archer(User): def __init__(self,name,arrows): self.name = name self.arrows = arrows def attack(self): print(f'{self.name} attacking with Arrows and {self.arrows} arrows left.') wizard1 = Wizard('Ayush',89) archer1 = Archer('Kohli',20) print('Example 1:') def player_attack(char): char.attack() player_attack(wizard1) player_attack(archer1) print('Example 2:') for char in [wizard1,archer1]: char.attack() print('Example 3:') wizard1.attack()
true
bd25b715de543f5ad54f7adc3fa0da0f237f86dd
dartleader/Learning
/Python/How to Think Like A Computer Scientist/4/exercises/8.py
373
4.4375
4
#Write a function area_of_circle(r) which returns the area of a circle with radius r. def area_of_circle(r): """Calculate area of a circle with radius r and return it.""" #Docstring #Declare temporary variable to hold the area. area = 0 #Calculate area. area = 3.14159 * r #Return area. return area print(input(area_of_circle("What is the radius of the circle?")))
true
b4f6d71f352434965960284a54113bc719abb2c6
Zidan2k9/PythonFundamentals
/loops.py
733
4.15625
4
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). people = ['Zain','Rida','Zaid','Mom','Dad'] for person in people: print('Current person is ' , person) #Break out for person in people: if person == 'Zaid': break print('Current person is ' , person) #Continue for person in people: if person == 'Mom': continue print('Current person is ', person) #Range for i in range(len(people)): print('Current person',people[i]) for i in range(0,11): print('Number ',i) # While loops execute a set of statements as long as a condition is true. count = 0 while count <= 10: print('Count ', count) count += 1
true
3e525a576deccda073de297716d21a6a2858e114
jingruhou/practicalAI
/Basics/PythonTutorialforBeginners/03strings.py
512
4.125
4
course = "Python's Course for Beginners" print(course) course = 'Python for "Beginners"' print(course) course = ''' Hi houjingur, The support team ''' print(course) course = 'Python for Beginners' # 012345 print(course[0]) print(course[0:3]) print(course[:-1]) print(course[-1]) print(course[-2]) print(course[-3]) print(course[0:]) print(course[1:]) print(course[1:5]) another = course[:] print(another) name = 'houjingru' print("First name: " + name[:3]) print("Last name: " + name[3:])
false
51f9a1607482265594555e7496c350ab2f1d82ad
parmar-mohit/Data-Structures-and-Algorithms
/Searching Algorithms/Python/Binary Search.py
861
4.15625
4
def binary_search( arr, len, num ) : ll = 0 ul = len - 1 mid = int( ll + ul / 2 ) while( ll < ul and mid < len ) : if arr[mid] > num : ul = mid - 1 elif arr[mid] < num : ll = mid + 1 else: break; mid = int( ul + ll / 2 ) if( mid < len ) : if( arr[mid] == num ) : return mid else : return -1 len = int( input( "Enter the length of array : " ) ) arr = [] print( "Enter Values in Ascending Order" ) for i in range( len ) : arr.append( int( input( "Enter value in array : " ) ) ) num = int( input( "Enter the number to find : " ) ) loc = binary_search( arr, len, num ) if( loc != -1 ) : print( "Number is found at index {}".format( loc ) ) else : print( "Number is not found in given array" )
false
236b634d4754fef2a4a56e828e8ae04be0bcacb5
parmar-mohit/Data-Structures-and-Algorithms
/Searching Algorithms/Python/Linear Search.py
519
4.125
4
def linearSearch( arr, len , num): for i in range( len ) : if arr[i] == num : return i else: return -1 len = int( input( "Enter Length of Array : " ) ) arr = [] for i in range( len ) : arr.append( int( input( "Enter Value in Array : " ) ) ) num = int( input( "Enter Number to find in array : " ) ) loc = linearSearch( arr, len , num ) if loc == -1 : print( "Number is Not found in Given array" ) else: print( "Number is found at index :", loc )
false
fb7e04ae9c850d0d23b8e69a6d1c29533514f771
ToddDiFronzo/cs-sprint-challenge-hash-tables
/hashtables/ex3/ex3.py
575
4.125
4
""" INTERSECTION OF MULTIPLE LISTS 1. Understand: Goal: find intersection of multiple lists of integers Test case --------- Input: list of lists [1,2,3,4,5] [12,7,2,9,1] [99,2,7,1] Output: (1,2) 2. Plan: NOTE: skipping this one. """ if __name__ == "__main__": arrays = [] arrays.append(list(range(1000000, 2000000)) + [1, 2, 3]) arrays.append(list(range(2000000, 3000000)) + [1, 2, 3]) arrays.append(list(range(3000000, 4000000)) + [1, 2, 3]) print(intersection(arrays))
true
0f12c136eb165f73e16dbc9d3c73d647ac6aa708
hamzai7/pythonReview
/nameLetterCount.py
302
4.25
4
# This program asks for your name and returns the length print("Hello! Please enter your name: ") userName = input() print("Hi " + userName + ", it is nice to meet you!") def count_name(): count = str(len(userName)) return count print("Your name has " + count_name() + " letters in it!")
true
4c9ae12c70a0170077b60a70a2339afbd85a9e52
ctwillson/algo
/python/sorting/InsertSort/InsertSort.py
563
4.21875
4
''' 插入排序 动画来源:https://visualgo.net/en/sorting?slide=9 ''' import numpy as np LENGTH = 10 a = np.random.randint(10,size=LENGTH) print(a) # print(list(range(10,0,-1))) #后面的元素往前插入 def InsertSort_demo(arr): ''' i 控制从第几个元素开始比较,j控制第几个元素往前比较 ''' for i in range(1,LENGTH): for j in range(i,0,-1): if(arr[j-1] < arr[j]): break else: arr[j-1],arr[j] = arr[j],arr[j-1] return arr print(InsertSort_demo(a))
false
3a55237ee2f95f66677b00a341d0b5f3585bb3d3
rayramsay/hackbright-2016
/01 calc1/arithmetic.py
922
4.28125
4
def add(num1, num2): """ Return the sum """ answer = num1 + num2 return answer def subtract(num1, num2): """ Return the difference """ answer = num1 - num2 return answer def multiply(num1, num2): """ Return the result of multiplication """ answer = num1 * num2 return answer def divide(num1, num2): """ Return the result of division """ answer = float(num1)/float(num2) # only one of these needs to be a float; an int divided by a float is a float return answer def square(num1): """ Return the square """ answer = num1 * num1 return answer def cube(num1): """ Return the cube """ answer = num1 ** 3 return answer def power(num1, num2): """ Return the num1 ^ num2 power """ answer = num1 ** num2 return answer def mod(num1, num2): """ Return the modulous or remainder """ answer = num1 % num2 return answer
true
43ff1d9bd4e3b0236126c9f138da52c3edd87064
Jordonguy/PythonTests
/Warhammer40k8th/Concept/DiceRollingAppv2.py
1,716
4.59375
5
# An small application that allows the user to select a number of 6 sided dice and roll them import random quit = False dice_rolled = 0 results = [] while(quit == False): # Taking User Input dice_rolled = dice_rolled dice_size = int(input("Enter the size of the dice you : ")) dice_num = int(input("Enter the number of dice you want : ")) print("You have selected " + str(dice_num) + " dice.") while(dice_num > 0): random_num = random.randint(1, dice_size) # make this random.randint(1,6) be assigned to a variable called random_num etc. # print(random_num) results.append(random_num) dice_num -= 1 dice_rolled += 1 print("Overall Dice Rolled : " + str(dice_rolled)) print("|| Results table ||") while (dice_size > 0): count = results.count(dice_size) print(str(dice_size) + " was rolled : " + str(count)) dice_size -= 1 # Brief experiment with informing the user if the roll was above or below average. #average = 0 # while(dice_rolled > 0): # average += 3 # dice_rolled -= 1 # if (sum(results) > average): # print("total : " + str(sum(results)) + " above average roll") # else: # print("total : " + str(sum(results)) + " below average roll") #print(str((sum(results)) - average) + " from the average") user_choice = str( input("|| Enter [Quit] to close the application : Press enter to perform another roll || ")) if(user_choice == "Quit"): quit = True else: quit = False # Make a better way of showing results # Allow user to keep rolling new dice(reset old results etc) # Allow the user to select the size of the dice
true
a4720d13bb654710000ccfb3a644af6914969c90
VladTano/code-study
/LABA 5.py
1,251
4.15625
4
#Програма. Дана послідовність, що містить від 2 до 20 слів, #в кожному з яких від 2 до 10 латинських букв; між сусідніми словами - #не менше одного пробілу, за останнім словом - крапка. Вивести на екран #всі слова, відмінні від останнього слова, попередньо видаливши з таких #слів першу букву. x = input() x = x.split() if 2<=len(x)<=20: while True: x = input('Введите слова в 1 строке:') frr = text.split() if len(frr) > 20: print('Введите меньше слов: ') print() continue elif len(frr) < 2: print('Введите больше слов ') print() continue break for i in range(len(frr)): n = i.split() if len(frr) > 10: print('Введите слова с меньшим количеством букв') break ''' я, ти, ти, врна, я ти, ти, врна, и, и, рна '''
false
172607053de3d302179eeadafe18f4331246fe9d
shusingh/My-Python
/dict.py
1,952
4.34375
4
# in this module we will learn about awesome dictionaries # defining a dictionary en_hin = {"good":"accha", "sit":"baithna", "walk":"chalna", "love":"pyar"} # now let's check our eng-hindi dictionary print(en_hin["good"]) print(en_hin["sit"]) print(en_hin["love"]) print(en_hin) # there is no ordering in dictionaries # let's try to mix things up a little grocery_list = {"mango":"Yes", "Orange":12, "Bananas":"No", "Pineapple":5} print(grocery_list["mango"]) print(grocery_list["Orange"]) print(grocery_list["Bananas"]) print(grocery_list["Pineapple"]) print(grocery_list) # adding a new entry to an existing dictionary grocery_list["Guava"] = "Yes" print(grocery_list) # so this way we can start with an empty dictionary and add items to it as we proceed #let's make a list of cities and their population city = {} city["Delhi"] = 78000 city["Mumbai"] = 80000 city["Gurgaon"] = 45000 city["Manali"] = 32000 print(city) # we can modify our dictionary as we go city["Mumbai"] = 81000 print(city) # let's perform some funcitons on our dictionaries len_city = len(city) #returns the number of key-value pairs print(len_city) del city["Gurgaon"] #deletes the key with its value print(city) print("Mumbai" in city) #returns true if the key exists in dictionary print("Lucknow" not in city) #returns true if the key does not exists in dictionary # iterating over a dictionary # iterating over keys: 1st way for keys in city: print(keys) # 2nd way for keys in city.keys(): print(keys) # iterating over values for values in city.values(): print(values) # now let's combine both # there are three ways # first way print("\ncity " + " population") for key,value in city.items(): print(f"{key} : {value}") #second way print("\ncity " + " population") for item in city: print(f"{item} : {city[item]}") #third way print("\ncity " + " population") for keys,values in zip(city.keys(),city.values()): print(f"{key} : {values}")
false
90ff8bcc34a2e380db6f0b71dd113e83dd764c46
EricksonGC2058/all-projects
/todolist.py
704
4.15625
4
print("Welcome to the To Do List! (:") todolist = [] while True: print("Enter 'a' to add an item") print("Enter 'r' to remove an item") print("Enter 'p' to print the list") print("Enter 'q' to quit") choice = input("Make your choice: ") if choice == "q": break elif choice == "a": todoitems = input("What will you add to your list? ") todolist.append(todoitems) elif choice == "r": todotakeout = input("What will you take out of your list? ") todolist.remove(todotakeout) elif choice == "p": count = 1 for todoitems in todolist: print("Task " + str(count) + ": " + todoitems) count = count + 1 else: print("That is not a choice, please try again.")
true
0c1cb03e151ed82f535ad691fb1f28d2539406c3
antonioleitebr1968/Estudos-e-Projetos-Python
/Exercicios&cursos/Curso_em_video(exercicios)/aula09.py
2,675
4.21875
4
frase = 'Curso em Vídeo Python' print('='*40, 'Bem vindo aos exemplos da Aula 09', '='*40) print(' '*50, 'Manipulando texto :)', ' '*50) print('') print('='*51, 'Fatiamento', '='*52) print('') print('1>>', frase[9])#ele vai indentificar a caractere 9 ou seja a 10 pq para o python começa a contar da caractere 0 print('') print('2>>', frase[9:13])#ele vai pegar do caractere 9 até o 13 print('') print('3>>', frase[9:21])#ele vai fatiar do 9 ate o final pq a caractere 21 n existe print('') print('4>>', frase[9:21:2])#ele vai fatiar do 9 até 21 pulando de dois em dois caracteres print('') print('5>>', frase[:5])#ele vai começar do inicio até o caractere 5 print('') print('6>>', frase[15:])#ele vai começar do 15 até o final da string print('') print('7>>', frase[9::3])#ele vai começar no 9 e vai até o final pulando de 3 em 3 print('') print('='*53, 'Análise', '='*53) print('8>>', len(frase))#mostra quantas caracteres tem na frase print('') print('9>>', frase.count('o', 0, 13))#fatia e mostra quantas caracteres 'o' tem na frase do 0 ao 13 print('') print('10>>', frase.find('deo'))#ele vai me dizer em que momento começou o 'deo' print('') print('11>>', frase.find('Android'))#ele vai mostrar -1 significa que a string que vc tentou encontrar não existe. print('') print('12>>', 'Curso' in frase)#ele vai me dizer se dentro da frase existe a palavra 'Curso' usando True ou False. print('') print('='*50, 'Transformação', '='*50) print('') print('13>>', frase.replace('Python', 'Android'))#ele substitui a palavra 'Python por a 'Android' print('') print('14>>', frase.upper())#ele vai manter as maiúsculas e transformar todas as que não são em maiúsculas print('') print('15>>', frase.lower())#mantem o que é minúscula e transforma o restante em minúscula print('') print('16>>', frase.capitalize())#transforma toda a string em minúscula deixando apenas a primeira caractere em maiúscula print('') print('17>>', frase.title())#ele vai analisar quantas palavras tem na string utilizando o espaço entre cada palavra print('') print('18>>', frase.strip())#ele vai remover todos os espaços inúteis no final e no inicio da string, mantendo a penas os do meio. print('') print('19>>', frase.rstrip())#remove todos os espaços a direita print('') print('20>>', frase.lstrip())#remove todos os espaços da esquerda print('') print('='*52, 'Divisão', '='*54) print('') print('21>>', frase.split())#Divide uma string em uma lista de strings númeradas print('') print('22>>', '-'.join(frase))#se eu tenho uma string dividida em uma lista essa função junta a lista e usa o separador'-' entre os espaços print('') print('='*53, 'FINISH', '='*54)
false
a82bf9799f8c2376e7f4ac60adb7aa9e45b76eec
antonioleitebr1968/Estudos-e-Projetos-Python
/Exercicios&cursos/Dicionarios/Dicionarios_03.py
385
4.25
4
## Dicionários parte 3 - Ordenação por chaves; método keys() e função sorted. # Exemplos: #Ordenação de dicionarios d = {'b': 2, 'a': 1, 'd': 4, 'c': 3} ordenada = list(d.keys()) ordenada.sort() for key in ordenada: print(key, '=', d[key]) print('-=' * 20) #=============================================== #outra forma for key in sorted(d): print(key, '=', d[key])
false
9dd4a8bea6d079f6bd3883fe53949bfbb1d58f1b
AndreasWJ/Plot-2d
/curve.py
2,638
4.3125
4
class Curve: def __init__(self, curve_function, color, width): self.curve_function = curve_function self.color = color self.width = width def get_pointlist(self, x_interval, precision=1): ''' The point precision works by multiplying the start and end of the interval. By doing so you're making the difference between the start and end bigger. By making the difference bigger you are allowing for more precision when generating the pointlist. More x values equals more points as the curve function is called for each x value. The index in the range between this multiplied interval can't simply be appended to the pointlist as the x values are too large. For example, if you are generating points for the interval 0 < x < 10, the multiplied interval with a precision of 10 would be 0 < x < 100. Anything beyond 10 is irrelevant to the user since that's what is the interval that's requested. Before appending the x and its y value to the pointlist you need to create a new variable where you reverse the changes you made when you multiplied the interval. This will normalize the interval back to its original state 0 < x < 10. By having an increased precision you will generate more x values between the x values in the interval. For example, the generated x values might look like: 0, 0.33, 0.66, 1, 1.33, 1.66, 2, etc. To reverse you multiply the multiplied interval index with (1 / precision) which removes the multiplication applied to the interval. :param x_interval: The interval of x values to generate points for :param precision: Set the point precision. The default value is 1 which will generate points for each x in the x interval. But with an increased precision more points are generated between each x value resulting in a better looking curve. :return: A list of points which are tuples ''' pointlist = [] x_start_with_precision = (x_interval[0] * precision) x_end_with_precision = ((x_interval[1] + 1) * precision) # Add one to the stop value of the range function. Otherwise if you have an x interval 0 < x < 10, it will # only generate points up to and including 9. Why is it so? for x in range(x_start_with_precision, x_end_with_precision): # print('Generated point ({}, {})'.format(x, self.curve_function(x))) point_x = x * (1 / precision) pointlist.append((point_x, self.curve_function(point_x))) return pointlist
true
4c1922842c2bb7027d6c1f77f5d11bb4d1250a1a
keeyong/state_capital
/learn_dict.py
906
4.4375
4
# two different types of dictionary usage # # Let's use first name and last name as an example # 1st approach is to use "first name" and "last name" as separate keys. this approach is preferred # 2nd approach is to use first name value as key and last name as value # ---- 1st apprach name_1 = { 'firstname': 'keeyong', 'lastname': 'han' } name_2 = { 'firstname': 'dennis', 'lastname': 'yang' } names = [] names.append(name_1) names.append(name_2) for name in names: print("1st approach - first name:" + name["firstname"] + ", last name:" + name["lastname"]) # ---- 2nd approach # 여기서는 키는 이름이 되고 값은 성이 되는 구조이다 name_1 = { 'keeyong': 'han' } name_2 = { 'dennis': 'yang' } names = [] names.append(name_1) names.append(name_2) for name in names: for key, value in name.items(): print("2nd approach - first name:" + key + ", last name:" + value)
true
877fe8b28feadb49c4b071d9d1e26a3796f466cc
scresante/codeeval
/crackFreq.py2
1,676
4.21875
4
#!/usr/bin/python from sys import argv try: FILE = argv[1] except NameError: FILE = 'tests/121' DATA = open(FILE, 'r').read().splitlines() for line in DATA: if not line: continue print line inputText = line #inputText = str(raw_input("Please enter the cipher text to be analysed:")).replace(" ", "") ##Input used to enter the cipher text. replace used to strip whitespace. ngramDict = {} highestValue = 0 def ngram(n): #Function used to populate ngramDict with n-grams. The argument is the amount of characters per n-gram. count = 0 for letter in inputText: if str(inputText[count : count + n]) in ngramDict: #Check if the current n-gram is in ngramDict ngramDict[str(inputText[count : count + n])] = ngramDict[str(inputText[count : count + n])] + 1 #increments its value by 1 else: ngramDict[str(inputText[count : count + n])] = 1 #Adds the n-gram and assigns it the value 1 count = count + 1 for bigram in ngramDict.keys(): #Iterates over the Bigram dict and removes any values which are less than the adaquate size (< n argument in function) if len(bigram) < n: del ngramDict[bigram] ngram(int(raw_input("Please enter the n-gram value. (eg bigrams = 2 trigrams = 3)"))) ngramList = [ (v,k) for k,v in ngramDict.iteritems() ] #iterates through the ngramDict. Swaps the keys and values and places them in a tuple which is in a list to be sorted. ngramList.sort(reverse=True) #Sorts the list by the value of the tuple for v,k in ngramList: #Iterates through the list and prints the ngram along with the amount of occurrences print("There are " + str(v) + " " + str(k))
true
f0b5f940a37acd4ac16a5ab76b9331b57dec7c57
kxhsing/dicts-word-count
/wordcount.py
1,258
4.28125
4
# put your code here. #putting it all in one function #will figure out if they can be broken later def get_word_list(file_name): """Separates words and creates master list of all the words Given a file of text, iterates through that file and puts all the words into a list. """ #empty list to hold all the words in this file all_the_words = [] #iterate through the file to get all the words #and put them in the list text = open(file_name) for lines in text: lines = lines.rstrip() word = lines.split(" ") #combine all words into one list all_the_words.extend(word) #make all lowercase for i, word in enumerate(all_the_words): all_the_words[i] = word.lower() #removing punctuation for i, word in enumerate(all_the_words): if not word.isalpha(): all_the_words[i] = word[:-1] #create an empty dictionary to hold the words word_count = {} #iterate though the list to count number of occurances for word in all_the_words: word_count[word] = word_count.get(word, 0) + 1 for word, count in word_count.iteritems(): print "%s %d" % (word, count) get_word_list("test.txt") #get_word_list("twain.txt")
true
4e9e37db57f014e20bde5806050022a9911a99ed
ottoguz/My-studies-in-Python
/ex018a.py
343
4.34375
4
#Calculate an angle and its Sen/Cos/Tg import math ang = float(input('Type an angle:')) # Used the function math.radians() to turn numbers into radians print('Sine:{:.2f}' .format(math.sin(math.radians(ang)))) print('Cosene:{:.2f}' .format(math.cos(math.radians(ang)))) print('Tangent:{:.2f}'.format(math.tan(math.radians(ang))))
false
93df2764f6fdcfb101521820aa3be80562e1bc47
ottoguz/My-studies-in-Python
/aula005s.py
816
4.125
4
#Function that receives an integer via keyboard and determines the range(which should comprehend positive numbers) def valid_int(question, min, max): x = int(input(question)) if ((x < min) or (x > max)): x = int(input(question)) return x #Function to calculate the factorial of a given number def factorial(num): """ :param num: number to be factored as a parameter :return: returns the result of the factored number """ fat = 1 if num == 0: return fat for i in range(1, num + 1, 1): fat *= i return fat # x = variable in which the function valid_int(question, min, max) is summoned x = valid_int('Type in a factorial:', 0, 99999) #result printed for the user print('{}! = {}' .format(x, factorial(x))) help(factorial)
true
5b928f4d9cfdd6bb4bcbca0500ffbdd6ac40c2c5
NinjaCodes119/PythonBasics
/basics.py
915
4.125
4
student_grades = [9, 8, 7 ] #List Example mySum = sum(student_grades) length = len(student_grades) mean = mySum / length print("Average=",mean) max_value = max(student_grades) print("Max Value=",max_value) print(student_grades.count(8)) #capitalize letter text1 = "This Text should be in capital" print(text1.upper()) #student grades using dictionary student_grades2 = {"marry":9, "Sim": 8 ,"Gary":7} mySum2 = sum (student_grades2.values()) #values is a method in dict length2 = len (student_grades2) mean2 = mySum2 / length2 print(mean2) print (student_grades2.keys()) #Creating Tuple #Tuples are immutable, difference to list #cannot use methods like using in list example list.remove() #Tuples are faster than list moday_temperatures = { 2,4,5} print("monday teperatures are:",moday_temperatures) #Creating List #This line is edited Online #this line is edited from PC github #this line is from laptop Win
true
0b1281fa76e4379219ec2637d53c94412547b52b
jemcghee3/ThinkPython
/05_14_exercise_2.py
970
4.375
4
"""Exercise 2 Fermat’s Last Theorem says that there are no positive integers a, b, and c such that an + bn = cn for any values of n greater than 2. Write a function named check_fermat that takes four parameters—a, b, c and n—and checks to see if Fermat’s theorem holds. If n is greater than 2 and an + bn = cn the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.” Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate Fermat’s theorem.""" def check_fermat(a, b, c, n): if n > 2 and a ** n + b ** n == c ** n: print("Holy smokes, Fermat was wrong!") else: print("No, that doesn't work.") a = int(input('Input "a": \n')) b = int(input('Input "b": \n')) c = int(input('Input "c": \n')) n = int(input('Input "n": \n')) check_fermat(a, b, c, n)
true
32ebb0dcbf831f71f2e24e72f38fdb3cb7af8fc1
jemcghee3/ThinkPython
/05_14_exercise_1.py
792
4.25
4
"""Exercise 1 The time module provides a function, also named time, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970. Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch.""" import time current_time = time.time() days = int(current_time // (60 * 60 * 24)) remaining = current_time % (60 * 60 * 24) hours = int(remaining // (60 * 60)) remaining = remaining % (60 * 60) minutes = int(remaining // 60) remaining = remaining % 60 seconds = int(remaining // 1) print(f'The time of day is {hours}:{minutes}:{seconds}, and it has been {days} days since the beginning of the epoch.')
true
4beaf5482d4fe8a76d30bb5548ae33192d33f19b
jemcghee3/ThinkPython
/09_02_exercise_4.py
672
4.125
4
"""Exercise 4 Write a function named uses_only that takes a word and a string of letters, and that returns True if the word contains only letters in the list. Can you make a sentence using only the letters acefhlo? Other than “Hoe alfalfa”?""" def letter_checker(c, letters): for l in letters: if c == l: return True return False def uses_only(word, letters): for c in word: if letter_checker(c, letters) is False: return False return True fin = open('words.txt') allowed_letters = 'acefhlo' for line in fin: line = line.rstrip() if uses_only(line, allowed_letters) is True: print(line)
true
fa53edb7fa96c64310f584cd9d7af86b0cc9ec24
jemcghee3/ThinkPython
/08_03_exercise_1.py
255
4.25
4
"""As an exercise, write a function that takes a string as an argument and displays the letters backward, one per line.""" def reverse(string): l = len(string) i = -1 while abs(i) <= l: print(string[i]) i -= 1 reverse('test')
true
2e55f9920fcf976b3027a7abf4bc175752fe2ec1
jemcghee3/ThinkPython
/10_15_exercise_02.py
682
4.28125
4
"""Exercise 2 Write a function called cumsum that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example: >>t = [1, 2, 3] >>cumsum(t) [1, 3, 6] """ def sum_so_far(input_list, n): # n is the number of items to sum, not position total = 0 for i in range(n): total += input_list[i] return total def cumsum(input_list): sum_list = list() for n in range(1, len(input_list)+1): # because n is the number of items to sum, not a position sum_list.append(sum_so_far(input_list, n)) return sum_list t = [1, 2, 3] print(cumsum(t))
true
7d832e6a251f1d4a1abd229eb3ea409f76f2f164
jemcghee3/ThinkPython
/08_13_exercise_5.py
2,356
4.1875
4
"""Exercise 5 A Caesar cypher is a weak form of encryption that involves “rotating” each letter by a fixed number of places. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so ’A’ rotated by 3 is ’D’ and ’Z’ rotated by 1 is ’A’. To rotate a word, rotate each letter by the same amount. For example, “cheer” rotated by 7 is “jolly” and “melon” rotated by -10 is “cubed”. In the movie 2001: A Space Odyssey, the ship computer is called HAL, which is IBM rotated by -1. Write a function called rotate_word that takes a string and an integer as parameters, and returns a new string that contains the letters from the original string rotated by the given amount. You might want to use the built-in function ord, which converts a character to a numeric code, and chr, which converts numeric codes to characters. Letters of the alphabet are encoded in alphabetical order, so for example: ord('c') - ord('a') 2 Because 'c' is the two-eth letter of the alphabet. But beware: the numeric codes for upper case letters are different. Potentially offensive jokes on the Internet are sometimes encoded in ROT13, which is a Caesar cypher with rotation 13. If you are not easily offended, find and decode some of them. Solution: http://thinkpython2.com/code/rotate.py.""" def rotate(num, n): return num + n def too_low(n): return n + 26 def too_high(n): return n - 26 def upper_wrap(n): if n < 65: return too_low(n) elif n > 90: return too_high(n) else: return n def lower_wrap(n): if n < 97: return too_low(n) elif n > 122: return too_high(n) else: return n def upper_caesar(num, n): num = rotate(num, n) num = upper_wrap(num) return chr(num) def lower_caesar(num, n): num = rotate(num, n) num = lower_wrap(num) return chr(num) def rotate_word(s, n): new_word = '' for c in s: if c.isalpha() == False: new_word += c continue num = ord(c) if 65 <= num <= 90: num = upper_caesar(num, n) elif 97 <= num <= 122: num = lower_caesar(num, n) else: print('something went wrong') new_word += num print(new_word) rotate_word('IBM', -1)
true
17df7ec92955ee72078b556e124938f1531f298a
jemcghee3/ThinkPython
/11_10_exercise_03.py
1,535
4.5
4
"""Exercise 3 Memoize the Ackermann function from Exercise 2 and see if memoization makes it possible to evaluate the function with bigger arguments. Hint: no. Solution: http://thinkpython2.com/code/ackermann_memo.py. The Ackermann function, A(m, n), is defined: A(m, n) = n+1 if m = 0 A(m−1, 1) if m > 0 and n = 0 A(m−1, A(m, n−1)) if m > 0 and n > 0. Here is the memoize code for Fibonacci sequence: known = {0:0, 1:1} def fibonacci(n): if n in known: return known[n] res = fibonacci(n-1) + fibonacci(n-2) known[n] = res return res""" known = {(0, 0): 1} def memo_ackermann(t): # takes a tuple if t in known: return known[t] # if len(t) != 2: # return 'This function only works with tuples formatted (m, n).' m, n = t if m < 0 or n < 0 or type(m) != int or type(n) != int or type(t) != tuple: return 'This function only works for tuples (m, n) where each is an integer greater than or equal to zero.' if m == 0: # n+1 if m = 0 known[t] = n + 1 return n + 1 elif m > 0 and n == 0: # A(m−1, 1) if m > 0 and n = 0 t2 = (m - 1, 1) res = memo_ackermann(t2) known[t] = res return res elif m > 0 and n > 0: # A(m−1, A(m, n−1)) if m > 0 and n > 0 tn = (m, n-1) n = memo_ackermann(tn) t2 = (m - 1, n) res = memo_ackermann(t2) known[t] = res return res ans = memo_ackermann((3, 5)) print(ans) # print(known)
true
7e90113bc6bd97d3d3728d2527698e0e26b159a2
shiva111993/python_exercises
/set_code.py
2,213
4.1875
4
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. # myset = {"apple", "ball", "cat", "dag", "elephate"} # print(myset) # myset.add("fan") # print(myset) # myset.add("apple") # print(myset) # ---------removing # myset.remove("ball") # print(myset) # myset.discard("apple") # print(myset) # myset.pop() # print(myset) # myset.clear() # print(myset) # del myset # print(myset) # ------------------loop # for x in myset: # print(x) # ------------------ adding & update # myset2 = {"car", "bike", "cycle"} # myset3 = {False, True, False, False, True} # myset4 = {1, 2, 3, 4, 5} # mylist = ["kiwi", "orange"] # myset.update(myset2, myset3, myset4, mylist) # print(myset) # print("kiwi" in myset) # ------------------ join set # myset = {"a", "b", "c"} # myset2 = {"a", "b", "c", "d"} # myset3 = {1, 2, 3} # myset3 = myset.union(myset2) # print(myset3) # --intersection and intersection_update # set1 = {"apple","banana","carry"} # set2 = {"google","microsoft","apple"} # intersction # set3 = set1.intersection(set2) # print(set3) # interction_update # set1.intersection_update(set2) # print(set1) # --symmetric_difference_update() & symmetric_difference() # method will keep only the elements that are NOT present in both sets. # Keep All, But NOT the Duplicates # set1 = {"apple","banana","carry"} # set2 = {"google","microsoft","apple"} # set1.symmetric_difference(set2) #it not work # set3 = set1.symmetric_difference(set2)#o/p:-{'microsoft', 'banana', 'google', 'carry'} # print(set3) # set1.symmetric_difference_update(set2) # print(set1) # --issubset() # set1= {"a","b","c"} # set2 = {"f", "e", "d", "a","b","c"} # set3 = set1.issubset(set2) # print(set3) # --issuperset() # x = {"f", "e", "d", "c", "b", "a"} # y = {"a", "b", "c"} # z = x.issuperset(y) # print(z) # --isdisjoin() # Return True if no items in set x is present in set y: # x = {"apple", "banana", "cherry"} # y = {"google", "microsoft", "facebook"} # # -------------- or ------------- # x = {"apple", "banana", "cherry"} # y = {"google", "microsoft", "apple"} # z = x.isdisjoint(y) # print(z)
true
6c463adbd86c53f3a17f58f960d6932134f29783
emaustin/Change-Calculator
/Change-Calculator.py
2,259
4.125
4
def totalpaid(cost,paid): #Checking to ensure that the values entered are numerical. Converts them to float numbers if so. try: cost = float(cost) paid = float(paid) #check to ensure the amount paid is greater than the cost except: print("Please enter in a number value.") dollars = 0 quarters = 0 dimes = 0 nickels = 0 pennies = 0 #Finds the amount of change based on the amount paid subtracted from the total amount, rounded to two places change = round(paid - cost,2) #Uses the number preceding the decimal dollars = int(change) #subtracts the dollars from the total change to get the amount of cents remaining, rounded to two places cents = round(change - dollars,2) remaining_change = cents #following sequence checks to see if there's enough change for each type of coin. If so, it subtracts from the running total if cents/.25 >= 1: quarters = int(cents/.25) remaining_change = round(cents - (quarters*.25),2) if remaining_change/.1 >= 1: dimes = int(remaining_change/.1) remaining_change = round(remaining_change - (dimes*.1),2) if remaining_change/.05 >=1: nickels = int(remaining_change/.05) remaining_change = round(remaining_change - (nickels*.05),2) if remaining_change/.01 >=1: pennies = int(remaining_change/.01) remaining_change = round(remaining_change - (pennies *.01),2) print(f"The total was ${cost}. The customer paid ${paid}. \n\n Amount Due: \n Dollars: {dollars} \n Quarters: {quarters} \n Dimes: {dimes} \n Nickels: {nickels} \n Pennies: {pennies} ") # #Asks for cost and amount paid #Removes leading dollar sign, if any, to convert input to float #Runs totalpaid function to calculate change needed # item_cost = input("What did the item cost?") if item_cost[0] == '$': item_cost = item_cost.replace('$','') item_cost = float(item_cost) amount_paid = input("How much did the customer pay?") if amount_paid[0] == '$': amount_paid = amount_paid.replace('$','') amount_paid = float(amount_paid) totalpaid(item_cost,amount_paid)
true
c674750f830792e233e5cb6cd0b7202dce23fddd
romulovieira777/Curso_Rapido_de_Python_3
/Seção 02 - Variáveis/variaveis.py
501
4.1875
4
# Definindo uma variável int e float a = 3 b = 4.4 print(a + b) # Definindo uma variável de texto texto = 'Sua idade é... ' idade = 23 print(texto + str(idade)) print(f'{texto} {idade}!') # Imprimindo string print(3 * 'Bom Dia! ') # Criando uma Interação com o Usuário pi = 3.14 raio = float(input('Informe o raio da circuferência: ')) area = pi * raio * raio # area = pi * pow(raio, 2) outra forma de calcular com uma função Bult-in print(f'A área da circuferência é {area} m2.')
false
5c8af61748085a7bf39a1a6dea1a134a8843005e
mattfisc/cs240
/HW6program3_binary_to_decimal.py
598
4.15625
4
def binary_to_decimal(x): num = 0 twoPower = 1 for i in range(len(x)-1,-1,-1): num += x[i] * (2**twoPower) twoPower += 1 return num def compare_two_binary(binary1,binary2): b1 = binary_to_decimal(binary1) b2 = binary_to_decimal(binary2) if b1 > b2: return binary1, " Is greater" elif b2 > b1: return binary2, " Is greater" else: binary1, " Is equal ", binary2 arr = [1,0,1] arr2 = [1,1,1] print(binary_to_decimal(arr)) print(compare_two_binary(arr,arr2)) # ------ OUTPUT -------- # 10 # ([1, 1, 1], ' Is greater')
false
cd736e4f096527ed9a012f7cb8e44b0c93f9d4df
eNobreg/holbertonschool-interview
/0x19-making_change/0-making_change.py
523
4.40625
4
#!/usr/bin/python3 """ Module for making change function """ def makeChange(coins, total): """ Making change function coins: List of coin values total: Total coins to meet Return: The lowest amount of coins to make total or -1 """ count = 0 if total <= 0: return 0 coins = sorted(coins, reverse=True) for coin in coins: while total >= coin: total -= coin count += 1 if total > 0: return -1 else: return count
true
b9b329934dc1865548940c95d89b3d6a1052f4a5
nikithapk/coding-tasks-masec
/fear-of-luck.py
423
4.34375
4
import datetime def has_saturday_eight(month, year): """Function to check if 8th day of a given month and year is Friday Args: month: int, month number year: int, year Returns: Boolean """ return True if datetime.date(year, month, 8).weekday() == 5 else False # Test cases print(has_saturday_eight(5, 2021)) print(has_saturday_eight(9, 2017)) print(has_saturday_eight(1, 1985))
true
7359fb54f366e1a261f06bf190c92f3ebc72d752
zvikazm/ProjectEuler
/9.py
583
4.28125
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ class P9(object): @staticmethod def run(): for i in range(1, 1000): for j in range(i + 1, 1000): for k in range(j + 1, 1000): if i ** 2 + j ** 2 == k ** 2 and i + j + k == 1000: print(i, j, k) pass if __name__ == '__main__': P9.run()
false
0260224543d1b2f8b51e3cbf22530d176fa1a684
Zane-ThummBorst/Python-code
/Factorial code.py
1,117
4.21875
4
# # Zane ThummBorst # #9/9/19 # # demonstrate recursiuon through the factorial # and list length def myFactorial(x): ''' return the factorial of x assuming x is > 0''' # if x == 0: # return 1 # else: # return x * myFactorial(x-1) return 1 if x==0 else x*myFactorial(x-1) #print(myFactorial(2)) def myLength(L): '''return the length of the list L''' if L == []: return 0 else: return 1 + myLength(L[1:]) #print(myLength([1,2,3])) def LCS(S1,S2): ''' return the longest common subsequence between the strings''' # if len(S1) == 0 or len(S2) == 0: # return 0 # elif S1[0] == S2[2]: # #A common firsdt character adds 1 to LCS # return 1 + LCS(S1[1:], S2[1:]) # else: # #Drop either first character and recurse # max(LCS(S1, S2[1:]), LCS(S1, S2[1:])) #NEXT EXAMPLE IS CRUCIAL FOR RECURSION LAB def deepLength(L): if not L: return 0 else: head, tail = L[0], L[1:] headVal = deepLength(head) if isinstance(head,list)else 1 return headVal + deepLength(tail)
false
58cdadc4d72f1a81b55e16f0a4067b44ae937f37
rcolistete/Plots_MicroPython_Microbit
/plot_bars.py
609
4.125
4
# Show up to 5 vertical bars from left to right using the components of a vector (list or tuple) # Each vertical bar starts from bottom of display # Each component of the vector should be >= 0, pixelscale is the value of each pixel with 1 as default value. # E. g., vector = (1,2,3,4,5) will show 5 verticals bars, with 1, 2, 3, 4 and 5 leds on. def plot_bars(vector, pixelscale = 1): for i in range(len(vector)): for y in range(5): if vector[i] - (y + 1)*pixelscale >= 0: display.set_pixel(i, 4 - y, 9) else: display.set_pixel(i, 4 - y, 0)
true
dc5a055097f7162f6204cbcbc66ec96eed827db4
DangGumball/DangGumball
/Homework/BMI.py
408
4.21875
4
height_cm = int(input('Enter your height here (cm): ')) weight = int(input('Enter your weight here (kg): ')) height_m = height_cm / 100 BMI = weight / (height_m * height_m) print(BMI) if BMI < 16: print('Severely underweight') elif 16 <= BMI <= 18.5: print('Underweight') elif 18.5 <= BMI <= 25: print('Normal') elif 25 <= BMI <= 30: print('Overweight') else: print('Obese')
false
d8301e71e2d210a4303273f2f875514bd4a6aff0
mansi05041/Computer_system_architecture
/decimal_to_any_radix.py
910
4.15625
4
#function of converting 10 to any radix def decimal_convert_radix(num,b): temp=[] while (num!=0): rem=num%b num=num//b temp.append(rem) result=temp[::-1] return result def main(): num=int(input("Enter the decimal number:")) radix=int(input("enter the base to be converted:")) result=decimal_convert_radix(num,radix) #creating dictonary for the values greater than 9 alphabet={} val=10 for i in list(map(chr, range(97, 123))): key=i.upper() value=val val=val+1 alphabet[key]=value print(num,' of base',10,' into base',radix,' is:',end="") for i in result: if i>9: i=list(alphabet.keys())[list(alphabet.values()).index(i)] #replacing the values starting from 10 print(i,end="") #calling main function if __name__ == "__main__": main()
true
0a6ce06157bd0fb4e30e2c98a8327f5b98f14682
zija1504/100daysofCode
/5.0 rock paper scissors/game.py
2,843
4.3125
4
#!/usr/bin/python3 # Text Game rock, paper, scissors to understand classes import random class Player: """name of player""" def __init__(self, name): self.name = name self.pkts = 0 def player_battle(self, pkt): self.pkts += pkt class Roll: """rolls in game""" def __init__(self, name, winning, losing): self.name = name self.winning = winning self.losing = losing def can_defeat(self, another_roll): """function that check what roll wins battle""" if self.winning == another_roll: return 1 elif self.name == another_roll: return 0 elif self.losing == another_roll: return -1 def build_rolls(): Rock = Roll('rock', 'scissors', 'paper') Scissors = Roll('scissors', 'paper', 'rock') Paper = Roll('paper', 'rock', 'scissors') return [Rock, Scissors, Paper] def header(): """simple header""" print('---------------------') print('---Welcome in Game---') print('Rock, Paper, Scissors') def get_player_name(): """ask for name of player""" name = input('Whats your name? ') print(f'Welcome in game {name}') return name def game_loop(Player1, Player2, rolls): """playing up to 3, or -3""" end_of_game = 0 while not end_of_game: player2_roll = rolls[random.randint(0, 2)] print( f'Choose roll: 1:{rolls[0].name} 2:{rolls[1].name} 3:{rolls[2].name}' ) choice = input(">>>") if int(choice) in (1, 2, 3): player1_roll = rolls[int(choice) - 1] print( f'Player {Player1.name} choose {player1_roll.name}, Player {Player2.name} choose {player2_roll.name}' ) part = player1_roll.can_defeat(player2_roll.name) if part == 1: Player1.player_battle(1) print( f'This round win Player {Player1.name} and has {Player1.pkts} point/points' ) elif part == -1: Player2.player_battle(1) print( f'This round win Player {Player2.name} and has {Player2.pkts} point/points' ) elif part == 0: print(f'Draw in this round.') if Player1.pkts == 3: print(f'End of game, won Player {Player1.name}') end_of_game = 1 elif Player2.pkts == 3: print(f'End of game, won Player {Player2.name}') end_of_game = 1 def main(): """main function of program""" header() player_name = get_player_name() Player1 = Player(player_name) Player2 = Player('computer') rolls = build_rolls() game_loop(Player1, Player2, rolls) if __name__ == '__main__': main()
true
f524472f1125b5d55bd1af74de6c5e0ba81c9f54
hiteshkrypton/Python-Programs
/sakshi1.py
310
4.25
4
def factorial(n): if n == 1: return n else: return n * factorial(n - 1) n = int(input("Enter a Number: ")) if n < 0: print("Factorial cannot be found for negative numbers") elif n == 0: print("Factorial of 0 is 1") else: print("Factorial of", n, "is: ", factorial(n))
true
a906a6093594811a719d8113acd7c7ddcb1897fe
hiteshkrypton/Python-Programs
/dice_game.py
1,665
4.1875
4
#Dice game #Made by satyam import random import time import sys while True : def start(): sum = 0 counter = 0 verification = 'y' while counter < 3 and verification == 'y' : dice_number = random.randint(1, 6) print('Computer is rolling a dice ',end ='') for i in range(3): time.sleep(random.random()) print('...', end='') print(f'\nResult {dice_number}') sum += dice_number if sum >= 12 and counter == 2 : print(f'HURRAY! , You Win \nTotal Score is {sum}') elif counter == 2 : print(f'OPPS!!! , You Lose \nTotal score is {sum}') if counter < 2 : verification = input("Continue [Y/N] \n-->").lower() counter += 1 else: if verification == 'n' : print('You exit from that game ') else : print('All three chances are over ') def stop(): print('Game is terminated ') sys.exit(0) def help(): print(''' You have 3 chance to roll the dice If the Sum of dice number is greater tham "12" then you win otherwise lose ''') try: choice_list = int(input('\nEnter choice \n1.Start Game \n2.Exit Game\n3.Help\n--> ')) except(ValueError): print('Your choice is not in numerical form ') sys.exit(0) if choice_list == 1 : start() elif choice_list == 2 : stop() elif choice_list == 3 : help() else : print('Wrong choice') sys.exit(0)
false
a8208d7d0d616979a5b0e40ae918bca80e5ae460
ZCKaufman/python_programming
/squareRoot.py
559
4.28125
4
import math class SquareRoot(): def sqrt(self, num) -> float: x0 = (1/2)*(num + 1.0) i = 0 while(i <= 5): x0 = (1/2)*(x0 + (num/x0)) i += 1 return x0 obj = SquareRoot() obj.sqrt(4) obj.sqrt(10) obj.sqrt(8) obj.sqrt(6) if __name__ == '__main__': obj = SquareRoot() i = 0 while(i <= 100): print("Using Newton's method, the square root of " + str(i) + " is " + str(obj.sqrt(i)) + ". The Python Math library .sqrt() of " + str(i) + " is " + str(math.sqrt(i)) + ".") i += 1
false
dfb693bb8093a5f86513a6cd0b565d5c1d0c2809
sachinsaurabh04/pythonpract
/Function/function1.py
544
4.15625
4
#!/usr/bin/python3 # Function definition is here def printme( str ): #"This prints a passed string into this function" print (str) return # Now you can call printme function printme("This is first call to the user defined function!") printme("Again second call to the same function") printme("hello sachin, this is 3rd call of the function") printme(2+3) printme("sachin") #Output: #This is first call to the user defined function! #Again second call to the same function #hello sachin, this is 3rd call of the function #5 #sachin
true
6449b99534151c641b5856b5bc31874d27eae50c
sachinsaurabh04/pythonpract
/Loop/forloop1.py
576
4.15625
4
#for letter in 'python': # print("Letter in python is ", letter) #print() #fruits=['banana','apple','mango'] #for x in fruits: # print('current fruit ', x) #print("Good bye") #!/usr/bin/python3 #fruits = ['banana','apple', 'mango'] #for x in range(len(fruits)): # print("My favourite fruits are : ", fruits[x]) #print("\n End of choice") #!/usr/bin/python3 numbers=[11,33,55,20,39,55,75,37,21,23,42,41,12,13] for num in numbers: if num%2==0: print ('The given number is even',num) # break else: print ('The given number is odd',num)
false
70b59046590e09cf64be5d6c6d210893ab3d7bfc
sachinsaurabh04/pythonpract
/Function/funtion7.py
1,115
4.3125
4
#keyword Argument #This allows you to skip arguments or place them out of order because the Python #interpreter is able to use the keywords provided to match the values with parameters. You #can also make keyword calls to the printme() function in the following ways- #Order of the parameters does not matter #!/usr/bin/python3 #Function definition is here def printinfo(name,age): print("NAME: ",name) print("AGE: ", age) return def calculation(): age=int(input("Please enter the age: ")) if (age>60): print("You are 60+") name=input("Please enter the name: ") print("***Nice Name****") print("\nWhat I got from you is: ") printinfo(name, age) return() calculation() print("\nWould you like to edit or save? Press 1 for Edit or 2 for Save: ") res = int(input()) while (res==1): calculation() print("\nWould you like to edit or save? Press 1 for Edit or 2 for Save: ") res = int(input()) if res==2: print("\nWe have SAVED your details. Thank you.") print("***Good bye***") else: print("you have not selected the right choice. Good Bye.")
true
870584ac512971e7b83b510160036437227417f9
Apoorva-K-N/Online-courses
/Day 12/coding/prog1(Day 12).py
280
4.125
4
1.Python Program for Sum of squares of first n natural numbers def squaresum(n): return (n * (n + 1) / 2) * (2 * n + 1) / 3 n=int(input("Enter number")) print("Sum of squares n numbers : ",squaresum(n)); output: Enter number5 Sum of squares n numbers : 55.0
false
1ced156b8bad36c94f49d1c51483611eba47754d
Deepomatic/challenge
/ai.py
2,709
4.125
4
import random def allowed_moves(board, color): """ This is the first function you need to implement. Arguments: - board: The content of the board, represented as a list of strings. The length of strings are the same as the length of the list, which represents a 8x8 checkers board. Each string is a row, from the top row (the black side) to the bottom row (white side). The string are made of five possible characters: - '_' : an empty square - 'b' : a square with a black disc - 'B' : a square with a black king - 'w' : a square with a white disc - 'W' : a square with a white king At the beginning of the game: - the top left square of a board is always empty - the square on it right always contains a black disc - color: the next player's color. It can be either 'b' for black or 'w' for white. Return value: It must return a list of all the valid moves. Please refer to the README for a description of what are valid moves. A move is a list of all the squares visited by a disc or a king, from its initial position to its final position. The coordinates of the square must be specified using (row, column), with both 'row' and 'column' starting from 0 at the top left corner of the board (black side). Example: >> board = [ '________', '__b_____', '_w_w____', '________', '_w______', '_____b__', '____w___', '___w____' ] The top-most black disc can chain two jumps and eat both left white discs or jump only over the right white disc. The other black disc cannot move because it does produces any capturing move. The output must thus be: >> allowed_moves(board, 'b') [ [(1, 2), (3, 0), (5, 2)], [(1, 2), (3, 4)] ] """ # TODO: Your turn now ! return [] def play(board, color): """ Play must return the next move to play. You can define here any strategy you would find suitable. """ return random_play(board, color) def random_play(board, color): """ An example of play function based on allowed_moves. """ moves = allowed_moves(board, color) # There will always be an allowed move # because otherwise the game is over and # 'play' would not be called by main.py return random.choice(moves)
true
c705cd6c2c07fab452bc83550ca83116952bc2b9
shnehna/python_study
/string.py
238
4.21875
4
num_str = "Hello world " # print(num_str.isdecimal()) # print(num_str.isdigit()) # print(num_str.isnumeric()) print(num_str.startswith("H")) print(num_str.endswith("d")) print(num_str.find(" ")) print(num_str.replace("world", "python"))
false
38a4524825587ad4c8d39ee9398d37ae760d8950
cceniam/BaiduNetdiskDownload
/python/python系统性学习/2020_04_18/list_learn.py
2,360
4.125
4
""" 类似于 int float 这种类型,没有可以访问的内部结构 类似于 字符串 (str) 是结构化非标量类型 有一系列的属性方法 今天学习 list 列表 : """ # list 有序 每个值可通过索引标识 import sys list1 = [1, 2, 3, 4, 5, 6] print(list1) # 乘号表示重复的次数 list2 = ['hello'] * 3 print(list2) list3 = list1 * 3 print(list3) # len() 计算list长度 print(len(list3)) # 通过enumerate函数处理列表之后再遍历可以同时获得元素索引和值 for we, elem in enumerate(list3): print(we, elem) # 添加元素 list3.append(30) print(list3) # 删除元素 list3.remove(3) # 从指定位置删除元素 list3.pop(4) # 清空列表 list3.clear() """ 切片操作 """ fruits = ['grape', 'apple', 'strawberry', 'waxberry'] fruits += ['pitaya', 'pear', 'mango'] # 列表切片 fruits2 = fruits[1:4] print(fruits2) # apple strawberry waxberry # 可以通过完整切片操作来复制列表 fruits3 = fruits[:] print(fruits3) # ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya', 'pear', 'mango'] fruits4 = fruits[-3:-1] print(fruits4) # ['pitaya', 'pear'] # 可以通过反向切片操作来获得倒转后的列表的拷贝 fruits5 = fruits[::-1] print(fruits5) # ['mango', 'pear', 'pitaya', 'waxberry', 'strawberry', 'apple', 'grape'] # 合并列表 list3.extend(list1) print(list3) # 列表排序 list3.sort(reverse=True) sorted(list3) ############################################################################# # 生成式和生成器 f = [x + y for x in 'ABCDE' for y in '1234567'] print(f) f = [x for x in range(1, 10)] print(f) f = [x + y for x in 'ABCDE' for y in '1234567'] print(f) # 用列表的生成表达式语法创建列表容器 # 用这种语法创建列表之后元素已经准备就绪所以需要耗费较多的内存空间 f = [x ** 2 for x in range(1, 1000)] print(sys.getsizeof(f)) # 查看对象占用内存的字节数 print(f) # 请注意下面的代码创建的不是一个列表而是一个生成器对象 # 通过生成器可以获取到数据但它不占用额外的空间存储数据 # 每次需要数据的时候就通过内部的运算得到数据(需要花费额外的时间) f = (x ** 2 for x in range(1, 1000)) print(sys.getsizeof(f)) # 相比生成式生成器不占用存储数据的空间 print(f) for val in f: print(val)
false
5e1e2e536787176e984cd8c7ad63169371361fb9
anokhramesh/Calculate-Area-Diameter-and-Circumference
/calculate_area_diametre_Circumference_of_a_circle.py
466
4.5625
5
print("A program for calculate the Area,Diameter and Circumference of a circle if Radius is known") print("******************************************************************************************") while True: pi = 3.14 r = float(input("\nEnter the Radius\n")) a = float(pi*r)*r d = (2*r) c = float(2*pi*r) print ("The Area of Circle is",a) print ("The Diameter of Circle is ",d) print ("The Circumference of Circle is",c)
true
b0f171588a69286bc1aaba953e45b712a23ffb66
ggrossvi/core-problem-set-recursion
/part-1.py
1,130
4.3125
4
# There are comments with the names of # the required functions to build. # Please paste your solution underneath # the appropriate comment. # factorial def factorial(num): # base case if num < 0: raise ValueError("num is less than 0") elif num == 0: # print("num is 0") return 1 # print(num - 1) #recursive return factorial(num -1) * num # reverse def factorial(num): # base case if num < 0: raise ValueError("num is less than 0") elif num == 0: # print("num is 0") return 1 # print(num - 1) #recursive return factorial(num -1) * num # bunny def bunny(count): #base case if count == 0: return 0 if count == 1: return 2 #recursive return bunny(count-1) + 2 # is_nested_parens def is_nested_parens(parens): #base cases - stopping condition if parens == "": return True if parens[0] != "(": return False if parens[-1] != ")": return False #recursion return True and is_nested_parens(parens[1:-1])
true
1be9a89c5edc52c684a62dcefcdd417a418ef797
aayishaa/aayisha
/factorialss.py
213
4.1875
4
no=int(input()) factorial = 1 if no < 0: print("Factorrial does not exist for negative numbers") elif no== 0: print("1") else: for i in range(1,no+ 1): factorial = factorial*i print(factorial)
true
557db6014ade0a2fc318b675bdc3fbf6aa9b3d30
JonasJR/zacco
/task-1.py
311
4.15625
4
str = "Hello, My name is Jonas" def reverseString(word): #Lets try this without using the easy methods like #word[::-1] #"".join(reversed(word)) reversed = [] i = len(word) while i: i -= 1 reversed.append(word[i]) return "".join(reversed) print reverseString(str)
true
e1cdeb27240a29c721298c5e69193576da556861
brunacorreia/100-days-of-python
/Day 1/finalproject-band-generator.py
565
4.5
4
# Concatenating variables and strings to create a Band Name #1. Create a greeting for your program. name = input("Hello, welcome to the Band Generator! Please, inform us your name.\n") #2. Ask the user for the city that they grew up in. city = input("Nice to meet you, " + name + "! Now please, tell us the city you grew up in.\n") #3. Ask the user for the name of a pet. pet = input("What's your pet's name?\n") #4. Combine the name of their city and pet and show them their band name. result = input("Cool! Your band name should be " + city + " " + pet + ".")
true
557e4d43a305b7ddcfe16e6151d7523468417278
axxypatel/Project_Euler
/stack_implementation_using_python_list.py
1,550
4.4375
4
# Implement stack data structure using list collection of python language class Stack: def __init__(self): self.item_list = [] def push(self, item): self.item_list.append(item) def pop(self): self.item_list.pop() def isempty(self): return self.item_list == [] def peek(self): return self.item_list[len(self.item_list)-1] def size(self): return len(self.item_list) def test_stack_class(): sample_object = Stack() sample_object.push(4) sample_object.push('dog') sample_object.push(4.7777) print("Added the value:", sample_object.item_list) sample_object.pop() print("Remove the top value:", sample_object.item_list) print("Show the top value:", sample_object.peek()) print("Size the stack:", sample_object.size()) if sample_object.isempty(): print("Stack is empty") else: print("Stack is not empty") def check_balanced_parentheses(parentheses_string): test_object = Stack() string_len = len(parentheses_string) status = True for temp in range(0, string_len): temp_char = parentheses_string[temp] if temp_char == "(": test_object.push(temp_char) else: if test_object.isempty(): status = False else: test_object.pop() if test_object.isempty() and status: return True else: return False print(check_balanced_parentheses('((()))')) print(check_balanced_parentheses('(()))'))
true
ed16d51907433405f06402bff946b63fc38a78dc
julianhyde/seb
/python_work/factor.py
1,678
4.125
4
# # # We want to print: # # a c e # ---- + ---- = ---- # b d f # # For example, given (3, 4, 1, 10), we should print # # 3 1 17 # ---- + ---- = ---- # 4 10 20 # def add_fractions(a, b, c, d): (e, f) = (c * b + a * d, b * d) # print(f"e={e},f={f}") g = gcd(e, f) return (int(e / g), int(f / g)) def gcd(e, f): if e == 0: if f == 0: return 1 # special case: gcd(0, 0) is 1 else: return f # special case: gcd(0, x) is x elif e < 0: return gcd(-e, f) elif f < 0: return gcd(e, -f) elif e == f: return e elif e < f: return gcd(e, f - e) else: return gcd(e - f, f) def check(success): if not success: raise Exception('failed!') check(9 == gcd(0, 9)) check(1 == gcd(0, 0)) check(1 == gcd(0, 1)) check(7 == gcd(0, 7)) check(2 == gcd(10, 8)) check(1 == gcd(1, 1)) check(4 == gcd(4, 4)) check(10 == gcd(30, 70)) check(1 == gcd(7, 4)) check(4 == gcd(8, 4)) check(1 == gcd(10, 21)) check((5, 4) == add_fractions(1, 2, 3, 4)) check((2, 1) == add_fractions(1, 1, 1, 1)) check((7, 12) == add_fractions(1, 3, 1, 4)) check((17, 20) == add_fractions(3, 4, 1, 10)) check((1, 1) == add_fractions(2, 3, 1, 3)) check((0, 1) == add_fractions(2, 3, -2, 3)) check((0, 1) == add_fractions(2, 3, -4, 6)) a = int(input("Top 1? ")) # print(a) b = int(input("Bottom 1? ")) # print(b) c = int(input("Top 2? ")) # print(c) d = int(input("Bottom 2? ")) # print(d) (e, f) = add_fractions(a, b, c, d) print("") print(f"{a:4} {c:4} {e:4}") print(" ---- + ---- = ----") print(f"{b:4} {d:4} {f:4}") print("")
false
20bdc091aa5936ed6cfbcec4f285e9337f6040c2
arkharman12/oop_rectangle
/ooprectangle.py
2,518
4.34375
4
class Size(object): #creating a class name Size and extending it from object def __init__(self, width=0, height=0): #basically it inherts whatever is defined in object self.__width = width #object is more than an simple argument self.__height = height def setWidth(self, width): self.__width = width #defining setters and getters functions for def getWidth(self): #width and Height and returning the value return self.__width #to use it later def setHeight(self, height): self.__height = height def getHeight(self): return self.__height width = property(fset = setWidth, fget = getWidth) height = property(fset = setHeight, fget = getHeight) class Rectangle(Size): #creating a class name Rectangle with a single argument def __init__(self, width=0, height=0): #of Size that way I can use the value of Size in this new class Size.__init__(self, width, height) def getArea(self): return self.width * self.height #area of a rectangle is width * height def setArea(self, area): print("Area is something that cannot be set using a setter.") def getPerimeter(self): return 2 * (self.width + self.height) #perimeter of a rectangle is 2 * (width + height) def setPerimeter(self, area): print("Perimeter is something that cannot be set using a setter.") area = property(fget = getArea, fset = setArea) perimeter = property(fget = getPerimeter, fset = setPerimeter) def getStats(self): print("width: {}".format(self.width)) print("height {}".format(self.height)) #defining a new function getStats with self print("area: {}".format(self.area)) #and printing the values for width, height, print("perimeter: {}".format(self.perimeter)) #perimeter and area def main(): print ("Rectangle a:") a = Rectangle(5, 7) print ("area: {}".format(a.area)) print ("perimeter: {}".format(a.perimeter)) #the whole main function was given to us print ("") print ("Rectangle b:") b = Rectangle() b.width = 10 b.height = 20 print (b.getStats()) main()
true
6ba40eec4a91f64bb1675e456566f2018de3c835
f73162818/270201070
/lab7/ex2.py
322
4.125
4
def is_prime(a): if a <= 1: return False for i in range(2,a): if a%i == 0: return False return True def print_primes_between(a,b): for i in range(a,b): if is_prime(i): print(i) a = int(input("Enter a number:")) b = int(input("Enter another number:")) print_primes_between(a,b)
true
76a39ca0738ac7528aa266fcda8343f5e65ba1e8
Jerasor01924/NikolasEraso
/ajedrez.py
2,256
4.4375
4
'''Descripción: Reeborg se mueve horizontal o verticalmente en linea recta en un campo de 8*8 de ajedrez, desde cualquier posición, según una direccion y el número de pasos a avanzar Pre: Reeborg debe mirar al norte y esta en la posicion (2,1) Reeborg recibe el parametro de direccion siendo direccion = 1 = --| direccion = 2 = - | | direccion = 3= - | | Pos: Reeborg llega la posición deseada y retorna verdadera Reeborg se retorna a la posición de inicio y retorna false Reeborg mira al norte Si puede moverse retorna verdadero. Fecha: 26/08/2019 autores: Julian Ortiz Juan Pablo Nikolas Eraso ''' def girar_derecha() : repeat 3: turn_left() def girar_180(): turn_left() turn_left() def mueve_caballo(direccion): contador = 0 while front_is_clear(): if direccion==1: girar_derecha() move() move() turn_left() move() if object_here(): print("No puedo moverme por que esta ocupado") girar_180() move() girar_derecha() move() move() return False elif direccion==2: move() move() girar_derecha() move() if object_here(): print("No puedo moverme por que esta ocupado") girar_180() move() turn_left() move() move() girar_180() return False elif direccion==3: move() move() turn_left() move() if object_here(): print("No puedo moverme por que esta ocupado") girar_180() move() girar_derecha() move() move() return False return True mueve_caballo(3) ################################################################ # WARNING: Do not change this comment. # Library Code is below. ################################################################
false
b68fa443c48907700332320459f7583e1d288f8a
Ealtunlu/GlobalAIHubPythonCourse
/Homeworks/day_5.py
1,358
4.3125
4
# Create three classes named Animals, Dogs and Cats Add some features to these # classes Create some functions with these attributes. Don't forget! You have to do it using inheritance. class Animal: def __init__(self,name,age): self.name = name self.age = age def is_mammel(self): return None class Dogs(Animal): def __init__(self,name,age): super().__init__(name,age) def speak(self): return "Woof" def likes_walks(self): return True def is_good_boy(self): return True def is_mammel(self): return True class Cats(Animal): def __init__(self,name,age): super().__init__(name,age) def speak(self): return "Meow!" def likes_sleeping(self): return True def is_mammel(self): return True cliffard = Dogs("Cliffard",3) leo = Cats("Leo",2) print("*"*50) print(f"Name is {cliffard.name} , Age is {cliffard.age}") print(f"Cliffard says {cliffard.speak()}") print(f"Cliffard likes walks : {cliffard.likes_walks()}") print(f"Cliffard is a Mammel : {cliffard.is_mammel()}") print("*"*50) print(f"Name is {leo.name} , Age is {leo.age}") print(f"Leo says {leo.speak()}") print(f"Leo likes sleeping : {leo.likes_sleeping()}") print(f"Leo is a Mammel : {leo.is_mammel()}") print("*"*50)
true
b5fd6cb27a327d0cede09f3eb7dbf5d6569cc63d
roselandroche/cs-module-project-recursive-sorting
/src/sorting/sorting.py
1,182
4.28125
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): # Your code here merged_arr = [] x = y = 0 while x < len(arrA) and y < len(arrB): if arrA[x] < arrB[y]: merged_arr.append(arrA[x]) x += 1 else: merged_arr.append(arrB[y]) y += 1 merged_arr.extend(arrA[x:]) merged_arr.extend(arrB[y:]) return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # Your code here if len(arr) <= 1: return arr midpoint = len(arr) // 2 lhs = merge_sort(arr[:midpoint]) rhs = merge_sort(arr[midpoint:]) return merge(lhs, rhs) # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input # def merge_in_place(arr, start, mid, end): # Your code here # def merge_sort_in_place(arr, l, r): # Your code here arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7] print(arr1) print(merge_sort(arr1))
true
7b071815a5785d809e38d2a4d64c1199c8c9b250
xlxmht/DS
/Sorting/bubblesort.py
450
4.3125
4
def bubble_sort(arr): is_swapped = True while is_swapped: is_swapped = False for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: swap(i, i + 1, arr) is_swapped = True return arr def swap(i, j, arr): arr[i], arr[j] = arr[j], arr[i] return arr input_array = [8, 5, 2, 9, 5, 6, 3] # input_array = [8, 5, 2] sorted_array = bubble_sort(input_array) print(sorted_array)
false