blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
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
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
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
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
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
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
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
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
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
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
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
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
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
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
4eda1153098fccefd3e311c6dde550759932a719
AJChestnut/Python-Projects
/14 Requesting 3 Numbers and then Mathing.py
2,059
4.5625
5
# Assignment 14: # Write a Python program requesting a name and three numbers from the user. The program will need # to calculate the following: # # the sum of the three numbers # the result of multiplying the three numbers # divide the first by the second then multiply by the third # Print a message greeting the user by name and the results of each of the mathematical operations. # # You must provide a comment block at the top indicating your name, the course, the section, and # the date as well as a description of the program. Also, comment as necessary to clearly explain # what it is you are doing where you are doing it in the program. # This was the first assignment of my second class on learning Python. It wasa mostly a refresher # on things that I had already learned from the first class, but there was one significant new # thing — storing number inputs as integers from the get go. I also did some additional research # to learn how to round the last answer to a set number of decimal places. Code: # Request a name and 3 numbers, perform multiple math fucntions on numbers and display results # Code by AJChestnut # July 10, 2020 #ask user for name and store as a variable print ('Hello, there. What\'s your name?') userName=input() #Ask user for 3 numbers and store the int value as variables print('It\'s nice to meet you,', userName + '.') print('And now, I am going to need 3 numbers from you.') print('What is your first favorite number?') firstNum=int(input()) print('Your second favorite number?') secondNum=int(input()) print('And lastly, what is your third favorite number?') thirdNum=int(input()) #mathing for winners sums=firstNum + secondNum + thirdNum products=firstNum * secondNum * thirdNum mixed=firstNum / secondNum * thirdNum #display math results print('Thank you,', userName + '.', 'The sum of your favorite numbers is:', sums) print('The product of your favorite numbers is: ', products) print('The first number, divided by the second number, then multiplied by the third is: ', round(mixed, 2))
true
f955b97f3ab252a2885a441f6c99773cd00efed7
AJChestnut/Python-Projects
/10 Comma Code.py
2,169
4.4375
4
# Assignment 10: # Say you have a list value like this: # listToPrint = ['apples', 'bananas', 'tofu', 'cats'] # Write a program that prints a list with all the items separated by a comma and a space, # with and inserted before the last item. For example, the above list would print 'apples, # bananas, tofu, and cats'. But your program should be able to work with any list not just # the one shown above. Because of this, you will need to use a loop in case the list to # print is shorter or longer than the above list. Make sure your program works for all # user inputs. For instance, we wouldn't want to print "and" or commas if the list only # contains one item. # The initial while loop that allows a user to input variables to a list was given to us # by the instructor. We were responsible for creating the rest of the script. The first two # if statements were the easy part of this assignment for me. If this, do that. Working to # create the for loop that went through every variable and had a step to change the output # for the last variable in the list was complicated for me. It took a few different iterations # before I wrote this one that worked. I've got to admit, I also spent longer than I probably # should have on deciding to end the list with a period or not. # Code: # Comma Code # Code by AJChestnut # April 14, 2019 listToPrint = [] #create variable with empty list while True: newWord = input("Enter a word to add to the list (press return to stop adding words) > ") if newWord == "": #If nothing input, stop adding things to list break else: listToPrint.append(newWord) #If something input, add to end of list if len(listToPrint) == 1: #if only 1 value in list, print value print(str(listToPrint[0])) if len(listToPrint) == 2: #If only 2 values, comma not needed just the "and" print(str(listToPrint[0] + ' and ' + str(listToPrint[1]))) if len(listToPrint) > 2: for newWord in listToPrint[:-1]: #print item + comma and space until the last value in list print(str(newWord) + ', ', end='') print('and ' + str(listToPrint[-1])) #finish list with "and" preceeding final value
true
c052253ac099375f8a3d9046395af382dc0c158b
mitchblaser02/Python-Scripts
/Python 3 Scripts/CSVOrganiser/CSVOrganiser.py
347
4.28125
4
#PYTHON CSV ORGANIZER #MITCH BLASER 2018 i = input("Enter CSV to sort (1, 2, 3): ") #Get the CSV from the user. p = i.split(", ") #Turn the CSV into tuple. o = sorted(p) #Set variable o to a sorted version of p. for i in range(0, len(o)): #Loop for the amount of entries in o. print(o[i]) #Print out each entry sepertely (of the sorted "o" tuple.)
true
4f80de4e3458af59a67a68e96b6b45e1e26bc1e3
j-sal/python
/3.py
1,305
4.375
4
''' Lists and tuples are ordered Tuples are unmutable but can contain mixed typed items Lists are mutable but don't often contain mixed items Sets are mutable, unordered and doesn't hold duplicate items, sets can also do Unions, Intersections, and Differences Dictionaries are neat ''' myList = ["coconut","pear","tomato","apple"] l2 = ["coconuts","pear","tomato","apple"] l3 = [56,5,4,3,88,17] mySet = {2.0, "Joey", ('Pratt')} mySet2 = {"Jo", 2.0} myD = {'Spanish level':5,'Eng level':5, 'Chinese level':3,'French level':1.5} if "apple" in myList: print("'apple' is on the list and its index is:",myList.index("apple")) print("The fruit apple appears",myList.count("apple"),"time(s)") else: print("'apple' is NOT on the list") print("potato" in myList) print(myList) print(cmp([l2],[myList])) #cmp only in py2, not in py3 l3.pop() print("after pop:",l3) l3.sort() print("l3 after sort: ", l3) l3.pop() l3.remove(l3[0]) l3.reverse() print("after pop, remove index 0, reverse:",l3) l3.append(3) print(l3) l3.insert(1,16) #insert([index],[value]) print(l3) l3.sort() print("l3 after sort: ", l3) print(mySet) print(mySet | mySet2) print(mySet & mySet2) print(mySet - mySet2) print(mySet ^ mySet2) print(sorted(list(myD))) print('Russian' not in myD) #myD.fromkeys(2[,3]) #to figure out
true
1147a10ab060451acbfe874b78c698435fa592d5
zmybr/PythonByJoker
/day01-1.py
1,456
4.125
4
#1.温度转换 #C = float(input('请输入一个温度')) #print((9/5)*C+32) #2.圆柱体体积 #import math #pai=math.pi #radius = float(input("请输入半径")) #length = float(input('请输入高')) #area = radius * radius * pai #volume = area * length #print("The area is %.4f"%area) #print("The volume is %.1f"%volume) #3.英尺转换 #feet = float(input("请输入英尺")) #meters = feet * 0.305 #print( "%f feet is %f meters"%(feet,meters)) #4.计算能量 #kg = float(input('Enter the amount of water in kilograms:')) #init = float(input('Enter the initial temperature:')) #final = float(input('Enter the final temperature:')) #Q = kg * (final - init) * 4184 #print("The energy needed is %.1f"%Q) #5.计算利息 #balance = float(input('请输入差额:')) #rate = float(input('请输入年利率:')) #interest = balance * (rate / 1200) #print('Th interest is %f'%interest) #6.加速度 #v0,v1,t = eval(input('Enter v0,v1 and t:')) #a = (v1 - v0)/t #print('The average acceleration is %.4f'%a) #7.复利值 #money = float(input("Enter the monthly saving amount:")) #value = money * (1 + 0.00417) #i=1 #while i < 6: # value = (money + value) * (1 + 0.00417) # i +=1 #print("After the sixth month,the account value is %.2f"%value) #8.求和 num = int(input("Enter a number between 0 and 1000:")) sum=0 b=num//100%10 c=num//10%10 a=num%10 sum=a+b+c print('The sum of the digits is %d'%sum)
true
6175197774940e0e5727c59210b9ea73139f6119
MarioAguilarCordova/LeetCode
/21. Merge Two Sorted Lists.py
1,812
4.15625
4
from typing import List class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next def printlist(self, list): itr = list while itr: print(list.val + " , ") itr = itr.next def mergeTwoLists(list1, list2): """ :type list1: Optional[ListNode] :type list2: Optional[ListNode] :rtype: Optional[ListNode] """ dummy = result = ListNode(0) while list1 and list2: if list1.val < list2.val: result.next = list1 list1 = list1.next else: result.next = list2 list2 = list2.next result = result.next result.next = list1 or list2 return dummy.next def main(): list1 = ListNode(1,2) list2 = ListNode(1,3) answer = ListNode(0) answer = mergeTwoLists(list1,list2) answer.printlist() main() # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeTwoLists(self, list1, list2): """ :type list1: Optional[ListNode] :type list2: Optional[ListNode] :rtype: Optional[ListNode] """ dummy = result = ListNode(0) while list1 and list2: if list1.val < list2.val: result.next = list1 list1 = list1.next else: result.next = list2 list2 = list2.next result = result.next result.next = list1 or list2 return dummy.next return result
true
555d058cd1706c702280037b4263de42b8c6c64d
dmserrano/python101
/foundations/exercises/randomSquared.py
635
4.3125
4
import random; # Using the random module and the range method, generate a list of 20 random numbers between 0 and 49. random_numbers = list(); def create_random_list (): ''' This function creates 20 random numbers from 0-49. ''' for x in range(0,20): random_numbers.append(random.randint(0,49)); create_random_list(); print(random_numbers); # With the resulting list, use a list comprehension to build a new list that contains each number squared. For example, if the original list is [2, 5], the final list will be [4, 25]. squared_list = [each * each for each in random_numbers ]; print(squared_list);
true
2b352b8bb78329976f0790e7a499a97e2d2d9dd2
siawyoung/practice
/problems/zip-list.py
1,328
4.125
4
# Write a function that takes a singly linked list L, and reorders the elements of L to form a new list representing zip(L). Your function should use 0(1) additional storage. The only field you can change in a node is next. # e.g. given a list 1 2 3 4 5, it should become 1 5 2 4 3 class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return str(self.data) def print_all(self): curr = self while True: print(curr) if curr.next: curr = curr.next else: break def zip(node): temp = node temp1 = node.next if not temp1: return node current_end = None current_pointer = node while True: while True: if current_pointer.next is current_end: break current_pointer = current_pointer.next current_end = current_pointer temp.next = current_end current_end.next = temp1 if temp1.next is current_end: temp1.next = None break temp = temp1 temp1 = temp1.next current_pointer = temp a = Node(1) b = Node(2) c = Node(3) d = Node(4) e = Node(5) a.next = b b.next = c c.next = d d.next = e zip(a) a.print_all()
true
7c77a7a8c7c90c1f626f96f392f3a9e3e6a58b60
siawyoung/practice
/problems/delete-single-linked-node.py
674
4.15625
4
# Delete a node from a linked list, given only a reference to the node to be deleted. # We can mimic a deletion by copying the value of the next node to the node to be deleted, before deleting the next node. # not a true deletion class LinkedListNode: def __init__(self, value): self.value = value self.next = None def __str__(self): return str(self.value) def delete_node(node): if node.next: _next = node.next.next else: _next = None node = node.next node.next = _next a = LinkedListNode('A') b = LinkedListNode('B') c = LinkedListNode('C') a.next = b b.next = c delete_node(b) print(a) print(b)
true
05c6d092439df7574bfb7b265007007b42816154
siawyoung/practice
/problems/reverse-words.py
986
4.15625
4
# Code a function that receives a string composed by words separated by spaces and returns a string where words appear in the same order but than the original string, but every word is inverted. # Example, for this input string # @"the boy ran" # the output would be # @"eht yob nar" # Tell the complexity of the solution. class Stack: def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): return self.stack.pop() def isEmpty(self): return len(self.stack) == 0 def reverse_words(string): stack = Stack() output = [] for i in range(len(string)): if string[i] == ' ': while not stack.isEmpty(): output.append(stack.pop()) output.append(' ') else: stack.push(string[i]) while not stack.isEmpty(): output.append(stack.pop()) return ''.join(output) print(reverse_words('the boy ran'))
true
9b73167d9095286071a4e5d2b9d61d1643ef874d
bluepine/topcoder
/cracking-the-coding-interview-python-master/3_5_myqueue.py
1,147
4.34375
4
#!/usr/bin/env python """ Implement a queue with two stacks in the MyQueue class. This should never be used, though -- the deque data structure from the standard library collections module should be used instead. """ class MyQueue(object): def __init__(self): self.first = [] self.second = [] def size(self): return len(self.first) + len(self.second) def add(self, number): self.first.append(number) def peek(self): first = self.first second = self.second if len(second): return second[-1] while len(first): second.append(first.pop()) return second[-1] def remove(self): first = self.first second = self.second if len(second): return second.pop() while len(first): second.append(first.pop()) return second.pop() def main(): queue = MyQueue() queue.add(1) queue.add(2) queue.add(3) print queue.size() # 3 print queue.peek() # 1 print queue.remove() # 1 print queue.peek() # 2 if __name__ == '__main__': main()
true
b72125acc6f31cb0d2e9a8e1881137c5d6974ae4
bluepine/topcoder
/algortihms_challenges-master/general/backwards_linked_list.py
1,474
4.125
4
""" Reverse linked list Input: linked list Output: reversed linked list """ class Node(object): def __init__(self, data, next=None): self.data = data self.next = next class LinkedList(object): def __init__(self, head=None): self.head = head def __str__(self): res = [] node = self.head while node: res.append(str(node.data)) node = node.next return '->'.join(res) def add(self, node): if node is None: return False if self.head is None: self.head = node else: current = self.head while current.next: current = current.next current.next = node def add_to_head(self, node): if node is None: return False if self.head is None: self.head = node else: node.next = self.head self.head = node def reverse(head): reversed_list = LinkedList() current = head while current: # make new node so you don't make reference to already # existing node reversed_list.add_to_head(Node(current.data)) current = current.next return reversed_list nodes = [Node("1"), Node("2"), Node("3"), Node("4"), Node("5"), Node("6")] list = LinkedList() for node in nodes: list.add(node) head = list.head print list reversed = reverse(list.head) print reversed
true
ccb57c809f7dba7cca387727438fbe8631579269
bluepine/topcoder
/algortihms_challenges-master/general/matrix.py
1,706
4.21875
4
""" 1.7. Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0 Idea: a) Have an additional matrix and go trough all elements in MxN matrix and set zeroes b) For each element you go trough - check if it is on a 'zero line' (has zero on it's column or row - do AND operator and if it is zero - put that element zero) """ def matrix_zero(matrix): if matrix is None or len(matrix) < 1: return False m = len(matrix) n = len(matrix[0]) init_zeros_x = [] init_zeros_y = [] for i in xrange(m): for j in xrange(n): # check if value is initially 0 if matrix[i][j] == 0: if i not in init_zeros_x: init_zeros_x.append(i) if j not in init_zeros_y: init_zeros_y.append(j) elif i in init_zeros_x or j in init_zeros_y: matrix[i][j] = 0 else: column = [matrix[x][j] for x in xrange(i,m) ] value_i = reduce(lambda x, y: x and y, column) value_j = reduce(lambda x, y: x and y, matrix[i][j:]) value = value_i and value_j if value == 0: matrix[i][j] = 0 return matrix matrix = [[1, 2, 1, 3, 2, 1, 1], [3, 5, 0, 1, 5, 0, 1], [2, 1, 4, 6, 1, 1, 2], [5, 1, 1, 1, 0, 1, 1], [1, 2, 2, 0, 1, 1, 0]] result = [[1, 2, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [2, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] print "method result", matrix_zero(matrix) print "expected result", result
true
8dd5870f0967b67a0ad2b81f71d521e6c6657e4d
bluepine/topcoder
/ctci-master/python/Chapter 1/Question1_3/ChapQ1.3.py
1,529
4.125
4
#Given two strings, write a method to decide if one is a permutation of the other. # O(n^2) def isPermutation(s1, s2): if len(s1)!=len(s2): return False else: for char in s1: if s2.find(char)==-1: return False else: s2.replace(char,"",1) return True # big O complexity depends on python list sort complexity, which should be better than O(n^2) def isPermutationSort(s1,s2): #sort both strings, check if they are equal if len(s1)!=len(s2): return False return sorted(s1) == sorted(s2) #O(n) #using a dict as a hash table to count occurences in s1, then comparing s2 with the dict def isPermutationHash(s1,s2): if len(s1) != len(s2): return False dic = {} for char in s1: dic[char] = dic.get(char, 0) + 1 for char in s2: if dic.get(char,0) <= 0: return False else: dic[char] -= 1 return True #testing #permutation postest1 = ["abcdefgh","abcdefhg"] #not permutation negtest2 = ["abcdefgh","gfsdgsdffsd"] #not permutation negtest3 = ["abcdefgh","gfsdgsdf"] #list of all functions to test funclist = [isPermutation,isPermutationSort,isPermutationHash] for func in funclist: print "Testing function " + str(func) if func(postest1[0],postest1[1]): print "Test 1 passed" if not func(negtest2[0],negtest2[1]): print "Test 2 passed" if not func(negtest3[0],negtest3[1]): print "Test 3 passed"
true
470543e4625aff4f2aeb99636a0880821f36f7ac
WaltXin/PythonProject
/Dijkstra_shortest_path_Heap/Dijkstra_shortest_path_Heap.py
2,719
4.15625
4
from collections import defaultdict def push(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) shiftup(heap, 0, len(heap)-1) def pop(heap): """Pop the smallest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt shiftdown(heap, 0) return returnitem return lastelt # 'heap' is a heap at all indices >= startpos, except possibly for pos. pos # is the index of a leaf with a possibly out-of-order value. Restore the # heap invariant. def shiftup(heap, startpos, pos): newitem = heap[pos] # Follow the path to the root, moving parents down until finding a place # newitem fits. while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if newitem < parent: heap[pos] = parent pos = parentpos continue break heap[pos] = newitem def shiftdown(heap, pos): endpos = len(heap) startpos = pos newitem = heap[pos] # Bubble up the smaller child until hitting a leaf. childpos = 2*pos + 1 # leftmost child position while childpos < endpos: # Set childpos to index of smaller child. rightpos = childpos + 1 if rightpos < endpos and not heap[childpos] < heap[rightpos]: childpos = rightpos # Move the smaller child up. heap[pos] = heap[childpos] pos = childpos childpos = 2*pos + 1 # The leaf at pos is empty now. Put newitem there, and bubble it up # to its final resting place (by sifting its parents down). heap[pos] = newitem shiftup(heap, startpos, pos) def dijkstra(edges, f, t): g = defaultdict(list) for l,r,c in edges: g[l].append((c,r)) q, seen = [(0,f,())], set() while q: (cost,v1,path) = pop(q) if v1 not in seen: seen.add(v1) path = (v1, path) if v1 == t: return (cost, path) for c, v2 in g.get(v1, ()): if v2 not in seen: push(q, (cost+c, v2, path)) return float("inf") if __name__ == "__main__": edges = [ ("A", "B", 7), ("A", "D", 5), ("B", "C", 8), ("B", "D", 9), ("B", "E", 7), ("C", "E", 5), ("D", "E", 15), ("D", "F", 6), ("E", "F", 8), ("E", "G", 9), ("F", "G", 11) ] print ("=== Dijkstra ===") print (edges) print ("A -> E:") print (dijkstra(edges, "A", "E")) print ("F -> G:") print (dijkstra(edges, "F", "G"))
true
33b0b54194338915d510c2b76cf0ada76ac053a6
digvijay-16cs013/FSDP2019
/Day_03/weeks.py
429
4.21875
4
# -*- coding: utf-8 -*- """ Created on Thu May 9 15:56:28 2019 @author: Administrator """ days_of_week = input('Enter days of week => ') .split(', ') weeks = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for index, day in enumerate(weeks): if day not in days_of_week: days_of_week.insert(index, day) days_of_week = tuple(days_of_week) print(days_of_week)
true
4042f285972f9bdf7d7d6c24cbbe8ae4cfe7baaa
digvijay-16cs013/FSDP2019
/Day_11/operations_numpy.py
1,309
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue May 21 23:29:54 2019 @author: Administrator """ # importing Counter from collections module from collections import Counter # importing numerical python (numpy) abbreviated as np import numpy as np # some values values = np.array([13, 18, 13, 14, 13, 16, 14, 21, 13]) # calculate mean or average of values mean = np.mean(values) # calculate median of values median = np.median(values) # create a range of values form 21 - 13 using numpy range_of_values = np.arange(21, 13, -1) # getting count of each values from the list of "values" and converting the result in the form of dictionary count = dict(Counter(values)) # finding the maximum occrances of a value maximum = max(count.values()) # to check printing the value of max ocurrances #print(count) # loop to find out the mode of "values"(Number which occurs most frequently) for key, value in count.items(): # to check if number has maximum ocurrances if maximum == value: # set mode = value(which is represented by key) mode = key # getting out of the loop once we get the most frequent value break # print what we calculated so far print('Mean =', mean) print('Median =', median) print('Mode =', mode) print('Range =', range_of_values)
true
35e551aa21266be0b9af0e54b2b205799e5b9b32
digvijay-16cs013/FSDP2019
/Day_06/odd_product.py
332
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue May 14 14:25:35 2019 @author: Administrator """ from functools import reduce numbers = list(map(int, input('Enter space separated integers : ').split())) product_odd = reduce(lambda x, y : x * y, list(filter(lambda x: x % 2 != 0, numbers))) print('product of odd numbers :', product_odd)
true
9346fd05be19a27fec2239194d70c986cfc3db5e
digvijay-16cs013/FSDP2019
/Day_01/string.py
401
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue May 7 17:44:40 2019 @author: Administrator """ # name from user name = input('Enter first and last name with a space between them : ') # finding index of space using find method index = name.find(' ') # taking first Name and last name separately first_name = name[:index] last_name = name[index+1:] # Printing names print(last_name + ' ' + first_name)
true
689f0134064076fa90882d24fc5af086a42a8978
digvijay-16cs013/FSDP2019
/Day_05/regex1.py
402
4.3125
4
# -*- coding: utf-8 -*- """ Created on Sat May 11 16:04:05 2019 @author: Administrator """ # regular expression number import re # scan number float_number = input('Enter anything to check if it is floating point number : ') # to check match if re.match(r'^[+-]?\d*\.\d+$', float_number): # if expression found print(True) else: # if expression not found print(False)
true
98fef15129c66c8a64de2cd051605a7405a202a5
ElijahMcKay/Blockchain
/standupQ.py
1,399
4.21875
4
""" You've been hired to write the software to count the votes for a local election. Write a function `countVotes` that receives an array of (unique) names, each one representing a vote for that person. Your function should return the name of the winner of the election. In the case of a tie, the person whose name comes last alphabetically wins the election (a dumb rule to be sure, but the voters don't need to know). Example: ``` input: ['veronica', 'mary', 'alex', 'james', 'mary', 'michael', 'alex', 'michael']; expected output: 'michael' ``` Analyze the time and space complexity of your solution. """ inputList = ['veronica', 'mary', 'alex', 'james', 'mary', 'michael', 'alex', 'michael'] def voter_count(array): winner = 'a' hashmap = {} votes = 0 max_votes = [] for name in array: if name not in hashmap: hashmap[name] = 1 else: hashmap[name] += 1 if hashmap[name] > votes: max_votes = [name] votes = hashmap[name] # print('greater than', max_votes) elif hashmap[name] == votes: max_votes.append(name) # print('equals', max_votes) if len(max_votes) == 1: winner = max_votes[0] else: for name in max_votes: if name > winner: winner = name return winner print(voter_count(inputList))
true
4c0c8b1478e505dd5734d3e902bea1d520dd80bc
paulonteri/google-get-ahead-africa
/exercises/longest_path_in_tree/longest_path_in_tree.py
1,489
4.21875
4
""" Longest Path in Tree: Write a function that computes the length of the longest path of consecutive integers in a tree. A node in the tree has a value and a set of children nodes. A tree has no cycles and each node has exactly one parent. A path where each node has a value 1 greater than its parent is a path of consecutive integers (e.g. 1,2,3 not 1,3,5). A few things to clarify: Integers are all positive Integers appear only once in the tree """ class Tree: def __init__(self, value, *children): self.value = value self.children = children def longest_path_helper(tree, parent_value, curr_length, longest_length): if not tree: return longest_length if tree.value == parent_value + 1: curr_length += 1 else: curr_length = 1 longest_length = max(longest_length, curr_length) for child in tree.children: longest_length = max(longest_length, longest_path_helper( child, tree.value, curr_length, longest_length) ) return longest_length def longest_path(tree): if not tree: return return longest_path_helper(tree, float('-inf'), 0, 0) assert longest_path( Tree(1, Tree(2, Tree(4)), Tree(3)) ) == 2 assert longest_path( Tree(5, Tree(6), Tree(7, Tree(8, Tree(9, Tree(15), Tree(10))), Tree(12))) ) == 4
true
3eb607c7fc1499c0d2aa9d28e25c8a32549cab54
celeritas17/python_puzzles
/is_rotation.py
634
4.25
4
from sys import argv, exit # is_rotation: Returns True if string t is a rotation of string s # (e.g., 'llohe' is a rotation of 'hello'). def is_rotation(s, t): if len(s) != len(t): return False if not s[0] in t: return False count_length = i = 0 t_len = len(t) while t[i] != s[0]: i += 1 while count_length < t_len and s[count_length] == t[i%t_len]: count_length += 1 i += 1 if count_length == t_len: return True return False if len(argv) < 3: print "Usage: %s <string> <string>\n" % argv[0] exit(1) print "%r is%s a rotation of %r\n" % (argv[2], "" if is_rotation(argv[1], argv[2]) else " not", argv[1])
true
5fb2788df1a6c3db25a31bfb310813353e6f31db
tjshaffer21/katas
/project_euler/python/p16.py
575
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Problem 16 - Power digit sum 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000? """ def pow_sum(x, n): """ Calculate the sum of the power. Parameters x : int : The base integer. n : int : The power. Return int : The sum. """ ps = x ** n s = 0 while ps > 0: s += ps%10 ps = ps // 10 return s print("Result: " + str(pow_sum(2, 1000))) # 1366
true
8fe165a793c2598d567fb11e5b55d238a1e7d6b1
UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated
/students/Ruohan/lesson03/list_lab.py
2,570
4.15625
4
#! /usr/bin/env python3 '''Exercise about list''' #series 1 #Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”. #Display the list print('============= series 1 ===============') list_fruit = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(list_fruit) #Ask the user for another fruit and add it to the end of the list. #Display the list. item = input('Enter another fruit: ') list_fruit.append(item) print(list_fruit) #Ask the user for a number and display the number back to the user #and the fruit corresponding to that number x = int(input('Enter the number: ')) print(x, list_fruit[x-1]) #Add another fruit to the beginning of the list using “+” and display the list. item_new = input('Enter another fruit: ') list_fruit_new = [item_new] + list_fruit print(list_fruit_new) #Add another fruit to the beginning of the list using insert() and display the list. item = input('Enter another fruit: ') list_fruit_new.insert(0, item) print('====original list: ', list_fruit_new, '=====') #Display all the fruits that begin with “P”, using a for loop. for ft in list_fruit_new: if ft[0] == 'P': print(ft) #Series 2 #Display the list. print('============= series 2 ===============') list_fruit_2 = list_fruit_new[:] print(list_fruit_2) #Remove the last fruit from the list and display the list list_fruit_2.pop() print(list_fruit_2) #Ask the user for a fruit to delete, find it and delete it. tgt = input('Enter the fruit you want to delete: ') idx = list_fruit_2.index(tgt) list_fruit_2.pop(idx) print(list_fruit_2) #Series 3 #Ask the user if he likes the fruit for each fruit in the list and display the list print('============= series 3 ===============') list_fruit_3 = list_fruit_new[:] for fruit in list_fruit_new: y = input('Do you likes {} ? '.format(fruit.lower())) while True: if y == 'no': list_fruit_3.pop(list_fruit_3.index(fruit)) break if y == 'yes': break else: y = input("invalid argument, please enter 'yes'or 'no': ") print(list_fruit_3) #Series 4 #Make a copy of the list and reverse the letters in each fruit in the copy. print('============= series 4 ===============') list_fruit_4 = [] for fruit in list_fruit_new: fruit = fruit[::-1] list_fruit_4.append(fruit) print(list_fruit_4) #Delete the last item of the original list. Display the original list and the copy. list_fruit_new.pop() list_fruit_4 = list_fruit_new[:] print('original list: ', list_fruit_new) print('new list: ', list_fruit_4)
true
daeba6dd81960befa2f59d9d98d9b930a3ff923e
UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated
/students/aravichander/lesson03/strformat_lab.py
1,052
4.1875
4
tuple1 = (2,123.4567,10000, 12345.67) #print(type(tuple1)) #Spent some time trying to understand the syntax of the string formats # print("First element of the tuple is: file_{:03}".format(tuple1[0])) # print("Second element of the tuple is: {0:.2f}".format(tuple1[1])) # print("Second element of the tuple is: {1:.2f}".format(tuple1)) # print("Third element of the tuple is: {0:.2e}".format(tuple1[2])) # print("Fourth element of the tuple is: {0:.3g}".format(tuple1[3])) #print("{:03},{0:.2f},{0:.2e},{0:.2e}".format(tuple1[0],tuple1[1],tuple1[2],tuple1[3])) #print("file_{:03},{:.2f},{:.2e},{:.3g}".format(tuple1[0],tuple1[1],tuple1[2],tuple1[3])) #Task Three - not the best formatting but the essence is there! # def multipletuple(*numbers): # listlen = len(numbers) # return "The",listlen,"numbers are {0}".format(numbers) # print(multipletuple(1,2)) #Task Four tuple3 = (4, 30, 2017, 2, 27) #print("{0[3]},{0[4]},{0[2]},{0[0]},{0[1]}".format(tuple3)) #Task Five - don't have Python 3.6 a = 5 b = 10 #f"The sum is: {a+b}." #Task Six
true