blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
12e5e732c419b74b89317f85d2a55fc440f93dde
kvguarin/Recursion-Examples
/lab8.py
1,854
4.375
4
def main(): #1test recursive printing n = input("Enter a number: ") rprint(int(n)) #2test recursive multiplication x = input("Enter a number: ") y = input("Enter a number: ") print(rmultiplication(int(x), int(y))) #3test out recursive lines n = input("Enter a number: ") rlines(int(n)) #4test out largest list item n = input("Enter a list of numbers: ") n = n.split(",") n = [int(i) for i in n] print(listItem(n)) # #5test out recursive list item n = input("Enter a list of numbers: ") n = n.split(",") n = [int(i) for i in n] print(rListSum(n)) #6test out sum of numbers n = input("Enter a number: ") print(sumofNumbers(int(n))) #7 test out recursive power method x = input("Enter a number: ") y = input("Enter an exponent: ") print(rpower(int(x), int(y))) #recursive printing def rprint(n): if n ==0: return rprint(n - 1) print(n) #recursive multiplication def rmultiplication(x, y): if y == 0: return 0 result = x + rmultiplication(x, y-1) return result #recursive lines def rlines(n): if n == 0: return 0 rlines(n -1) list = n while list > 0: print("*", end="") list = list -1 print(end="\n") #4 largest list item def listItem(n): if len(n)==1: return n[0] n.sort() result = listItem(n[1:]) return result #5 recursive list sum def rListSum(n): if len(n) == 0: return 0 result = n[0] + rListSum(n[1:]) return result #6 sum of numbers def sumofNumbers(n): if n ==0: return 0 result = n + sumofNumbers(n - 1) return result #7 recursive power method def rpower(x,y): if y ==0: return 1 result = x * rpower(x, y-1) return result main()
false
f9eb94c80dc1c3ecb13f02972c98c3f9f7a98adb
acode-pixel/YT_Tutorials
/Python/Password Generator/passwordgen.py
938
4.4375
4
import random import string import pyperclip # pip install pyperclip # Alphabet, letters will be picked out of this randomly alphabet = string.ascii_letters + string.digits + string.digits + string.punctuation # Output password password = "" # Desired password length password_length = 0 # Try to parse password length from user try: password_length = int(input("Please input password length: ")) # The intered input was not a number, error thrown by the int() conversion attempt except: print("The entered input was not a number") exit() # Randomly pick out characters out of the alphabet for a in range(0,password_length): password += alphabet[random.randint(0,len(alphabet)-1)] user_input = input("Do you want the password to be shown? y/n: ") pyperclip.copy(password) if 'y' in user_input: print("The generated password is: %s" % password) else: print("The password was copied to the clipboard!")
true
0843641cd5ea25605cacc906a8ab988d83e20afb
kaiqinhuang/Python_hw
/lab8.py
1,348
4.40625
4
""" lab8.py Name: Kaiqin Huang Date: 1/17/2017 A module of functions count_merge(), count_as(), and split_evens(). """ def count_merge(set1, set2): '''Merges two sets and returns the length of the new set Args: set1 and set2: Two sets Returns: len: The length of the merged set ''' my_set = set1 my_set_new = my_set.union(set2) return len(my_set_new) def count_as(string_list): '''Counts how many times lower case letter "a" appears in the string list Args: string_list: A list of strings Returns: num_as: Counter of how many times letter "a" appears ''' num_as = 0 for s in string_list: num_as += s.count("a") return num_as def split_evens(int_list): '''Splits an integer list into an even number list and a odd number list Args: int_list: A list of integers Returns: even_list: A list of even numbers in the given integer list odd_list: A list of odd numbers in the given integer list ''' even_list = [] odd_list = [] for i in int_list: if i % 2 == 0: even_list.append(i) else: odd_list.append(i) return (even_list, odd_list)
true
08f51d0480b9941cb45193217932ed301858120e
broepke/GTx
/part_2/3.4.3_leap_year.py
1,529
4.6875
5
# A year is considered a leap year if it abides by the # following rules: # # - Every 4th year IS a leap year, EXCEPT... # - Every 100th year is NOT a leap year, EXCEPT... # - Every 400th year IS a leap year. # # This starts at year 0. For example: # # - 1993 is not a leap year because it is not a multiple of 4. # - 1996 is a leap year because it is a multiple of 4. # - 1900 is not a leap year because it is a multiple of 100, # even though it is a multiple of 4. # - 2000 is a leap year because it is a multiple of 400, # even though it is a multiple of 100. # # Write a function called is_leap_year. is_leap_year should # take one parameter: year, an integer. It should return the # boolean True if that year is a leap year, the boolean False # if it is not. # Write your function here! def is_leap_year(year): if year % 100 == 0: if year % 400 == 0: return True else: return False elif year % 4 == 0: return True else: return False # Below are some lines of code that will test your function. # You can change the value of the variable(s) to test your # function with different inputs. # # If your function works correctly, this will originally # print False, True, False, and True, each preceded by the # label "[year] is a leap year:". print("1993 is a leap year:", is_leap_year(1993)) print("1996 is a leap year:", is_leap_year(1996)) print("1900 is a leap year:", is_leap_year(1900)) print("2000 is a leap year:", is_leap_year(2000))
true
d230225cc9bbc3dbc9f78411744aae6a13d87b14
broepke/GTx
/part_1/2.2.5_printing_variable_labels.py
1,444
5.03125
5
my_int1 = 1 my_int2 = 5 my_int3 = 9 # You may modify the lines of code above, but don't move them! # When you Submit your code, we'll change these lines to # assign different values to the variables. # # The code above creates three variables: my_int1, my_int2, # and my_int3. Each will always be an integer # # Now, add three lines of code that will print the values # of those three variables with "my_int1:", "my_int2:", and # "my_int3:" labeling the output. So, if the variables' values # were 1, 5, and 9, your lines would print: # # my_int1: 1 # my_int2: 5 # my_int3: 9 # Add your lines of code here! print("my_int1:", my_int1) print("my_int2:", my_int2) print("my_int3:", my_int3) # Next, these lines of code will modify the values of those # three variables. You don't need to worry about how these # work. We'll talk about it in the next couple chapters. my_int1 += 5 my_int2 *= 3 my_int3 **= 2 # Now, copy and paste the same lines from above into the lines # below. This way, your output will show you the new values of # these variables. # Add your lines of code here! print("my_int1:", my_int1) print("my_int2:", my_int2) print("my_int3:", my_int3) # If your code works correctly, then when run, it should print: # my_int1: 1 # my_int2: 5 # my_int3: 9 # my_int1: 6 # my_int2: 15 # my_int3: 81 # # This should be the output when Running. When Submitting, # we'll test your code with other values of these three # variables.
true
c85f996ea4ff3b1e73c3a6b4714613206ef35cbe
broepke/GTx
/part_3/4.5.9_word_length.py
2,263
4.21875
4
# Recall last exercise that you wrote a function, word_lengths, # which took in a string and returned a dictionary where each # word of the string was mapped to an integer value of how # long it was. # # This time, write a new function called length_words so that # the returned dictionary maps an integer, the length of a # word, to a list of words from the sentence with that length. # If a word occurs more than once, add it more than once. The # words in the list should appear in the same order in which # they appeared in the sentence. # # For example: # # length_words("I ate a bowl of cereal out of a dog bowl today.") # -> {3: ['ate', 'dog', 'out'], 1: ['a', 'a', 'i'], # 5: ['today'], 2: ['of', 'of'], 4: ['bowl'], 6: ['cereal']} # # As before, you should remove any punctuation and make the # string lowercase. # # Hint: To create a new list as the value for a dictionary key, # use empty brackets: lengths[wordLength] = []. Then, you would # be able to call lengths[wordLength].append(word). Note that # if you try to append to the list before creating it for that # key, you'll receive a KeyError. # Write your function here! def length_words(a_string): a_string = a_string.replace(".", "") a_string = a_string.replace("!", "") a_string = a_string.replace("'", "") a_string = a_string.replace(",", "") a_string = a_string.replace("?", "") a_string = a_string.lower() string_list = a_string.split() string_dict = {} for word in string_list: try: if string_dict[len(word)]: string_dict[len(word)].append(word) except: string_dict[len(word)] = [] string_dict[len(word)].append(word) return string_dict # Below are some lines of code that will test your function. # You can change the value of the variable(s) to test your # function with different inputs. # # If your function works correctly, this will originally # print: # {1: ['i', 'a', 'a'], 2: ['of', 'of'], 3: ['ate', 'out', 'dog'], 4: ['bowl', 'bowl'], 5: ['today'], 6: ['cereal']} # # The keys may appear in a different order, but within each # list the words should appear in the order shown above. print(length_words("I ate a bowl of cereal out of a dog bowl today."))
true
37051b0a6dba88f6aab62a6a1d08e897ca8b71f1
broepke/GTx
/final_problem_set/2_moon_moon.py
2,828
4.625
5
# A common meme on social media is the name generator. These # are usually images where they map letters, months, days, # etc. to parts of fictional names, and then based on your # own name, birthday, etc., you determine your own. # # For example, here's one such image for "What's your # superhero name?": https://i.imgur.com/TogK8id.png # # Write a function called generate_name. generate_name should # have two parameters, both strings. The first string will # represent a filename from which to read name parts. The # second string will represent an individual person's name, # which will always be a first and last name separate by a # space. # # The file with always contain 52 lines. The first 26 lines # are the words that map to the letters A through Z in order # for the person's first name, and the last 26 lines are the # words that map to the letters A through Z in order for the # person's last name. # # Your function should return the person's name according to # the names in the file. # # For example, take a look at the names in heronames.txt # (look in the drop-down in the top left). If we were to call # generate_name("heronames.txt", "Addison Zook"), then the # function would return "Captain Hawk": Line 1 would map to # "A", which is the first letter of Addison's first name, and # line 52 would map to "Z", which is the first letter of # Addison's last name. The contents of those lines are # "Captain" and "Hawk", so the function returns "Captain Hawk". # # You should assume the contents of the file will change when # the autograder runs your code. You should NOT assume # that every name will appear only once. You may assume that # both the first and last name will always be capitalized. # # HINT: Use chr() to convert an integer to a character. # chr(65) returns "A", chr(90) returns "Z". # Add your code here! def generate_name(file_name, name): hero_file = open(file_name, "r") hero_list = [] for lines in hero_file: hero_list.append(lines.rstrip("\n")) name_list = name.split() first_char = name_list[0] first_char = first_char[:1] first_char = ord(first_char) - 65 last_char = name_list[1] last_char = last_char[:1] last_char = ord(last_char) - 39 hero_first_name = hero_list[first_char] hero_last_name = hero_list[last_char] hero_file.close() return hero_first_name + " " + hero_last_name # Below are some lines of code that will test your function. # You can change the value of the variable(s) to test your # function with different inputs. # # If your function works correctly, this will originally # print: Captain Hawk, Doctor Yellow Jacket, and Moon Moon, # each on their own line. print(generate_name("heronames.txt", "Bddison Rook")) print(generate_name("heronames.txt", "Uma Irwin")) print(generate_name("heronames.txt", "David Joyner"))
true
1f76b2f5c2026de6f80747b54d5514580d7a02ab
broepke/GTx
/part_2/3.4.12_vowels_and_consonants.py
1,615
4.40625
4
# In this problem, your goal is to write a function that can # either count all the vowels in a string or all the consonants # in a string. # # Call this function count_letters. It should have two # parameters: the string in which to search, and a boolean # called find_consonants. If find_consonants is True, then the # function should count consonants. If it's False, then it # should instead count vowels. # # Return the number of vowels or consonants in the string # depending on the value of find_consonants. Do not count # any characters that are neither vowels nor consonants (e.g. # punctuation, spaces, numbers). # # You may assume the string will be all lower-case letters # (no capital letters). # Add your code here! def count_letters(a_string, find_consonants): str_len = len(a_string) num_vowels = 0 are_vowels = ["a", "e", "i", "o", "u"] num_spaces = 0 total = 0 # count the vowels for i in a_string: if i in are_vowels: num_vowels += 1 # get the number of spaces for i in a_string: if i == " ": num_spaces += 1 # generate the total if find_consonants: total = str_len - num_vowels - num_spaces else: total = num_vowels return total # Below are some lines of code that will test your function. # You can change the value of the variable(s) to test your # function with different inputs. # # If your function works correctly, this will originally # print 14, then 7. a_string = "up with the white and gold" print(count_letters(a_string, True)) print(count_letters(a_string, False))
true
f4d20669a86ca333aab2533c2009c25f9648ae00
broepke/GTx
/part_2/3.4.8_bood_pressure.py
1,425
4.21875
4
# Consult this blood pressures chart: http://bit.ly/2CloACs # # Write a function called check_blood_pressure that takes two # parameters: a systolic blood pressure and a diastolic blood # pressure, in that order. Your function should return "Low", # "Ideal", "Pre-high", or "High" -- whichever corresponds to # the given systolic and diastolic blood pressure. # # You should assume that if a combined blood pressure is on the # line between two categories (e.g. 80 and 60, or 120 and 70), # the result should be the higher category (e.g. Ideal and # Pre-high for those two combinations). # # HINT: Don't overcomplicate this! Think carefully about in # what order you should check the different categories. This # problem could be easy or extremely hard depending on the # order you change and whether you use returns or elifs wisely. # Add your code here! def check_blood_pressure(sys, dia): if sys >= 140 or dia >= 90: return "High" elif sys >= 120 or dia >= 80: return "Pre-high" elif sys >= 90 or dia >= 60: return "Ideal" else: return "Low" # Below are some lines of code that will test your function. # You can change the value of the variable(s) to test your # function with different inputs. # # If your function works correctly, this will originally # print: Ideal test_systolic = 110 test_diastolic = 70 print(check_blood_pressure(test_systolic, test_diastolic))
true
075ecb060a7f0b6d9cd8fa05d7da73768e32f604
broepke/GTx
/part_2/3.4.6_ideal_gas_law_2.py
1,539
4.1875
4
# Last problem, we wrote a function that calculated pressure # given number of moles, temperature, and volume. We told you # to assume a value of 0.082057 for R. This value means that # pressure must be given in atm, or atmospheres, one of the # common units of measurement for pressure. # # atm is the most common unit for pressure, but there are # others: mmHg, Torr, Pa, kPa, bar, and mb, for example. what # if pressure was sent in using one of these units? Our # calculation would be wrong! # # So, we want to *assume* that pressure is in atm (and thus, # that R should be 0.082057), but we want to let the person # calling our function change that if need be. So, revise # your find_pressure function so that R is a keyword parameter. # Its default value should be 0.082057, but the person calling # the function can override that. The name of the parameter for # the gas constant must be R for this to work. # # As a reminder, you're writing a function that calculates: # # P = (nRT) / V # # Write your function here! You may copy your work from 3.4.5 # if you'd like. def find_pressure(moles, temp, volume, R=0.082057): return moles * R * temp / volume # Below are some lines of code that will test your function. # You can change the value of the variable(s) to test your # function with different inputs. # # If your function works correctly, this will originally # print: "Result: 37168.944". test_n = 10 test_T = 298 test_V = 5 test_R = 62.364 # Torr! print("Result:", find_pressure(test_n, test_T, test_V, R=test_R))
true
2cfa42ff4415d16c64e6472d5e77a3e44a2b128f
broepke/GTx
/part_1/2.4.3_tip_tax_calculator.py
1,426
4.28125
4
meal_cost = 10.00 tax_rate = 0.08 tip_rate = 0.20 # You may modify the lines of code above, but don't move them! # When you Submit your code, we'll change these lines to # assign different values to the variables. # When eating at a restaurant in the United States, it's # customary to have two percentage-based surcharges added on # top of your bill: sales tax and tip. These percentages are # both applies to the original cost of the meal. For example, # a 10.00 meal with 8% sales tax and 20% tip would add 0.80 # for tax (0.08 * 10.00) and 2.00 for tip (0.20 * 10.00). # # The variables above create the cost of a meal and identify # what percentage should be charged for tax and tip. # # Add some code below that will print the "receipt" for a # meal purchase. The receipt should look like this: # # Subtotal: 10.00 # Tax: 0.8 # Tip: 2.0 # Total: 12.8 # # Subtotal is the original value of meal_cost, tax is the # tax rate times the meal cost, tip is the tip rate times # the meal cost, and total is the sum of all three numbers. # Don't worry about the number of decimal places; it's fine # if your code leaves off some numbers (like 0.8 for tax) or # includes too many decimal places (like 2.121212121 for tip). # Add your code here! print("Subtotal:", meal_cost) print("Tax:", meal_cost * tax_rate) print("Tip:", meal_cost * tip_rate) print("Total:", (meal_cost + (meal_cost * tax_rate)) + (meal_cost * tip_rate))
true
695f060a489383010787ba21a5b912dfd98ab83e
broepke/GTx
/part_4/5.2.6_binary.py
2,311
4.53125
5
# Recall in Worked Example 5.2.5 that we showed you the code # for two versions of binary_search: one using recursion, one # using loops. For this problem, use the recursive one. # # In this problem, we want to implement a new version of # binary_search, called binary_search_year. binary_search_year # will take in two parameters: a list of instances of Date, # and a year as an integer. It will return True if any date # in the list occurred within that year, False if not. # # For example, imagine if listOfDates had three instances of # date: one for January 1st 2016, one for January 1st 2017, # and one for January 1st 2018. Then: # # binary_search_year(listOfDates, 2016) -> True # binary_search_year(listOfDates, 2015) -> False # # You should not assume that the list is pre-sorted, but you # should know that the sort() method works on lists of dates. # # Instances of the Date class have three attributes: year, # month, and day. You can access them directly, you don't # have to use getters (e.g. myDate.month will access the # month of myDate). # # You may copy the code from Worked Example 5.2.5 and modify # it instead of starting from scratch. You must implement # binary_search_year recursively. # # Don't move this line: from datetime import date def binary_search_year(searchList, searchTerm): # First, the list must be sorted. searchList.sort() if len(searchList) == 0: return False middle = len(searchList) // 2 if searchList[middle].year == searchTerm: return True elif searchTerm < searchList[middle].year: return binary_search_year(searchList[:middle], searchTerm) else: return binary_search_year(searchList[middle + 1:], searchTerm) # Below are some lines of code that will test your function. # You can change the value of the variable(s) to test your # function with different inputs. # # If your function works correctly, this will originally # print: True, then False listOfDates = [date(2016, 11, 26), date(2014, 11, 29), date(2008, 11, 29), date(2000, 11, 25), date(1999, 11, 27), date(1998, 11, 28), date(1990, 12, 1), date(1989, 12, 2), date(1985, 11, 30)] print(binary_search_year(listOfDates, 2016)) print(binary_search_year(listOfDates, 2007))
true
81362c17cae57d883a967c67f3f9139a59e26b9a
anthonyz98/Python-Challenges
/Chapter 9 - Challenge 9-14.py
539
4.125
4
from random import randint # This is what helps me to create a random generator class Die: def roll_die(self, number_of_sides): for number in range(10): random_number = randint(1, number_of_sides) if number < 10: print("The first few choices were: " + str(random_number)) elif number == 10: print("The final choice is: " + str(random_number)) return "The final choice is " + str(random_number) roll_dice = Die().roll_die(20) print(roll_dice)
true
f48fff4737b10860529bd8f50efc880819793896
jn7163/pyinaction
/lesson10/reporting_scores_final.py
2,522
4.25
4
''' 分数处理程序最终版 文本格式如下 学号,姓名,语文,数学,英语 1,王小明,100,88,90 2,李思思,90,70,85 3,刘畅,88,78,92 ''' class ClassRoom: def __init__(self, name): self.name = name self.students = [] self.lessons = [] def __str__(self): return '班级: {}'.format(self.name) def add_student(self, no, student_name): self.students.append((no, student_name)) def add_lesson(self, lesson): self.lessons.append(lesson) def print_details(self): print(self) print('学号: 姓名 ') for no, student_name in self.students: print('{:3}: {:>5}'.format(no, student_name)) for lesson in self.lessons: lesson.summary_scores(self.students) class Lesson: def __init__(self, name): self.name = name self.scores = [] def add_score(self, score): value = int(score) if value < 0: raise ValueError('{} must above 0'.format(value)) if value > 100: raise ValueError('{} must less than 100'.format(value)) self.scores.append(value) def summary_scores(self, students): count = len(self.scores) total = 0 avg = 0 highest = max(self.scores) idx = self.scores.index(highest) for value in self.scores: total += value avg = total / count print() print(self) print('总人数:', count) print('平均分:', avg) print('最高分:', highest, students[idx][1]) def __str__(self): return '课程: {}'.format(self.name) if __name__ == "__main__": f_name = 'scores_final.txt' myclass = ClassRoom('五一班') # 读取第一行 f = open(f_name, encoding='utf-8') title_line = f.readline() lines = f.readlines() f.close() # process first line title_line = title_line.strip() titles = title_line.split(',') lessons_title = titles[2:] lessons = [] for title in lessons_title: lesson = Lesson(title) myclass.add_lesson(lesson) lessons.append(lesson) for line in lines: line = line.strip() items = line.split(',') scores = items[2:] myclass.add_student(items[0], items[1]) for i in range(len(lessons)): lessons[i].add_score(scores[i]) myclass.print_details()
false
0f5c6af7067abf2be115a148e4943a419029b725
snwalchemist/Python-Exercises
/Strings.py
2,991
4.25
4
long_string = ''' WOW O O --- ||| ''' print(long_string) first_name = 'Seth' last_name = 'Hahn' # string concatenation (only works with strings, can't mix) full_name = first_name + ' ' + last_name print(full_name) #TYPE CONVERSION #str is a built in function #coverting integer to string and checking type print(type(str(100))) #coverting integer to string and string back to integer and output checking type print(type(int(str(100)))) #ESCAPE SEQUENCE #back slash tells python whatever comes after is a string #\n tells python to start on a new license #\t tells python to tab weather1 = "it\'s \"kind of\" sunny" weather2 = "it\\s \"kind of\" sunny" weather3 = "\t it\'s \"kind of\" sunny \n hope you have a good day!" print(weather1) print(weather2) print(weather3) #FORMATTED STRINGS name = 'johnny' age = 55 print('hi ' + name + '. You are ' + str(age) + ' years old' ) #new way in python 2 called an f-string print(f'hi {name}. You are {age} years old') #old way print('hi {}. You are {} years old'.format(name, age)) #could reaarrange variables print('hi {1}. You are {0} years old'.format(name, age)) #could assign new vriables print('hi {new_name}. You are {age} years old'.format(new_name = 'Sally', age=100)) #STRING INDEXES #pythong indexes each character in a string including spaces selfish = 'me me me' print(selfish[3]) #can start and stop at different indexes selfish2 = '01234567' print(selfish2[0:8]) #***[start:stop:stepover]*** print(selfish2[0:8:2]) print(selfish2[1:]) print(selfish2[:5]) print(selfish2[::1]) print(selfish2[-1:]) print(selfish2[-2:]) #**useful notation to reverse a string print(selfish2[::-1]) #IMMUTABILITY: Strings cannot be changed #selfish3[8] = '01234567' (can't change the string to 8 here) #you can reassign the vairable like this to change it selfish2 = selfish2 + '8' print(selfish2) #LEN (LENGTH) #len doesn't start from zero greet = 'helllooooo' print(len('hellloooo')) print(greet[0:len(greet)]) #STRING METHODS #methods are owned by built-in functions quote = 'to be or not to be' print(quote.upper()) print(quote.capitalize()) #.find outputs the index of what's being found print(quote.find('be')) print(quote.replace('be', 'me')) #the quote looks like it's been changed but it's immutable so "quote" stays the same print(quote) quote2 = quote.replace('be', 'me') print(quote2) #BOOLEANS name = 'Seth' is_cool = False is_cool = True print(bool(1)) #this is True print(bool(0)) #this is False print(bool('True')) #this is True print(bool('False')) #this is also True #TYPE CONVERSION EXERCISE birth_year = input('what year were you born? -->') current_year = input('enter the current year -->') age = int(current_year) - int(birth_year) print(f'Your age is: {age}') #PASSWORD CHECKER EXERCISE username = input('username -->') password = input('password -->') password_length = len(password) secret_password = '*' * password_length print(f'{username}, your password {secret_password} is {password_length} letters long')
true
c85a823c75350ae4e867cdf035fa786d108e6ae7
alephist/edabit-coding-challenges
/python/odd_or_even_string.py
233
4.21875
4
""" Is the String Odd or Even? Given a string, return True if its length is even or False if the length is odd. https://edabit.com/challenge/YEwPHzQ5XJCafCQmE """ def odd_or_even(word: str) -> True: return len(word) % 2 == 0
true
7214521f443d6bc968cc44a96693a14ef9570085
alephist/edabit-coding-challenges
/python/give_me_even_numbers.py
387
4.15625
4
""" Give Me the Even Numbers Create a function that takes two parameters (start, stop), and returns the sum of all even numbers in the range. Notes Remember that the start and stop values are inclusive. https://edabit.com/challenge/b4fsyhyiRptsBzhcm """ def sum_even_nums_in_range(start: int, stop: int) -> int: return sum(num for num in range(start, stop + 1) if num % 2 == 0)
true
b2b884acb6b2556429015f0aeb153895a9242681
alephist/edabit-coding-challenges
/python/sweetest_ice_cream.py
1,047
4.25
4
""" The Sweetest Ice Cream Create a function which takes a list of objects from the class IceCream and returns the sweetness value of the sweetest icecream. Each sprinkle has a sweetness value of 1 Check below for the sweetness values of the different flavors. Flavors Sweetness Value Plain 0 Vanilla 5 ChocolateChip 5 Strawberry 10 Chocolate 10 https://edabit.com/challenge/uerTkWm9K3oMtMZKz """ from typing import List class IceCream: def __init__(self, flavor: str, num_sprinkles: int) -> None: self.__flavor = flavor self.__num_sprinkles = num_sprinkles @property def flavor(self) -> str: return self.__flavor @property def num_sprinkles(self) -> int: return self.__num_sprinkles def sweetest_ice_cream(lst: List[IceCream]) -> int: flavor_sweetness = { 'Plain': 0, 'Vanilla': 5, 'ChocolateChip': 5, 'Strawberry': 10, 'Chocolate': 10 } return max(flavor_sweetness[ice_cream.flavor] + ice_cream.num_sprinkles for ice_cream in lst)
true
4e10af8ac9c4715985095b319e82135c0d25f4ba
alephist/edabit-coding-challenges
/python/name_classes.py
936
4.34375
4
""" Name Classes Write a class called Name and create the following attributes given a first name and last name (as fname and lname): An attribute called fullname which returns the first and last names. A attribute called initials which returns the first letters of the first and last name. Put a . between the two letters. Remember to allow the attributes fname and lname to be accessed individually as well. https://edabit.com/challenge/kbtju9wk5pjGYMmHF """ class Name: def __init__(self, fname: str, lname: str) -> None: self.__fname = fname self.__lname = lname @property def fname(self) -> str: return self.__fname.title() @property def lname(self) -> str: return self.__lname.title() @property def fullname(self) -> str: return f"{self.fname} {self.lname}" @property def initials(self) -> str: return f"{self.fname[0]}.{self.lname[0]}"
true
1ef5f82d753596c3bab615f1a8e03b7c3a6cef95
alephist/edabit-coding-challenges
/python/longest_word.py
400
4.28125
4
""" Longest Word Write a function that finds the longest word in a sentence. If two or more words are found, return the first longest word. Characters such as apostophe, comma, period (and the like) count as part of the word (e.g. O'Connor is 8 characters long). https://edabit.com/challenge/Aw2QK8vHY7Xk8Keto """ def longest_word(sentence: str) -> str: return max(sentence.split(), key=len)
true
f9a0aaf41836d4b08beccc61fa560cc8a908daa4
alephist/edabit-coding-challenges
/python/factorize_number.py
291
4.1875
4
""" Factorize a Number Create a function that takes a number as its argument and returns a list of all its factors. https://edabit.com/challenge/dSbdxuapwsRQQPuC6 """ from typing import List def factorize(num: int) -> List[int]: return [x for x in range(1, num + 1) if num % x == 0]
true
2b3dfc742dbb00d5a3e1371026f1ed677cf70494
alephist/edabit-coding-challenges
/python/summing_squares.py
270
4.15625
4
""" Summing the Squares Create a function that takes a number n and returns the sum of all square numbers up to and including n. https://edabit.com/challenge/aqDGJxTYCx7XWyPKc """ def squares_sum(n: int) -> int: return sum([num ** 2 for num in range(1, n + 1)])
true
4427e2e6710c395ef38c7b7c255346c2e7b1b2ca
bgescami/CIS-2348
/Homework 2/Zylabs7.25.py
2,970
4.28125
4
# Brandon Escamilla PSID: 1823960 # # Write a program with total change amount as an integer input that outputs the change using the fewest coins, one coin type per line. # The coin types are dollars, quarters, dimes, nickels, and pennies. Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies. # Ex: If the input is: # # 0 # or less, the output is: # # no change # Ex: If the input is: # # 45 # the output is: # # 1 quarter # 2 dimes def exact_change(user_total): num_dollars = user_total // 100 # convert to dollars user_total %= 100 # get remainder after conversion num_quarters = user_total // 25 # convert to quarters user_total %= 25 # get remainder after conversion num_dimes = user_total // 10 # convert to dimes user_total %= 10 # get remainder after conversion num_nickels = user_total // 5 # convert to nickels user_total %= 5 # get remainder after conversion num_pennies = user_total return (num_dollars, num_quarters, num_dimes, num_nickels, num_pennies) if __name__ == '__main__': input_val = int(input()) # prompt user to input an integer num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change( input_val) # recall exact_change function # define output statements to output number of exact_change variables: # num_dollars, num_quarters, num_dimes, num_nickels, num_pennies if input_val <= 0: # if amount is zero print('no change') # print output else: if num_dollars > 1: # if number of dollars is greater than one print('%d dollars' % num_dollars) # print number of dollars elif num_dollars == 1: # if number of dollars equal 1 print('%d dollar' % num_dollars) # print dollar in singular if num_quarters > 1: # if number of quarters is greater than one print('%d quarters' % num_quarters) # print number of quarters elif num_quarters == 1: # if number of quarters equal 1 print('%d quarter' % num_quarters) # print quarter in singular if num_dimes > 1: # if number of dimes is greater than one print('%d dimes' % num_dimes) # print number of dimes elif num_dimes == 1: # if number of dimes equal 1 print('%d dime' % num_dimes) # print dime in singular if num_nickels > 1: # if number of nickels is greater than one print('%d nickels' % num_nickels) # print number of nickels elif num_nickels == 1: # if number of nickels equal 1 print('%d nickel' % num_nickels) # print nickel in singular if num_pennies > 1: # if number pennies is greater than one print('%d pennies' % num_pennies) # print number of pennies elif num_pennies == 1: # if number of pennies equal 1 print('%d penny' % num_pennies) # print penny in singular
true
138d341c3b3cab8f6cc5a21f379137c42032d202
xiaoahang/teresa
/python_exercise_solutions/lab3/soln_lab3_sec1.py
943
4.1875
4
########################### # Factorial def factorial(n): fact = 1 while n > 1: fact = fact * n n = n - 1 return fact ########################### # Guessing Game from random import randint # import statements should really be at top of file def guess(attempts,numrange): number = randint(1,numrange) print("Welcome! Can you guess my secret number?") while attempts > 0: print('You have', attempts, 'guesses remaining') guess = input('Make a guess: ') guess = int(guess) if number == guess: print("Well done! You got it right.") break elif guess < number: print("No - too low!") elif guess > number: print("No - too high!") attempts = attempts - 1 if attempts == 0: print("No more guesses - bad luck!") print("GAME OVER: thanks for playing. Bye.") ###########################
true
9c38f0a0fd982e5cfbe1c52313c58d1dcbfbc527
uzzal408/learning_python
/basic/list.py
978
4.21875
4
#asigning list list1 = ['apple','banana','orange','mango','blackberry'] print(type(list1)) print(list1) #get length of a list print(len(list1)) #create a list using list constructor list2 = list(('Juice','ice-cream',True,'43')) #accessing list print(list2[0]) #negetive indexing print(list2[-1]) #Range of index print(list1[2:5]) print(list1[:2]) print(list1[2:]) #check if exist any value if "apple" in list1: print('Yes,Apple is exist in list2') #change the value of list in specific index list1[1] = "Pineapple" print(list1) #change a range of value list1[2:4] = ["change item 1",'change item 2'] print(list1) #loop throgh list for li in list1: print(li) ## print item refering their index for li in range(len(list1)): print(list1[li]) #Print all items, using a while loop to go through all the index numbers i=0 while i<len(list1): print(list1[i]) i = i+1 #list comprehension new_list = [x for x in list1 if "p" in x] print(new_list)
true
0fe6b610f1ca3c349a9eea94e9c52b6d2bf10b41
uzzal408/learning_python
/basic/lambda.py
435
4.34375
4
#A lambda function is a small anonymous function. #A lambda function can take any number of arguments, but can only have one expression x = lambda a:a*10 print(x(5)) #Multiply argument a with argument b and return the result y = lambda a,b,c:a+b+c print(y(10,15,5)) #Example of lambda inside function def my_func(n): return lambda a:a*n my_double = my_func(2) print(my_double(35)) my_triple = my_func(3) print(my_triple(50))
true
aa242b4c078deaa804e459013c657d3672988272
AlexBarbash0118/02_Area_Perim_Calc
/03_perim_area_calculator.py
875
4.4375
4
# functions go here # checks if input is a number more than zero def num_check(question): valid = False while not valid: error = "Please enter a number that is more than zero" try: response = float(input(question)) if response > 0: return response else: print("Please enter a number that is more than zero") print() except ValueError: print(error) # Main routine goes here width = num_check("Width: ") height = num_check("Height: ") # Calculate area (width x height) area = width * height # Calculate perimeter (width x height) x 2 perimeter = 2 * (width + height) # Output area and perimeter print("Perimeter: {} units".format(perimeter)) print("Area: {} square units".format(area))
true
781712626c80e2ee3cfe2663c511ba45eed66b23
DmitrievaOlga/Python_lab
/Task_1.py
581
4.1875
4
number = int(input('Введите число ')) border_number = int(input('Введите пограничное число ')) if number < border_number: print('Ваше число меньше пограничного') elif number > border_number: if number/border_number > 3: print('Ваше число больше пограничного более, чем в три раза') else: print('Ваше число больше пограничного') else: print('Ваше число совпадает с пограничным')
false
a6bb292e99bf1955a2592bc00fa4b11e31238725
Lindaxu88/lab1-python
/main.py
551
4.40625
4
#Author: Yeman Xu ybx5148@psu.edu #Collaborator: Shiao Zhuang sqz5328@psu.edu #Collaborator: Zhihong Jiang zbj5088@psu.edu temperature = input ("Enter temperature: ") Ftemperature = float(temperature) unit = input("Enter unit in F/f or C/c: ") if unit == "c" or unit == "C": print(str(temperature) + "°" + " in Celsius is equivalent to " + str(Ftemperature*1.8+32) + "°" + " Fahrenheit.") elif unit == "f" or unit == "F": print(str(temperature) + "°" + " in Fahrenheit is equivalent to " + str((Ftemperature-32)*(5/9)) + "°" + " Celsius.") else : print(f"Invalid unit({unit}).")
false
051cd729f80322625ba31db19e952ae904e15d68
kodfactory/AdvayaGameDev
/LambdaFunction.py
624
4.1875
4
# def sum(a,b): # c = (a*2) + (b*2) # return c # sum(5,10) # Lambda function: inline function or 1 liner function # 3 -> 3**3 # def square(a): # return a**2 # print(square(5)) # Syntax: lambda a : a**2 # x = lambda a : a**2 # print(x(10)) # Filter: What is filter in python? # for i in listA: # if i%2 == 0: # print(i) # listA = [1,2,3,4,5,6,7,8,8,8] # listB = list(filter(lambda i: i%2 == 0, listA)) # print(listB) # Map: What is map? # listA = [1,2,3,4,5,6,7,8,8,8] # listB = list(map(lambda i: i**3, listA)) # print(listB) print(" --\n/ \\\n --\n /\\")
false
4e79db4cdeca3aec368c6d54c48b205af84fad0e
kodfactory/AdvayaGameDev
/SetExample.py
1,343
4.21875
4
# listB = [1,2,3] # tupleA = (1,2,3,4,5) # setA = {'test', 1, 2, 3, 4} # Set? : It is used to remove duplicate values from collection and it's and unordered collection # setA = {1,2,3,4,5,6,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5,6,6,6,6,7,7,7} # listA = [1,2,2,2,2,2,2,3,3,3,3,3,3,4,5,6,7,8,8,8] # listB = [] # for i in listA: # if i not in listB: # listB.append(i) # print(listB) # listA = [1,2,2,2,2,2,2,3,3,3,3,3,3,4,5,6,7,8,8,8] # setA = set(listA) # print(setA) ################## setA = {1,2,3,10} print("I am doing something") # setA.add(4) # setA.update([10,20,30,40,50]) # setA.update((10,20,30,40,50)) # setA.discard(100) # it will not throw error if key doesn't exist try: setA.remove(100) # it will throw error if key doesn't exist except Exception as e: print("Error") print("I have removed something") print(setA) print("End") # setA = {1,2,3} # setB = {3,4,5} # setC = {3,4,10} ## intersection (To find the common elements from two sets) # print(setA & setB) # print(setA.intersection(setB)) # setA.intersection_update(setB, setC) # {3,4} & {1,2,3} => {3} # print(setA) ## Union (Used to merge two sets) # print(setA | setB) # print(setA.union(setB)) # setA = {50,55,60,75} # setB = {75,25,58,55} # setC = {75,85,55,95,60} # setA.intersection_update(setB, setC)
true
020edcdb427275c281acb7bbbcc1246424a3997f
ChristopherSClosser/python-data-structures
/src/stack.py
1,007
4.125
4
"""Implementation of a stack.""" from linked_list import LinkedList class Stack(object): """Class for a stack.""" def __init__(self, iterable=None): """Function to create an instance of a stack.""" self.length = 0 self._stack = LinkedList() self.top = None if isinstance(iterable, (str, tuple, list)): for i in iterable: self.push(i) def pop(self): """Use LinkedList pop method.""" """Remove the head of the list and return it.""" if self.top is None: raise IndexError("List is empty, cannot pop from an empty list") val = self.top.val self.top = self.top.next_node self.length -= 1 return val def push(self, val): """Use push method from LinkedList.""" self._stack.push(val) self.top = self._stack.head def __len__(self): """Redifine the built in len function for the list.""" return self._stack.length
true
d037f7008e387b29a4ed7eb9a45c773340b286cc
pshappyyou/CodingDojang
/SalesbyMatch.py
1,405
4.15625
4
# There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. # Example # There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is . # Function Description # Complete the sockMerchant function in the editor below. # sockMerchant has the following parameter(s): # int n: the number of socks in the pile # int ar[n]: the colors of each sock # Returns # int: the number of pairs # Input Format # The first line contains an integer , the number of socks represented in . # The second line contains space-separated integers, , the colors of the socks in the pile. # Constraints # where # Sample Input # STDIN Function # ----- -------- # 9 n = 9 # 10 20 20 10 10 30 50 10 20 ar = [10, 20, 20, 10, 10, 30, 50, 10, 20] # Sample Output # 3 # https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup inX=9 inY=[10,20,20,10,10,10,30,50,10,20] uniY=set(inY) for val in uniY: cnt = 0 ans = 0 for i in range(0, len(inY)-1): if val == intY(i): cnt = cnt +1 if cnt > 2: ans = print(val)
true
78901929ac5489a5c87506dd1e9a0289d0e7cdf8
pshappyyou/CodingDojang
/LeetCode/ConvertNumbertoList.py
249
4.1875
4
num = -2019 # printing number print ("The original number is " + str(num)) # using list comprehension # to convert number to list of integers res = [int(x) for x in str(num)] # printing result print ("The list from number is " + str(res))
true
e7e6f6f920cac9d89420df579892dc4e96cfa8ef
4ug-aug/hangman
/game
2,205
4.3125
4
#! /usr/bin/env python3 #! python3 # a program to pick a random word and letting the player guess the word, uses a dictionary to replace 0'es in the word to print import random from nltk.corpus import words word_list = words.words() # Get desired level, assign variables to levels and assign a variable to the dictionary which is to hold each letter in the hidden word level = str(input('1= easy, 2=medium, 3=hard: ')) chars = {} easy = [] medium = [] hard = [] # Give the user guesses according to the desired level def playGame(): # create list for each level according to the length of the word and give the player an amount of guesses depending on the level if level == '1': for word in word_list: if len(word) < 5: easy.append(word) gWord = random.choice(easy) mg = 12 elif level == '2': for word in word_list: if len(word) < 7: medium.append(word) gWord = random.choice(medium) mg = 8 elif level == '3': for word in word_list: if 7 < len(word): hard.append(word) gWord = random.choice(hard) mg = 10 # where the guessing happens, mg = max_guesses and g = guesses so far for g in range(mg): for i in gWord: chars.setdefault(i, 0) print(chars[i], end=' ') guesses = str(g) print('\nGuesses: '+guesses) print('Guess a letter or the word!: ') guess = input() if guess == gWord: print('Good job! You did it in '+guesses+' guess(es)!') break # if the guess is one letter it will be assignes the word, if it is longer than a single letter ex: Carpenter - enter - each letter in the guess will be assigned if guess in gWord: if len(guess) < 2: print(guess+' is in the hidden word!') chars[guess] = guess mg+1 else: for letter in guess: chars[letter] = letter else: print('guess not in the word! You have '+str(mg-(g+1))+' guesses left') print('The word was '+gWord) playGame()
true
7519d41fb031a20c15612d4a57c9dc9d1fa43697
Anknoit/PyProjects
/OOPS PYTHON/OOPS_python.py
2,128
4.3125
4
#What is OOPS - Coding of objects that are used in your project numerous times so we code it one time by creating class and use it in different parts of project class Employee: #Class is a template that contains info that You can use in different context without making it everytime #These are class variables sal_increment = 2 no_of_empl = 0 def __init__(self, fname, lname, salary): #THIS __init__ is CONSTRUCTOR #This instance is for every employee, basic essential info that every employee should have #These are instance variables self.fname = fname self.lname = lname self.salary = int(salary) Employee.no_of_empl += 1 self.sal_increment = 5 #It will be taken before the class Employee by the incrment(), Comment this out to use sal_increment=2 def increment(self): #THIS IS ANOTHER METHOD self.salary = int(self.salary * self.sal_increment) #Here "self.sal_increment" is present in the instance which is the first place this function will search for "sal_incrment" if its not in it it will go for main class Employee and search. # So if you comment OUT "self.sal_increment" in increment() it will still work coz # its present in class Employee(): #THIS IS DRIVER CODE print(Employee.no_of_empl) ankit = Employee('Ankit', 'Jha', '1200000') #OBJECTS billi = Employee('Billi', 'Jackson', '1200000') #OBJECTS print(Employee.__dict__)#TO display directory of class print("All information of Employee:",ankit.__dict__) #To display whole directory of employee name Ankit print("Name of Employee:",ankit.fname) print("Number of Employees:",Employee.no_of_empl) print("Old salary:",ankit.salary) ankit.increment() print("New salary:",ankit.salary) stud = [] def entry_stud(n): """ entry_stud() takes only one argument n, which is the number of entry """ for n in range(0,n): name_studs = input("NAME: ") score_studs = input("SCORE: ") name = name_studs score = score_studs comb = (name, score) stud.append(comb) return print(stud) entry_stud(3)
true
9ffb92983051919884f5953a1f593b6ce7ac033c
Code141421425/pyPractise
/16_格式时间输出.py
2,062
4.28125
4
#https://www.runoob.com/python/python-exercise-example16.html #输出指定格式的日期。 ##分析 #以前写过: #就是以一个python相关的时间模块,提取当时具体的年,月,日,时,分,秒进行 #然后就可以随意输出了 #程序规模:随便写 import datetime year = datetime.datetime.now().year month = datetime.datetime.now().month day = datetime.datetime.now().day hour =datetime.datetime.now().hour minute =datetime.datetime.now().minute print("当前时间:%d-%d-%d %d:%d"%(year,month,day,hour,minute)) ##总结 #1.查了下,datetime比time模块更高级一些,是根据dt是根据t封装的 #python中时间日期格式化符号: # %y 两位数的年份表示(00-99) # %Y 四位数的年份表示(000-9999) # %m 月份(01-12) # %d 月内中的一天(0-31) # %H 24小时制小时数(0-23) # %I 12小时制小时数(01-12) # %M 分钟数(00=59) # %S 秒(00-59) # %a 本地简化星期名称 # %A 本地完整星期名称 # %b 本地简化的月份名称 # %B 本地完整的月份名称 # %c 本地相应的日期表示和时间表示 # %j 年内的一天(001-366) # %p 本地A.M.或P.M.的等价符 # %U 一年中的星期数(00-53)星期天为星期的开始 # %w 星期(0-6),星期天为星期的开始 # %W 一年中的星期数(00-53)星期一为星期的开始 # %x 本地相应的日期表示 # %X 本地相应的时间表示 # %Z 当前时区的名称 ##%% %号本身 print(1) print(datetime.date.today().strftime("%d/%m/%A/%z")) #3.strftime 是格式化显示时间 #4.可以创建时间对象,用以在做时间上的处理,如: # 创建日期对象 miyazakiBirthDate = datetime.date(1941, 1, 5) print(miyazakiBirthDate.strftime('%d/%m/%Y')) # 日期算术运算 miyazakiBirthNextDay = miyazakiBirthDate + datetime.timedelta(days=1) print(miyazakiBirthNextDay.strftime('%d/%m/%Y')) # 日期替换 miyazakiFirstBirthday = miyazakiBirthDate.replace(year=miyazakiBirthDate.year + 1) print(miyazakiFirstBirthday.strftime('%d/%m/%Y'))
false
a4c287127286484047e854a7342cd8f79eae0a19
Code141421425/pyPractise
/24_求数列前20项和.py
2,630
4.28125
4
#https://www.runoob.com/python/python-exercise-example24.html #有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 # #分析: # 总述:看到这题第一个反应,就是分子分母分别存在一个数组里求前n项和, # 然后在通过一个合成函数将这两个数组合并起来,求和 # 不过问题是合并的时候,肯定是除完之后,用一个小数相加,这样势必会对精准度造成影响。如果求前n项和的最大公约数分母,又会非常复杂1 # 不过想想也可以看看有没有分数相关的函数库支撑一下 # 查了一下,有个fraction的函数,可以用下。感觉还不错. # 不过这么一想,递归是不是也挺好的? # # fraction 调研 # from fractions import Fraction # f = Fraction(1,2) # print(f) # print(f.denominator) # 可以调取分母 # print(f.numerator) # 可以调取分子 # # 递归调研 # def a(x): # if x == 1: # return 1 # return x * a(x-1) # print(a(100)) # 思路:由题可得,下一项的分子是前一项的分子与分母已和,分母是前一项的分子 # ∴ an+1/bn+1 = (an + bn )/an # ∵ 首项 = 1/2 ∴ from fractions import Fraction f1 = Fraction(1,2) #f2 = Fraction(2,3) def py24(x): if x == 1: return Fraction(2,1) return Fraction(py24(x-1).denominator+py24(x-1).numerator,py24(x-1).numerator).real #+ py24(x-1) sum =0 # for i in range(1,21): # a = py24(i) # print(a) # #sum += a #print(998361233/60580520) # 第1——10 项 998361233/60580520 # # # 2 # 3/2 # 5/3 # 8/5 # 13/8 # 21/13 # 34/21 # 55/34 # 89/55 # 144/89 # 233/144 # 377/233 # 610/377 # 987/610 # 1597/987 # 2584/1597 #终于就像军少说的,递归写起来真的简单,但是性能消耗真的大。要是用一些数组来村,估计可以秒出 # 为了出个答案换种方法来一发 # denominator = [1] numerator = [2] f = [] times = 20 #得出数列 for i in range(times): numerator.append(denominator[i]+numerator[i]) denominator.append(numerator[i]) #合成二维数组 for x in range(times): f.append([numerator[x],denominator[x]]) print(f) #公倍数 def getCommonMultiple(FA,FB): return [FA[0]*FB[1]+FA[1]*FB[0],FA[1]*FB[1]] # 得出分数 sum = 0 for b in range(times-1): if b == 0: sum = getCommonMultiple(f[b],f[b+1]) else: sum = getCommonMultiple(sum,f[b+1]) print(sum) print(sum[0]/sum[1]) #302163077445280087617864490505 / 9251704366605890848773498384 # 实际上最后并没有区别[捂脸哭]
false
6d11be7b10ff8034ebe0edd99273c64104d9412f
amisha1garg/Arrays_In_Python
/BinaryArraySorting.py
1,188
4.28125
4
# Given a binary array A[] of size N. The task is to arrange the array in increasing order. # # Note: The binary array contains only 0 and 1. # # Example 1: # # Input: # N = 5 # A[] = {1,0,1,1,0} # Output: 0 0 1 1 1 # User function Template for python3 ''' arr: List of integers denoting the input array n : size of the given array You need to return the sorted binary array ''' class Solution: def sortBinaryArray(self, arr, n): # Your code here i = -1 pivot = 0 for j in range(0, len(arr)): if (arr[j] <= pivot): i += 1 arr[i], arr[j] = arr[j], arr[i] return arr # { # Driver Code Starts # Initial Template for Python 3 # Initial Template for Python 3 import math def main(): T = int(input()) while (T > 0): n = int(input()) arr = [int(x) for x in input().strip().split()] ob = Solution() res = ob.sortBinaryArray(arr, n) for i in range(n): print(res[i], end=" ") print("") T -= 1 if __name__ == "__main__": main() # } Driver Code Ends
true
a8cf5626cfd591b015537d963deb9dd08e5657eb
sanpadhy/GITSOURCE
/src/Datastructure/BinaryTree/DC247/solution.py
841
4.1875
4
# Given a binary tree, determine whether or not it is height-balanced. A height-balanced binary tree can # be defined as one in which the heights of the two subtrees of any node never differ by more than one. class node: def __init__(self, key): self.left = None self.right = None def heightofTree(root): if not root: return 0 lheight = heightofTree(root.left) rheight = heightofTree(root.right) return max(lheight, rheight)+1 def isHeightBalanced(root): if not root: return true lheight = heightofTree(root.left) rheight = heightofTree(root.right) return True if abs(lheight - rheight) < 2 else False n1 = node(23) n2 = node(14) n3 = node(25) n4 = node(39) n5 = node(47) n1.left = n2 n1.right = n3 n3.right = n4 n4.right = n5 print(isHeightBalanced(n1))
true
1478c759eba3c8ab035955abfd78e2c05f9fe706
bgenchel/practice
/HackerRank/MachineLearning/CorrelationAndRegressionLinesQuickRecap2.py
1,414
4.4375
4
""" Here are the test scores of 10 students in physics and history: Physics Scores 15 12 8 8 7 7 7 6 5 3 History Scores 10 25 17 11 13 17 20 13 9 15 Compute the slope of the line of regression obtained while treating Physics as the independent variable. Compute the answer correct to three decimal places. Output Format In the text box, enter the floating point/decimal value required. Do not leave any leading or trailing spaces. Your answer may look like: 0.255 This is NOT the actual answer - just the format in which you should provide your answer. """ import math def mean(nums): return float(sum(nums))/len(nums) def center_data(nums): m = mean(nums) return [(n - m) for n in nums] def variance(nums): m = mean(nums) variance = mean([(n - m)**2 for n in nums]) return variance def standard_deviation(nums): stdev = math.sqrt(variance(nums)) return stdev def correlation(X, Y): # pearson's correlation assert len(X) == len(Y) x = center_data(X) y = center_data(Y) top = sum([x[i]*y[i] for i in xrange(len(x))]) bottom = math.sqrt(sum([n**2 for n in x])*sum([n**2 for n in y])) return float(top)/bottom physics = [15, 12, 8, 8, 7, 7, 7, 6, 5, 3] history = [10, 25, 17, 11, 13, 17, 20, 13, 9, 15] slope = correlation(physics, history)*standard_deviation(history)/standard_deviation(physics) print "%.3f"%slope
true
07983f3a2a0469f5aebbc056e1bd5dd7cf1f3d37
ivanwakeup/algorithms
/algorithms/prep/ctci/8.2_robot_in_grid.py
2,076
4.46875
4
''' Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right. restate problem: we have a robot at a starting position in a matrix, and we need to find him a path to the end ideas: we could use a DFS to find a path, just checking boundaries along the way (We keep track of the current path with an arrays_and_strings) DFS would check almost every cell in the worst case, r*c complexity there might be multiple valid paths? 0 0 x 0 0 0 0 0 0 0 x 0 two paths in this example: one of length 5 and one of 7 alternatives: instead, we could compute the path from the end matrix[-1][-1] a path from matrix[-1][-1] must include a path from matrix[-2][-1] or matrix[-1][-2]....and so on algorithm: path(matrix, matrix[end][end]) = if exists path(matrix, matrix[end-1][end], cur_path) then cur_path + matrix[end][end] or if exists path(matrix, r, c-1) then same ''' matrix = [ [0,0,0,0,0,0,0], [1,1,0,0,0,0,0], [0,0,1,0,0,0,0], [0,0,1,0,0,0,0], [0,0,1,0,0,0,0] ] def find_path(matrix): def do_find(matrix, r, c, result, memo): if r < 0 or c < 0 or matrix[r][c] == 1: return False key = (r,c) if key in memo: print("found memo!") return False at_origin = (r == 0) and (c == 0) if at_origin or do_find(matrix, r-1, c, result, memo) or do_find(matrix, r, c-1, result, memo): result.append(key) print("find path! row {} and col {}".format(r,c)) return True memo.add(key) return False result = [] memo = set() do_find(matrix, len(matrix)-1, len(matrix[0])-1, result, memo) return result print(find_path(matrix)) ''' we've gone from a 2^(r+c) to an r*c solution, because with the memoization we only need to consider each path once '''
true
c9686fbbd56e64d04af916d2669aeaed445ef8b3
ivanwakeup/algorithms
/algorithms/binary_search/find_num_rotations.py
1,189
4.1875
4
''' given a rotated sorted array, find the number of times the array is rotated! ex: arr = [8,9,10,2,5,6] ans = rotated 3 times arr = [2,5,6,8,9,10] ans = rotated 0 times intuition: if the array is sorted (but rotated some number of times), we will have 1 element that is less than both of its neighbors! using this fact, we know we've found the min when we find an element i such that i-1 > i < i + 1 so we can use the same approach as binary search to find a given target in a rotated sorted array. ''' import logging log = logging.getLogger() def find_num_rotations(arr): lo, hi = 0, len(arr)-1 while lo<= hi: mid = (lo+hi)//2 prev,next = (mid-1)%len(arr), (mid+1)%len(arr) if prev > mid < next: return mid elif arr[mid] > arr[hi]: lo = mid + 1 else: hi = mid - 1 return lo data = [([8,9,10,2,5,6], 3), ([2,5,6,8,9,10], 0), ([1,2], 0), ([2,3,1], 2), ([8,9,10,1,2], 3), ([3,4,1], 2)] for arr, expected in data: try: assert find_num_rotations(arr) == expected except AssertionError: log.error((f"{arr} did not return expected result of {expected}")) raise
true
2cca77c1ac6730329cafbb23a02499ad0b02c48e
ivanwakeup/algorithms
/algorithms/data_structures/ivn_Queue.py
1,087
4.3125
4
class LinkedListQueue: class Node: def __init__(self, val): self.val = val self.next = None def __init__(self): self.head = None self.cur = None #you need the self.cur pointer (aka the "tail" pointer) def enqueue(self, value): if not self.head: self.head = self.Node(value) self.cur = self.head else: #when you set cur.next, head.next also is updated! this is because CUR itself is reference, but when you use self.cur.next you're actually assigning the NEXT pointer from the physical object in memory self.cur.next = self.Node(value) self.cur = self.cur.next def dequeue(self): if not self.head: raise ValueError("nope!! its not here") result = self.head.val new_head = self.head.next self.head = new_head return result queue = LinkedListQueue() queue.enqueue(-1) queue.enqueue(-2) queue.enqueue(3000) queue.enqueue(4) queue.enqueue(5) while queue.head: print(queue.dequeue())
true
b7bdee4bc45c3d4ec6e0d9a122f2b3f888669ecb
ivanwakeup/algorithms
/algorithms/prep/ctci/str_unique_chars.py
498
4.125
4
''' want to use bit masking to determine if i've already seen a character before my bit arrays_and_strings will be 26 bits long and represent whether i've seen the current character already ''' def str_unique_chars(s): bit_vector = 0 for char in s: char_bit = ord(char) - ord('a') mask = (1 << char_bit) #have we seen this bit already? if bit_vector & mask: return False bit_vector |= mask return True print(str_unique_chars("thih"))
true
35dd3ef835c6e0256b80dc62e69f02505749e604
ivanwakeup/algorithms
/algorithms/greedy_and_backtracking/letter_tile_possibilites.py
1,292
4.15625
4
''' You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make. Example 1: Input: "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: "AAABBC" Output: 188 INTUITION 1. there are some sequences that will be repeated, so if we can build the path in some order that avoids reconsidering sequences that we've already built, then we don't have to build EVERY permutation of EVERY possible ''' def numTilePossibilities(tiles): result = set() def dfs(arr, path): # this is the "backtracking" part. if we've already started # to build a path that contains a prefix we've seen before, # we KNOW we've already built anything else that path can contain # because we would've encountered it on an earlier DFS. if path in result: return if path: print(path) result.add(path) nxt = list(arr)[:] for j in range(len(nxt)): nxtpath = path + nxt[j] pas = nxt[:j] + nxt[j+1:] dfs("".join(pas), nxtpath) dfs(tiles, "") return len(result) print(numTilePossibilities("AAABDLAHDFBC"))
true
d6a029452757778866d432e9e3db3f08e20e3235
ivanwakeup/algorithms
/algorithms/prep/microsoft/lexicographically_smallest_Str.py
612
4.125
4
''' Lexicographically smallest string formed by removing at most one character. Example 1: Input: "abczd" Output: "abcd" "ddbfa" => "dbfa" "abcd" => "abc" "dcba" => "cba" "dbca" => "bca" approach: just remove the first character that we find that appears later in the alphabet than the char after it. ''' def lexicograph(s): arr = list(s) result = [] removed=False for item in arr: if result and ord(result[-1]) >= ord(item) and not removed: result.pop() removed=True result.append(item) return "".join(result) print( lexicograph("abczd") )
true
0c45d4bec9078117031e2983bd1322d3ccea2405
uyiekpen/python-assignment
/range.py
538
4.40625
4
#write a program that print the highest number from this range [2,8,0,6,16,14,1] # using the sort nethod to print the highest number in a list #declaring a variable to hold the range of value number = [2,8,0,6,16,14,1] number.sort() #displaying the last element of the list print("largest number in the list is:",number[-1]) #using the loop throught method #variable to store the largest number highest_number = number[0] for i in number: if i > highest_number: highest_number= i print("largest number is:",highest_number)
true
372c35882c20d508444ea7f46529ac4565742829
finddeniseonline/sea-c34-python.old
/students/JonathanStallings/session05/subclasses.py
2,934
4.34375
4
from __future__ import print_function import sys import traceback # 4 Questions def class_chaos(): """What happens if I try something silly, like cyclical inheritance?""" class Foo(Bar): """Set up class Foo""" color = "red" def __init__(self, x, y): self.x = x self.y = y class Bar(Foo): """Set up class Bar""" color = "green" def __init__(self, x, y): self.x = x self.y = y b = Bar(10, 5) print(b.color) def import_list_methods(): """Can I use subclassing to import built-in list methods?""" class my_list(list): """Set up my list class.""" pass a = my_list() print( u"my_list methods include: {methods}" .format(methods=dir(a)) ) def update_superclass_attributes(): """Will a changed superclass attribute update in instance?""" class Foo(object): """Set up class Foo.""" color = "red" class Bar(Foo): """Set up class Bar""" def __init__(self, x, y): self.x = x self.y = y thing = Bar(10, 20) assert(thing.color == "red") print(thing.color) Foo.color = "green" assert(thing.color == "green") print(thing.color) def update_superclass_methods(): """Will a changed superclass method update in instance?""" class Foo(object): """Set up class Foo.""" def __init__(self, x, y): """Set up class Foo.""" self.x = x self.y = y def move(self): """Move to a forward along x axis.""" print(u"Moving!") self.x += 10 def report(self): """Print out current position.""" print( u"I am at position {x}, {y}." .format(x=self.x, y=self.y) ) class Bar(Foo): """Set up class Bar.""" def __init__(self, x, y): self.x = x self.y = y def move_faster(self): """Updated move method.""" print(u"Moving faster!") self.x += 20 thing = Bar(10, 20) thing.report() thing.move() thing.report() Foo.move = move_faster thing.move() thing.report() if __name__ == '__main__': print(u"\nQuestion 1:\n") try: class_chaos() except UnboundLocalError: traceback.print_exc(file=sys.stdout) # result: This silly setup doesn't even get off the ground due to an # UnboundLocalError since Bar is reference on line 10 before assignment. print(u"\nQuestion 2:\n") import_list_methods() # result: Yes, I can. print(u"\nQuestion 3:\n") update_superclass_attributes() # result: Yes, the changes are updated in derived instances. print(u"\nQuestion 4:\n") update_superclass_methods() # result: Yes, the changes are updated in derived instances.
true
2b215df8bea9bdc218cbee6a5a43bf9d6474a00e
finddeniseonline/sea-c34-python.old
/students/MeganSlater/session05/comprehensions.py
783
4.40625
4
"""Question 1: How can I use a list comprehension to generate a mathmatical sequence? """ def cubes_by_four(num): cubes = [x**3 for x in range(num) if x**3 % 4 == 0] print cubes cubes_by_four(50) """Question 2: Can I use lambda to act as a filter for a list already in existence? """ squares = [x**2 for x in range(1, 11)] def between_30_and_70(lst): print filter(lambda x: x > 29 and x < 71, lst) between_30_and_70(squares) """Question 3: What does a a nested for loop look like when using a list comprehension? """ suits = ["S", "H", "C", "D"] faces = ['A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] def deck_of_cards(suits, faces): deck = [face + suit for suit in suits for face in faces] print deck deck_of_cards(suits, faces)
true
8c4e39374ac2c5dc102fd452b5ac4c84249c38f2
finddeniseonline/sea-c34-python.old
/students/PeterMadsen/session05/classes.py
577
4.21875
4
class TestClass(object): """ Can you overwrite the constructor function with one that contains default values (as shown below the answer is NO) The way you do it was a little confusing to me, and I hope to spend more time on it soon. """ def __init__(self, x=1, y=2): self.x = x self.y = y def multiply_values(self): return self.x * self.y # Test Code if __name__ == '__main__': FirstObj = TestClass() print(FirstObj.multiply_values()) SecondObj = TestClass(x=4, y=4) print(FirstObj.multiply_values())
true
6170427920af9ef1e1d424c9a8b903438a33a6f7
finddeniseonline/sea-c34-python.old
/students/YIGU/session03/dictionaries.py
1,647
4.4375
4
# Dictionaries and Sets questions def q1(): """What happen when I have the same keys in a dict?""" q1 = {1: 1, 2: 2, 1: 3} print q1[1] print q1 # Anwser: the key get overwrite # 3 # {1: 3, 2: 2} q1() def q2(): """Can I have dict inside of dict?""" q2 = {1: {'key1': 'a', 'key2': 'b'}, 2: {'key1': 'c', 'key2': 'd'}} print q2 # Anwser: Yes # {1: {'key1': 'a', 'key2': 'b'}, 2: {'key1': 'c', 'key2': 'd'}} q2() def q3(): """What happen when I sort by keys or values?""" q3t = {1: ('c', 'd'), 3: ('a', 'b'), 2: ('j', 'k')} q3l = {1: ['c', 'd'], 3: ['a', 'b'], 2: ['j', 'k']} q3d = {1: {'k1': 'k', 'k2': 'z'}, 2: {'k1': 'c', 'k2': 'd'}, 3: {'k1': 'a', 'k2' : 'b'}} q3mix = {1: ('c', 'd'), 3: ['a', 'b'], 2: {'k1': 'c', 'k2': 'd'}} print sorted(q3t.keys()) # a:[1, 2, 3] print sorted(q3t.values()) # a:[('a', 'b'), ('c', 'd'), ('j', 'k')] print sorted(q3l.values()) # a:[['a', 'b'], ['c', 'd'], ['j', 'k']] print sorted(q3d.values()) # a:[{'k2': 'b', 'k1': 'a'}, {'k2': 'd', 'k1': 'c'}, {'k2': 'z', 'k1': 'k'}] print sorted(q3mix.values()) # a:[{'k2': 'd', 'k1': 'c'}, ['a', 'b'], ('c', 'd')] q3() def q4(): """I don't understand pop out an arbitrary key, value pair example.""" q1 = {1: 1, 2: 2, 1: 3} q4_1 = q1.popitem() print q4_1 q1 = {1: 1, 2: 2, 1: 3} q4_2 = q1.popitem() print q4_2 q1 = {1: 1, 2: 2, 1: 3} q4_3 = q1.popitem() print q4_3 # pop out an arbitrary key = pop out an random key then turn them into tuple # I don't know when will I use it. # (2,2) # (1,1) # (1,1) q4()
false
48ef5affa92f8cc375610ecbe14852eef5aa40b4
Vahid-Esmaeelzadeh/CTCI-Python
/Chapter3/Q3_1.py
1,713
4.125
4
''' Three in One: Describe how you could use a single array to implement three stacks. ''' # region fixed-size class fixedMultiStack: def __init__(self, stackSize: int): self.numberOfStacks = 3 self.stackCapacity = stackSize self.values = [None for _ in range(stackSize * self.numberOfStacks)] self.sizes = [0 for _ in range(self.numberOfStacks)] def push(self, stackNum: int, value: int): if self.isFull(stackNum): print("Error! the stack is full.") return self.sizes[stackNum] += 1 self.values[self.indexOfTop(stackNum)] = value def pop(self, stackNum: int) -> int: if self.isEmpty(stackNum): print("Error! the stack is empty.") return value = self.values[self.indexOfTop(stackNum)] self.values[self.indexOfTop(stackNum)] = None self.sizes[stackNum] -= 1 # shrink return value def peek(self, stackNum: int) -> int: if self.isEmpty(stackNum): print("Error! the stack is empty.") return return self.values[self.indexOfTop(stackNum)] def isEmpty(self, stackNum: int) -> bool: return self.sizes[stackNum] == 0 def isFull(self, stackNum: int) -> bool: return self.sizes[stackNum] == self.stackCapacity def indexOfTop(self, stackNum: int) -> int: return (stackNum * self.stackCapacity) + self.sizes[stackNum] - 1 # endregion multiStack1 = fixedMultiStack(3) multiStack1.push(0, 1) multiStack1.push(0, 2) multiStack1.push(1, 4) multiStack1.push(2, 7) print(multiStack1.pop(0)) print(multiStack1.sizes) print(multiStack1.pop(2)) print(multiStack1.sizes) # endregion
true
38fa747ccf995ee04a0aa5e771b85882e03daed1
Vahid-Esmaeelzadeh/CTCI-Python
/Chapter8/Q8_2.py
2,495
4.25
4
''' Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits"such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right. S 1 1 1 1 1 1 1 1 0 1 1 0 0 1 0 1 1 0 1 1 1 0 0 0 1 1 D ''' # region Recursive approach def pathFinder(maze): path = [] if len(maze) == 0: return path pathFinder_helper(maze, len(maze) - 1, len(maze[0]) - 1, path) return path def pathFinder_helper(maze, r, c, path): if (maze[r][c] is False) or r < 0 or c < 0: return False isOrigin = (r == 0 and c == 0) if isOrigin or pathFinder_helper(maze, r, c-1, path) or pathFinder_helper(maze, r-1, c, path): path.append((r, c)) return True return False maze = [[True, True, True, False, True, True, True, True], [True, True, True, False, True, True, False, True], [True, False, True, True, True, False, False, True], [True, False, False, False, True, False, True, True], [True, True, True, False, True, True, True, True]] print(pathFinder(maze)) # endregion # solve in opposite direction def robot_in_grid(maze): path = [] if len(maze) == 0: return path helper(maze, 0, 0, path) return path[::-1] def helper(maze, r, c, path): if r >= len(maze) or c >= len(maze[0]) or maze[r][c] is False: return False if (r == len(maze) - 1 and c == len(maze[0]) - 1) or helper(maze, r+1, c, path) or helper(maze, r, c+1, path): path.append((r, c)) return True return False print(robot_in_grid(maze)) # endregion # region Dynamic programming approach def pathFinder_DP(maze): if len(maze) == 0: return [] path = [] failedPoints = set() pathFinder_helper_DP(maze, len(maze) - 1, len(maze[0]) - 1, path, failedPoints) return path def pathFinder_helper_DP(maze, r, c, path, failedPoints): if (maze[r][c] is False) or r < 0 or c < 0: return False if (r, c) in failedPoints: return False isOrigin = (r == 0 and c == 0) if isOrigin or pathFinder_helper_DP(maze, r, c-1, path, failedPoints) or pathFinder_helper_DP(maze, r-1, c, path, failedPoints): path.append((r, c)) return True failedPoints.add((r, c)) # cache the failed point return False print(pathFinder_DP(maze))
true
ef29d4ff21ae527067dddfc8d8de956102d6dccf
Vahid-Esmaeelzadeh/CTCI-Python
/Chapter3/Q3_4.py
1,258
4.21875
4
''' Queue via Stack: Implement a MyQueue class which implements a queue using two stacks. ''' class stackQueue: def __init__(self, capacity): self.capacity = capacity self.pushStack = [] self.popStack = [] def add(self, val): if self.isFull(): print("The stackQueue is full.") return self.pushStack.append(val) def remove(self): if self.isEmpty(): print("The stackQueue is empty.") return self.moveElements() return self.popStack.pop() def isEmpty(self): if len(self.pushStack) + len(self.popStack) == 0: return True return False def isFull(self): if len(self.pushStack) + len(self.popStack) >= self.capacity: return True return False def moveElements(self): if len(self.popStack) == 0: length = len(self.pushStack) for i in range(length): self.popStack.append(self.pushStack.pop()) stkQueue1 = stackQueue(10) stkQueue1.add(1) stkQueue1.add(2) stkQueue1.add(3) stkQueue1.add(4) print(stkQueue1.remove()) print(stkQueue1.remove()) print(stkQueue1.remove()) print(stkQueue1.remove()) print(stkQueue1.remove())
true
fba8aca7b4a8ecaac6249ef3196599f404bf2194
zhangsong1417/xx
/nested.py
213
4.125
4
nested = [[1,2],[3,4],[5]] def flatten(nested): for sublist in nested: for element in sublist: yield element for num in flatten(nested): print(num) print(list(flatten(nested)))
false
94014789fe3a5e8d575dfe704cd5ed21fac51d60
Ompragash/python-ex...
/HCF_of_a_given_number.py
407
4.21875
4
#Python Program to find H.C.F of a given number def compute(x, y): if x < y: smaller = x else: smaller = y for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf n1 = int(input("Enter the first number: ")) n2 = int(input("Enter the second number: ")) print("The H.C.F of a given number",n1,"and",n2,"is",compute(n1, n2))
true
1ad981e7d96940aedadaeb8f229916923b489054
Ompragash/python-ex...
/Fibonacci.py
393
4.375
4
#Python program to find the fibonacci of a given number nterm = eval(input("Enter the number: ")) a, b = 0, 1 if nterm <= 0: print("Please enter a positive number") elif nterm == 1: print("Fibonacci sequence upto",nterm,":") print(a) else: print("Fibonacci sequence upto",nterm,":") while a < nterm: print(a,end=' ') nth = a + b a, b = b, a+b
true
ecacc443035b003d0f728d9b3dc49b453aceb32b
GyutaeSon/hello-world
/noc_09.py
1,383
4.25
4
#スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し, # それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ. # ただし,長さが4以下の単語は並び替えないこととする. # 適当な英語の文(例えば”I couldn’t believe that I could actually # understand what I was reading : the phenomenal power of the human mind .”)を与え, # その実行結果を確認せよ #ランダム import random def narabi(bun) : #文字列をスペースで区切ってリスト化 waketa = bun.split() res = [] for i in waketa: t = len(i) moji = [] #文字数が4以上か判別 if t > 4 : s = list(i) moji.append(s[0]) #先頭と末尾以外の文字をランダムで選択 m = s[1:t-1] r = ''.join(random.sample(m, len(m))) moji.append(r) moji.append(s[t-1]) moji = ''.join(moji) res.append(moji) else : res.append(i) #リストを文字列に変更 out = ' '.join(res) return out sen = """I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .""" kaeta = narabi(sen) print("原文:",sen) print("替え:",kaeta)
false
332dd9a117679d63899f56acb6699d00948e104f
jadentheprogrammer06/lessons-self-taught-programmer
/ObjectOrientedProgramming/ch14moar_oop/square_list.py
652
4.21875
4
# we are creating a square_list class variable. An item gets appended to this class variable list every time a Square object gets created. class Square(): square_list = [] def __init__(self, name, sidelength): self.name = name self.sl = sidelength self.slstr = str(self.sl) self.square_list.append(self.name) print(self.square_list) # every time we print the object we want it to print the object dimensions def __repr__(self): return ' by '.join([self.slstr, self.slstr, self.slstr, self.slstr]) square = Square('square', 10) print(square) square2 = Square('square2', 20) print(square2)
true
896f1909793a98e532b0bfbfa90e645af68819ff
jadentheprogrammer06/lessons-self-taught-programmer
/IntroToProgramming/ch4questions_functions/numsquare.py
312
4.125
4
def numsquared(): ''' asks user for input of integer number. returns that integer squared. ''' while 1 > 0: try: i = int(input('what number would you like to square? >>> ')) return i**2 except (ZeroDivisionError, ValueError): print('Invalid Input, sir. Please try again') print(numsquared())
true
8a7daf6d4675b3be76e8b1457087b7cf728f59e1
blissfulwolf/code
/hungry.py
338
4.125
4
hungry = input("are you hungry") if hungry=="yes": print("eat burger") print("eat pizza") print("eat fries") else: thirsty=input("are you thirsty?") if thirsty=="yes": print("drink water") print("drink soda") else: tired=input("are you tired") if tired=="yes": print("Go to sleep")
true
515e10e395e15408b7552d46d53e95d690aea87a
xuetingandyang/leetcode
/quoraOA/numOfEvenDigit.py
545
4.125
4
from typing import List class Solution: def numEvenDigit(self, nums:List[int]) -> int: """ Find how many numbers have even digit in a list. Ex. Input: A = [12, 3, 5, 3456] Output: 2 Sol. Use a for loop """ count = 0 for num in nums: for char in str(num): if int(char) % 2 == 0: count += 1 break return count test = Solution() print(test.numEvenDigit([13456, 2456, 661, 135, 235]))
true
2ce8e58e240f67128711f9c3f345cc5e867d3abd
CdtDelta/YOP
/yop-week3.py
917
4.15625
4
# This is a script to generate a random number # and then convert it to binary and hex values # # Licensed under the GPL # http://www.gnu.org/copyleft/gpl.html # # Version 1.0 # Tom Yarrish import random # This function is going to generate a random number from 1-255, and then # return the decimal,along with the corresponding binary and hexidecimal value def random_number_generator(): ran_decimal = random.randint(1, 255) return (ran_decimal, bin(ran_decimal), hex(ran_decimal)) numbers_start = 0 numbers_end = 40 # We're going to open a file to write the output too and then run the # random number generator function with open("random_list.txt", "w") as ran_file: ran_file.write("Decimal\t\t\tBinary\t\t\tHexadecimal\n") while numbers_start < numbers_end: results = random_number_generator() ran_file.write("{}\t\t\t{}\t\t\t{}\n".format(*results)) numbers_start += 1
true
881419414edbdc56e6b5a20db9766c19d5540643
BJahanyar/Data_Mining_Exercises
/2) Class_Excerise/EX_02/EX_05.py
1,100
4.21875
4
Row = int(input("Please Enter Row Number:")) #تعداد درایه های یک سطر را بگیر Col = int(input("Please Enter Col Number:")) #تعداد درایه های یک ستون را بگیر Main = [] #یک آرایه برای نگهداری ماتریس ایجاد کن for i in range(Row): #حلقه را تا کمتر از عدد سطر تکرار کن TempRow = [] # یک آرایه برای نگه داری سطر ایجاد کن for j in range(Col): # حلقه را تا کمتر از عدد ستون تکرار کن TempRow.append(int(input())) #عددی که کاربر وارد کرده را به آرایه تمپ اضافه کن Main.append(TempRow) #عددی که کاربر وارد کرده را به آرایه مین اضافه کن print('___________Main Matris___________' ) print(Main) #آرایه مین را چاپ کن Mysparse = [] for i in range(Row): for j in range(Col): if Main[i][j] != 0: Temp = [i,j,Main[i][j]] Mysparse.append (Temp) print('___________Sparse Matris___________' ) print(Mysparse)
false
6ae9b4424765d3a40efa4499ea723fbcf802a5ad
EngiBarnaby/Geekbrains_Practice
/Lesson_3/Task_3.py
496
4.40625
4
""" 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. """ def my_func(num1, num2, num3): sort_nums = (sorted((num1, num2, num3))) return sort_nums[-1] + sort_nums[-2] print(my_func(int(input("Введите число: ")), int(input("Введите число: ")), int(input("Введите число: "))))
false
dd9d5cd2d32fb92c288624ded6f3fc678f6491c2
EngiBarnaby/Geekbrains_Practice
/Lesson_3/Task_1.py
628
4.1875
4
""" 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. """ def my_func(num_1, num_2): try: res = num_1 / num_2 print(res) except ZeroDivisionError: print("Деление на 0 запрещено") my_func(int(input("Введите делимое число: ")), int(input("Введите делитель: ")))
false
2135c333157d201c6a62a194fd6867ca853d1ce7
nakednamor/naked-python
/samples/dictionary.py
575
4.3125
4
# a Java.Map equivalent in Python is called 'Dictionary' my_dict = {'some-key' : 'some-value', 'another-key' : 'another-value'} print(my_dict) # get the value by key using brackets print(my_dict['another-key']) # you can loop through all keys for k in my_dict.keys(): print(k) # ommiting .keys() loops also on keys for k in my_dict: print(k) # you can loop through all values for v in my_dict.values(): print("this is a map value: " + v) # you can loop through all key-values for k, v in my_dict.items(): print("key: " + k + ", with value: " + v)
false
23a4519c0d8cdcb3ee96fb3aec1ce39f06786d24
marilyn1nguyen/Love-Letter
/card.py
2,696
4.3125
4
#Represents a single playing card class Card: def __init__(self): """ Constructor for a card name of card rank of card description of card """ self.name = "" self.rank = 0 self.description = "" def getName(self) -> str: """ Returns name of card """ return self.name def getRank(self) -> int: """ Returns rank of card """ return self.rank def getDescription(self) -> str: """ Returns description of card """ return self.description def displayCard(self): """ Displays card's details """ print(" Name: ", self.name) print(" Rank: ", self.rank) print("Description: ", self.description) print("") # specific playing cards class Princess(Card): def __init__(self): Card.__init__(self) self.name = "Princess" self.rank = 8 self.description = "If you discard this card, you are out of the round." class Countess(Card): def __init__(self): Card.__init__(self) self.name = "Countess" self.rank = 7 self.description = "If you have this card and the King or Prince in your hand, you must discard this card." class King(Card): def __init__(self): Card.__init__(self) self.name = "King" self.rank = 6 self.description = "Trade hands with another player of your choice." class Prince(Card): def __init__(self): Card.__init__(self) self.name = "Prince" self.rank = 5 self.description = "Choose any player (including yourself) to discard his or her hand and draw a new card." class Handmaid(Card): def __init__(self): Card.__init__(self) self.name = "Handmaid" self.rank = 4 self.description = "Until your next turn, ignore all effects from other players' cards." class Baron(Card): def __init__(self): Card.__init__(self) self.name = "Baron" self.rank = 3 self.description = "You and another player secretly compare hands. The player with the lower value is out of the round." class Priest(Card): def __init__(self): Card.__init__(self) self.name = "Priest" self.rank = 2 self.description = "Look at another player's hand." class Guard(Card): def __init__(self): Card.__init__(self) self.name = "Guard" self.rank = 1 self.description = "Name a non-Guard card and choose a player. If that player has that card, he or she is out of the round."
true
d4ca90349aec7b230c1bf3a23626c318a5ae4ae5
AngelPerezRodriguezRodriguez/CYPAngelPRR
/libro/problemas_resueltos/capitulo3/3_08.py
278
4.125
4
num = int(input("Ingresa un número entero: ")) if num > 0: while num != 1: print(num) if (-1) ** num > 0: num = num / 2 else: num = num * 3 + 1 print(num) else: print("Tienes que ingresar un número entero positivo")
false
d72b4aa2724dcbffa282f956563e814c3197f125
AngelPerezRodriguezRodriguez/CYPAngelPRR
/Python/Listas/introListas.py
1,086
4.5625
5
print("###Listas") lista = [] #Primera forma de representar una lista lista2 = list() #Segunda forma de representar una lista #Función constructor print(lista) print(lista2) numeros = [2,5,6,8,5,6,3,9,1,9] #Cada uno de elos elementos, al igual que los strings, están INDEXADOS print(numeros) print(numeros[2])#6 print(numeros[-1])#9 #Slicing print() print("###Listas con slicing") print(numeros[2:5:]) print(numeros[1:9:]) print(numeros[:-6:-1]) #Se pueden almacenar elementos de diferentes tipos de elementos #Incluso SUBLISTAS print() print("###Almacenaje de diferentes tipos de elementos") cosas = ["Angel",14.5,18,True,None,[1,2,3,4,5]] print(cosas) print(cosas[3]) print(cosas[5]) print(cosas[5][2]) #Selección de elementos de una sublista #Son mutables. Se puede modificar cualquiera de los valores #Los STRINGS NO son MUTABLES, las LISTAS SI print() print("###Se puede modificar cualquiera de los valores") print("Valores base:") print(cosas) print() print("Cambios:") cosas[1] = 33 print(cosas) cosas[3] = False print(cosas)
false
7af4cb1f0415adbcebf55ea3434d9e383303a6df
ask902/AndrewStep
/practice.py
1,132
4.21875
4
''' Practice exercises for lesson 3 of beginner Python. ''' # Level 1 # Ask the user if they are hungry # If "yes": print "Let's get food!" # If "no": print "Ok. Let's still get food!" inp = input("Are you hungry? ") if inp == "yes": print("Lets get food") elif inp == "no": print("Ok,Lets still get food") # Level 2 # Ask the user if it is cold and if it is snowing # If cold and snowing, print "Put on a hat and jacket" # If only cold, print "Put on a jacket" # If only snowing, print "Put on a hat" # Otherwise, print "Have fun outside!" is_cold = input("Is it cold outside? ") if is_cold= is_snowy = input("Is it snowy outside? ") # Level 3 # Ask the user for their first and last name # If the user's first name comes before their last name # in the alphabet, print "first", otherwise "long" # If the length of the first name is greater, print "long first", # if the last name is longer, print "long last", otherwise print "equal" first = input("First name: ") last = input("Last name: ") A= True B= False print("Are you hungry?") print("If yes, let's get food; ")
true
b1b6b2ec0a6dbf6c5c2615b4c85f2e6b46e4bf48
INF1007-2021A/2021a-c01-ch4-exercices-naname1
/exercice.py
2,474
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def is_even_len(string: str) -> bool: if((len(string) % 2) == 0): return True return False def remove_third_char(string: str) -> str: resultat = "" for k in range(0, len(string)): if k == 2: continue resultat += string[k] #return string[0,2]+string[3:] return resultat def replace_char(string: str, old_char: str, new_char: str) -> str: resultat = "" for k in range(0, len(string)): if string[k] == old_char: resultat += new_char continue resultat += string[k] return resultat def get_number_of_char(string: str, char: str) -> int: resultat = 0 for lettre in string: if lettre == char: resultat += 1 return resultat def get_number_of_words(sentence: str, word: str) -> int: resultat = 0 # ou si on assume que les mots sont séparer par des espaces: # split_sentence = sentence.split() # count = 0 # for w in split_sentence: # if w == word: # count += 1 # return count for k in range(0,len(sentence)): if sentence[k] == word[0]: #Verifier si le mot est trop long pour rentrer entre la fin de la chaine et la ou on est if len(sentence) < k + len(word): break #Verifier le mot for j in range(1,len(word)): if sentence[k+j] != word[j]: k += j break if j == len(word)-1: k += j resultat += 1 return resultat def main() -> None: chaine = "Bonjour!" if is_even_len(chaine): print(f"Le nombre de caractère dans la chaine {chaine} est pair") else: print(f"Le nombre de caractère dans la chaine {chaine} est impair") chaine = "salut monde!" print(f"On supprime le 3e caratère dans la chaine: {chaine}. Résultat : {remove_third_char(chaine)}") chaine = "hello world!" print(f"On remplace le caratère w par le caractère z dans la chaine: {chaine}. Résultat : {replace_char(chaine, 'w', 'z')}") print(f"Le nombre d'occurrence de l dans hello est : {get_number_of_char(chaine, 'l')}") chaine = "Baby shark doo doo doo doo doo doo do" print(f"L'occurence du mot doo dans la chaine {chaine} est: {get_number_of_words(chaine, 'doo')}") if __name__ == '__main__': main()
false
74ad71ebae96038fba59c54e75bd676c323e4dbe
hariharaselvam/python
/day3_regex/re1_sumof.py
424
4.34375
4
import re print "Problem # 1 - regular expression" print "The sum of numbers in a string" s=raw_input("Enter a string with numbers ") #pat=raw_input("Enter the patten : ") pat=r"\b\d+\b" list_of_numbers=re.findall(pat,s) result=0 print list_of_numbers for l in list_of_numbers: result=result+float(l) print "The given string is",s print "The list of numbers are",list_of_numbers print "The sum of the numbers are:",result
true
631942833993b241647c3c853987bcdf1150eeab
hariharaselvam/python
/day6_logics/nextprime.py
400
4.21875
4
def isprime(num): for i in range(2,num): if num % i ==0: return False return True def nextprime(num): num=num+1 while isprime(num)!= True: num=num+1 return num number=input("Enter a number : ") if isprime(number): print "The number ",number," is a prime" else: print "The number ",number," is not a prime" next=nextprime(number) print "The next prime number of " ,number," is ",next
true
b996f6cf67a24047ffb3d6934b37e5acd76869e1
PravinSelva5/OneMonth
/Python/my_math.py
318
4.15625
4
''' + plus - minus / divide * multiplication % modulo ** exponents < less than > greater than ''' print("what is the answer to life, the universe, and everything?", int((40 + 30 - 7) * 2 / 3)) print("Is it true that 5 * 2 > 3 * 4") print(5 * 2 > 3 * 4) print("What is 5 * 2?", 5 * 2) print("What is 3 * 4?", 3 * 4)
false
7321b3bc2e47878871a7ae29d87794c33b852211
iot49/iot49
/boards/esp32/libraries/lib/ranges.py
656
4.1875
4
def linrange(start, stop, n=10): '''generator for n evenly spaced numbers from start to stop Example: >>> list(linrange(2, 7, 5)) [2.0, 3.25, 4.5, 5.75, 7.0] ''' assert n > 0 step = (stop-start)/(n-1) if n>1 else 0 for i in range(n): yield start + i * step def logrange(start, stop, n=10): '''generator for n logarithmically spaced numbers from start to stop Example: >>> list(logrange(10, 1000, 3)) [10, 100.0, 1000.0] ''' assert n > 0 assert start > 0 assert stop > 0 factor = (stop/start)**(1/(n-1)) x = start for i in range(n): yield x x *= factor
false
72f2efd27f13893f6bd688f920b9f8ce0b49f84a
root-11/graph-theory
/tests/test_facility_location_problem.py
1,231
4.21875
4
from examples.graphs import london_underground """ The problem of deciding the exact place in a community where a school or a fire station should be located, is classified as the facility location problem. If the facility is a school, it is desirable to locate it so that the sum of distances travelled by all members of the communty is as short as possible. This is the minimum of sum - or in short `minsum` of the graph. If the facility is a firestation, it is desirable to locate it so that the distance from the firestation to the farthest point in the community is minimized. This is the minimum of max distances - or in short `minmax` of the graph. """ def test_minsum(): g = london_underground() stations = g.minsum() assert len(stations) == 1 station_list = [g.node(s) for s in stations] assert station_list == [(51.515, -0.1415, 'Oxford Circus')] def test_minmax(): g = london_underground() stations = g.minmax() assert len(stations) == 3 station_list = [g.node(s) for s in stations] assert station_list == [(51.5226, -0.1571, 'Baker Street'), (51.5142, -0.1494, 'Bond Street'), (51.5234, -0.1466, "Regent's Park")]
true
8a31884880e53891dd239b99ce032f21edac2c8b
atlasbc/mit_6001x
/exercises/week3/oddTuples.py
475
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 19 15:22:02 2017 @author: Atlas """ def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' # Your Code Here tupplelist=[] print("This is the length of tuple", len(aTup)) for i in range(len(aTup)): print(aTup[i]) if i % 2 == 0: print(i) tupplelist.append(aTup[i]) return tuple(tupplelist) print(oddTuples((8,)))
true
cfa4c33da903fc9bb86a278369d276635fab0ac4
yuangaonyc/lynda_python
/up_n_running_with_py/date_time_n_datetime.py
2,657
4.1875
4
from datetime import date from datetime import time from datetime import datetime def main(): # Date Objects # get today's date today = date.today() print("Today's date is " + str(today)) # get individual components of today's date print("Date Components: " + str(today.day) + " " + str(today.month) + " " + str(today.year)) # retrieve today's weekday (0 = Monday, 6 = Sunday) print("Today's weekday #: " + str(today.weekday())) # Datetime Objects # get today's date using datetime today = datetime.now() print("The current datetime is " + str(today)) d = datetime.date(today) print("The current date is " + str(d)) # get the current time t = datetime.time(today) print("The current time is " + str(t)) # get the current weekday w = date.weekday(today) days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] print("The current weekday is " + str(days[w])) # Formatting now = datetime.now() print("%Y: " + now.strftime("%Y")) print("%a, %d, %B, %y: " + now.strftime("%a, %d, %B, %y")) print("local formatting %c: " + now.strftime("%c")) print("local formatted date %x: " + now.strftime("%x")) print("local formatted time %X: " + now.strftime("%X")) print("%I:%M:%S %p: " + now.strftime("%I:%M:%S %p")) print("%H:%M: " + now.strftime("%H:%M")) # Timedeltas from datetime import timedelta print("timedelta: " + str(timedelta(days=365, hours=5, minutes=1))) print("one year from now it will be: " + str(datetime.now() + timedelta(days=365))) print("two weeks and 3 days it will be: " + str(datetime.now() + timedelta(weeks=2, days=3))) t = datetime.now() - timedelta(weeks=1) s = t.strftime("%A %B %d, %Y") print("one week ago it was: " + s) # how many days until april fool's day today = date.today() afd = date(today.year, 4, 1) if afd < today: print("April Fool's Day already went by %d days ago" %(today-afd).days) afd = date(afd.year+1, 4, 1) time_to_afd = afd - today print("next April Fool's Day is %d days away" %time_to_afd.days) # Calendars import calendar c = calendar.TextCalendar(calendar.SUNDAY) str1 = c.formatmonth(2016, 11, 0, 0) print(str1) hc = calendar.HTMLCalendar(calendar.SUNDAY) str1 = hc.formatmonth(2016, 11) print(str1) for i in c.itermonthdays(2013, 8): print(i) # print out the first Friday of every month for m in range(1,13): cal = calendar.monthcalendar(2013,m) weekone = cal[0] weektwo = cal[1] if weekone[calendar.FRIDAY] != 0: meetday = weekone[calendar.FRIDAY] else: meetday = weektwo[calendar.FRIDAY] print("%10s %2d" %(calendar.month_name[m], meetday)) if __name__ == "__main__": main()
false
8f19194bd265ecd11ea80e6c07601ba32ba79871
24gaurangi/Python-practice-scripts
/Capitalize.py
581
4.40625
4
''' This program takes the input string and capitalizes first letter of every word in the string ''' # Naive approach def LetterCapitalize(str): new_str="" cc=False for i in range(len(str)): if i == 0: new_str=new_str + str[i].upper() elif str[i] == " ": cc=True new_str=new_str + str[i] elif cc: new_str=new_str + str[i].upper() cc=False else: new_str=new_str + str[i] return new_str print(LetterCapitalize(input("Please enter a string to capitalize\n")))
true
2682fe48af90b3441b789048b092ab00b4c45b57
k4rm4/Python-Exercises
/esercizio27.py
391
4.375
4
#scrivi una funzione a cui passerai come parametro una stringa e ti restituirà #una versione della stessa stringa al contrario (esempio "abcd" --> "dcba") def reverse (stringa): stringaReverse = "" for i in range(len(stringa)-1,-1,-1): stringaReverse = stringaReverse + stringa[i] print(stringaReverse) stringa = input("Inserisci una stringa: \n") reverse(stringa)
false
07ae78f4bf5326346ccd4ce4833b110369b963d4
onestarYX/cogs18Project
/my_module/Stair.py
2,834
4.46875
4
""" The file which defines the Stair class""" import pygame class Stair(pygame.sprite.Sprite): # The number of current stairs existed in the game current_stairs = 0 color = 255, 255, 255 def __init__(self, pos, screen, speed = 10): """ Constructor for Stair objects ===== Parameters: pos--tuple: The tuple which contains two integers to tell Stair's initial coordinates. screen--Surface: The main screen of the program which is used to pass the size speed--Int: The initial speed of stairs going up. """ pygame.sprite.Sprite.__init__(self) # Define an area of rectangle and fill it with color to represent # our stairs. self.image = pygame.Surface([80, 8]) self.image.fill(Stair.color) # Wrap up the stair image with rectangle and move it to its initial # position self.rect = self.image.get_rect().move(pos[0], pos[1]) self.area = screen.get_rect() self.speed = speed def update(self): """ This function tells us how Stair objects would update for every frame ===== Parameters: None ===== Returns: None """ # In every the stairs just move up by their speed. self.rect = self.rect.move(0, -self.speed) # Check whether or not the stair has left the screen. If # it does, destruct itself and remove it from every sprite # groups. if self.rect.bottom < self.area.top: self.kill() Stair.current_stairs -= 1 def set_speed_lv1(self): """ The function which increases stair speed to level 1. ===== Parameters: None ===== Returns: None """ self.speed = 4 def set_speed_lv2(self): """ The function which increases stair speed to level 2. ===== Parameters: None ===== Returns: None """ self.speed = 6 def get_pos(self): """ This function returns the position of the stair. ===== Parameters: None ===== Returns: A tuple which contains the coordinates of the stair's rectangle's top left point. """ return (self.rect.left, self.rect.top) def get_rect(self): """ The function which returns a stair's rectangle. ===== Parameters: None ===== Returns: A rect object which wraps up some stair """ return self.rect
true
2b1a87af8a0346792ac0f2777d4d63929786819f
alaesbayji/atelier1-atelier2
/ex1 Atelier2.py
824
4.4375
4
#Exercice1 Atelier2 list1 = [3, 6, 9, 12, 15, 18, 21] list2 = [4, 8, 12, 16, 20, 24, 28] res = list() #declarer une liste vide odd_elements = list1[1::2] #une liste qui commence par l'element de position 1 de la liste 1 et saute par 2 print("Element at odd-index positions from list one") print(odd_elements) even_elements = list2[0::2] #une liste qui commence par l'element de position 0 de la liste 2 et saute par 2 print("Element at even-index positions from list two") print(even_elements) #donc la liste even-element prende les valeurs des element : 0,2,4,6 print("Printing Final third list") res.extend(odd_elements) #ajouter les elements de la liste odd_element res.extend(even_elements) #ajouter les elements de la liste even_element apres avoir deja ajouter les element de odd_element print(res)
false
250b3ad85be16616693856b593611dd01b6d179a
anax32/pychain
/pychain/chain.py
2,917
4.25
4
""" Basic blockchain data-structure A block is a dictionary object: ``` { "data": <some byte sequence>, "time": <timestamp>, "prev": <previous block hash> } ``` a blockchain is a sequence of blocks such that the hash value of the previous block is used in the definition of the current block hash, in pseudocode: ``` block(n+1)["prev"] = hash(block(n)) ``` """ import hashlib import logging from .genesis_blocks import default_genesis_fn from .hash import SimpleHash from .block import SimpleBlockHandler logger = logging.getLogger(__name__) class Chain: """ Chain class creates and manages a blockchain data structure in memory """ def __init__(self, genesis_fn=None, hash_fn=None, block_fn=None): """ genesis_fn: the function which creates the genesis block hash_fn: function to compute the block hash (any hashlib function will work) block_fn: object providing interface to block creation and serialisation TODO: change this to block_create_fn, block_read_fn etc, so we can disable creation/serialisation optionally? """ self.blocks = [] if genesis_fn is None: self.genesis_fn = default_genesis_fn if genesis_fn is None else genesis_fn else: self.genesis_fn = genesis_fn if hash_fn is None: self.hash_fn = SimpleHash(ignore_keys=["hash"]) else: self.hash_fn = hash_fn if block_fn is None: self.block_fn = SimpleBlockHandler() else: self.block_fn = block_fn # get a genesis block g = self.genesis_fn() g["hash"] = self.hash_fn(g) self.blocks.append(g) def __len__(self): """ return length of the chain """ return len(self.blocks) def append(self, data): """ create a block containing data and append to the chain """ block = self.block_fn.create(data) block["prev"] = self.blocks[-1]["hash"] block["hash"] = self.hash_fn(block) self.blocks.append(block) def validate(self): """ validate all the blocks in a chain object """ p_hash = self.hash_fn(self.blocks[0]) for idx, block in enumerate(self.blocks[1:]): b_hash = self.hash_fn(block) logger.info("block[%i]: [%s] %s" % (idx, block["prev"], block["hash"])) if block["prev"] != p_hash: logger.error( "block.prev != hash (%s != %s)" % (str(block["prev"]), str(p_hash)) ) raise Exception() if block["hash"] != b_hash: logger.error( "block.hash != hash (%s != %s)" % (str(block["hash"]), str(b_hash)) ) raise Exception() p_hash = b_hash return True
true
aef397049e77a5080a5530d9d100c62e5cd05049
milfordn/Misc-OSU
/cs160/integration.py
2,799
4.125
4
def f1(x): return 5*x**4+3*x**3-10*x+2; def f2(x): return x**2-10; def f3(x): return 40*x+5; def f4(x): return x**3; def f5(x): return 20*x**2+10*x-2; # Main loop while(True): # get function from user (or quit, that's cool too) fnSelect = input("Choose a function (1, 2, 3, 4, 5, other/quit): ") selectedFn = "" if(fnSelect == "" or fnSelect[0] < '1' or fnSelect[0] > '5'): break; elif fnSelect == "1": selectedFn = "5x^4 + 3x^3 - 10x + 2" elif fnSelect == "2": selectedFn = "x^2 - 10" elif fnSelect == "3": selectedFn = "40x + 5" elif fnSelect == "4": selectedFn = "x^3" elif fnSelect == "5": selectedFn = "20x^2 + 10x - 2" # get trapezoid or rectabgle mode mTrapz = False; mRect = False; while(not (mTrapz or mRect)): mode = input("Would you like to calculate the area using rectangles, trapezoids, or both (1, 2, 3): "); if(mode == "1" or mode == "3"): mRect = True; if(mode == "2" or mode == "3"): mTrapz = True; # get number of trapezoids and rectangles numTrapz, numRects = 0, 0 while(mTrapz and numTrapz == 0): try: numTrapz = int(input("How many trapezoids do you want? ")) except(ValueError): print("Not a Number") while(mRect and numRects == 0): try: numRects = int(input("How many rectangles do you want? ")) except(ValueError): print("Not a Number") # get start and end points while(True): try: start = float(input("Please select a starting point: ")) break; except(ValueError): print("Not a Number"); while(True): try: end = float(input("Please select an ending point: ")) break; except(ValueError): print("Not a Number"); #start integration #Rectangles if(mTrapz): trapWidth = (end - start) / numTrapz accum = 0; x = start; while(x < end): xn = x + rectWidth; if(fnSelect == "1"): accum += (f1(x) + f1(xn)) * trapWidth / 2; elif(fnSelect == "2"): accum += (f2(x) + f2(xn)) * trapWidth / 2; elif(fnSelect == "3"): accum += (f3(x) + f3(xn)) * trapWidth / 2; elif(fnSelect == "4"): accum += (f4(x) + f5(xn)) * trapWidth / 2; elif(fnSelect == "5"): accum += (f5(x) + f5(xn)) * trapWIdth / 2; x += trapWidth; print("The area under "+selectedFn+" between "+str(start)+" and "+str(end)+" is "+str(accum)) #Trapezoids if(mRect): rectWidth = (end - start) / numRects accum = 0; x = start; while(x<end): if(fnSelect == "1"): accum += (f1(x)) * rectWidth; elif(fnSelect == "2"): accum += (f2(x)) * rectWidth; elif(fnSelect == "3"): accum += (f3(x)) * rectWidth; elif(fnSelect == "4"): accum += (f4(x)) * rectWidth; elif(fnSelect == "5"): accum += (f5(x)) * rectWIdth; x += rectWidth; print("The area under "+selectedFn+" between "+str(start)+" and "+str(end)+" is "+str(accum));
true
d3c88dd9ea3d2223577142bfde8531a9c510f86c
J-Molenaar/Python_Projects
/02_Python_OOP/Bike.py
778
4.1875
4
class Bike(object): def __init__(self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print self.price print self.max_speed print self.miles def ride(self): print "Riding" self.miles += 10 return self def reverse(self): print "Reversing" if (self.miles > 0): self.miles -= 5 else: print "You have no where left to go..." return self bike1 = Bike(150, "30 mph") bike2 = Bike(200, "45 mph") bike3 = Bike(250, "60 mph") bike1.ride().ride().ride().reverse().displayInfo() bike2.ride().ride().reverse().reverse().displayInfo() bike3.reverse().reverse().reverse().displayInfo()
true
e904af6b143e0576e75e0a7854d7e89a03d0f8a8
HeidiTran/py4e
/Chap4Ex6computePay.py
440
4.125
4
# Pay computation with time-and-a-half for over-time try: hours = int(input("Please enter hours: ")) rate_per_hour = float(input("Please enter rate per hour: ")) if hours > 40: overtime_rate_per_hour = rate_per_hour * 1.5 print("Gross pay is: ", round(40*rate_per_hour + (hours-40)*overtime_rate_per_hour, 2)) else: print("Gross pay is: ", round(hours*rate_per_hour, 2)) except: print("Error, please enter numeric input")
true
3d6d2f81aae823ee65c3b1d23cb0e72e6947bc1c
HeidiTran/py4e
/Chap8Ex6calMinMax.py
509
4.34375
4
# This program prompts the user for a list of # numbers and prints out the maximum and minimum of the numbers at # the end when the user enters “done”. list_num = list() while True: num = input("Enter a number: ") try: list_num.append(float(num)) except: if num == "done": print("Maximum:", max(list_num)) print("Minimum:", min(list_num)) break else: print("Invalid input") continue
true
2c4c06ef8427d8b44065ecd9f831957a89c62dd4
PatchworkCookie/Programming-Problems
/listAlternator.py
716
4.15625
4
''' Programming problems from the following blog-post: https://www.shiftedup.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour Problem 2 Write a function that combines two lists by alternatingly taking elements. For example: given the two lists [a, b, c] and [1, 2, 3], the function should return [a, 1, b, 2, c, 3]. ''' import logging def alternateLists(firstList, secondList): newList = [] if len(firstList) >= len(secondList): length = len(firstList) else: length = len(secondList) for i in range(length): if len(firstList) > i: newList.append(firstList[i]) if len(secondList) > i: newList.append(secondList[i]) return newList
true
4bfa9cbe6169da66fc77958b327cfcec15d0593c
wook971215/p1_201611107
/w6main(9).py
384
4.125
4
import turtle wn=turtle.Screen() print "Sum of Multiples of 3 or 5!" begin=raw_input("input begin number:") end=raw_input("input end number:") begin=int(begin) end=int(end) def sumOfMultiplesOf3_5(begin,end): sum=0 for i in range(begin,end): if i%3==0 or i%5==0: sum=sum+i print sum return sum sumOfMultiplesOf3_5(1,1000) wn.exitonclick()
true
5d043bd427e0164684abb00dc1c2891305634955
scifinet/Network_Automation
/Python/PracticePython/List_Overlap.py
907
4.34375
4
#!/usr/bin/env python #"""TODO: Take two lists, say for example these two: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] #and write a program that returns a list that contains only the elements that #are common between the lists (without duplicates). Make sure your program works on #two lists of different sizes.""" import random def compare(): x = set() a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] print(a) print(b) for i in a: if i in b: x.add(i) print(x) def comparerand(): y = set() c = random.sample(range(1,20),3) d = random.sample(range(1,20),6) print(c) print(d) for i in c: if i in d: y.add(i) if len(y) == 0: print("No duplicates found!") else: print(y) compare() comparerand()
true
a4ab0332626eeeff5dbf28a1248837b87867a432
GenerationTRS80/Kaggle
/Kaggle_Lessons/PythonCourse/StringAndDictionaries.py
2,699
4.625
5
# Exercises hello = "hello\n\rworld" print(hello) # >> Strings are sequences # Indexing planet = 'Pluto' print(planet[0]) # Last 3 characters and first 3 characters print(planet[-3:]) print(planet[:3]) # char comprehesion loop list = [char + '!' for char in planet] print(list) # String methonds # ALL CAPS strText = "Pluto is a planet" print(strText.upper()) # Searching for the first index of a substring print('First Index = ', strText.index('plan')) print('Start with planet ', strText.startswith('planet')) # Going between strings and lists words = strText.split() print(words) # Yes, we can put unicode characters right in our string literals :) sString = ' 👏 '.join([word.upper() for word in words]) print(sString) # str.split() turns a string into a list of smaller strings, breaking on whitespace by default. datestr = '1956-01-31' year, month, day = datestr.split('-') print('Year '+year + ' Month '+month+' Day '+day) print('/'.join([year, month, day])) # Concatenate sConcatenate = planet + ' we, miss you' print(sConcatenate) intPosition = 9 sConcatenate = planet + ' You will always be the ' + \ str(intPosition) + 'th planet to me' print(sConcatenate) #Format .format() # call .format() on a "format string", where the Python values we want to insert are represented with {} placeholders. pluto_mass = 1.303 * 10**22 earth_mass = 5.9722 * 10**24 population = 52910390 # 2 decimal points 3 decimal points, format as percent separate with commas strPlutoMass = "{} weights about {: .2} kilograms ({: .3%} of earths mass). It's home to {:,} Plutonians.".format( planet, pluto_mass, pluto_mass / earth_mass, population) print(strPlutoMass) # Referring to format() arguments by index, starting from 0 s = """Pluto's as {0}. No, it's a {1}. No. it's a {1}.{0}!{1}!""" .format('planet', 'dwarf planet') print(s) # Dictionaries # data structure for mapping keys to values. numbers = {'one': 1, 'two': 2, 'three': 3} # dictionary comprehensions with a syntax similar to the list comprehensions planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] planet_to_initial = {planet: planet[0] for planet in planets} print(planet_to_initial) # in operator tells us whether something is a key in the dictionary print('Saturn' in planet_to_initial) print('Betelgeuse' in planet_to_initial) for k in numbers: print("{}={}".format(k, numbers[k])) # access a collection of all the keys or all the values with dict.keys() and dict.values() # Get all the initials, sort them alphabetically, and put them in a space-separated string. tmpInitial = ''.join(sorted(planet_to_initial.values())) print(tmpInitial)
true
9b7dc58865cca2f5ee9a8a3877e4dcc2648dab7e
tigranmovsisyan123/introtopython
/week2/homework/problem2.py
358
4.1875
4
import argparse parser = argparse.ArgumentParser() parser.add_argument("text", type=str) args = parser.parse_args() odd = int(len(args.text)-1) mid = int(odd/2) mid_three = args.text[mid-1:mid+2] new = args.text.replace(mid_three, mid_three.upper()) print("the old string", args.text) print("middle three characters", mid_three) print("the new string", new)
true
c1a8c6c1307193d59b61ce5cf82cf9143fa94c5c
ayush1612/5th-Sem
/SL-lab/PythonTest/13NovQpaper/9/9.py
1,230
4.4375
4
if __name__ == "__main__": # this line is not necessary in this program (it depicts the main function) # i) Create a dictionary atomDict = { 'Na' : 'Sodium', 'K' : 'Potassium', 'Mn' : 'Manganese', 'Mg' : 'Magnesium', 'Li' : 'Lithium' } # ii) Adding unique and duplicate elements in the dictionary print('Dictinary before :',atomDict) atomDict['He'] = 'Helium' print('Dictionary after adding a unique element :',atomDict) # a new key value pair will be added as 'He' : 'Helium' atomDict['Na'] = 'SODIUM' print('Dictionary after adding a duplicate value :',atomDict) # 'Na' value will change from 'Sodium' to 'SODIUM' # iii) Number of elements in the dictionary print('Number of Atomic Elements in the dictionary are : ',len(atomDict.items())) # iv) Ask user to enter an element and search in the dictionary searchElement = input('Enter an element to search in the dictionary:\n') if searchElement not in atomDict.keys(): #dict.keys() returns the list of keys in the doctionary print('Element not in the dictionary') else: print('Name of the element ',searchElement,' is ',atomDict[searchElement])
true
affa042743329e963d1b14e38af86e50221f96f6
PedroEFLourenco/PythonExercises
/scripts/exercise6.py
724
4.1875
4
''' My solution ''' eventualPalindrome = str(input("Give me a String so I can validate if it is a \ Palindrome: ")) i = 0 paliFlag = True length = len(eventualPalindrome) while(i < (length/2)): if eventualPalindrome[i] != eventualPalindrome[length-1-i]: print("Not a Palindrome") paliFlag = False break print(i) i += 1 if paliFlag: print("It is a Palindrome") '''Solution from exercise solutions - Actually more elegant than mine''' wrd = input("Please enter a word") wrd = str(wrd) rvs = wrd[::-1] # Reversing the string with string[start_index:end_index:step] print(rvs) if wrd == rvs: print("This word is a palindrome") else: print("This word is not a palindrome")
true
86d27e2e2c5cd7e54cb51b9d15a7ce58f5293293
AnhellO/DAS_Sistemas
/Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-9/Privileges.py
2,064
4.375
4
"""9-8. Privileges: Write a separate Privileges class . The class should have one attribute, privileges, that stores a list of strings as described in Exercise 9-7 . Move the show_privileges() method to this class . Make a Privileges instance as an attribute in the Admin class . Create a new instance of Admin and use your method to show its privileges.""" class User(): def __init__(self, first_name, last_name, username, email, number): self.first_name = first_name.title() self.last_name = last_name.title() self.username = username self.email = email self.number = number.title() self.login_attempts = 0 def describe_user(self): print(f"\n{self.first_name} {self.last_name}") print(f" Username: {self.username}") print(f" Email: {self.email}") print(f" Number: {self.number}") def greet_user(self): print(f"\n Hola {self.username} que tengas un excelente dia!") def increment_login_attempts(self): self.login_attempts += 1 def reset_login_attempts(self): self.login_attempts = 0 class Admin(User): def __init__(self, first_name, last_name, username, email, number): super().__init__(first_name, last_name, username, email, number) self.privileges = Privileges() class Privileges(): def __init__(self, privileges=[]): self.privileges = privileges def show_privileges(self): print("\nPrivilegios:") if self.privileges: for privilege in self.privileges: print(f"- {privilege}") else: print("Este usuario no cuenta con privilegios.") Alexa = Admin('Alexa', 'Cazarez', 'Alex', 'Alex@hotmail.com', '844631126') Alexa.describe_user() Alexa.privileges.show_privileges() print("\nAñadiendo privilegios:") Alexa_privileges = [ 'can add post', 'can delete post', 'can ban user', ] Alexa.privileges.privileges = Alexa_privileges Alexa.privileges.show_privileges()
true
b2b2c5cbe0caaf832f392e52f0e69f260e4a99a2
AnhellO/DAS_Sistemas
/Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-8/8-9. Magicians.py
379
4.15625
4
""" Practica 8-9 - Magicians Make a list of magician’s names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list .""" def show_messages(mensaje): for mensaje in mensaje: print(mensaje) mensaje = ["Hola soy el mensaje 1", "Hi i am the message 2", "Salut je suis le message 3"] show_messages(mensaje)
true
33b1739dad1c8aaeb59570ab8a93dcc160815965
AnhellO/DAS_Sistemas
/Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-9/OrderedDict Rewrite.py
1,151
4.3125
4
"""9-13. OrderedDict Rewrite: Start with Exercise 6-4 (page 108), where you used a standard dictionary to represent a glossary. Rewrite the program using the OrderedDict class and make sure the order of the output matches the order in which key-value pairs were added to the dictionary.""" from collections import OrderedDict glossary = OrderedDict() glossary['string'] = 'Una serie de caracteres.' glossary['comment'] = 'A note in a program that the Python interpreter ignores.' glossary['list'] = 'A collection of items in a particular order.' glossary['loop'] = 'Work through a collection of items, one at a time.' glossary['dictionary'] = "A collection of key-value pairs." glossary['key'] = 'The first item in a key-value pair in a dictionary.' glossary['value'] = 'An item associated with a key in a dictionary.' glossary['conditional test'] = 'A comparison between two values.' glossary['float'] = 'A numerical value with a decimal component.' glossary['boolean expression'] = 'An expression that evaluates to True or False.' for word, definition in glossary.items(): print("\n" + word.title() + ": " + definition)
true
d2f6058cdbe98127e39ccf57a52ef1fea06273a6
AnhellO/DAS_Sistemas
/Ene-Jun-2022/jesus-raul-alvarado-torres/Practica-5/E1.py
962
4.125
4
from abc import ABC, abstractmethod class Poligono(ABC): @abstractmethod def Num_lados(self): pass ###Sobrescribiendo el método abstracto Num_lados para los siguientes tipos de figuras: class Triangulo(Poligono): # Triángulo def Num_lados(self): lados = 3 return lados class Cuadrado(Poligono): # Cuadrado def Num_lados(self): lados = 4 return lados class Pentagono(Poligono): # Pentágono def Num_lados(self): lados = 5 return lados class Hexagono(Poligono): # Hexágono def Num_lados(self): lados = 6 return lados if __name__ == "__main__": Triangulo = Triangulo() print(Triangulo.Num_lados()) Cuadrado = Cuadrado() print(Cuadrado.Num_lados()) Pentagono = Pentagono() print(Pentagono.Num_lados()) Hexagono = Hexagono() print(Hexagono.Num_lados())
false