├── .gitignore ├── README.md ├── assets └── star.png ├── find_matches ├── find_matches.py ├── input1.csv ├── input2.csv └── input3.csv ├── programs ├── add_to_zero.py ├── anagram_of_palindrome.py ├── award_budget_cuts.py ├── binary_search.py ├── bst_add_child.py ├── calculator.py ├── climb_stairs.py ├── coins.py ├── count_employees.py ├── count_recursively.py ├── create_queue.py ├── create_queue_ll.py ├── create_stack.py ├── decode_string.py ├── etl_client.py ├── find_longest_word.py ├── find_mode.py ├── first_duplicate.py ├── has_balanced_brackets.py ├── hash_map.py ├── highest_product_of_three.py ├── is_binary_tree.py ├── is_unique.py ├── linked_list.py ├── make_change.py ├── merge_ranges.py ├── min_heap.py ├── most_frequent_word.py ├── non_neg_int.py ├── palindrome_permutation.py ├── print_recursively.py ├── products_of_all_ints.py ├── quote_generator.py ├── rate_checker.py ├── recursive_index.py ├── reverse_linked_list.py ├── reverse_order_of_words.py ├── reverse_string.py ├── rommon_to_integer.py ├── sort_dict_by_value.py ├── sort_fractions.py ├── stock-price.py ├── sum_list.py ├── sum_tree_nodes.py ├── transpose_of_matrix.py ├── valid_parenthesis_permutations.py └── zig_zag.py ├── python-programs.md └── task_handler ├── task0.py ├── task1.py ├── task2.py ├── task3.py ├── task4.py └── taskhandler.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.pyc 3 | -------------------------------------------------------------------------------- /assets/star.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/python-basics/a28d9b2980b76070bd57f3720151d8b521a83807/assets/star.png -------------------------------------------------------------------------------- /find_matches/find_matches.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import csv 3 | import re 4 | 5 | 6 | class FindMatches(object): 7 | """ Takes a .csv input file and a matching type and returns a copy of the original csv with the unique identifier of the person each row represents prepended to the row. 8 | 9 | Matching types: 10 | > email 11 | > phone 12 | > email_phone 13 | """ 14 | 15 | def __init__(self, input_file, matching_type): 16 | """ Opens the csv file and declares the phone and email columns. """ 17 | 18 | # Check if matching_type input is valid 19 | self.matching_type = matching_type.lower() 20 | if self.matching_type not in ['email', 'phone', 'email_phone']: 21 | print "Please use a valid matching type: 'email', 'phone', or 'email_phone'." 22 | 23 | # Initialize variables for later assignment 24 | self.input_file = input_file 25 | self.rownum = 0 26 | self.header = None 27 | self.email_col_2 = None 28 | self.email_col = None 29 | self.phone_col_2 = None 30 | self.phone_col = None 31 | 32 | # Keep track of entry duplicates/key assignments via ids dictionary 33 | self.ids = {} 34 | self.id = 1 35 | 36 | # Open the file with a csv reader 37 | csv_file_in = open(self.input_file, 'rU') 38 | reader = csv.reader(csv_file_in) 39 | 40 | # Declare the header for the file 41 | for row in reader: 42 | if self.rownum == 0: 43 | self.header = row 44 | self.rownum += 1 45 | break 46 | 47 | # Get the column number(s) for email 48 | for col in range(len(self.header)): 49 | if 'email2' in self.header[col].lower(): 50 | self.email_col_2 = col 51 | if 'email1' in self.header[col].lower() or 'email' == self.header[col].lower(): 52 | self.email_col = col 53 | 54 | # Get the column number(s) for phone 55 | for col in range(len(self.header)): 56 | if 'phone2' in self.header[col].lower(): 57 | self.phone_col_2 = col 58 | if 'phone1' in self.header[col].lower() or 'phone' == self.header[col].lower(): 59 | self.phone_col = col 60 | 61 | # Write to csv after all ids are assigned 62 | self.write_csv(reader, self.header) 63 | 64 | 65 | def email_match(self, row, min_id): 66 | """ Creates email tuples and insert unique tuples into the ids dictionary. """ 67 | 68 | row_id = None 69 | 70 | # Assigns the id value to min_id if it exists, otherwise assigns it the next id value available 71 | if min_id: 72 | iden = min_id 73 | else: 74 | iden = self.id 75 | 76 | # Checks if a second email column exists 77 | if self.email_col_2: 78 | # Checks if value exists in second email column/row, and assigns it as the key 79 | if row[self.email_col_2]: 80 | email2 = row[self.email_col_2] 81 | self.add_key_to_dict(email2, iden) 82 | 83 | # If key exists in dictionary, assign it the row_id 84 | if self.ids.get(email2): 85 | row_id = self.ids.get(email2) 86 | 87 | # Checks if value exists in first email column/row, and assigns it as the key 88 | if row[self.email_col]: 89 | email1 = row[self.email_col] 90 | # Sets the row_id to the minimum common value if it exists, otherwise sets it to the next available identifier value 91 | self.add_key_to_dict(email1, iden) 92 | row_id = self.ids.get(email1, self.id) 93 | 94 | # If no value in the field, sets the row_id to the next available identifier value 95 | if row_id is None: 96 | row_id = self.id 97 | 98 | return row_id 99 | 100 | 101 | def format_phone(self, row, column): 102 | """ Removes formatting of phone numbers for direct comparison. """ 103 | 104 | format_phone_col = re.sub('\D+','',row[column]) 105 | 106 | if len(format_phone_col) > 10: 107 | format_phone_col[1:] 108 | 109 | return format_phone_col 110 | 111 | 112 | def phone_match(self, row, min_id): 113 | """ Creates phone tuples and insert unique tuples into the ids dictionary. """ 114 | 115 | row_id = None 116 | 117 | # Assigns the id value to min_id if it exists, otherwise assigns it the next id value available 118 | if min_id: 119 | iden = min_id 120 | else: 121 | iden = self.id 122 | 123 | # Checks if a second phone column exists 124 | if self.phone_col_2: 125 | # Checks if value exists in second phone column/row, and assigns it as the key 126 | if row[self.phone_col_2]: 127 | ids_key = self.format_phone(row, self.phone_col_2) 128 | self.add_key_to_dict(ids_key, iden) 129 | 130 | # If key exists in dictionary, assign it the row_id 131 | if self.ids.get(ids_key): 132 | row_id = self.ids.get(ids_key) 133 | 134 | if row[self.phone_col]: 135 | ids_key = self.format_phone(row, self.phone_col) 136 | # Sets the row_id to the minimum common value if it exists, otherwise sets it to the next available identifier value 137 | self.add_key_to_dict(ids_key, iden) 138 | row_id = self.ids.get(ids_key, self.id) 139 | 140 | # If no value in the field, sets the row_id to the next available identifier value 141 | if row_id is None: 142 | row_id = self.id 143 | 144 | return row_id 145 | 146 | 147 | def add_key_to_dict(self, ids_key, iden): 148 | """ Places keys into a dictionary. If the key exists the key-value pair does not change. Otherwise, place it in the dictionary and assign it a new id. """ 149 | 150 | self.ids[ids_key] = self.ids.get(ids_key, iden) 151 | 152 | 153 | def write_csv(self, reader, header, row_is_header=True): 154 | """ Using a csv writer, creates a copy of the file with unique ids prepended to each row. """ 155 | 156 | csv_file_out = open('output_file.csv', 'w') 157 | writer = csv.writer(csv_file_out) 158 | 159 | while row_is_header: 160 | # Add 'id' column to header 161 | header = ['id'] + self.header 162 | 163 | # Write header row to new file 164 | writer.writerow(header) 165 | 166 | row_is_header = False 167 | 168 | # Runs matching type tests based on match type given 169 | for row in reader: 170 | row_id = None 171 | email_row_id = None 172 | phone_row_id = None 173 | 174 | # If the matching type is 'email' 175 | if self.matching_type == 'email': 176 | email2 = None 177 | email1 = None 178 | min_id = None 179 | 180 | # Check if email columns exist 181 | if self.email_col_2: 182 | email2 = row[self.email_col_2] 183 | if self.email_col: 184 | email1 = row[self.email_col] 185 | 186 | # Check if either email is in ids dictionary, get the value 187 | if email2 in self.ids or email1 in self.ids: 188 | email2_exists = self.ids.get(email2) 189 | email_exists = self.ids.get(email1) 190 | 191 | # If multiple values exist, find the lowest and set that to min_id (row_id) 192 | id_values = [email2_exists, email_exists] 193 | min_id = min(iden for iden in id_values if iden is not None) 194 | 195 | # See if a second email column exists 196 | row_id = self.email_match(row, min_id) 197 | 198 | 199 | 200 | # If the matching type is 'phone' 201 | elif self.matching_type == 'phone': 202 | 203 | phone2 = None 204 | phone1 = None 205 | min_id = None 206 | 207 | # Check if phone columns exist 208 | if self.phone_col_2: 209 | phone2 = self.format_phone(row, self.phone_col_2) 210 | if self.phone_col: 211 | phone1 = self.format_phone(row, self.phone_col) 212 | 213 | # Check if either email is in ids dictionary, get the value 214 | if phone2 in self.ids or phone1 in self.ids: 215 | phone2_exists = self.ids.get(phone2) 216 | phone_exists = self.ids.get(phone1) 217 | 218 | # If multiple values exist, find the lowest and set that to min_id (row_id) 219 | id_values = [phone2_exists, phone_exists] 220 | min_id = min(iden for iden in id_values if iden is not None) 221 | 222 | # See if a second phone column exists 223 | row_id = self.phone_match(row, min_id) 224 | 225 | 226 | # If the matching type is email OR phone 227 | elif self.matching_type == 'email_phone': 228 | 229 | email2 = None 230 | email1 = None 231 | phone2 = None 232 | phone1 = None 233 | min_id = None 234 | 235 | # Check if email and phone columns exist 236 | if self.email_col_2: 237 | email2 = row[self.email_col_2] 238 | if self.email_col: 239 | email1 = row[self.email_col] 240 | if self.phone_col_2: 241 | phone2 = self.format_phone(row, self.phone_col_2) 242 | if self.phone_col: 243 | phone1 = self.format_phone(row, self.phone_col) 244 | 245 | # Check if either email or phone is in ids dictionary, get the value 246 | if email2 in self.ids or email1 in self.ids or phone2 in self.ids or phone1 in self.ids: 247 | email2_exists = self.ids.get(email2) 248 | email_exists = self.ids.get(email1) 249 | phone2_exists = self.ids.get(phone2) 250 | phone_exists = self.ids.get(phone1) 251 | 252 | # If multiple values exist, find the lowest and set that to min_id (row_id) 253 | id_values = [email2_exists, email_exists, phone2_exists, phone_exists] 254 | min_id = min(iden for iden in id_values if iden is not None) 255 | row_id = min_id 256 | 257 | email_row_id = self.email_match(row, min_id) 258 | phone_row_id = self.phone_match(row, min_id) 259 | 260 | if email_row_id < phone_row_id: 261 | row_id = email_row_id 262 | else: 263 | row_id = phone_row_id 264 | 265 | # Writes a new row with the id appended 266 | new_row = [row_id] + row 267 | writer.writerow(new_row) 268 | 269 | # Increments id in ids dictionary for unique row ids 270 | self.id += 1 271 | 272 | 273 | 274 | FindMatches(input_file=sys.argv[1], matching_type=sys.argv[2]) 275 | 276 | 277 | -------------------------------------------------------------------------------- /find_matches/input1.csv: -------------------------------------------------------------------------------- 1 | FirstName,LastName,Phone,Email,Zip John,Smith,(555) 123-4567,johns@home.com,94105 Jane,Smith,(555) 123-4567,janes@home.com,94105-1245 Jack,Smith,444.123.4567,jacks@home.com,94105 Josh,Smith,(456) 789-0123,joshs@home.com,94109 ,,15556549873,, Jack,,14441234567,, ,Smith,,janes@home.com, Josh,Smith,,,94109 -------------------------------------------------------------------------------- /find_matches/input2.csv: -------------------------------------------------------------------------------- 1 | FirstName,LastName,Phone1,Phone2,Email1,Email2,Zip 2 | John,Doe,(555) 123-4567,(555) 987-6543,johnd@home.com,,94105 3 | Jane,Doe,(555) 123-4567,(555) 654-9873,janed@home.com,johnd@home.com,94105 4 | Jack,Doe,(444) 123-4567,(555) 654-9873,jackd@home.com,,94109 5 | John,Doe,(555) 123-4567,(555) 987-6543,jackd@home.com,,94105 6 | Josh,Doe,(456) 789-0123,,joshd@home.com,jackd@home.com,94109 7 | Jill,Doe,(654) 987-1234,,jill@home.com,,94129 8 | -------------------------------------------------------------------------------- /programs/add_to_zero.py: -------------------------------------------------------------------------------- 1 | def add_to_zero(nums): 2 | """ Given list of ints, return True if any two nums sum to 0. 3 | 4 | >>> add_to_zero([]) 5 | False 6 | 7 | >>> add_to_zero([1]) 8 | False 9 | 10 | >>> add_to_zero([1, 2, 3]) 11 | False 12 | 13 | >>> add_to_zero([1, 2, 3, -2]) 14 | True 15 | """ 16 | 17 | # Runtime: O(n) 18 | # Spacetime: O(n) 19 | 20 | if len(nums) < 2: 21 | return False 22 | 23 | num_set = set(nums) 24 | 25 | for num in nums: 26 | if -num in num_set: 27 | return True 28 | 29 | return False 30 | 31 | 32 | 33 | if __name__ == '__main__': 34 | import doctest 35 | results = doctest.testmod() 36 | 37 | if results.failed == 0: 38 | print("ALL TESTS PASSED!") 39 | -------------------------------------------------------------------------------- /programs/anagram_of_palindrome.py: -------------------------------------------------------------------------------- 1 | # Is the word an anagram of a palindrome? 2 | 3 | # A palindrome is a word that reads the same forward and backwards (eg, "racecar", "tacocat"). An anagram is a rescrambling of a word (eg for "racecar", you could rescramble this as "arceace"). 4 | 5 | # Determine if the given word is a re-scrambling of a palindrome. 6 | 7 | # The word will only contain lowercase letters, a-z. 8 | 9 | def is_anagram_of_palindrome(word): 10 | """ Is the word an anagram of a palindrome? 11 | >>> is_anagram_of_palindrome("a") 12 | True 13 | 14 | >>> is_anagram_of_palindrome("ab") 15 | False 16 | 17 | >>> is_anagram_of_palindrome("aab") 18 | True 19 | 20 | >>> is_anagram_of_palindrome("arceace") 21 | True 22 | 23 | >>> is_anagram_of_palindrome("arceaceb") 24 | False 25 | """ 26 | 27 | # Runtime: O(n) 28 | 29 | word_dict = {} 30 | 31 | for l in word: 32 | word_dict['l'] = word_dict.get(l, 0) + 1 33 | 34 | for letter in word_dict: 35 | if word_dict[letter] % 2 != 0 and len(word) % 2 == 0: 36 | return False 37 | return True 38 | 39 | 40 | 41 | 42 | if __name__ == '__main__': 43 | import doctest 44 | results = doctest.testmod() 45 | 46 | if results.failed == 0: 47 | print("ALL TESTS PASSED!") 48 | -------------------------------------------------------------------------------- /programs/award_budget_cuts.py: -------------------------------------------------------------------------------- 1 | # Award Budget Cuts 2 | 3 | # The awards committee of your alma mater (i.e. your college/university) asked for your assistance with a budget allocation problem they're facing. Originally, the committee planned to give N research grants this year. However, due to spending cutbacks, the budget was reduced to newBudget dollars and now they need to reallocate the grants. The committee made a decision that they'd like to impact as few grant recipients as possible by applying a maximum cap on all grants. Every grant initially planned to be higher than cap will now be exactly cap dollars. Grants less or equal to cap, obviously, won't be impacted. 4 | 5 | # Given an array grantsArray of the original grants and the reduced budget newBudget, write a function findGrantsCap that finds in the most efficient manner a cap such that the least number of recipients is impacted and that the new budget constraint is met (i.e. sum of the N reallocated grants equals to newBudget). 6 | 7 | # Analyze the time and space complexities of your solution. 8 | 9 | # Example: 10 | 11 | # input: grantsArray = [2, 100, 50, 120, 1000], newBudget = 190 12 | 13 | # output: 47 # and given this cap the new grants array would be 14 | # # [2, 47, 47, 47, 47]. Notice that the sum of the 15 | # # new grants is indeed 190 16 | # Constraints: 17 | 18 | # [time limit] 5000ms 19 | 20 | # [input] array.double grantsArray 21 | 22 | # 0 <= grantsArray.length <= 20 23 | # 0 <= grantsArray[i] 24 | # [input] double newBudget 25 | 26 | # [output] double 27 | 28 | # Steps 29 | # 1. Sort reversed (or not reversed) 30 | # 2. Stop iteration conditions: 31 | # - cap < lowest grant amount 32 | # - when i doesn't move (flag) 33 | 34 | 35 | 36 | import unittest 37 | 38 | 39 | def find_grant_cap(grantsArray, newBudget): 40 | grantsArray = sorted(grantsArray, reverse=True) 41 | i = len(grantsArray) - 1 42 | flag = False 43 | cap = float(newBudget)/len(grantsArray) 44 | newBudget = float(newBudget) 45 | 46 | while not flag: 47 | 48 | while cap > grantsArray[i]: 49 | newBudget -= grantsArray[i] 50 | i -= 1 51 | 52 | new_cap = newBudget/(i + 1) 53 | 54 | if cap == new_cap: 55 | flag = True 56 | 57 | cap = new_cap 58 | 59 | return cap 60 | 61 | 62 | 63 | class Testing(unittest.TestCase): 64 | def test_find_grant_cap(self): 65 | self.assertEqual(find_grant_cap([2, 100, 50, 120, 1000], 190), 47) 66 | self.assertEqual(find_grant_cap([2,4], 3), 1.5) 67 | self.assertEqual(find_grant_cap([2,4,6], 3), 1) 68 | self.assertEqual(find_grant_cap([2,100,50,120,1000], 190), 47) 69 | self.assertEqual(find_grant_cap([2,100,50,120,167], 400), 128) 70 | self.assertEqual(find_grant_cap([21,100,50,120,130,110], 140), 23.8) 71 | self.assertEqual(find_grant_cap([210,200,150,193,130,110,209,342,117], 1530), 211) 72 | 73 | 74 | 75 | 76 | if __name__ == '__main__': 77 | unittest.main() 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /programs/binary_search.py: -------------------------------------------------------------------------------- 1 | # In this challenge, you'll make binary search for the classic children's guessing game of "pick a number from 1 to 100". 2 | 3 | def binary_search(val): 4 | """ Using binary search, find val in range 1-100. Return # of guesses. 5 | >>> binary_search(50) 6 | 1 7 | 8 | >>> binary_search(25) 9 | 2 10 | 11 | >>> binary_search(75) 12 | 2 13 | 14 | >>> binary_search(31) <= 7 15 | True 16 | 17 | >>> max([binary_search(i) for i in range(1, 101)]) 18 | 7 19 | """ 20 | 21 | # Runtime: O(nlogn) 22 | 23 | assert 0 < val < 101, "Val must be between 1-100" 24 | 25 | num_guesses = 0 26 | 27 | guess = None 28 | low = 0 29 | high = 101 30 | 31 | while guess != val: 32 | num_guesses += 1 33 | guess = (high - low)/2 + low 34 | 35 | if guess > val: 36 | high = guess 37 | elif guess < val: 38 | low = guess 39 | 40 | 41 | return num_guesses 42 | 43 | 44 | if __name__ == '__main__': 45 | import doctest 46 | results = doctest.testmod() 47 | 48 | if results.failed == 0: 49 | print("ALL TESTS PASSED") 50 | -------------------------------------------------------------------------------- /programs/bst_add_child.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | 3 | def __init__(self, data, left=None, right=None): 4 | """ Creates a node with data and optional left/right nodes. """ 5 | self.data = data 6 | self.left = left 7 | self.right = right 8 | 9 | 10 | def insert(self, new_data): 11 | """ Inserts a new node with 'new_data' to BST tree rooted here. 12 | A "balanced" binary search tree is one where the nodes are equitably spread out to guarantee O(log n) search. For this code challenge, you should not try to re-arrange the tree to rebalance it after adding an item; instead, you should simply find the correct place in the current tree to add it. 13 | 14 | 4 15 | 2 7 16 | 1 3 5 8 17 | 18 | >>> t = Node(4, Node(2, Node(1), Node(3)), Node(7, Node(5), Node(8))) 19 | 20 | >>> t.insert(0) 21 | >>> t.left.left.left.data == 0 22 | True 23 | >>> t.left.left.right is None 24 | True 25 | 26 | >>> t.insert(9) 27 | >>> t.right.right.right.data == 9 28 | True 29 | >>> t.right.right.left is None 30 | True 31 | 32 | >>> t.insert(6) 33 | >>> t.right.left.right.data == 6 34 | True 35 | >>> t.right.left.left is None 36 | True 37 | """ 38 | 39 | if new_data < self.data: 40 | 41 | if self.left is None: 42 | self.left = Node(new_data) 43 | else: 44 | self.left.insert(new_data) 45 | 46 | else: 47 | if self.right is None: 48 | self.right = Node(new_data) 49 | else: 50 | self.right.insert(new_data) 51 | 52 | 53 | 54 | 55 | if __name__ == '__main__': 56 | import doctest 57 | results = doctest.testmod() 58 | 59 | if results.failed == 0: 60 | print("ALL TESTS PASSED!") 61 | -------------------------------------------------------------------------------- /programs/calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # Correct, but uses eval 4 | # def evaluate(expression): 5 | # return eval(expression) 6 | 7 | 8 | # Correct, but uses eval 9 | # def evaluate(expression): 10 | # storage = [] 11 | # parens_indices = [] 12 | 13 | # for i in range(len(expression)): 14 | # char = expression[i] 15 | # if char == '(': 16 | # parens_indices.append(i) 17 | # elif char == ')': 18 | # start = parens_indices.pop() + 1 # parens + 1 position 19 | # total = str(eval(expression[start:i])) 20 | # storage = storage[:start-1] 21 | # storage.append(total) 22 | # else: 23 | # storage.append(char) 24 | 25 | # string_expression = ''.join(storage) 26 | # return eval(string_expression) 27 | 28 | 29 | # Without using eval: 30 | def evaluate(expression): 31 | expression = ''.join(expression.split(' ')) 32 | storage = [] 33 | parens_indices = [] 34 | operators = {'*': [], '/': [], '+': [],'-': []} 35 | 36 | for i in range(len(expression)): 37 | char = expression[i] 38 | if char == '(': 39 | parens_indices.append(i) 40 | elif char == ')': 41 | start = parens_indices.pop() + 1 42 | total = str(calculate(expression[start:i], operators)) 43 | storage = storage[:start-1] 44 | storage.append(total) 45 | else: 46 | storage.append(char) 47 | 48 | if char in operators: 49 | operators[char].append(i) 50 | 51 | string_expression = ''.join(storage) 52 | return calculate(string_expression, operators) 53 | 54 | 55 | def calculate(inner_expression, operators): 56 | total = 0 57 | operators = {'*': [], '/': [], '+': [],'-': []} 58 | new_expr = inner_expression 59 | 60 | for i in range(len(inner_expression)): 61 | char = inner_expression[i] 62 | if char in operators: 63 | operators[char].append(i) 64 | 65 | while operators['*'] != []: 66 | op_index = operators['*'].pop() 67 | prev = new_expr[op_index-1] 68 | nxt = new_expr[op_index+1] 69 | total = int(prev) * int(nxt) 70 | new_expr = new_expr[:op_index-1] + str(total) + new_expr[op_index+2:] 71 | print(new_expr) 72 | 73 | while operators['/'] != []: 74 | op_index = operators['/'].pop() 75 | prev = new_expr[op_index-1] 76 | nxt = new_expr[op_index+1] 77 | total = int(prev) / int(nxt) 78 | new_expr = new_expr[:op_index-1] + str(total) + new_expr[op_index+2:] 79 | 80 | while operators['-'] != []: 81 | op_index = operators['-'].pop() 82 | prev = new_expr[op_index-1] 83 | nxt = new_expr[op_index+1] 84 | total = int(prev) - int(nxt) 85 | new_expr = new_expr[:op_index-1] + str(total) + new_expr[op_index+2:] 86 | 87 | while operators['+'] != []: 88 | op_index = operators['+'].pop() 89 | prev = new_expr[op_index-1] 90 | nxt = new_expr[op_index+1] 91 | total = int(prev) + int(nxt) 92 | new_expr = new_expr[:op_index-1] + str(total) + new_expr[op_index+2:] 93 | 94 | return total 95 | 96 | 97 | 98 | class Testing(unittest.TestCase): 99 | 100 | def test_no_parens(self): 101 | self.assertEqual(evaluate('1 + 3 * 2'), 7) 102 | 103 | def test_single_parens(self): 104 | self.assertEqual(evaluate('(1 + 7) * 2'), 16) 105 | 106 | def test_operations_order(self): 107 | self.assertEqual(evaluate('4 * (1 + 7) - 3'), 29) 108 | 109 | def test_long_parens(self): 110 | self.assertEqual(evaluate('(4 - 7 - 1) * 3'), -6) 111 | 112 | def test_decimals(self): 113 | self.assertEqual(evaluate('(1.2 + 1.3) * 2.5'), 6.25) 114 | 115 | 116 | if __name__ == '__main__': 117 | unittest.main() 118 | 119 | -------------------------------------------------------------------------------- /programs/climb_stairs.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def climb_stairs(n): 5 | """ A fox needs to climb n number of steps. It can jump up 1 step, 2 steps, or 3 steps at a time. How many possible ways are there to get to the top of n steps? """ 6 | 7 | if n == 0 or n == 1: 8 | return 1 9 | 10 | if n == 2: 11 | return 2 12 | 13 | return climb_stairs(n-1) + climb_stairs(n-2) + climb_stairs(n-3) 14 | 15 | # Runtime: O(3^n) 16 | 17 | 18 | def climb_stairs_dp(n): 19 | """ A fox needs to climb n number of steps. It can jump up 1 step, 2 steps, or 3 steps at a time. How many possible ways are there to get to the top of n steps? Solve with dynamic programming using the memoization method. """ 20 | 21 | cache = { 2: 2, 1: 1, 0: 1 } 22 | 23 | if n in cache: 24 | return cache[n] 25 | 26 | cache[n] = climb_stairs(n-1) + climb_stairs(n-2) + climb_stairs(n-3) 27 | return cache[n] 28 | 29 | # Runtime: O(n) 30 | 31 | 32 | def climb_stairs_tab(n, steps): 33 | """ A fox needs to climb n number of steps. It can jump up X steps (array of possibilities) at a time. How many possible ways are there to get to the top of n steps? Solve with dynamic programming using the tabulation method. """ 34 | result = [0 for x in range(n)] 35 | result[0] = 1 36 | 37 | for i in range(len(steps)): 38 | for j in range(steps[i], len(steps)): 39 | sum = 0 40 | for k in range(0, i+1): 41 | sum += result[j - steps[k]]; 42 | result[j] = sum 43 | 44 | return result[n] 45 | 46 | 47 | 48 | class Testing(unittest.TestCase): 49 | def test_climb_stairs(self): 50 | self.assertEqual(climb_stairs(6), 24) 51 | self.assertEqual(climb_stairs(8), 81) 52 | 53 | def test_climb_stairs_dp(self): 54 | self.assertEqual(climb_stairs_dp(6), 24) 55 | self.assertEqual(climb_stairs_dp(8), 81) 56 | 57 | def test_climb_stairs_tab(self): 58 | self.assertEqual(climb_stairs_tab(6, [1, 2, 3]), 24) 59 | self.assertEqual(climb_stairs_tab(10, [2, 3, 5]), 14) 60 | 61 | 62 | 63 | 64 | 65 | if __name__ == '__main__': 66 | unittest.main() 67 | -------------------------------------------------------------------------------- /programs/coins.py: -------------------------------------------------------------------------------- 1 | def coins(num_coins): 2 | """ Find change from combinations of `num_coins` of dimes and pennies. 3 | 4 | This should return a set of the unique amounts of change possible. 5 | 6 | >>> coins(1) == {1, 10} 7 | True 8 | 9 | >>> coins(2) == {2, 11, 20} 10 | True 11 | 12 | >>> coins(3) == {3, 12, 21, 30} 13 | True 14 | 15 | >>> coins(4) == {4, 13, 22, 31, 40} 16 | True 17 | 18 | >>> coins(10) == {10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 100} 19 | True 20 | """ 21 | 22 | 23 | combos = set() 24 | coins = [1, 10] 25 | 26 | 27 | def _coins(coins_left, combos, total): 28 | 29 | if not coins_left: 30 | combos.add(total) 31 | return 32 | 33 | for coin in coins: 34 | _coins(coins_left - 1, combos, total + coin) 35 | 36 | _coins(num_coins, combos, 0) 37 | 38 | 39 | return combos 40 | 41 | 42 | def coins_2(num_coins): 43 | """ Find change from combinations of `num_coins` of dimes and pennies. 44 | 45 | This should return a set of the unique amounts of change possible. 46 | 47 | >>> coins_2(1) == {1, 10} 48 | True 49 | 50 | >>> coins_2(2) == {2, 11, 20} 51 | True 52 | 53 | >>> coins_2(3) == {3, 12, 21, 30} 54 | True 55 | 56 | >>> coins_2(4) == {4, 13, 22, 31, 40} 57 | True 58 | 59 | >>> coins_2(10) == {10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 100} 60 | True 61 | """ 62 | 63 | 64 | combos = set() 65 | dimes = 10 66 | pennies = 1 67 | 68 | 69 | def _coins_2(coins_left, combos, total): 70 | 71 | if not coins_left: 72 | combos.add(total) 73 | return 74 | 75 | _coins_2(coins_left - 1, combos, total + dimes) 76 | _coins_2(coins_left - 1, combos, total + pennies) 77 | 78 | _coins_2(num_coins, combos, 0) 79 | 80 | 81 | return combos 82 | 83 | 84 | 85 | 86 | 87 | if __name__ == '__main__': 88 | import doctest 89 | results = doctest.testmod() 90 | 91 | if not results.failed: 92 | print("ALL TESTS PASSED!") 93 | -------------------------------------------------------------------------------- /programs/count_employees.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | """ Node in a tree. """ 3 | 4 | def __init__(self, name, children=None): 5 | self.name = name 6 | self.children = children or [] 7 | 8 | 9 | def count_employees(self): 10 | """Return a count of how many employees this person manages. 11 | 12 | Return a count of how many people that manager manages. This should 13 | include *everyone* under them, not just people who directly report to 14 | them. 15 | 16 | >>> henri = Node("Henri") 17 | >>> nora = Node("Nora", [henri]) 18 | >>> nick = Node("Nick") 19 | >>> janet = Node("Janet", [nick, nora]) 20 | >>> al = Node("Al") 21 | >>> bob = Node("Bob") 22 | >>> jen = Node("Jen") 23 | >>> jessica = Node("Jessica", [al, bob, jen]) 24 | >>> jane = Node("Jane", [jessica, janet]) 25 | 26 | >>> henri.count_employees() 27 | 0 28 | 29 | >>> janet.count_employees() 30 | 3 31 | 32 | >>> jessica.count_employees() 33 | 3 34 | 35 | >>> jane.count_employees() 36 | 8 37 | 38 | """ 39 | 40 | if not self.children: 41 | return 0 42 | 43 | count = 0 44 | 45 | for child in self.children: 46 | count += 1 + child.count_employees() 47 | 48 | return count 49 | 50 | 51 | 52 | 53 | if __name__ == '__main__': 54 | import doctest 55 | results = doctest.testmod() 56 | 57 | if results.failed == 0: 58 | print("ALL TESTS PASSED!") 59 | -------------------------------------------------------------------------------- /programs/count_recursively.py: -------------------------------------------------------------------------------- 1 | def count_recursively(lst): 2 | """ Return number of items in a list, using recursion. 3 | >>> count_recursively([]) 4 | 0 5 | 6 | >>> count_recursively([1, 2, 3]) 7 | 3 8 | """ 9 | 10 | 11 | if not lst: 12 | return 0 13 | 14 | return 1 + count_recursively(lst[1:]) 15 | 16 | 17 | if __name__ == '__main__': 18 | import doctest 19 | results = doctest.testmod() 20 | 21 | if results.failed == 0: 22 | print("ALL TESTS PASSED!") 23 | -------------------------------------------------------------------------------- /programs/create_queue.py: -------------------------------------------------------------------------------- 1 | class Queue(object): 2 | """ Creates a queue. """ 3 | 4 | def __init__(self): 5 | self.items = [] 6 | 7 | 8 | def __repr__(self): 9 | if not self.length(): 10 | return '' 11 | else: 12 | return '' % self.items 13 | 14 | 15 | def length(self): 16 | return len(self.items) 17 | 18 | 19 | def dequeue(self): 20 | """ Removes item from the front of the queue. """ 21 | 22 | if self.items > 0: 23 | return self.items.pop(0) 24 | else: 25 | raise IndexError('queue is empty.') 26 | 27 | 28 | def enqueue(self, item): 29 | """Add item to end of queue:: 30 | 31 | >>> q = Queue() 32 | >>> q.enqueue("buy flight") 33 | >>> q.enqueue("pack") 34 | >>> q.enqueue("enjoy vacation") 35 | 36 | >>> q 37 | 38 | 39 | >>> q.length() 40 | 3 41 | """ 42 | self.items.append(item) 43 | 44 | 45 | def is_empty(self): 46 | return not self.items 47 | 48 | 49 | def peek(self): 50 | """Return but don't remove the first item in the queue. 51 | 52 | >>> q = Queue() 53 | >>> q.enqueue("buy flight") 54 | >>> q.enqueue("pack") 55 | >>> q.enqueue("enjoy vacation") 56 | 57 | >>> q.peek() 58 | 'buy flight' 59 | 60 | >>> q 61 | 62 | """ 63 | return self.items[0] 64 | 65 | if __name__ == '__main__': 66 | import doctest 67 | results = doctest.testmod() 68 | 69 | if not results.failed: 70 | print("ALL TESTS PASSED!") 71 | 72 | -------------------------------------------------------------------------------- /programs/create_queue_ll.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | """ Creates a node class. """ 3 | 4 | def __init__(self, data): 5 | self.data = data 6 | self.next = None 7 | 8 | 9 | 10 | class Queue(object): 11 | """ Creates a queue using a linked list. """ 12 | 13 | def __init__(self): 14 | self.head = None 15 | self.tail = None 16 | 17 | 18 | def __repr__(self): 19 | if not self.length(): 20 | return '' 21 | else: 22 | return '' % self.head 23 | 24 | 25 | def length(self): 26 | """ Gets length of queue. 27 | 28 | >>> q = Queue() 29 | 30 | >>> q.length() 31 | 0 32 | """ 33 | 34 | curr = self.head 35 | 36 | length = 0 37 | 38 | while curr is not None: 39 | length += 1 40 | curr = curr.next 41 | 42 | return length 43 | 44 | 45 | def enqueue(self, item): 46 | """ Add item to end of queue:: 47 | 48 | >>> q = Queue() 49 | >>> q.enqueue("buy flight") 50 | >>> q.enqueue("pack") 51 | >>> q.enqueue("enjoy vacation") 52 | 53 | >>> q.print_queue() 54 | ['buy flight', 'pack', 'enjoy vacation'] 55 | 56 | >>> q.length() 57 | 3 58 | """ 59 | 60 | new_node = Node(item) 61 | 62 | if self.head is None and self.tail is None: 63 | self.head = new_node 64 | self.tail = new_node 65 | else: 66 | self.tail.next = new_node 67 | self.tail = new_node 68 | 69 | 70 | def dequeue(self): 71 | """ Add item to end of queue:: 72 | 73 | >>> q = Queue() 74 | >>> q.enqueue("buy flight") 75 | >>> q.enqueue("pack") 76 | >>> q.enqueue("vacation") 77 | 78 | >>> q.print_queue() 79 | ['buy flight', 'pack', 'vacation'] 80 | 81 | >>> q.dequeue() 82 | 'buy flight' 83 | 84 | >>> q.print_queue() 85 | ['pack', 'vacation'] 86 | 87 | >>> q2 = Queue() 88 | >>> q2.dequeue() 89 | 90 | """ 91 | 92 | if self.head is None: 93 | return None 94 | else: 95 | dequeued = self.head.data 96 | self.head = self.head.next 97 | return dequeued 98 | 99 | 100 | def is_empty(self): 101 | """ True/false if queue is empty. 102 | 103 | >>> q = Queue() 104 | >>> q.enqueue("buy flight") 105 | >>> q.enqueue("pack") 106 | >>> q.enqueue("vacation") 107 | >>> q.is_empty() 108 | False 109 | 110 | >>> q2 = Queue() 111 | >>> q2.is_empty() 112 | True 113 | """ 114 | 115 | return self.head is None 116 | 117 | 118 | def peek(self): 119 | """ Return but don't remove the first item in the queue. 120 | 121 | >>> q = Queue() 122 | >>> q.enqueue("buy flight") 123 | >>> q.enqueue("pack") 124 | >>> q.enqueue("enjoy vacation") 125 | 126 | >>> q.peek() 127 | 'buy flight' 128 | 129 | >>> q.print_queue() 130 | ['buy flight', 'pack', 'enjoy vacation'] 131 | 132 | """ 133 | 134 | return self.head.data 135 | 136 | 137 | def print_queue(self): 138 | """ Prints items in queue in a list. 139 | 140 | >>> q = Queue() 141 | >>> q.enqueue("buy flight") 142 | >>> q.enqueue("pack") 143 | >>> q.enqueue("enjoy vacation") 144 | 145 | >>> q.print_queue() 146 | ['buy flight', 'pack', 'enjoy vacation'] 147 | 148 | >>> q2 = Queue() 149 | >>> q2.print_queue() 150 | [] 151 | 152 | """ 153 | 154 | curr = self.head 155 | 156 | if curr is None: 157 | return list() 158 | 159 | queue = [] 160 | 161 | while curr is not None: 162 | queue.append(curr.data) 163 | curr = curr.next 164 | 165 | return queue 166 | 167 | 168 | 169 | if __name__ == '__main__': 170 | import doctest 171 | results = doctest.testmod() 172 | 173 | if not results.failed: 174 | print("ALL TESTS PASSED!") 175 | 176 | -------------------------------------------------------------------------------- /programs/create_stack.py: -------------------------------------------------------------------------------- 1 | class Stack(object): 2 | """LIFO stack. 3 | 4 | Implemented using a Python list; since stacks just need 5 | to pop and push, a list is a good implementation, as 6 | these are O(1) for native Python lists. However, in cases 7 | where performance really matters, it might be best to 8 | use a Python list directly, as it avoids the overhead 9 | of a custom class. 10 | 11 | Or, for even better performance (& typically smaller 12 | memory footprint), you can use the `collections.deque` 13 | object, which can act like a stack. 14 | 15 | (We could also write our own LinkedList class for a 16 | stack, where we push things onto the head and pop things 17 | off the head (effectively reversing it), but that would be less 18 | efficient than using a built-in Python list or a 19 | `collections.deque` object) 20 | """ 21 | 22 | def __init__(self): 23 | self.items = [] 24 | self.min_stack = [] 25 | 26 | 27 | def __repr__(self): 28 | if not self.items: 29 | return "" 30 | else: 31 | return "" % ( 32 | self.items[-1], len(self.items)) 33 | 34 | 35 | def push(self, item): 36 | """Add item to end of stack.""" 37 | 38 | self.items.append(item) 39 | 40 | if self.min_stack == [] or self.min_stack[-1] > item: 41 | self.min_stack.append(item) 42 | 43 | else: 44 | self.min_stack.append(self.min_stack[-1]) 45 | 46 | 47 | def pop(self): 48 | """Remove item from end of stack and return it.""" 49 | 50 | if self.is_empty(): 51 | return IndexError('pop from empty list') 52 | 53 | self.min_stack.pop() 54 | 55 | return self.items.pop() 56 | 57 | 58 | def __iter__(self): 59 | """Allow iteration over list. 60 | 61 | __iter__ is a special method that, when defined, 62 | allows you to loop over a list, so you can say things 63 | like "for item in my_stack", and it will pop 64 | successive items off. 65 | """ 66 | 67 | while True: 68 | try: 69 | yield self.pop() 70 | except StackEmptyError: 71 | raise StopIteration 72 | 73 | 74 | def length(self): 75 | """Return length of stack:: 76 | 77 | >>> s = Stack() 78 | >>> s.length() 79 | 0 80 | 81 | >>> s.push(3) 82 | >>> s.push(4) 83 | >>> s.push(5) 84 | 85 | >>> s.length() 86 | 3 87 | """ 88 | 89 | count = 0 90 | for item in self.items: 91 | count += 1 92 | return count 93 | 94 | 95 | def empty(self): 96 | """Empty stack:: 97 | 98 | >>> s = Stack() 99 | >>> s.push(4) 100 | >>> s.push(3) 101 | >>> s.push(2) 102 | 103 | >>> s.length() 104 | 3 105 | 106 | >>> s.empty() 107 | 108 | >>> s.length() 109 | 0 110 | """ 111 | 112 | self.items = [] 113 | self.min_stack = [] 114 | 115 | 116 | def is_empty(self): 117 | """Is stack empty? 118 | 119 | >>> s = Stack() 120 | 121 | >>> s.is_empty() 122 | True 123 | 124 | >>> s.push(3) 125 | >>> s.push(2) 126 | >>> s.push(4) 127 | 128 | >>> s.is_empty() 129 | False 130 | """ 131 | 132 | return self.items == [] 133 | 134 | 135 | def find_min(self): 136 | """ Returns the minimum value of a numerical stack. 137 | 138 | >>> s = Stack() 139 | >>> s.push(2) 140 | >>> s.push(1) 141 | >>> s.push(3) 142 | >>> s.push(-1) 143 | >>> s.find_min() 144 | -1 145 | 146 | >>> s2 = Stack() 147 | >>> s2.push(2) 148 | >>> s2.push(1) 149 | >>> s2.push(3) 150 | >>> s2.find_min() 151 | 1 152 | 153 | >>> s3 = Stack() 154 | >>> s3.push(2) 155 | >>> s3.push(1) 156 | >>> s3.push(3) 157 | >>> s3.push(3) 158 | >>> s3.push(1) 159 | >>> s3.find_min() 160 | 1 161 | 162 | >>> s3.pop() 163 | 1 164 | >>> s3.find_min() 165 | 1 166 | 167 | >>> s3.pop() 168 | 3 169 | >>> s3.pop() 170 | 3 171 | >>> s3.pop() 172 | 1 173 | >>> s3.find_min() 174 | 2 175 | """ 176 | 177 | if not self.is_empty(): 178 | return self.min_stack[-1] 179 | 180 | 181 | 182 | if __name__ == "__main__": 183 | import doctest 184 | 185 | print 186 | result = doctest.testmod() 187 | if not result.failed: 188 | print("ALL TESTS PASSED. GOOD WORK!") 189 | print 190 | 191 | -------------------------------------------------------------------------------- /programs/decode_string.py: -------------------------------------------------------------------------------- 1 | def decode(s): 2 | """ Decodes a string. A valid code is a sequence of numbers and letters, always starting with a number and ending with letter(s). 3 | 4 | Each number tells you how many characters to skip before finding a good letter. After each good letter should come the next next number. 5 | 6 | >>> decode("0h") 7 | 'h' 8 | 9 | >>> decode("2abh") 10 | 'h' 11 | 12 | >>> decode("0h1ae2bcy") 13 | 'hey' 14 | """ 15 | 16 | # Runtime: O(n) 17 | # Spacetime: O(n) 18 | 19 | decoded = '' 20 | 21 | for l in range(len(s)): 22 | try: 23 | int(s[l]) 24 | decoded += s[int(s[l]) + l + 1] 25 | except: 26 | continue 27 | 28 | return decoded 29 | 30 | 31 | 32 | def decode_2(s): 33 | """ Decodes a string. A valid code is a sequence of numbers and letters, always starting with a number and ending with letter(s). 34 | 35 | Each number tells you how many characters to skip before finding a good letter. After each good letter should come the next next number. 36 | 37 | >>> decode_2("0h") 38 | 'h' 39 | 40 | >>> decode_2("2abh") 41 | 'h' 42 | 43 | >>> decode_2("0h1ae2bcy") 44 | 'hey' 45 | """ 46 | 47 | # Runtime: O(n) 48 | # Spacetime: O(n) 49 | 50 | def _decode_2(s, decoded, i): 51 | 52 | if i >= len(s): 53 | return decoded 54 | 55 | current = s[i] 56 | 57 | if current.isdigit(): 58 | decoded += s[int(current) + i + 1] 59 | 60 | return _decode_2(s, decoded, i+1) 61 | 62 | return _decode_2(s, '', 0) 63 | 64 | 65 | 66 | 67 | if __name__ == '__main__': 68 | import doctest 69 | results = doctest.testmod() 70 | 71 | if results.failed == 0: 72 | print("ALL TESTS PASSED!") 73 | -------------------------------------------------------------------------------- /programs/etl_client.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | class ETLClient: 4 | def run(self, service, max_requests): 5 | """ 6 | Handle max_requests calls to the given DocumentService. 7 | RetryImmediatelyError should be silently ignored and should *not* 8 | count as a request. 9 | Return document list. 10 | Content truncated due to max data buffer of 50kb being reached. Try flushing buffer with less content. 11 | 12 | Please write a simple ETL client for an fake document service. 13 | 14 | Requirements 15 | 1: run() must return a JSON string. 16 | See test_req_1 17 | 18 | 2: run() must return a JSON string as a dictionary, containing: 19 | 20 | 'doc-count': [integer] the number of documents received 21 | 'error-count':[integer] the number of errors received 22 | 'docs': [dictionary] keys are a document's ID string and values are arrays of words in the document 23 | See test_req_2 24 | 3: all of run()'s output words must be lower case 25 | See test_req_3 26 | 27 | 4: these words must not appear in the word array: and, or, not, but, to, in 28 | See test_req_4 29 | 30 | 5: RetryImmediatelyError. 31 | The service's handle_request() may raise RetryImmediatelyError. 32 | Do not count the error against the number of requests to run. 33 | Re-try the operation (by calling the handle_request() again) until successful. 34 | Include the number of errors in the output as in described in 2 above. 35 | See test_req_5 36 | 37 | 6: The service may ask you to 'update' docs. These requests will look like: 38 | 39 | {'operation': 'update', 40 | 'document': { 41 | 'id': [string] document id 42 | 'data': [string] new document data 43 | } 44 | } 45 | Expect that the document ID will match an existing document previously sent by an 'add' operation. 46 | The document with the matching ID should have its data replaced with the data sent in the 'update' operation. 47 | See test_req_6 48 | 49 | 7: 50 | The service may ask you to 'delete' docs. These requests will look like: 51 | 52 | {'operation': 'delete', 53 | 'document-id': [string] document id 54 | } 55 | Expect that the document ID will match an existing document previously sent by an 'add' operation. 56 | Delete the document that matches that ID. 57 | See test_req_7 58 | """ 59 | documents = [] 60 | 61 | documents.append({ 62 | 'doc-count': 0, 63 | 'error-count': 0, 64 | 'docs': {} 65 | }) 66 | 67 | for i in range(0, max_requests): 68 | 69 | while True: 70 | 71 | try: 72 | event = service.handle_request() 73 | 74 | if event['operation'] == 'add': 75 | # 'add': service sends us: 76 | # {'operation':'add','document':{'data':'','id':''}} 77 | doc_id = event['document']['id'] 78 | doc_data = self.remove_words(event['document']['data']) 79 | 80 | # adds new doc_id and data 81 | documents[0]['docs'][doc_id] = doc_data 82 | 83 | # counts number of documents 84 | documents[0]['doc-count'] = documents[0].get('doc-count') + 1 85 | 86 | if event['operation'] == 'update': 87 | doc_id = event['document']['id'] 88 | doc_data = self.remove_words(event['document']['data']) 89 | 90 | # updates doc data by on doc id 91 | documents[0]['docs'][doc_id] = doc_data 92 | 93 | if event['operation'] == 'delete': 94 | # removes document 95 | doc_id = event['document-id'] 96 | docs = documents[0]['docs'] 97 | for docid, data in docs.items(): 98 | if docid == doc_id: 99 | del docs[docid] 100 | 101 | # subtracts 1 from number of documents 102 | documents[0]['doc-count'] = documents[0].get('doc-count') - 1 103 | 104 | except RetryImmediatelyError: 105 | # counts number of retry errors 106 | documents[0]['error-count'] = documents[0].get('error-count') + 1 107 | continue 108 | 109 | break 110 | 111 | return json.dumps(documents[0]) 112 | 113 | 114 | def remove_words(self, string): 115 | # sanitizes string data in documents 116 | 117 | remove_words = set(['and', 'or', 'not', 'but', 'to', 'in']) 118 | words = string.lower().split(' ') 119 | 120 | for word in words: 121 | if word in remove_words: 122 | words.remove(word) 123 | 124 | return words 125 | 126 | 127 | 128 | class Test(unittest.TestCase): 129 | def test_req_1(self): 130 | self.assertIsInstance(ETLClient().run(DocumentService(2), 1), basestring) 131 | 132 | def test_req_2(self): 133 | r = ETLClient().run(DocumentService(2), 2) 134 | expect = [ 135 | json.dumps({ 136 | 'doc-count': 2, 137 | 'error-count': 0, 138 | 'docs': { 139 | 'f01dba4999266bff87400756e8830528': "aliquid cum ut labore nesciunt Voluptatibus eius Fugiat Sunt not error Nulla vitae rerum".split(), 140 | '87e8d5ee79eb735b2e4e4fb88a9438e9': "nihil natus Voluptatibus aperiam Quo".split() 141 | } 142 | }), 143 | json.dumps({ 144 | 'doc-count': 2, 145 | 'error-count': 0, 146 | 'docs': { 147 | 'f01dba4999266bff87400756e8830528': "aliquid cum ut labore nesciunt voluptatibus eius fugiat sunt not error nulla vitae rerum".split(), 148 | '87e8d5ee79eb735b2e4e4fb88a9438e9': "nihil natus voluptatibus aperiam quo".split() 149 | } 150 | }), 151 | json.dumps({ 152 | 'doc-count': 2, 153 | 'error-count': 0, 154 | 'docs': { 155 | 'f01dba4999266bff87400756e8830528': "aliquid cum ut labore nesciunt voluptatibus eius fugiat sunt error nulla vitae rerum".split(), 156 | '87e8d5ee79eb735b2e4e4fb88a9438e9': "nihil natus voluptatibus aperiam quo".split() 157 | } 158 | }) 159 | ] 160 | self.assertIn(r,expect) 161 | 162 | def test_req_3(self): 163 | r = ETLClient().run(DocumentService(2), 2) 164 | expect = [ 165 | json.dumps({ 166 | 'doc-count': 2, 167 | 'error-count': 0, 168 | 'docs': { 169 | 'f01dba4999266bff87400756e8830528': "aliquid cum ut labore nesciunt voluptatibus eius fugiat sunt not error nulla vitae rerum".split(), 170 | '87e8d5ee79eb735b2e4e4fb88a9438e9': "nihil natus voluptatibus aperiam quo".split() 171 | } 172 | }), 173 | json.dumps({ 174 | 'doc-count': 2, 175 | 'error-count': 0, 176 | 'docs': { 177 | 'f01dba4999266bff87400756e8830528': "aliquid cum ut labore nesciunt voluptatibus eius fugiat sunt error nulla vitae rerum".split(), 178 | '87e8d5ee79eb735b2e4e4fb88a9438e9': "nihil natus voluptatibus aperiam quo".split() 179 | } 180 | }) 181 | ] 182 | self.assertIn(r,expect) 183 | 184 | def _ordered(self, obj): 185 | """ 186 | sorts multi-level objects recursively 187 | """ 188 | if isinstance(obj, dict): 189 | return sorted((k, self._ordered(v)) for k, v in obj.items()) 190 | if isinstance(obj, list): 191 | return sorted(self._ordered(x) for x in obj) 192 | else: 193 | return obj 194 | 195 | def test_req_4(self): 196 | r = ETLClient().run(DocumentService(2), 2) 197 | expect = json.dumps({ 198 | 'doc-count': 2, 199 | 'error-count': 0, 200 | 'docs': { 201 | 'f01dba4999266bff87400756e8830528': "aliquid cum ut labore nesciunt voluptatibus eius fugiat sunt error nulla vitae rerum".split(), 202 | '87e8d5ee79eb735b2e4e4fb88a9438e9': "nihil natus voluptatibus aperiam quo".split() 203 | } 204 | }) 205 | self.assertIn(self._ordered(r),self._ordered(expect)) 206 | 207 | def test_req_5(self): 208 | r = ETLClient().run(DocumentService(2), 3) 209 | expect = json.dumps({ 210 | 'doc-count': 3, 211 | 'error-count': 1, 212 | 'docs': { 213 | 'f01dba4999266bff87400756e8830528': "aliquid cum ut labore nesciunt voluptatibus eius fugiat sunt error nulla vitae rerum".split(), 214 | '87e8d5ee79eb735b2e4e4fb88a9438e9': "nihil natus voluptatibus aperiam quo".split(), 215 | '43e18d33e6b052a1f0b04d22b60f2059': "non occaecati accusantium animi eius sit placeat fugit dolor voluptate iure a".split() 216 | } 217 | }) 218 | self.assertIn(self._ordered(r),self._ordered(expect)) 219 | 220 | def test_req_6(self): 221 | r = ETLClient().run(DocumentService(6), 3) 222 | expect = json.dumps({ 223 | 'doc-count': 2, 224 | 'error-count': 1, 225 | 'docs': { 226 | 'd740a7c5c4cb68a38c4cad51cc713a4f': 'quia consectetur maiores mollitia'.split(), 227 | '9491e81a43723db0c05e94662f06b6f3': 'ut accusantium recusandae animi velit labore id iure voluptate vel enim quo consequatur saepe'.split() 228 | } 229 | }) 230 | self.assertIn(self._ordered(r),self._ordered(expect)) 231 | 232 | def test_req_7(self): 233 | r = ETLClient().run(DocumentService(6), 9) 234 | expect = json.dumps({ 235 | 'doc-count': 0, 236 | 'error-count': 1, 237 | 'docs': { 238 | } 239 | }) 240 | self.assertIn(self._ordered(r),self._ordered(expect)) 241 | -------------------------------------------------------------------------------- /programs/find_longest_word.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | 5 | def find_longest_word(words): 6 | """Return longest word in list of words.""" 7 | 8 | longest = 0 9 | 10 | for word in words: 11 | longest = max(len(word), longest) 12 | 13 | return longest 14 | 15 | 16 | class test_solution(unittest.TestCase): 17 | 18 | def test_find_longest_word(self): 19 | self.assertEqual(find_longest_word(["hi", "hello"]), 5) 20 | self.assertEqual(find_longest_word(["Balloonicorn", "Hackbright"]), 12) 21 | 22 | 23 | 24 | if __name__ == "__main__": 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /programs/find_mode.py: -------------------------------------------------------------------------------- 1 | def find_mode(arr): 2 | """ Finds the mode(s) of the array. 3 | 4 | >>> find_mode([3,5,6,2,6,7,8,3,6,6]) 5 | set([6]) 6 | 7 | >>> find_mode([1,2,3,4,5]) 8 | set([1, 2, 3, 4, 5]) 9 | 10 | >>> find_mode([2,1,2,1]) 11 | set([1, 2]) 12 | 13 | >>> find_mode([1,2,3,2,4]) 14 | set([2]) 15 | 16 | >>> find_mode([]) 17 | set([]) 18 | 19 | """ 20 | 21 | if not arr: 22 | return set([]) 23 | if len(arr) < 2: 24 | return set([arr[0]]) 25 | 26 | nums = {} 27 | mode = None 28 | n = set() 29 | 30 | for i in arr: 31 | nums[i] = nums.get(i, 0) + 1 32 | 33 | for num, val in nums.iteritems(): 34 | if val > mode: 35 | mode = val 36 | n = set([num]) 37 | if val == mode and num not in n: 38 | n.add(num) 39 | return n 40 | 41 | 42 | 43 | 44 | 45 | if __name__ == '__main__': 46 | import doctest 47 | results = doctest.testmod() 48 | 49 | if not results.failed: 50 | print("ALL TESTS PASSED!") 51 | -------------------------------------------------------------------------------- /programs/first_duplicate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Note: Write a solution with O(n) time complexity and O(1) additional space complexity, since this is what you would be asked to do during a real interview. 3 | 4 | Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1. 5 | 6 | Example 7 | 8 | For a = [2, 3, 3, 1, 5, 2], the output should be 9 | firstDuplicate(a) = 3. 10 | 11 | There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than than second occurrence of 2 does, so the answer is 3. 12 | 13 | For a = [2, 4, 3, 5, 1], the output should be 14 | firstDuplicate(a) = -1. 15 | 16 | Input/Output 17 | 18 | [time limit] 4000ms (py) 19 | [input] array.integer a 20 | 21 | Guaranteed constraints: 22 | 1 <= a.length <= 105, 23 | 1 <= a[i] <= a.length. 24 | 25 | [output] integer 26 | 27 | The element in a that occurs in the array more than once and has the minimal index for its second occurrence. If there are no such elements, return -1. 28 | """ 29 | 30 | def first_duplicate(a): 31 | """ 32 | 33 | >>> first_duplicate([8, 4, 6, 2, 6, 4, 7, 9, 5, 8]) 34 | 6 35 | 36 | >>> first_duplicate([2, 3, 3, 1, 5, 2]) 37 | 3 38 | 39 | >>> first_duplicate([1]) 40 | -1 41 | 42 | >>> first_duplicate([2, 1]) 43 | -1 44 | 45 | >>> first_duplicate([2, 2]) 46 | 2 47 | 48 | >>> first_duplicate([2, 4, 3, 5, 1]) 49 | -1 50 | 51 | """ 52 | 53 | # time: O(n^2) 54 | # space: O(n) 55 | 56 | lowest_index = len(a) 57 | for i in range(len(a)): 58 | num = a[i] 59 | if num in a[i+1:]: 60 | index = a[i+1:].index(num) + i + 1 61 | if index < lowest_index: 62 | lowest_index = index 63 | 64 | if lowest_index < len(a): 65 | return a[lowest_index] 66 | 67 | 68 | return -1 69 | 70 | 71 | def first_duplicate_optimized(arr): 72 | """ 73 | >>> first_duplicate_optimized([8, 4, 6, 2, 6, 4, 7, 1, 5, 8]) 74 | 6 75 | 76 | >>> first_duplicate_optimized([2, 3, 3, 1, 5, 2]) 77 | 3 78 | 79 | >>> first_duplicate_optimized([1]) 80 | -1 81 | 82 | >>> first_duplicate_optimized([2, 1]) 83 | -1 84 | 85 | >>> first_duplicate_optimized([2, 2]) 86 | 2 87 | 88 | >>> first_duplicate([2, 4, 3, 5, 1]) 89 | -1 90 | 91 | """ 92 | 93 | # time: O(n) 94 | # space: O(1) 95 | 96 | 97 | for i in range(len(arr)): 98 | 99 | value = arr[abs(arr[i])-1] 100 | 101 | if value >= 0: 102 | arr[abs(arr[i])-1] = -value 103 | else: 104 | return abs(arr[i]) 105 | 106 | return -1 107 | 108 | 109 | 110 | if __name__ == "__main__": 111 | import doctest 112 | results = doctest.testmod() 113 | 114 | if not results.failed: 115 | print("All tests passed!") 116 | -------------------------------------------------------------------------------- /programs/has_balanced_brackets.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def has_balanced_brackets(phrase): 5 | """Does a given string have balanced pairs of brackets? 6 | 7 | Given a string as input, return True or False depending on whether the 8 | string contains balanced (), {}, [], and/or <>. 9 | """ 10 | brackets = { 11 | ']': '[', 12 | '}': '{', 13 | '[': '[', 14 | '>': '<', 15 | ')': '(' 16 | } 17 | open_brackets = set(['[', '{', '[', '<', '(']) 18 | close_brackets = set([']', '}', ']', '>', ')']) 19 | seen = [] 20 | 21 | for let in phrase: 22 | if let in open_brackets: 23 | seen.append(let) 24 | if let in close_brackets: 25 | if seen != [] and brackets[let] == seen[-1]: 26 | seen.pop() 27 | else: 28 | return False 29 | 30 | 31 | if seen == []: 32 | return True 33 | 34 | 35 | 36 | class test_solutions(unittest.TestCase): 37 | 38 | def test_has_balanced_brackets(self): 39 | self.assertTrue(has_balanced_brackets("")) 40 | self.assertTrue(has_balanced_brackets("<[ok]>")) 41 | self.assertTrue(has_balanced_brackets("<[{(yay)}]>")) 42 | self.assertTrue(has_balanced_brackets("No brackets here!")) 43 | 44 | self.assertFalse(has_balanced_brackets("(Oops!){")) 45 | self.assertFalse(has_balanced_brackets("{[[This has too many open square brackets.]}")) 46 | self.assertFalse(has_balanced_brackets(">")) 47 | self.assertFalse(has_balanced_brackets("(This has {too many} ) closers. )")) 48 | self.assertFalse(has_balanced_brackets("<{Not Ok>}")) 49 | 50 | 51 | 52 | if __name__ == "__main__": 53 | unittest.main() 54 | -------------------------------------------------------------------------------- /programs/hash_map.py: -------------------------------------------------------------------------------- 1 | """ Create a hash map. """ 2 | 3 | class HashMap(object): 4 | 5 | def __init__(self): 6 | """ Creates hash list of lists. """ 7 | 8 | # In a 64-bit system, creates 64 lists in a list 9 | self.hash = [[] for x in range(64)] 10 | 11 | 12 | def hashing(self, key): 13 | """ Hashes a key and returns the hashed index. """ 14 | 15 | value = 0 16 | 17 | # Gets the total ASCII value of the key 18 | for char in key: 19 | value += ord(char) 20 | 21 | # Returns index of range(0, 64) for each of the 64 slots 22 | index = value % 64 23 | 24 | return index 25 | 26 | 27 | def find_val(self, key): 28 | """ Finds the key and returns the value in hashmap, if none returns keyerror. """ 29 | 30 | index = self.hashing(key) 31 | position = self.hash[index] 32 | 33 | if position != []: 34 | # Loops through items at hashed index to return tuple value 35 | for item in position: 36 | if item[0] == key: 37 | return item[1] 38 | raise KeyError('Key does not exist.') 39 | 40 | else: 41 | raise KeyError('Key does not exist.') 42 | 43 | 44 | def update_or_add(self, key, val): 45 | """ Updates or adds a new key value pair. """ 46 | 47 | index = self.hashing(key) 48 | position = self.hash[index] 49 | 50 | # Loops through items at hashed index 51 | # If the position is not empty 52 | if position != []: 53 | # Update the value if the key exists 54 | for item in position: 55 | if item[0] == key: 56 | item[1] = val 57 | break 58 | # If no key exists 59 | position.append((key, value)) 60 | 61 | # If list is empty 62 | else: 63 | position.append((key, value)) 64 | 65 | 66 | def delete(self, key): 67 | """ Takes a key and deletes the key and value from the hashmap. """ 68 | 69 | index = self.hashing(key) 70 | position = self.hash[index] 71 | 72 | if position != []: 73 | for i, item in enumerate(position): 74 | if item[0] == key: 75 | del position[i] 76 | break 77 | raise KeyError('Key does not exist.') 78 | 79 | else: 80 | raise KeyError('Key does not exist.') 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /programs/highest_product_of_three.py: -------------------------------------------------------------------------------- 1 | def highest_product_of_three(list_of_ints): 2 | """ Takes a list of integers and returns the highest product of three of the integers. The input list_of_ints will always have at least three integers. 3 | 4 | >>> highest_product_of_three([1,2,3,4,5]) 5 | 60 6 | 7 | >>> highest_product_of_three([1,2,3,4,-5]) 8 | 24 9 | 10 | >>> highest_product_of_three([-10,-10,1,3,2]) 11 | 300 12 | 13 | >>> highest_product_of_three([10,2,5]) 14 | 100 15 | 16 | >>> highest_product_of_three([5,4,3,2,1]) 17 | 60 18 | 19 | """ 20 | 21 | # Runtime: O(n) 22 | # Spacetime: O(1) 23 | 24 | highest_product = list_of_ints[0] * list_of_ints[1] * list_of_ints[2] 25 | highest = list_of_ints[0] 26 | lowest = list_of_ints[0] 27 | highest_two = list_of_ints[0] * list_of_ints[1] 28 | lowest_two = list_of_ints[0] * list_of_ints[1] 29 | 30 | if len(list_of_ints) == 3: 31 | return highest_product 32 | 33 | 34 | for i in range(2,len(list_of_ints)-1): 35 | product = list_of_ints[i] * list_of_ints[i + 1] 36 | current_num = list_of_ints[i] 37 | 38 | if current_num > highest: 39 | highest = current_num 40 | if product > highest_two: 41 | highest_two = product 42 | elif current_num < lowest: 43 | lowest = current_num 44 | if product < lowest_two: 45 | lowest_two = product 46 | 47 | if highest_two * highest > lowest_two * lowest: 48 | highest_product = highest_two * highest 49 | elif highest_two * highest < lowest_two * lowest: 50 | highest_product = lowest_two * lowest 51 | elif highest_two * lowest < lowest_two * highest: 52 | highest_product = lowest_two * highest 53 | else: 54 | highest_product = highest_two * lowest 55 | 56 | return highest_product 57 | 58 | 59 | 60 | 61 | if __name__ == "__main__": 62 | import doctest 63 | results = doctest.testmod() 64 | 65 | if results.failed == 0: 66 | print("ALL TESTS PASSED!") 67 | -------------------------------------------------------------------------------- /programs/is_binary_tree.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def is_bst(root): 5 | """ 6 | Given the root of a binary tree, return true if it is a binary search tree. 7 | """ 8 | 9 | def is_bst_recursive(root, smallest, largest): 10 | 11 | if root is None: 12 | return True 13 | 14 | if largest is not None and root.data > largest: 15 | return False 16 | 17 | if smallest is not None and root.data < smallest: 18 | return False 19 | 20 | if not is_bst_recursive(root.left, smallest, root.data): 21 | return False 22 | 23 | if not is_bst_recursive(root.right, root.data, largest): 24 | return False 25 | 26 | return True 27 | 28 | return is_bst_recursive(root, smallest=None, largest=None) 29 | 30 | 31 | class Node(object): 32 | def __init__(self, data, left=None, right=None): 33 | self.data = data 34 | self.left = left 35 | self.right = right 36 | 37 | 38 | class Tests(unittest.TestCase): 39 | 40 | def create_bst_1(self): 41 | return Node(5, Node(3, Node(1), Node(9)), Node(6)) 42 | 43 | def create_bst_2(self): 44 | return Node(5, Node(3, Node(1), Node(4)), Node(7, Node(6), Node(8))) 45 | 46 | def test_is_bst(self): 47 | self.assertFalse(is_bst(self.create_bst_1())) 48 | self.assertTrue(is_bst(self.create_bst_2())) 49 | 50 | 51 | if __name__ == '__main__': 52 | unittest.main() 53 | -------------------------------------------------------------------------------- /programs/is_unique.py: -------------------------------------------------------------------------------- 1 | # import unittest 2 | 3 | 4 | # def is_unique(string): 5 | # """ Takes a string and returns True if it has all unique characters. """ 6 | 7 | # str_set = set(string) 8 | 9 | # return str_set == string 10 | 11 | 12 | # class Testing(unittest.TestCase): 13 | # def is_unique_test(self): 14 | # assertEqual(is_unique('asdfghjkl'), True) 15 | # assertEqual(is_unique('1234567asdf'), True) 16 | # assertEqual(is_unique('!@#$%^&asdfg123'), True) 17 | # assertEqual(is_unique('abcdABCD'), True) 18 | 19 | # assertEqual(is_unique('asdfghjkll'), False) 20 | # assertEqual(is_unique('1qwerty1'), False) 21 | # assertEqual(is_unique('poiu$asdf$'), False) 22 | 23 | # if __name__ == '__main__': 24 | # unittest.main() 25 | 26 | import unittest 27 | 28 | 29 | def is_unique(string): 30 | """ Takes a string and returns True if it has all unique characters. """ 31 | 32 | str_set = set(string) 33 | 34 | return str_set == string 35 | 36 | 37 | class Testing(unittest.TestCase): 38 | def test_is_unique(self): 39 | self.assertEqual(is_unique('asdfghjkl'), True) 40 | self.assertEqual(is_unique('1234567asdf'), True) 41 | self.assertEqual(is_unique('!@#$%^&asdfg123'), True) 42 | self.assertEqual(is_unique('abcdABCD'), True) 43 | 44 | self.assertEqual(is_unique('asdfghjkll'), False) 45 | self.assertEqual(is_unique('1qwerty1'), False) 46 | self.assertEqual(is_unique('poiu$asdf$'), False) 47 | 48 | if __name__ == '__main__': 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /programs/linked_list.py: -------------------------------------------------------------------------------- 1 | """ Implement a singly linked list. """ 2 | 3 | class Node(object): 4 | """ Creates a node. """ 5 | 6 | def __init__(self, data=None, nxt=None): 7 | self.data = data 8 | self.next = nxt 9 | 10 | 11 | 12 | class LinkedList(object): 13 | """ Creates a linked list. """ 14 | 15 | def __init__(self, head=None): 16 | self.head = head 17 | self.tail = tail 18 | 19 | def insert(self, data, position): 20 | """ Takes data as an input and a position and adds it to the linked list as a node before that position. """ 21 | 22 | new_node = Node(data) 23 | 24 | if position == 0: 25 | new_node.next = self.head 26 | self.head = new_node 27 | 28 | if position == self.size(): 29 | self.tail.next = new_node 30 | self.tail = new_node 31 | 32 | 33 | prev = None 34 | curr = self.head 35 | index = 0 36 | 37 | while curr.next: 38 | if position == index: 39 | prev.next = new_node 40 | new_node.next = curr 41 | return 42 | index +=1 43 | prev = prev.next 44 | curr = curr.next 45 | 46 | 47 | def size(self): 48 | """ Returns the length of the linked list. """ 49 | 50 | size = 0 51 | 52 | if head is None and tail is None: 53 | return size 54 | 55 | curr = self.head 56 | 57 | while curr: 58 | size += 1 59 | curr = curr.next 60 | 61 | return size 62 | 63 | 64 | def search(self, data): 65 | """ Takes data as an input and returns the node holding the data. """ 66 | 67 | curr = self.head 68 | 69 | while curr: 70 | if curr.data == data: 71 | return curr 72 | curr = curr.next 73 | 74 | raise ValueError('Data not in linked list.') 75 | 76 | 77 | def delete(self, data): 78 | """ Takes data as an input and deletes the node with that data. """ 79 | 80 | prev = None 81 | curr = self.head 82 | 83 | while curr: 84 | if curr.data == data: 85 | if curr == self.head: 86 | self.head = curr.next 87 | else: 88 | prev.next = curr.next 89 | 90 | prev = curr 91 | curr = curr.next 92 | 93 | if curr is None: 94 | raise ValueError('Data not in linked list.') 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /programs/make_change.py: -------------------------------------------------------------------------------- 1 | def make_change(amount, denominations, index=0): 2 | """ Write a function that, given: 3 | 1. an amount of money 4 | 2. a list of coin denominations 5 | computes the number of ways to make the amount of money with coins of the available denominations. 6 | 7 | >>> make_change(amount=4, denominations=[1,2,3]) 8 | 4 9 | [1,1,1,1] 10 | [1,1,2] 11 | [1,3] 12 | [2,2] 13 | 14 | >>> make_change(amount=20, denominations=[5, 10]) 15 | 3 16 | [5,5,5,5] 17 | [5,5,10] 18 | [10,10] 19 | 20 | """ 21 | 22 | 23 | # time: 24 | # space: 25 | 26 | 27 | if amount == 0: 28 | return 1 29 | 30 | if amount < 0: 31 | return 0 32 | 33 | if index == len(denominations): 34 | return 0 35 | 36 | current_coin = denominations[index] 37 | 38 | combos = 0 39 | 40 | while amount >=0: 41 | combos += make_change(amount, denominations, index+1) 42 | amount -=current_coin 43 | 44 | return combos 45 | 46 | 47 | 48 | if __name__ == '__main__': 49 | import doctest 50 | results = doctest.testmod() 51 | if not results.failed: 52 | print 'All tests passed!' 53 | -------------------------------------------------------------------------------- /programs/merge_ranges.py: -------------------------------------------------------------------------------- 1 | def merge_ranges(lst): 2 | """ In HiCal, a meeting is stored as tuples of integers (start_time, end_time). These integers represent the number of 30-minute blocks past 9:00am. For example: 3 | (2, 3) # meeting from 10:00 - 10:30 am 4 | (6, 9) # meeting from 12:00 - 1:30 pm 5 | Write a function merge_ranges() that takes a list of meeting time ranges and returns a list of condensed ranges. 6 | 7 | >>> merge_ranges([(3, 5), (4, 8), (10, 12), (9, 10), (0, 1)]) 8 | [(0, 1), (3, 8), (9, 12)] 9 | 10 | >>> merge_ranges([(0, 3), (3, 5), (4, 8), (10, 12), (9, 10)]) 11 | [(0, 8), (9, 12)] 12 | 13 | >>> merge_ranges([(0, 3), (3, 5)]) 14 | [(0, 5)] 15 | 16 | >>> merge_ranges([(0, 3), (3, 5), (7, 8)]) 17 | [(0, 5), (7, 8)] 18 | 19 | >>> merge_ranges([(1, 5), (2, 3)]) 20 | [(1, 5)] 21 | """ 22 | 23 | # time: O(nlogn) 24 | # space: O(n) 25 | 26 | 27 | meeting_times = sorted(lst) 28 | 29 | merged_range = [meeting_times[0]] 30 | 31 | for start, end in meeting_times[1:]: 32 | last_start, last_end = merged_range[-1] 33 | 34 | if last_end >= start: 35 | merged_range[-1] = (last_start, max(last_end, end)) 36 | else: 37 | merged_range.append((start, end)) 38 | 39 | 40 | 41 | 42 | 43 | 44 | return merged_range 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | if __name__ == '__main__': 54 | import doctest 55 | results = doctest.testmod() 56 | if not results.failed: 57 | print 'All tests passed!' 58 | -------------------------------------------------------------------------------- /programs/min_heap.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class MinHeap(object): 5 | 6 | def __init__(self): 7 | self.storage = [] 8 | 9 | 10 | def swap(self, a, b): 11 | self.storage[a], self.storage[b] = self.storage[b], self.storage[a] 12 | 13 | 14 | def size(self): 15 | return len(self.storage) 16 | 17 | 18 | def peak(self): 19 | return self.storage[0] 20 | 21 | 22 | def insert(self, value): 23 | self.storage.append(value) 24 | index = self.size() - 1 25 | self.bubbleUp(index) 26 | 27 | 28 | def get_parent(self, child): 29 | if child % 2 == 0: 30 | return (child - 2)/2 31 | else: 32 | return (child - 1)/2 33 | 34 | 35 | def bubbleUp(self, child): 36 | parent = self.get_parent(child) 37 | 38 | while (child > 0) and parent >= 0 and (self.storage[child] < self.storage[parent]): 39 | self.swap(child, parent) 40 | child = parent 41 | parent = self.get_parent(child) 42 | 43 | 44 | def remove_peak(self): 45 | self.swap(0, self.size()-1) 46 | min_elem = self.storage.pop() 47 | self.bubbleDown(0) 48 | 49 | return min_elem 50 | 51 | 52 | def get_child(self, parent): 53 | child1 = 2 * parent + 1 54 | child2 = 2 * parent + 2 55 | 56 | if child1 >= self.size(): 57 | return 58 | elif child2 >= self.size(): 59 | return child1 60 | elif self.storage[child1] < self.storage[child2]: 61 | return child1 62 | else: 63 | return child2 64 | 65 | 66 | def bubbleDown(self, parent): 67 | child = self.get_child(parent) 68 | 69 | while child is not None and self.storage[parent] > self.storage[child]: 70 | self.swap(child, parent) 71 | parent = child 72 | child = self.get_child(parent) 73 | 74 | 75 | def remove(self, item): 76 | last_index = self.size() - 1 77 | swap_index = 0 78 | 79 | # can implement with hash table instead of for loop to keep this in 80 | # O(logn) time complexity, however need to keep track of every element 81 | # in hash table and update hash table in each method +O(n) space 82 | for i in range(len(self.storage)): 83 | if item == self.storage[i]: 84 | swap_index = i 85 | self.storage[i], self.storage[last_index] = self.storage[last_index], self.storage[i] 86 | 87 | self.bubbleUp(swap_index) 88 | self.bubbleDown(swap_index) 89 | 90 | removed_item = self.storage.pop() 91 | 92 | return removed_item 93 | 94 | 95 | 96 | def __repr__(self): 97 | return ''.format(self.storage) 98 | 99 | 100 | 101 | class Testing(unittest.TestCase): 102 | 103 | def setUp(self): 104 | self.test = MinHeap() 105 | self.test.storage = [4, 5, 6, 7, 8] 106 | 107 | def test_swap(self): 108 | self.test.swap(0, 3) 109 | self.assertEqual(repr(self.test), '', 'swap is incorrect') 110 | 111 | def test_size(self): 112 | self.assertEqual(self.test.size(), 5, 'size is incorrect') 113 | 114 | def test_peak(self): 115 | self.assertEqual(self.test.peak(), 4, 'peak is the wrong value') 116 | 117 | def test_insert(self): 118 | self.test.storage = [] 119 | self.test.insert(7) 120 | self.test.insert(4) 121 | self.test.insert(10) 122 | self.test.insert(1) 123 | self.test.insert(8) 124 | self.test.insert(11) 125 | self.test.insert(9) 126 | self.test.insert(2) 127 | print self.test 128 | self.assertEqual(repr(self.test), '', 'did not insert new value properly') 129 | 130 | def test_get_parent(self): 131 | self.assertEqual(self.test.get_parent(7), 3, 'getting child\'s parent index is incorrect') 132 | 133 | 134 | def test_bubbleUp(self): 135 | self.test.insert(1) 136 | self.assertEqual(repr(self.test), '', 'did not bubble up correctly') 137 | self.test.insert(10) 138 | self.assertEqual(repr(self.test), '', 'did not bubble up correctly') 139 | self.test.insert(2) 140 | self.assertEqual(repr(self.test), '', 'did not bubble up correctly') 141 | self.test.insert(9) 142 | self.assertEqual(repr(self.test), '', 'did not bubble up correctly') 143 | 144 | 145 | def test_remove_peak(self): 146 | self.test.storage = [1, 2, 4, 11] 147 | self.assertEqual(self.test.remove_peak(), 1, 'did not remove correct value') 148 | self.assertEqual(self.test.remove_peak(), 2, 'did not remove correct value') 149 | self.assertEqual(self.test.remove_peak(), 4, 'did not remove correct value') 150 | self.assertEqual(self.test.remove_peak(), 11, 'did not remove correct value') 151 | 152 | 153 | def test_get_child(self): 154 | self.assertEqual(self.test.get_child(0), 1, 'did not select the right child index') 155 | 156 | 157 | def test_bubbleDown(self): 158 | self.test.storage = [1, 2, 4, 11] 159 | self.test.remove_peak() 160 | self.assertEqual(repr(self.test), '', 'did not bubble down correctly') 161 | self.test.remove_peak() 162 | self.assertEqual(repr(self.test), '', 'did not bubble down correctly') 163 | self.test.remove_peak() 164 | self.assertEqual(repr(self.test), '', 'did not bubble down correctly') 165 | self.test.remove_peak() 166 | self.assertEqual(repr(self.test), '', 'did not bubble down correctly') 167 | 168 | 169 | def test_remove(self): 170 | self.assertEqual(self.test.remove(8), 8, 'did not remove correct value') 171 | self.assertEqual(repr(self.test), '', 'did not bubble down correctly') 172 | 173 | 174 | if __name__ == '__main__': 175 | unittest.main() 176 | -------------------------------------------------------------------------------- /programs/most_frequent_word.py: -------------------------------------------------------------------------------- 1 | def most_frequent_word(str): 2 | """ Find k most frequent words in a string of words, and print them in space-separated alphabetical order. 3 | 4 | >>> most_frequent_word('hello my name is hello joanne') 5 | hello 6 | 7 | >>> most_frequent_word('hello my name is hello joanne is') 8 | hello is 9 | 10 | >>> most_frequent_word('hello my name is joanne') 11 | hello is joanne my name 12 | """ 13 | 14 | # time: O(n log n) 15 | # space: O(n) 16 | 17 | words = {} 18 | list_of_words = str.split() 19 | 20 | for word in list_of_words: 21 | words[word] = words.get(word, 0) + 1 22 | 23 | most_frequent_words = [] 24 | 25 | max_value = max(words.values()) 26 | 27 | for word, value in words.iteritems(): 28 | if value == max_value: 29 | most_frequent_words.append(word) 30 | 31 | for word in sorted(most_frequent_words): 32 | print word, 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | if __name__ == '__main__': 41 | import doctest 42 | results = doctest.testmod() 43 | if not results.failed: 44 | print 'All tests passed!' 45 | -------------------------------------------------------------------------------- /programs/non_neg_int.py: -------------------------------------------------------------------------------- 1 | # Given an array arr of n unique non-negative integers, how can you most efficiently find a non-negative integer that is not in the array? 2 | 3 | # Your solution should return such an integer or null if arr contains all possible integers. 4 | # Analyze the runtime and space complexity of your solution. 5 | 6 | 7 | import sys 8 | 9 | 10 | def find_int(arr): 11 | """ Takes an array and returns a non-negative integer that is not in the original array. Returns null if all integers are in the array. 12 | 13 | Runtime: O(n) 14 | Spacetime: O(n) 15 | 16 | >>> find_int([0, 2, 1, 3, 4, 5, 11, 32, 42, 50, 100, 6]) 17 | 7 18 | 19 | >>> find_int([2, 4, 5, 1, 3]) 20 | 0 21 | 22 | >>> find_int([0, 2, 4, 5, 1, 3]) 23 | 6 24 | 25 | >>> find_int([0, 2, 4, 5, 1, 3, 6, 8]) 26 | 7 27 | 28 | >>> find_int([]) 29 | 0 30 | 31 | """ 32 | 33 | arr2 = {} 34 | 35 | # If the length of the array is equal to the maximum allowed integers, there are no missing integers in the array. 36 | if len(arr) == sys.maxint: 37 | return None 38 | 39 | # Create an O(1) lookup hashtable using the integers from the array as the key, and set the value to True 40 | for i in range(len(arr)): 41 | arr2[arr[i]] = True 42 | 43 | # Loop through the length of the array + 1 and check if the number is a key in the hashtable. If it isn't return that number. 44 | for i in range(len(arr) + 1): 45 | if not arr2.get(i): 46 | return i 47 | 48 | return None 49 | 50 | 51 | if __name__ == '__main__': 52 | import doctest 53 | results = doctest.testmod() 54 | 55 | if results.failed == 0: 56 | print 'ALL TESTS PASSED!' 57 | 58 | -------------------------------------------------------------------------------- /programs/palindrome_permutation.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def is_pal_perm(string): 5 | """ 6 | Takes a string and returns true if the string is a permutation of a 7 | palindrome. 8 | """ 9 | 10 | let_counts = {} 11 | odd = 0 12 | 13 | for let in string: 14 | let_counts[let] = let_counts.get(let, 0) + 1 15 | 16 | for val in let_counts.values(): 17 | if val % 2 != 0: 18 | odd += 1 19 | 20 | return odd <= 1 21 | 22 | 23 | class Testing(unittest.TestCase): 24 | 25 | def test_is_pal_perm(self): 26 | self.assertTrue(is_pal_perm('carereca')) 27 | self.assertTrue(is_pal_perm('a')) 28 | self.assertFalse(is_pal_perm('carelnreca')) 29 | 30 | 31 | if __name__ == '__main__': 32 | unittest.main() 33 | -------------------------------------------------------------------------------- /programs/print_recursively.py: -------------------------------------------------------------------------------- 1 | def print_recursively(lst): 2 | """ Print items in the list, using recursion. 3 | 4 | >>> print_recursively([1, 2, 3]) 5 | 1 6 | 2 7 | 3 8 | """ 9 | 10 | if not lst: 11 | return 12 | 13 | print lst[0] 14 | 15 | print_recursively(lst[1:]) 16 | 17 | 18 | if __name__ == '__main__': 19 | import doctest 20 | results = doctest.testmod() 21 | 22 | if results.failed == 0: 23 | print "ALL TESTS PASSED" 24 | -------------------------------------------------------------------------------- /programs/products_of_all_ints.py: -------------------------------------------------------------------------------- 1 | def get_products_of_all_ints_except_at_index(lst): 2 | """ Takes a list of integers and returns a list of the products except the integer at that index. Do not use division. 3 | 4 | >>> get_products_of_all_ints_except_at_index([1, 7, 3, 4]) 5 | [84, 12, 28, 21] 6 | 7 | >>> get_products_of_all_ints_except_at_index([1, 0, 3, 4]) 8 | [0, 12, 0, 0] 9 | """ 10 | 11 | # Runtime: O(n^2) 12 | # Spacetime: O(n^2) 13 | 14 | products = [] 15 | 16 | for a in range(len(lst)): 17 | product = 1 18 | 19 | for b in range(len(lst)): 20 | if a != b: 21 | product *= lst[b] 22 | products.append(product) 23 | 24 | return products 25 | 26 | # Testing 27 | # a = 0 28 | # product = 1 29 | # b = 0 30 | # skip 31 | # b = 1 32 | # product = 1 * 7 33 | # b = 2 34 | # product = 1 * 7 * 3 35 | # b = 3 36 | # product = 1 * 7 * 3 * 4 37 | 38 | # products = [84] 39 | 40 | # a = 1 41 | # product = 7 42 | 43 | # b = 0 44 | # product = 7 * 1 45 | 46 | 47 | 48 | def get_products_of_all_ints_except_at_index_optimized(lst): 49 | """ Takes a list of integers and returns a list of the products except the integer at that index. Do not use division. 50 | 51 | >>> get_products_of_all_ints_except_at_index_optimized([1, 7, 3, 4]) 52 | [84, 12, 28, 21] 53 | 54 | >>> get_products_of_all_ints_except_at_index_optimized([1, 0, 3, 4]) 55 | [0, 12, 0, 0] 56 | """ 57 | 58 | # Runtime: O(n) 59 | # Spacetime: O(n) 60 | 61 | products = [] 62 | product = 1 63 | product_reverse = 1 64 | products_before = [] 65 | products_after = [] 66 | 67 | for i in range(len(lst)): 68 | products_before.append(product) 69 | product *= lst[i] 70 | 71 | for i in range(len(lst)-1, -1, -1): 72 | products_after.append(product_reverse) 73 | product_reverse *= lst[i] 74 | 75 | for i in range(len(products_before)): 76 | products.append(products_after[-i-1] * products_before[i]) 77 | 78 | return products 79 | 80 | 81 | # Testing 82 | # lst = [1, 7, 3, 4] 83 | 84 | # first for loop 85 | # i = 0 86 | # products_before = [1] 87 | # product = 1 88 | # i = 1 89 | # products_before = [1, 1] 90 | # product = 7 91 | # i = 2 92 | # products_before = [1, 1, 7] 93 | # product = 21 94 | # i = 3 95 | # products_before = [1, 1, 7, 21] 96 | # product = 84 97 | # i = 4 98 | 99 | # second for loop 100 | # i = 3 101 | # products_after = [1] 102 | # product_reverse = 4 103 | # i = 2 104 | # products_after [1, 4] 105 | # product_reverse = 12 106 | # i = 1 107 | # products_after = [1, 4, 12] 108 | # product_reverse = 84 109 | # i = 0 110 | # products_after = [1, 4, 12, 84] 111 | # product_reverse = 84 112 | # i = -1 113 | 114 | 115 | 116 | 117 | if __name__ == '__main__': 118 | import doctest 119 | results = doctest.testmod() 120 | 121 | if results.failed == 0: 122 | print "ALL TESTS PASSED" 123 | 124 | -------------------------------------------------------------------------------- /programs/quote_generator.py: -------------------------------------------------------------------------------- 1 | from random import * 2 | 3 | quotes = ['hi', 'hello', 'goodbye', 'dog', 'cat', 'banana'] 4 | 5 | 6 | class QuoteGenerator(object): 7 | 8 | def __init__(self, quotes): 9 | self.last_rand_num = -1 10 | self.quotes = quotes 11 | 12 | def generate_quote(self): 13 | random_num = randint(0, len(self.quotes)-1) 14 | 15 | if random_num != self.last_rand_num: 16 | self.last_rand_num = random_num 17 | return self.quotes[random_num] 18 | else: 19 | return self.generator() 20 | 21 | 22 | generator1 = QuoteGenerator(quotes) 23 | print generator1.generate_quote() 24 | print generator1.generate_quote() 25 | print generator1.generate_quote() 26 | print generator1.generate_quote() 27 | print generator1.generate_quote() 28 | print generator1.generate_quote() 29 | print generator1.generate_quote() 30 | print generator1.generate_quote() 31 | print generator1.generate_quote() 32 | print generator1.generate_quote() 33 | -------------------------------------------------------------------------------- /programs/rate_checker.py: -------------------------------------------------------------------------------- 1 | """ Create a rate checker which takes actions, for number of occurrences, and seconds, for time in which those actions have occurred. Using a check method return True if it is called at least N times (actions) in up to Q seconds. Otherwise, return False. """ 2 | 3 | import datetime 4 | from time import sleep 5 | 6 | 7 | class RateChecker(object): 8 | 9 | def __init__(self, actions, seconds): 10 | self.actions = actions 11 | self.seconds = seconds 12 | self.times = [] # Queue needed to keep track of how many times it's being checked 13 | 14 | def check(self): 15 | """ 16 | >>> clicks = RateChecker(3, 14) 17 | >>> clicks.check() 18 | >>> clicks.check() 19 | >>> clicks.check() 20 | >>> clicks.check() 21 | False 22 | 23 | """ 24 | current_time = datetime.datetime.now().time() 25 | self.times.append(current_time) # Append each check time to the queue 26 | 27 | if len(self.times) > self.actions: # First check if the queue is greater than the number of actions 28 | return False # Returning false here gives a quick win 29 | 30 | return datetime.datetime.strptime(str(current_time), "%H:%M:%S.%f") - datetime.datetime.strptime(str(self.times.pop()), "%H:%M:%S.%f") <= datetime.timedelta(seconds=self.seconds) # Check times in the queue 31 | # (Slower approach if the queue is really huge, hence why queue length vs. actions should be checked first.) 32 | 33 | 34 | 35 | if __name__ == "__main__": 36 | import doctest 37 | results = doctest.testmod() 38 | 39 | if not results.failed: 40 | print "All tests passed!" 41 | -------------------------------------------------------------------------------- /programs/recursive_index.py: -------------------------------------------------------------------------------- 1 | def recursive_index(needle, haystack): 2 | """Given list (haystack), return index (0-based) of needle in the list. 3 | 4 | Return None if needle is not in haystack. 5 | 6 | Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP. 7 | 8 | >>> lst = ["hey", "there", "you"] 9 | 10 | >>> recursive_index("hey", lst) 11 | 0 12 | 13 | >>> recursive_index("you", lst) 14 | 2 15 | 16 | >>> recursive_index("porcupine", lst) is None 17 | True 18 | """ 19 | 20 | if not haystack or needle not in haystack: 21 | return None 22 | 23 | count = 0 24 | 25 | if needle == haystack[0]: 26 | return count 27 | 28 | 29 | count += 1 + recursive_index(needle, haystack[1:]) 30 | 31 | return count 32 | 33 | 34 | def recursive_index_2(needle, haystack): 35 | """Given list (haystack), return index (0-based) of needle in the list. 36 | 37 | Return None if needle is not in haystack. 38 | 39 | Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP. 40 | 41 | >>> lst = ["hey", "there", "you"] 42 | 43 | >>> recursive_index_2("hey", lst) 44 | 0 45 | 46 | >>> recursive_index_2("you", lst) 47 | 2 48 | 49 | >>> recursive_index_2("porcupine", lst) is None 50 | True 51 | """ 52 | 53 | if not haystack or needle not in haystack: 54 | return None 55 | 56 | if needle == haystack[0]: 57 | return 0 58 | 59 | 60 | else: 61 | return 1 + recursive_index_2(needle, haystack[1:]) 62 | 63 | 64 | def recursive_index_3(needle, haystack): 65 | """Given list (haystack), return index (0-based) of needle in the list. 66 | 67 | Return None if needle is not in haystack. 68 | 69 | Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP. 70 | 71 | >>> lst = ["hey", "there", "you"] 72 | 73 | >>> recursive_index_3("hey", lst) 74 | 0 75 | 76 | >>> recursive_index_3("you", lst) 77 | 2 78 | 79 | >>> recursive_index_3("porcupine", lst) is None 80 | True 81 | """ 82 | 83 | def _recursive_index_3(needle, haystack, count): 84 | 85 | if len(haystack) == count: 86 | return None 87 | 88 | if needle == haystack[count]: 89 | return count 90 | 91 | return _recursive_index_3(needle, haystack, count+1) 92 | 93 | return _recursive_index_3(needle, haystack, 0) 94 | 95 | 96 | 97 | if __name__ == '__main__': 98 | import doctest 99 | results = doctest.testmod() 100 | 101 | if results.failed == 0: 102 | print "ALL TESTS PASSED!" 103 | -------------------------------------------------------------------------------- /programs/reverse_linked_list.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | """ Class in a linked list. """ 3 | 4 | def __init__(self, data, next=None): 5 | self.data = data 6 | self.next = next 7 | 8 | def as_string(self): 9 | """Represent data for this node and it's successors as a string. 10 | 11 | >>> Node(3).as_string() 12 | '3' 13 | 14 | >>> Node(3, Node(2, Node(1))).as_string() 15 | '321' 16 | """ 17 | 18 | out = [] 19 | n = self 20 | 21 | while n: 22 | out.append(str(n.data)) 23 | n = n.next 24 | 25 | return ''.join(out) 26 | 27 | 28 | def reverse_linked_list(head): 29 | """Given singly linked list head node, return head node of new, reversed linked list. 30 | 31 | >>> ll = Node(1, Node(2, Node(3))) 32 | >>> reverse_linked_list(ll).as_string() 33 | '321' 34 | 35 | >>> ll = Node(1, Node(2, Node(3))) 36 | >>> new_ll = reverse_linked_list(ll) 37 | >>> new_ll.as_string() 38 | '321' 39 | """ 40 | 41 | prev = None 42 | curr = head 43 | 44 | while curr: 45 | next = curr.next 46 | curr.next = prev 47 | prev = curr 48 | curr = next 49 | 50 | 51 | return prev 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | if __name__ == '__main__': 64 | import doctest 65 | results = doctest.testmod() 66 | 67 | if results.failed == 0: 68 | print "ALL TESTS PASSED!" 69 | -------------------------------------------------------------------------------- /programs/reverse_order_of_words.py: -------------------------------------------------------------------------------- 1 | def reverse_order_of_words(lst): 2 | """ 3 | >>> reverse_order_of_words(['p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'y', 'o', 'u']) 4 | ['y', 'o', 'u', ' ', 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e'] 5 | 6 | """ 7 | 8 | # Runtime: O(n) 9 | 10 | reversed_arr = [] 11 | words = ''.join(lst) 12 | # 'practice makes perfect you' 13 | words_arr = words.split(' ') 14 | # ['practice', 'makes', 'perfect', 'you'] 15 | while len(words_arr) > 0: 16 | word = words_arr.pop() 17 | reversed_arr.append(word) 18 | # ['you', 'perfect', 'makes', 'practice'] 19 | reversed_words = ' '.join(reversed_arr) 20 | # 'you perfect makes practice' 21 | 22 | return list(reversed_words) 23 | 24 | if __name__ == '__main__': 25 | import doctest 26 | results = doctest.testmod() 27 | 28 | if results.failed == 0: 29 | print "ALL TESTS PASSED" 30 | -------------------------------------------------------------------------------- /programs/reverse_string.py: -------------------------------------------------------------------------------- 1 | # Given a string, return the same string, reversed. 2 | # can't use .reverse() 3 | 4 | def rev_str(string): 5 | """ 6 | >>> rev_str('hello') 7 | 'olleh' 8 | 9 | >>> rev_str('1234h') 10 | 'h4321' 11 | 12 | >>> rev_str('') 13 | '' 14 | """ 15 | 16 | # Runtime: O(n) 17 | 18 | reversed_str = "" 19 | list_str = list(string) 20 | # ['h', 'e', l, l, o] 21 | for l in range(len(list_str)): 22 | letter = list_str.pop() 23 | # l 24 | reversed_str += letter 25 | # oll 26 | return reversed_str 27 | 28 | 29 | def rev_str_2(string): 30 | """ 31 | >>> rev_str_2('hello') 32 | 'olleh' 33 | 34 | >>> rev_str_2('1234h') 35 | 'h4321' 36 | 37 | >>> rev_str_2('') 38 | '' 39 | """ 40 | 41 | # Runtime: O(n) 42 | 43 | return string[::-1] 44 | 45 | 46 | def rev_str_3(string): 47 | """ 48 | >>> rev_str_3('hello') 49 | 'olleh' 50 | 51 | >>> rev_str_3('1234h') 52 | 'h4321' 53 | 54 | >>> rev_str_3('') 55 | '' 56 | """ 57 | 58 | # Runtime: O(n) 59 | 60 | if len(string) == 0: 61 | return string 62 | 63 | return string[-1] + rev_str_3(string[:-1]) 64 | 65 | 66 | 67 | if __name__ == '__main__': 68 | import doctest 69 | results = doctest.testmod() 70 | 71 | if results.failed == 0: 72 | print "ALL TESTS PASSED!" 73 | -------------------------------------------------------------------------------- /programs/rommon_to_integer.py: -------------------------------------------------------------------------------- 1 | def roman_to_int(s: str) -> int: 2 | roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 3 | result = 0 4 | for i in range(len(s)): 5 | if i < len(s) - 1 and roman_dict[s[i]] < roman_dict[s[i+1]]: 6 | result -= roman_dict[s[i]] 7 | else: 8 | result += roman_dict[s[i]] 9 | return result 10 | 11 | 12 | ''' 13 | >>> roman_to_int('III') 14 | 3 15 | >>> roman_to_int('IV') 16 | 4 17 | >>> roman_to_int('IX') 18 | 9 19 | >>> roman_to_int('LVIII') 20 | 58 21 | >>> roman_to_int('MCMXCIV') 22 | 1994 23 | ''' -------------------------------------------------------------------------------- /programs/sort_dict_by_value.py: -------------------------------------------------------------------------------- 1 | data = { 2 | 'one':1, 3 | 'two':2, 4 | 'four':4, 5 | 'three':3 6 | } 7 | 8 | sort_dict = {key:val for key,val in sorted(data.items(),key= lambda x : x[1]) } 9 | print(sort_dict) 10 | -------------------------------------------------------------------------------- /programs/sort_fractions.py: -------------------------------------------------------------------------------- 1 | from random import uniform 2 | nums = [round(uniform(0, 1000), 3) for _ in range(100)] 3 | 4 | # Sort nums using only the fractional portion of each number. 5 | # Example: 30.12 is bigger than 100.01 6 | 7 | def sort_fractional(nums): 8 | nums = map(str, nums) 9 | for i, num in enumerate(nums): 10 | index = num.find('.') 11 | nums[i] = num[index+1:] 12 | return sorted(nums) 13 | 14 | print sort_fractional(nums) 15 | -------------------------------------------------------------------------------- /programs/stock-price.py: -------------------------------------------------------------------------------- 1 | def get_max_profit(prices): 2 | """ Finds the maximum profit for buying and selling stock within a day. 3 | 4 | >>> stock_prices_yesterday = [10, 7, 5, 8, 11, 9] 5 | >>> get_max_profit(stock_prices_yesterday) 6 | 6 7 | 8 | >>> stock_prices_yesterday = [10, 3] 9 | >>> get_max_profit(stock_prices_yesterday) 10 | -7 11 | 12 | >>> stock_prices_yesterday = [1, 10, 7, 14, 2, 11] 13 | >>> get_max_profit(stock_prices_yesterday) 14 | 13 15 | 16 | >>> stock_prices_yesterday = [11, 10, 9, 8, 2, 1] 17 | >>> get_max_profit(stock_prices_yesterday) 18 | -1 19 | 20 | >>> stock_prices_yesterday = [11, 9, 5, 2, 2, 0] 21 | >>> get_max_profit(stock_prices_yesterday) 22 | 0 23 | 24 | >>> stock_prices_yesterday = [1, 1, 1, 1, 1, 1] 25 | >>> get_max_profit(stock_prices_yesterday) 26 | 0 27 | """ 28 | 29 | # Runtime: O(n^2) 30 | # Spacetime: O(n) 31 | 32 | 33 | max_profit = prices[1] - prices[0] 34 | 35 | for a in range(len(prices)): # O(n) 36 | for b in range(a + 1, len(prices)): # O(n) 37 | gain_loss = prices[b] - prices[a] 38 | if gain_loss > max_profit: 39 | max_profit = gain_loss 40 | print max_profit 41 | 42 | 43 | def get_max_profit_optimized(prices): 44 | """ Finds the maximum profit for buying and selling stock within a day. 45 | 46 | >>> stock_prices_yesterday = [10, 7, 5, 8, 11, 9] 47 | >>> get_max_profit_optimized(stock_prices_yesterday) 48 | 6 49 | 50 | >>> stock_prices_yesterday = [10, 3] 51 | >>> get_max_profit_optimized(stock_prices_yesterday) 52 | -7 53 | 54 | >>> stock_prices_yesterday = [1, 10, 7, 14, 2, 11] 55 | >>> get_max_profit_optimized(stock_prices_yesterday) 56 | 13 57 | 58 | >>> stock_prices_yesterday = [11, 10, 9, 8, 2, 1] 59 | >>> get_max_profit_optimized(stock_prices_yesterday) 60 | -1 61 | 62 | >>> stock_prices_yesterday = [11, 9, 5, 2, 2, 0] 63 | >>> get_max_profit_optimized(stock_prices_yesterday) 64 | 0 65 | 66 | >>> stock_prices_yesterday = [1, 1, 1, 1, 1, 1] 67 | >>> get_max_profit_optimized(stock_prices_yesterday) 68 | 0 69 | """ 70 | 71 | 72 | # Runtime: O(n) 73 | # Spacetime: O(1) 74 | 75 | 76 | max_profit = prices[1] - prices[0] 77 | low = prices[0] 78 | 79 | for i in prices: 80 | 81 | # Skip the first price in list 82 | if prices[0] == i: 83 | continue 84 | 85 | potential_profit = i - low 86 | max_profit= max(max_profit, potential_profit) 87 | low = min(low, i) 88 | 89 | print max_profit 90 | 91 | 92 | if __name__ == '__main__': 93 | import doctest 94 | results = doctest.testmod() 95 | 96 | if results.failed == 0: 97 | print "ALL TESTS PASSED" 98 | -------------------------------------------------------------------------------- /programs/sum_list.py: -------------------------------------------------------------------------------- 1 | def sum_list(nums): 2 | """ Using recursion, return the sum of numbers in a list. 3 | 4 | >>> sum_list([5, 5]) 5 | 10 6 | 7 | >>> sum_list([-5, 10, 4]) 8 | 9 9 | 10 | >>> sum_list([20]) 11 | 20 12 | 13 | >>> sum_list([]) 14 | 0 15 | """ 16 | 17 | # Runtime: O(n) 18 | # Spacetime: O(1) 19 | 20 | if not nums: 21 | return 0 22 | 23 | return nums[0] + sum_list(nums[1:]) 24 | 25 | 26 | 27 | if __name__ == '__main__': 28 | import doctest 29 | results = doctest.testmod() 30 | 31 | if results.failed == 0: 32 | print "ALL TESTS PASSED!" 33 | -------------------------------------------------------------------------------- /programs/sum_tree_nodes.py: -------------------------------------------------------------------------------- 1 | def num_nodes(tree): 2 | """Counts the number of nodes in a tree. 3 | 4 | >>> class Node(object): 5 | ... def __init__(self, data): 6 | ... self.data=data 7 | ... self.children = [] 8 | ... def add_child(self, obj): 9 | ... self.children.append(obj) 10 | ... 11 | >>> one = Node(1) 12 | >>> two = Node(2) 13 | >>> three = Node(3) 14 | >>> one.add_child(two) 15 | >>> one.add_child(three) 16 | >>> num_nodes(one) 17 | 3 18 | >>> four = Node(4) 19 | >>> five = Node(5) 20 | >>> two.add_child(four) 21 | >>> two.add_child(five) 22 | >>> num_nodes(one) 23 | 5 24 | >>> six = Node(6) 25 | >>> three.add_child(six) 26 | >>> num_nodes(one) 27 | 6 28 | """ 29 | 30 | nodes = 1 31 | 32 | if tree is None: 33 | return 0 34 | 35 | for child in tree.children: 36 | nodes += num_nodes(child) 37 | 38 | 39 | return nodes 40 | 41 | 42 | 43 | if __name__ == "__main__": 44 | import doctest 45 | results = doctest.testmod() 46 | 47 | if not results.failed: 48 | print "ALL TESTS PASSED" 49 | -------------------------------------------------------------------------------- /programs/transpose_of_matrix.py: -------------------------------------------------------------------------------- 1 | class Matrix(object): 2 | def __init__(self,mat = None): 3 | self.mat = mat 4 | 5 | def get_matrix(self) -> list: 6 | return self.mat 7 | 8 | def transpose(self) -> list: 9 | if self.mat: 10 | try: 11 | return list(zip(*self.mat)) 12 | except Exception as e: 13 | return f"Failed to convert transpose because {e}" 14 | mat = [ 15 | [1,2,3], 16 | [4,5,6], 17 | [7,8,9] 18 | ] 19 | 20 | matrix_obj = Matrix(mat) 21 | print(f"Original Matrix is : \n {matrix_obj.get_matrix()}") 22 | print(f"Transpose of above matrix is : \n {matrix_obj.transpose()}") 23 | -------------------------------------------------------------------------------- /programs/valid_parenthesis_permutations.py: -------------------------------------------------------------------------------- 1 | # Given a num, get all the valid parenthesis permutations. 2 | # Observations: 3 | # - All permutations start with opens 4 | # - Base case: if num of open used == num of closed used 5 | # - Num of opens used up, then next to the end must be closed 6 | 7 | import unittest 8 | 9 | 10 | def valid_parens_perms(num): 11 | 12 | result = [] 13 | 14 | def recurse(substr, left, right): 15 | if left == 0 and right == 0: 16 | result.append(substr) 17 | return 18 | 19 | elif left == 0: 20 | recurse(substr + ')', left, right - 1) 21 | 22 | elif left < right: 23 | recurse(substr + '(', left - 1, right) 24 | recurse(substr + ')', left, right - 1) 25 | 26 | elif left == right: 27 | recurse(substr + '(', left - 1, right) 28 | 29 | recurse('', num, num) 30 | 31 | return result 32 | 33 | 34 | class Testing(unittest.TestCase): 35 | def test_valid_parens_perms(self): 36 | self.assertEqual(valid_parens_perms(1), ['()']) 37 | self.assertEqual(valid_parens_perms(2), ['(())', '()()']) 38 | self.assertEqual(valid_parens_perms(3), ['((()))', '(()())', '(())()', '()(())', '()()()']) 39 | self.assertEqual(valid_parens_perms(4), ['(((())))', '((()()))', '((())())', '((()))()', '(()(()))', '(()()())', '(()())()', '(())(())', '(())()()', '()((()))', '()(()())', '()(())()', '()()(())', '()()()()']) 40 | 41 | 42 | if __name__ == '__main__': 43 | unittest.main() 44 | -------------------------------------------------------------------------------- /programs/zig_zag.py: -------------------------------------------------------------------------------- 1 | """A sequence of integers is called a zigzag sequence if each of its elements is either strictly less than both neighbors or strictly greater than both neighbors. For example, the sequence 4 2 3 1 5 3 is a zigzag, but 7 3 5 5 2 and 3 8 6 4 5 aren't. 2 | 3 | For a given array of integers return the length of its longest contiguous sub-array that is a zigzag sequence. 4 | 5 | Example 6 | 7 | For a = [9, 8, 8, 5, 3, 5, 3, 2, 8, 6], the output should be 8 | zigzag(a) = 4. 9 | 10 | The longest zigzag sub-arrays are [5, 3, 5, 3] and [3, 2, 8, 6] and they both have length 4. 11 | 12 | Input/Output 13 | 14 | [time limit] 4000ms (py) 15 | [input] array.integer a 16 | 17 | Guaranteed constraints: 18 | 2 <= a.length <= 25, 19 | 0 <= a[i] <= 100. 20 | 21 | [output] integer""" 22 | 23 | 24 | 25 | def zigzag(a): 26 | """ 27 | >>> zigzag([9, 8, 8, 5, 3, 5, 3, 2, 8, 6]) 28 | 4 29 | 30 | >>> zigzag([2, 3, 1, 0, 2]) 31 | 3 32 | 33 | >>> zigzag([1, 2, 3, 2, 1]) 34 | 3 35 | 36 | >>> zigzag([2, 3, 1, 4, 2]) 37 | 5 38 | 39 | >>> zigzag([1, 2, 0, 3, 2, 1, 3, 2, 4, 0]) 40 | 6 41 | 42 | >>> zigzag([1, 2]) 43 | 2 44 | 45 | >>> zigzag([1, 2, 1]) 46 | 3 47 | 48 | >>> zigzag([1, 1]) 49 | 1 50 | 51 | """ 52 | 53 | # time: O(n) 54 | # space: O(1) 55 | 56 | longest = 1 57 | curr_length = 1 58 | 59 | if len(a) == 2 and a[0] != a[1]: 60 | return len(a) 61 | 62 | 63 | for i in range(len(a)-2): 64 | prev = a[i] 65 | curr = a[i+1] 66 | nxt = a[i+2] 67 | 68 | if (prev < curr and curr > nxt) or (prev > curr and curr < nxt): 69 | if nxt == a[-1]: 70 | curr_length += 2 71 | else: 72 | curr_length += 1 73 | 74 | longest = max(longest, curr_length) 75 | 76 | else: 77 | curr_length += 1 78 | longest = max(longest, curr_length) 79 | curr_length = 1 80 | 81 | return longest 82 | 83 | 84 | 85 | def zigzag_recursive(a): 86 | """ 87 | >>> zigzag_recursive([9, 8, 8, 5, 3, 5, 3, 2, 8, 6]) 88 | 4 89 | 90 | >>> zigzag_recursive([2, 3, 1, 0, 2]) 91 | 3 92 | 93 | >>> zigzag_recursive([1, 2, 3, 2, 1]) 94 | 3 95 | 96 | >>> zigzag_recursive([2, 3, 1, 4, 2]) 97 | 5 98 | 99 | >>> zigzag_recursive([1, 2, 0, 3, 2, 1, 3, 2, 4, 0]) 100 | 6 101 | 102 | >>> zigzag_recursive([1, 2]) 103 | 2 104 | 105 | >>> zigzag_recursive([1, 2, 1]) 106 | 3 107 | 108 | >>> zigzag_recursive([1, 1]) 109 | 1 110 | 111 | """ 112 | 113 | # time: O(n) 114 | # space: O(n) 115 | 116 | 117 | if len(a) < 2: 118 | return len(a) 119 | 120 | if len(a) == 2 and a[0] != a[1]: 121 | return len(a) 122 | 123 | longest = 1 124 | i = 1 125 | good = True 126 | 127 | while good and i < len(a) - 1: 128 | curr = a[i] 129 | prev = a[i-1] 130 | nxt = a[i+1] 131 | 132 | if (prev < curr and curr > nxt) or (prev > curr and curr < nxt): 133 | i +=1 134 | if i == len(a)-1: 135 | longest += 1 136 | else: 137 | good = False 138 | longest += 1 139 | 140 | return max(longest, zigzag_recursive(a[i:])) 141 | 142 | 143 | 144 | if __name__ == "__main__": 145 | import doctest 146 | results = doctest.testmod() 147 | 148 | if not results.failed: 149 | print "All tests passed" 150 | -------------------------------------------------------------------------------- /python-programs.md: -------------------------------------------------------------------------------- 1 | # Python challenging programming exercises 2 | 3 | 4 | ## Q. Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. 5 | 6 | Hints: 7 | Consider use range(#begin, #end) method 8 | 9 | Solution: 10 | 11 | ```py 12 | l=[] 13 | for i in range(2000, 3201): 14 | if (i%7==0) and (i%5!=0): 15 | l.append(str(i)) 16 | 17 | print ','.join(l) 18 | ``` 19 | 20 | 21 | Question 2 22 | Level 1 23 | 24 | ## Q. Write a program which can compute the factorial of a given numbers. 25 | The results should be printed in a comma-separated sequence on a single line. 26 | Suppose the following input is supplied to the program: 27 | 8 28 | Then, the output should be: 29 | 40320 30 | 31 | Hints: 32 | In case of input data being supplied to the question, it should be assumed to be a console input. 33 | 34 | Solution: 35 | ```py 36 | def fact(x): 37 | if x == 0: 38 | return 1 39 | return x * fact(x - 1) 40 | 41 | x=int(raw_input()) 42 | print fact(x) 43 | ``` 44 | 45 | 46 | Question 3 47 | Level 1 48 | 49 | ## Q. 50 | With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. 51 | Suppose the following input is supplied to the program: 52 | 8 53 | Then, the output should be: 54 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 55 | 56 | Hints: 57 | In case of input data being supplied to the question, it should be assumed to be a console input. 58 | Consider use dict() 59 | 60 | Solution: 61 | ```py 62 | n=int(raw_input()) 63 | d=dict() 64 | for i in range(1,n+1): 65 | d[i]=i*i 66 | 67 | print d 68 | ``` 69 | 70 | 71 | Question 4 72 | Level 1 73 | 74 | ## Q. 75 | Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. 76 | Suppose the following input is supplied to the program: 77 | 34,67,55,33,12,98 78 | Then, the output should be: 79 | ['34', '67', '55', '33', '12', '98'] 80 | ('34', '67', '55', '33', '12', '98') 81 | 82 | Hints: 83 | In case of input data being supplied to the question, it should be assumed to be a console input. 84 | tuple() method can convert list to tuple 85 | 86 | Solution: 87 | ```py 88 | values=raw_input() 89 | l=values.split(",") 90 | t=tuple(l) 91 | print l 92 | print t 93 | ``` 94 | 95 | 96 | Question 5 97 | Level 1 98 | 99 | ## Q. 100 | Define a class which has at least two methods: 101 | getString: to get a string from console input 102 | printString: to print the string in upper case. 103 | Also please include simple test function to test the class methods. 104 | 105 | Hints: 106 | Use __init__ method to construct some parameters 107 | 108 | Solution: 109 | ```py 110 | class InputOutString(object): 111 | def __init__(self): 112 | self.s = "" 113 | 114 | def getString(self): 115 | self.s = raw_input() 116 | 117 | def printString(self): 118 | print self.s.upper() 119 | 120 | strObj = InputOutString() 121 | strObj.getString() 122 | strObj.printString() 123 | 124 | ``` 125 | 126 | Question 6 127 | Level 2 128 | 129 | ## Q. 130 | Write a program that calculates and prints the value according to the given formula: 131 | Q = Square root of [(2 * C * D)/H] 132 | Following are the fixed values of C and H: 133 | C is 50. H is 30. 134 | D is the variable whose values should be input to your program in a comma-separated sequence. 135 | Example 136 | Let us assume the following comma separated input sequence is given to the program: 137 | 100,150,180 138 | The output of the program should be: 139 | 18,22,24 140 | 141 | Hints: 142 | If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26) 143 | In case of input data being supplied to the question, it should be assumed to be a console input. 144 | 145 | Solution: 146 | ```py 147 | #!/usr/bin/env python 148 | import math 149 | c=50 150 | h=30 151 | value = [] 152 | items=[x for x in raw_input().split(',')] 153 | for d in items: 154 | value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) 155 | 156 | print ','.join(value) 157 | ``` 158 | 159 | 160 | Question 7 161 | Level 2 162 | 163 | ## Q. 164 | Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. 165 | Note: i=0,1.., X-1; j=0,1,¡­Y-1. 166 | Example 167 | Suppose the following inputs are given to the program: 168 | 3,5 169 | Then, the output of the program should be: 170 | [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 171 | 172 | Hints: 173 | Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. 174 | 175 | Solution: 176 | ```py 177 | input_str = raw_input() 178 | dimensions=[int(x) for x in input_str.split(',')] 179 | rowNum=dimensions[0] 180 | colNum=dimensions[1] 181 | multilist = [[0 for col in range(colNum)] for row in range(rowNum)] 182 | 183 | for row in range(rowNum): 184 | for col in range(colNum): 185 | multilist[row][col]= row*col 186 | 187 | print multilist 188 | ``` 189 | 190 | 191 | Question 8 192 | Level 2 193 | 194 | ## Q. 195 | Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. 196 | Suppose the following input is supplied to the program: 197 | without,hello,bag,world 198 | Then, the output should be: 199 | bag,hello,without,world 200 | 201 | Hints: 202 | In case of input data being supplied to the question, it should be assumed to be a console input. 203 | 204 | Solution: 205 | ```py 206 | items=[x for x in raw_input().split(',')] 207 | items.sort() 208 | print ','.join(items) 209 | ``` 210 | 211 | 212 | Question 9 213 | Level 2 214 | 215 | Question£º 216 | Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. 217 | Suppose the following input is supplied to the program: 218 | Hello world 219 | Practice makes perfect 220 | Then, the output should be: 221 | HELLO WORLD 222 | PRACTICE MAKES PERFECT 223 | 224 | Hints: 225 | In case of input data being supplied to the question, it should be assumed to be a console input. 226 | 227 | Solution: 228 | ```py 229 | lines = [] 230 | while True: 231 | s = raw_input() 232 | if s: 233 | lines.append(s.upper()) 234 | else: 235 | break; 236 | 237 | for sentence in lines: 238 | print sentence 239 | ``` 240 | 241 | 242 | Question 10 243 | Level 2 244 | 245 | ## Q. 246 | Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. 247 | Suppose the following input is supplied to the program: 248 | hello world and practice makes perfect and hello world again 249 | Then, the output should be: 250 | again and hello makes perfect practice world 251 | 252 | Hints: 253 | In case of input data being supplied to the question, it should be assumed to be a console input. 254 | We use set container to remove duplicated data automatically and then use sorted() to sort the data. 255 | 256 | Solution: 257 | ```py 258 | s = raw_input() 259 | words = [word for word in s.split(" ")] 260 | print " ".join(sorted(list(set(words)))) 261 | ``` 262 | 263 | 264 | Question 11 265 | Level 2 266 | 267 | ## Q. 268 | Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. 269 | Example: 270 | 0100,0011,1010,1001 271 | Then the output should be: 272 | 1010 273 | Notes: Assume the data is input by console. 274 | 275 | Hints: 276 | In case of input data being supplied to the question, it should be assumed to be a console input. 277 | 278 | Solution: 279 | ```py 280 | value = [] 281 | items=[x for x in raw_input().split(',')] 282 | for p in items: 283 | intp = int(p, 2) 284 | if not intp%5: 285 | value.append(p) 286 | 287 | print ','.join(value) 288 | ``` 289 | 290 | 291 | Question 12 292 | Level 2 293 | 294 | ## Q. 295 | Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. 296 | The numbers obtained should be printed in a comma-separated sequence on a single line. 297 | 298 | Hints: 299 | In case of input data being supplied to the question, it should be assumed to be a console input. 300 | 301 | Solution: 302 | ```py 303 | values = [] 304 | for i in range(1000, 3001): 305 | s = str(i) 306 | if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): 307 | values.append(s) 308 | print ",".join(values) 309 | ``` 310 | 311 | 312 | Question 13 313 | Level 2 314 | 315 | ## Q. 316 | Write a program that accepts a sentence and calculate the number of letters and digits. 317 | Suppose the following input is supplied to the program: 318 | hello world! 123 319 | Then, the output should be: 320 | LETTERS 10 321 | DIGITS 3 322 | 323 | Hints: 324 | In case of input data being supplied to the question, it should be assumed to be a console input. 325 | 326 | Solution: 327 | ```py 328 | s = raw_input() 329 | d={"DIGITS":0, "LETTERS":0} 330 | for c in s: 331 | if c.isdigit(): 332 | d["DIGITS"]+=1 333 | elif c.isalpha(): 334 | d["LETTERS"]+=1 335 | else: 336 | pass 337 | print "LETTERS", d["LETTERS"] 338 | print "DIGITS", d["DIGITS"] 339 | ``` 340 | 341 | 342 | Question 14 343 | Level 2 344 | 345 | ## Q. 346 | Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. 347 | Suppose the following input is supplied to the program: 348 | Hello world! 349 | Then, the output should be: 350 | UPPER CASE 1 351 | LOWER CASE 9 352 | 353 | Hints: 354 | In case of input data being supplied to the question, it should be assumed to be a console input. 355 | 356 | Solution: 357 | ```py 358 | s = raw_input() 359 | d={"UPPER CASE":0, "LOWER CASE":0} 360 | for c in s: 361 | if c.isupper(): 362 | d["UPPER CASE"]+=1 363 | elif c.islower(): 364 | d["LOWER CASE"]+=1 365 | else: 366 | pass 367 | print "UPPER CASE", d["UPPER CASE"] 368 | print "LOWER CASE", d["LOWER CASE"] 369 | ``` 370 | 371 | 372 | Question 15 373 | Level 2 374 | 375 | ## Q. 376 | Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. 377 | Suppose the following input is supplied to the program: 378 | 9 379 | Then, the output should be: 380 | 11106 381 | 382 | Hints: 383 | In case of input data being supplied to the question, it should be assumed to be a console input. 384 | 385 | Solution: 386 | ```py 387 | a = raw_input() 388 | n1 = int( "%s" % a ) 389 | n2 = int( "%s%s" % (a,a) ) 390 | n3 = int( "%s%s%s" % (a,a,a) ) 391 | n4 = int( "%s%s%s%s" % (a,a,a,a) ) 392 | print n1+n2+n3+n4 393 | ``` 394 | 395 | 396 | Question 16 397 | Level 2 398 | 399 | ## Q. 400 | Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. 401 | Suppose the following input is supplied to the program: 402 | 1,2,3,4,5,6,7,8,9 403 | Then, the output should be: 404 | 1,3,5,7,9 405 | 406 | Hints: 407 | In case of input data being supplied to the question, it should be assumed to be a console input. 408 | 409 | Solution: 410 | ```py 411 | values = raw_input() 412 | numbers = [x for x in values.split(",") if int(x)%2!=0] 413 | print ",".join(numbers) 414 | ``` 415 | 416 | 417 | Question 17 418 | Level 2 419 | 420 | ## Q. 421 | Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: 422 | D 100 423 | W 200 424 | 425 | D means deposit while W means withdrawal. 426 | Suppose the following input is supplied to the program: 427 | D 300 428 | D 300 429 | W 200 430 | D 100 431 | Then, the output should be: 432 | 500 433 | 434 | Hints: 435 | In case of input data being supplied to the question, it should be assumed to be a console input. 436 | 437 | Solution: 438 | ```py 439 | netAmount = 0 440 | while True: 441 | s = raw_input() 442 | if not s: 443 | break 444 | values = s.split(" ") 445 | operation = values[0] 446 | amount = int(values[1]) 447 | if operation=="D": 448 | netAmount+=amount 449 | elif operation=="W": 450 | netAmount-=amount 451 | else: 452 | pass 453 | print netAmount 454 | ``` 455 | 456 | 457 | Question 18 458 | Level 3 459 | 460 | ## Q. 461 | A website requires the users to input username and password to register. Write a program to check the validity of password input by users. 462 | Following are the criteria for checking the password: 463 | 1. At least 1 letter between [a-z] 464 | 2. At least 1 number between [0-9] 465 | 1. At least 1 letter between [A-Z] 466 | 3. At least 1 character from [$#@] 467 | 4. Minimum length of transaction password: 6 468 | 5. Maximum length of transaction password: 12 469 | Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. 470 | Example 471 | If the following passwords are given as input to the program: 472 | ABd1234@1,a F1#,2w3E*,2We3345 473 | Then, the output of the program should be: 474 | ABd1234@1 475 | 476 | Hints: 477 | In case of input data being supplied to the question, it should be assumed to be a console input. 478 | 479 | Solutions: 480 | ```py 481 | import re 482 | value = [] 483 | items=[x for x in raw_input().split(',')] 484 | for p in items: 485 | if len(p)<6 or len(p)>12: 486 | continue 487 | else: 488 | pass 489 | if not re.search("[a-z]",p): 490 | continue 491 | elif not re.search("[0-9]",p): 492 | continue 493 | elif not re.search("[A-Z]",p): 494 | continue 495 | elif not re.search("[$#@]",p): 496 | continue 497 | elif re.search("\s",p): 498 | continue 499 | else: 500 | pass 501 | value.append(p) 502 | print ",".join(value) 503 | ``` 504 | 505 | 506 | Question 19 507 | Level 3 508 | 509 | ## Q. 510 | You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: 511 | 1: Sort based on name; 512 | 2: Then sort based on age; 513 | 3: Then sort by score. 514 | The priority is that name > age > score. 515 | If the following tuples are given as input to the program: 516 | Tom,19,80 517 | John,20,90 518 | Jony,17,91 519 | Jony,17,93 520 | Json,21,85 521 | Then, the output of the program should be: 522 | [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] 523 | 524 | Hints: 525 | In case of input data being supplied to the question, it should be assumed to be a console input. 526 | We use itemgetter to enable multiple sort keys. 527 | 528 | Solutions: 529 | ```py 530 | from operator import itemgetter, attrgetter 531 | 532 | l = [] 533 | while True: 534 | s = raw_input() 535 | if not s: 536 | break 537 | l.append(tuple(s.split(","))) 538 | 539 | print sorted(l, key=itemgetter(0,1,2)) 540 | ``` 541 | 542 | 543 | Question 20 544 | Level 3 545 | 546 | ## Q. 547 | Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. 548 | 549 | Hints: 550 | Consider use yield 551 | 552 | Solution: 553 | ```py 554 | def putNumbers(n): 555 | i = 0 556 | while ilen2: 827 | print s1 828 | elif len2>len1: 829 | print s2 830 | else: 831 | print s1 832 | print s2 833 | 834 | 835 | printValue("one","three") 836 | ``` 837 | 838 | 839 | 840 | 2.10 841 | 842 | ## Q. 843 | Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number". 844 | 845 | Hints: 846 | 847 | Use % operator to check if a number is even or odd. 848 | 849 | Solution: 850 | ```py 851 | def checkValue(n): 852 | if n%2 == 0: 853 | print "It is an even number" 854 | else: 855 | print "It is an odd number" 856 | 857 | 858 | checkValue(7) 859 | ``` 860 | 861 | 862 | 2.10 863 | 864 | ## Q. 865 | Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. 866 | 867 | Hints: 868 | 869 | Use dict[key]=value pattern to put entry into a dictionary. 870 | Use ** operator to get power of a number. 871 | 872 | Solution: 873 | ```py 874 | def printDict(): 875 | d=dict() 876 | d[1]=1 877 | d[2]=2**2 878 | d[3]=3**2 879 | print d 880 | 881 | 882 | printDict() 883 | ``` 884 | 885 | 886 | 887 | 888 | 889 | 2.10 890 | 891 | ## Q. 892 | Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. 893 | 894 | Hints: 895 | 896 | Use dict[key]=value pattern to put entry into a dictionary. 897 | Use ** operator to get power of a number. 898 | Use range() for loops. 899 | 900 | Solution: 901 | ```py 902 | def printDict(): 903 | d=dict() 904 | for i in range(1,21): 905 | d[i]=i**2 906 | print d 907 | 908 | 909 | printDict() 910 | ``` 911 | 912 | 913 | 2.10 914 | 915 | ## Q. 916 | Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. 917 | 918 | Hints: 919 | 920 | Use dict[key]=value pattern to put entry into a dictionary. 921 | Use ** operator to get power of a number. 922 | Use range() for loops. 923 | Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. 924 | 925 | Solution: 926 | ```py 927 | def printDict(): 928 | d=dict() 929 | for i in range(1,21): 930 | d[i]=i**2 931 | for (k,v) in d.items(): 932 | print v 933 | 934 | 935 | printDict() 936 | ``` 937 | 938 | 2.10 939 | 940 | ## Q. 941 | Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. 942 | 943 | Hints: 944 | 945 | Use dict[key]=value pattern to put entry into a dictionary. 946 | Use ** operator to get power of a number. 947 | Use range() for loops. 948 | Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. 949 | 950 | Solution: 951 | ```py 952 | def printDict(): 953 | d=dict() 954 | for i in range(1,21): 955 | d[i]=i**2 956 | for k in d.keys(): 957 | print k 958 | 959 | 960 | printDict() 961 | ``` 962 | 963 | 964 | 2.10 965 | 966 | ## Q. 967 | Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). 968 | 969 | Hints: 970 | 971 | Use ** operator to get power of a number. 972 | Use range() for loops. 973 | Use list.append() to add values into a list. 974 | 975 | Solution: 976 | ```py 977 | def printList(): 978 | li=list() 979 | for i in range(1,21): 980 | li.append(i**2) 981 | print li 982 | 983 | 984 | printList() 985 | ``` 986 | 987 | 2.10 988 | 989 | ## Q. 990 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. 991 | 992 | Hints: 993 | 994 | Use ** operator to get power of a number. 995 | Use range() for loops. 996 | Use list.append() to add values into a list. 997 | Use [n1:n2] to slice a list 998 | 999 | Solution: 1000 | ```py 1001 | def printList(): 1002 | li=list() 1003 | for i in range(1,21): 1004 | li.append(i**2) 1005 | print li[:5] 1006 | 1007 | 1008 | printList() 1009 | ``` 1010 | 1011 | 1012 | 2.10 1013 | 1014 | ## Q. 1015 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. 1016 | 1017 | Hints: 1018 | 1019 | Use ** operator to get power of a number. 1020 | Use range() for loops. 1021 | Use list.append() to add values into a list. 1022 | Use [n1:n2] to slice a list 1023 | 1024 | Solution: 1025 | ```py 1026 | def printList(): 1027 | li=list() 1028 | for i in range(1,21): 1029 | li.append(i**2) 1030 | print li[-5:] 1031 | 1032 | 1033 | printList() 1034 | ``` 1035 | 1036 | 1037 | 2.10 1038 | 1039 | ## Q. 1040 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. 1041 | 1042 | Hints: 1043 | 1044 | Use ** operator to get power of a number. 1045 | Use range() for loops. 1046 | Use list.append() to add values into a list. 1047 | Use [n1:n2] to slice a list 1048 | 1049 | Solution: 1050 | ```py 1051 | def printList(): 1052 | li=list() 1053 | for i in range(1,21): 1054 | li.append(i**2) 1055 | print li[5:] 1056 | 1057 | 1058 | printList() 1059 | 1060 | ``` 1061 | 1062 | 2.10 1063 | 1064 | ## Q. 1065 | Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). 1066 | 1067 | Hints: 1068 | 1069 | Use ** operator to get power of a number. 1070 | Use range() for loops. 1071 | Use list.append() to add values into a list. 1072 | Use tuple() to get a tuple from a list. 1073 | 1074 | Solution: 1075 | ```py 1076 | def printTuple(): 1077 | li=list() 1078 | for i in range(1,21): 1079 | li.append(i**2) 1080 | print tuple(li) 1081 | 1082 | printTuple() 1083 | ``` 1084 | 1085 | 1086 | 1087 | 2.10 1088 | 1089 | ## Q. 1090 | With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. 1091 | 1092 | Hints: 1093 | 1094 | Use [n1:n2] notation to get a slice from a tuple. 1095 | 1096 | Solution: 1097 | ```py 1098 | tp=(1,2,3,4,5,6,7,8,9,10) 1099 | tp1=tp[:5] 1100 | tp2=tp[5:] 1101 | print tp1 1102 | print tp2 1103 | ``` 1104 | 1105 | 1106 | 2.10 1107 | 1108 | ## Q. 1109 | Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). 1110 | 1111 | Hints: 1112 | 1113 | Use "for" to iterate the tuple 1114 | Use tuple() to generate a tuple from a list. 1115 | 1116 | Solution: 1117 | ```py 1118 | tp=(1,2,3,4,5,6,7,8,9,10) 1119 | li=list() 1120 | for i in tp: 1121 | if tp[i]%2==0: 1122 | li.append(tp[i]) 1123 | 1124 | tp2=tuple(li) 1125 | print tp2 1126 | 1127 | ``` 1128 | 1129 | 1130 | 2.14 1131 | 1132 | ## Q. 1133 | Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". 1134 | 1135 | Hints: 1136 | 1137 | Use if statement to judge condition. 1138 | 1139 | Solution: 1140 | ```py 1141 | s= raw_input() 1142 | if s=="yes" or s=="YES" or s=="Yes": 1143 | print "Yes" 1144 | else: 1145 | print "No" 1146 | ``` 1147 | 1148 | 1149 | 1150 | 3.4 1151 | 1152 | ## Q. 1153 | Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. 1154 | 1155 | Hints: 1156 | 1157 | Use filter() to filter some elements in a list. 1158 | Use lambda to define anonymous functions. 1159 | 1160 | Solution: 1161 | ```py 1162 | li = [1,2,3,4,5,6,7,8,9,10] 1163 | evenNumbers = filter(lambda x: x%2==0, li) 1164 | print evenNumbers 1165 | ``` 1166 | 1167 | 1168 | 3.4 1169 | 1170 | ## Q. 1171 | Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. 1172 | 1173 | Hints: 1174 | 1175 | Use map() to generate a list. 1176 | Use lambda to define anonymous functions. 1177 | 1178 | Solution: 1179 | ```py 1180 | li = [1,2,3,4,5,6,7,8,9,10] 1181 | squaredNumbers = map(lambda x: x**2, li) 1182 | print squaredNumbers 1183 | ``` 1184 | 1185 | 3.5 1186 | 1187 | ## Q. 1188 | Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. 1189 | 1190 | Hints: 1191 | 1192 | Use map() to generate a list. 1193 | Use filter() to filter elements of a list. 1194 | Use lambda to define anonymous functions. 1195 | 1196 | Solution: 1197 | ```py 1198 | li = [1,2,3,4,5,6,7,8,9,10] 1199 | evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) 1200 | print evenNumbers 1201 | ``` 1202 | 1203 | 1204 | 1205 | 1206 | 3.5 1207 | 1208 | ## Q. 1209 | Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). 1210 | 1211 | Hints: 1212 | 1213 | Use filter() to filter elements of a list. 1214 | Use lambda to define anonymous functions. 1215 | 1216 | Solution: 1217 | ```py 1218 | evenNumbers = filter(lambda x: x%2==0, range(1,21)) 1219 | print evenNumbers 1220 | 1221 | ``` 1222 | 1223 | 3.5 1224 | 1225 | ## Q. 1226 | Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). 1227 | 1228 | Hints: 1229 | 1230 | Use map() to generate a list. 1231 | Use lambda to define anonymous functions. 1232 | 1233 | Solution: 1234 | ```py 1235 | squaredNumbers = map(lambda x: x**2, range(1,21)) 1236 | print squaredNumbers 1237 | ``` 1238 | 1239 | 1240 | 1241 | 1242 | 7.2 1243 | 1244 | ## Q. 1245 | Define a class named American which has a static method called printNationality. 1246 | 1247 | Hints: 1248 | 1249 | Use @staticmethod decorator to define class static method. 1250 | 1251 | Solution: 1252 | ```py 1253 | class American(object): 1254 | @staticmethod 1255 | def printNationality(): 1256 | print "America" 1257 | 1258 | anAmerican = American() 1259 | anAmerican.printNationality() 1260 | American.printNationality() 1261 | 1262 | ``` 1263 | 1264 | 1265 | 1266 | 1267 | 7.2 1268 | 1269 | ## Q. 1270 | Define a class named American and its subclass NewYorker. 1271 | 1272 | Hints: 1273 | 1274 | Use class Subclass(ParentClass) to define a subclass. 1275 | 1276 | Solution: 1277 | ```py 1278 | 1279 | class American(object): 1280 | pass 1281 | 1282 | class NewYorker(American): 1283 | pass 1284 | 1285 | anAmerican = American() 1286 | aNewYorker = NewYorker() 1287 | print anAmerican 1288 | print aNewYorker 1289 | 1290 | ``` 1291 | 1292 | 1293 | 1294 | 1295 | 1296 | 7.2 1297 | 1298 | ## Q. 1299 | Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. 1300 | 1301 | Hints: 1302 | 1303 | Use def methodName(self) to define a method. 1304 | 1305 | Solution: 1306 | ```py 1307 | 1308 | class Circle(object): 1309 | def __init__(self, r): 1310 | self.radius = r 1311 | 1312 | def area(self): 1313 | return self.radius**2*3.14 1314 | 1315 | aCircle = Circle(2) 1316 | print aCircle.area() 1317 | 1318 | ``` 1319 | 1320 | 1321 | 1322 | 1323 | 1324 | 1325 | 7.2 1326 | 1327 | Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. 1328 | 1329 | Hints: 1330 | 1331 | Use def methodName(self) to define a method. 1332 | 1333 | Solution: 1334 | ```py 1335 | 1336 | class Rectangle(object): 1337 | def __init__(self, l, w): 1338 | self.length = l 1339 | self.width = w 1340 | 1341 | def area(self): 1342 | return self.length*self.width 1343 | 1344 | aRectangle = Rectangle(2,10) 1345 | print aRectangle.area() 1346 | ``` 1347 | 1348 | 1349 | 1350 | 1351 | 1352 | 7.2 1353 | 1354 | Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. 1355 | 1356 | Hints: 1357 | 1358 | To override a method in super class, we can define a method with the same name in the super class. 1359 | 1360 | Solution: 1361 | ```py 1362 | 1363 | class Shape(object): 1364 | def __init__(self): 1365 | pass 1366 | 1367 | def area(self): 1368 | return 0 1369 | 1370 | class Square(Shape): 1371 | def __init__(self, l): 1372 | Shape.__init__(self) 1373 | self.length = l 1374 | 1375 | def area(self): 1376 | return self.length*self.length 1377 | 1378 | aSquare= Square(3) 1379 | print aSquare.area() 1380 | 1381 | ``` 1382 | 1383 | 1384 | 1385 | 1386 | 1387 | 1388 | 1389 | 1390 | 1391 | Please raise a RuntimeError exception. 1392 | 1393 | Hints: 1394 | 1395 | Use raise() to raise an exception. 1396 | 1397 | Solution: 1398 | ```py 1399 | 1400 | raise RuntimeError('something wrong') 1401 | ``` 1402 | 1403 | 1404 | 1405 | Write a function to compute 5/0 and use try/except to catch the exceptions. 1406 | 1407 | Hints: 1408 | 1409 | Use try/except to catch exceptions. 1410 | 1411 | Solution: 1412 | ```py 1413 | 1414 | def throws(): 1415 | return 5/0 1416 | 1417 | try: 1418 | throws() 1419 | except ZeroDivisionError: 1420 | print "division by zero!" 1421 | except Exception, err: 1422 | print 'Caught an exception' 1423 | finally: 1424 | print 'In finally block for cleanup' 1425 | ``` 1426 | 1427 | 1428 | Define a custom exception class which takes a string message as attribute. 1429 | 1430 | Hints: 1431 | 1432 | To define a custom exception, we need to define a class inherited from Exception. 1433 | 1434 | Solution: 1435 | ```py 1436 | 1437 | class MyError(Exception): 1438 | """My own exception class 1439 | 1440 | Attributes: 1441 | msg -- explanation of the error 1442 | """ 1443 | 1444 | def __init__(self, msg): 1445 | self.msg = msg 1446 | 1447 | error = MyError("something wrong") 1448 | ``` 1449 | 1450 | ## Q. 1451 | 1452 | Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. 1453 | 1454 | Example: 1455 | If the following email address is given as input to the program: 1456 | 1457 | john@google.com 1458 | 1459 | Then, the output of the program should be: 1460 | 1461 | john 1462 | 1463 | In case of input data being supplied to the question, it should be assumed to be a console input. 1464 | 1465 | Hints: 1466 | 1467 | Use \w to match letters. 1468 | 1469 | Solution: 1470 | ```py 1471 | import re 1472 | emailAddress = raw_input() 1473 | pat2 = "(\w+)@((\w+\.)+(com))" 1474 | r2 = re.match(pat2,emailAddress) 1475 | print r2.group(1) 1476 | ``` 1477 | 1478 | 1479 | ## Q. 1480 | 1481 | Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. 1482 | 1483 | Example: 1484 | If the following email address is given as input to the program: 1485 | 1486 | john@google.com 1487 | 1488 | Then, the output of the program should be: 1489 | 1490 | google 1491 | 1492 | In case of input data being supplied to the question, it should be assumed to be a console input. 1493 | 1494 | Hints: 1495 | 1496 | Use \w to match letters. 1497 | 1498 | Solution: 1499 | ```py 1500 | import re 1501 | emailAddress = raw_input() 1502 | pat2 = "(\w+)@(\w+)\.(com)" 1503 | r2 = re.match(pat2,emailAddress) 1504 | print r2.group(2) 1505 | ``` 1506 | 1507 | 1508 | 1509 | 1510 | ## Q. 1511 | 1512 | Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. 1513 | 1514 | Example: 1515 | If the following words is given as input to the program: 1516 | 1517 | 2 cats and 3 dogs. 1518 | 1519 | Then, the output of the program should be: 1520 | 1521 | ['2', '3'] 1522 | 1523 | In case of input data being supplied to the question, it should be assumed to be a console input. 1524 | 1525 | Hints: 1526 | 1527 | Use re.findall() to find all substring using regex. 1528 | 1529 | Solution: 1530 | ```py 1531 | import re 1532 | s = raw_input() 1533 | print re.findall("\d+",s) 1534 | ``` 1535 | 1536 | 1537 | ## Q. 1538 | 1539 | 1540 | Print a unicode string "hello world". 1541 | 1542 | Hints: 1543 | 1544 | Use u'strings' format to define unicode string. 1545 | 1546 | Solution: 1547 | ```py 1548 | 1549 | unicodeString = u"hello world!" 1550 | print unicodeString 1551 | 1552 | 1553 | Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. 1554 | 1555 | Hints: 1556 | 1557 | Use unicode() function to convert. 1558 | 1559 | Solution: 1560 | ```py 1561 | 1562 | s = raw_input() 1563 | u = unicode( s ,"utf-8") 1564 | print u 1565 | ``` 1566 | 1567 | ## Q. 1568 | 1569 | Write a special comment to indicate a Python source code file is in unicode. 1570 | 1571 | Hints: 1572 | 1573 | Solution: 1574 | ```py 1575 | 1576 | # -*- coding: utf-8 -*- 1577 | 1578 | 1579 | ## Q. 1580 | 1581 | Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). 1582 | 1583 | Example: 1584 | If the following n is given as input to the program: 1585 | 1586 | 5 1587 | 1588 | Then, the output of the program should be: 1589 | 1590 | 3.55 1591 | 1592 | In case of input data being supplied to the question, it should be assumed to be a console input. 1593 | 1594 | Hints: 1595 | Use float() to convert an integer to a float 1596 | 1597 | Solution: 1598 | ```py 1599 | 1600 | n=int(raw_input()) 1601 | sum=0.0 1602 | for i in range(1,n+1): 1603 | sum += float(float(i)/(i+1)) 1604 | print sum 1605 | ``` 1606 | 1607 | 1608 | ## Q. 1609 | 1610 | Write a program to compute: 1611 | 1612 | f(n)=f(n-1)+100 when n>0 1613 | and f(0)=1 1614 | 1615 | with a given n input by console (n>0). 1616 | 1617 | Example: 1618 | If the following n is given as input to the program: 1619 | 1620 | 5 1621 | 1622 | Then, the output of the program should be: 1623 | 1624 | 500 1625 | 1626 | In case of input data being supplied to the question, it should be assumed to be a console input. 1627 | 1628 | Hints: 1629 | We can define recursive function in Python. 1630 | 1631 | Solution: 1632 | ```py 1633 | 1634 | def f(n): 1635 | if n==0: 1636 | return 0 1637 | else: 1638 | return f(n-1)+100 1639 | 1640 | n=int(raw_input()) 1641 | print f(n) 1642 | ``` 1643 | 1644 | 1645 | ## Q. 1646 | 1647 | 1648 | The Fibonacci Sequence is computed based on the following formula: 1649 | 1650 | 1651 | f(n)=0 if n=0 1652 | f(n)=1 if n=1 1653 | f(n)=f(n-1)+f(n-2) if n>1 1654 | 1655 | Please write a program to compute the value of f(n) with a given n input by console. 1656 | 1657 | Example: 1658 | If the following n is given as input to the program: 1659 | 1660 | 7 1661 | 1662 | Then, the output of the program should be: 1663 | 1664 | 13 1665 | 1666 | In case of input data being supplied to the question, it should be assumed to be a console input. 1667 | 1668 | Hints: 1669 | We can define recursive function in Python. 1670 | 1671 | 1672 | Solution: 1673 | ```py 1674 | 1675 | def f(n): 1676 | if n == 0: return 0 1677 | elif n == 1: return 1 1678 | else: return f(n-1)+f(n-2) 1679 | 1680 | n=int(raw_input()) 1681 | print f(n) 1682 | ``` 1683 | 1684 | 1685 | 1686 | 1687 | 1688 | ## Q. 1689 | 1690 | The Fibonacci Sequence is computed based on the following formula: 1691 | 1692 | 1693 | f(n)=0 if n=0 1694 | f(n)=1 if n=1 1695 | f(n)=f(n-1)+f(n-2) if n>1 1696 | 1697 | Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. 1698 | 1699 | Example: 1700 | If the following n is given as input to the program: 1701 | 1702 | 7 1703 | 1704 | Then, the output of the program should be: 1705 | 1706 | 0,1,1,2,3,5,8,13 1707 | 1708 | 1709 | Hints: 1710 | We can define recursive function in Python. 1711 | Use list comprehension to generate a list from an existing list. 1712 | Use string.join() to join a list of strings. 1713 | 1714 | In case of input data being supplied to the question, it should be assumed to be a console input. 1715 | 1716 | Solution: 1717 | ```py 1718 | 1719 | def f(n): 1720 | if n == 0: return 0 1721 | elif n == 1: return 1 1722 | else: return f(n-1)+f(n-2) 1723 | 1724 | n=int(raw_input()) 1725 | values = [str(f(x)) for x in range(0, n+1)] 1726 | print ",".join(values) 1727 | ``` 1728 | 1729 | 1730 | 1731 | ## Q. 1732 | 1733 | Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. 1734 | 1735 | Example: 1736 | If the following n is given as input to the program: 1737 | 1738 | 10 1739 | 1740 | Then, the output of the program should be: 1741 | 1742 | 0,2,4,6,8,10 1743 | 1744 | Hints: 1745 | Use yield to produce the next value in generator. 1746 | 1747 | In case of input data being supplied to the question, it should be assumed to be a console input. 1748 | 1749 | Solution: 1750 | ```py 1751 | 1752 | def EvenGenerator(n): 1753 | i=0 1754 | while i<=n: 1755 | if i%2==0: 1756 | yield i 1757 | i+=1 1758 | 1759 | 1760 | n=int(raw_input()) 1761 | values = [] 1762 | for i in EvenGenerator(n): 1763 | values.append(str(i)) 1764 | 1765 | print ",".join(values) 1766 | ``` 1767 | 1768 | 1769 | 1770 | ## Q. 1771 | 1772 | Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. 1773 | 1774 | Example: 1775 | If the following n is given as input to the program: 1776 | 1777 | 100 1778 | 1779 | Then, the output of the program should be: 1780 | 1781 | 0,35,70 1782 | 1783 | Hints: 1784 | Use yield to produce the next value in generator. 1785 | 1786 | In case of input data being supplied to the question, it should be assumed to be a console input. 1787 | 1788 | Solution: 1789 | ```py 1790 | 1791 | def NumGenerator(n): 1792 | for i in range(n+1): 1793 | if i%5==0 and i%7==0: 1794 | yield i 1795 | 1796 | n=int(raw_input()) 1797 | values = [] 1798 | for i in NumGenerator(n): 1799 | values.append(str(i)) 1800 | 1801 | print ",".join(values) 1802 | ``` 1803 | 1804 | 1805 | 1806 | ## Q. 1807 | 1808 | 1809 | Please write assert statements to verify that every number in the list [2,4,6,8] is even. 1810 | 1811 | 1812 | 1813 | Hints: 1814 | Use "assert expression" to make assertion. 1815 | 1816 | 1817 | Solution: 1818 | ```py 1819 | 1820 | li = [2,4,6,8] 1821 | for i in li: 1822 | assert i%2==0 1823 | 1824 | ``` 1825 | 1826 | ## Q. 1827 | 1828 | Please write a program which accepts basic mathematic expression from console and print the evaluation result. 1829 | 1830 | Example: 1831 | If the following string is given as input to the program: 1832 | 1833 | 35+3 1834 | 1835 | Then, the output of the program should be: 1836 | 1837 | 38 1838 | 1839 | Hints: 1840 | Use eval() to evaluate an expression. 1841 | 1842 | 1843 | Solution: 1844 | ```py 1845 | 1846 | expression = raw_input() 1847 | print eval(expression) 1848 | ``` 1849 | 1850 | 1851 | ## Q. 1852 | 1853 | Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. 1854 | 1855 | 1856 | Hints: 1857 | Use if/elif to deal with conditions. 1858 | 1859 | 1860 | Solution: 1861 | ```py 1862 | 1863 | import math 1864 | def bin_search(li, element): 1865 | bottom = 0 1866 | top = len(li)-1 1867 | index = -1 1868 | while top>=bottom and index==-1: 1869 | mid = int(math.floor((top+bottom)/2.0)) 1870 | if li[mid]==element: 1871 | index = mid 1872 | elif li[mid]>element: 1873 | top = mid-1 1874 | else: 1875 | bottom = mid+1 1876 | 1877 | return index 1878 | 1879 | li=[2,5,7,9,11,17,222] 1880 | print bin_search(li,11) 1881 | print bin_search(li,12) 1882 | ``` 1883 | 1884 | 1885 | 1886 | 1887 | ## Q. 1888 | 1889 | Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. 1890 | 1891 | 1892 | Hints: 1893 | Use if/elif to deal with conditions. 1894 | 1895 | 1896 | Solution: 1897 | ```py 1898 | 1899 | import math 1900 | def bin_search(li, element): 1901 | bottom = 0 1902 | top = len(li)-1 1903 | index = -1 1904 | while top>=bottom and index==-1: 1905 | mid = int(math.floor((top+bottom)/2.0)) 1906 | if li[mid]==element: 1907 | index = mid 1908 | elif li[mid]>element: 1909 | top = mid-1 1910 | else: 1911 | bottom = mid+1 1912 | 1913 | return index 1914 | 1915 | li=[2,5,7,9,11,17,222] 1916 | print bin_search(li,11) 1917 | print bin_search(li,12) 1918 | ``` 1919 | 1920 | 1921 | 1922 | 1923 | ## Q. 1924 | 1925 | Please generate a random float where the value is between 10 and 100 using Python math module. 1926 | 1927 | 1928 | 1929 | Hints: 1930 | Use random.random() to generate a random float in [0,1]. 1931 | 1932 | 1933 | Solution: 1934 | ```py 1935 | 1936 | import random 1937 | print random.random()*100 1938 | ``` 1939 | 1940 | ## Q. 1941 | 1942 | Please generate a random float where the value is between 5 and 95 using Python math module. 1943 | 1944 | 1945 | 1946 | Hints: 1947 | Use random.random() to generate a random float in [0,1]. 1948 | 1949 | 1950 | Solution: 1951 | ```py 1952 | 1953 | import random 1954 | print random.random()*100-5 1955 | ``` 1956 | 1957 | 1958 | ## Q. 1959 | 1960 | Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. 1961 | 1962 | 1963 | 1964 | Hints: 1965 | Use random.choice() to a random element from a list. 1966 | 1967 | 1968 | Solution: 1969 | ```py 1970 | 1971 | import random 1972 | print random.choice([i for i in range(11) if i%2==0]) 1973 | ``` 1974 | 1975 | 1976 | ## Q. 1977 | 1978 | Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. 1979 | 1980 | 1981 | 1982 | Hints: 1983 | Use random.choice() to a random element from a list. 1984 | 1985 | 1986 | Solution: 1987 | ```py 1988 | 1989 | import random 1990 | print random.choice([i for i in range(201) if i%5==0 and i%7==0]) 1991 | ``` 1992 | 1993 | 1994 | 1995 | 1996 | ## Q. 1997 | 1998 | Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. 1999 | 2000 | 2001 | 2002 | Hints: 2003 | Use random.sample() to generate a list of random values. 2004 | 2005 | 2006 | Solution: 2007 | ```py 2008 | 2009 | import random 2010 | print random.sample(range(100), 5) 2011 | ``` 2012 | 2013 | ## Q. Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. 2014 | 2015 | 2016 | 2017 | Hints: 2018 | Use random.sample() to generate a list of random values. 2019 | 2020 | 2021 | Solution: 2022 | ```py 2023 | 2024 | import random 2025 | print random.sample([i for i in range(100,201) if i%2==0], 5) 2026 | ``` 2027 | 2028 | 2029 | ## Q. 2030 | Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. 2031 | 2032 | 2033 | 2034 | Hints: 2035 | Use random.sample() to generate a list of random values. 2036 | 2037 | 2038 | Solution: 2039 | ```py 2040 | 2041 | import random 2042 | print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) 2043 | 2044 | ``` 2045 | 2046 | ## Q. 2047 | Please write a program to randomly print a integer number between 7 and 15 inclusive. 2048 | 2049 | 2050 | 2051 | Hints: 2052 | Use random.randrange() to a random integer in a given range. 2053 | 2054 | 2055 | Solution: 2056 | ```py 2057 | 2058 | import random 2059 | print random.randrange(7,16) 2060 | ``` 2061 | 2062 | 2063 | ## Q. 2064 | Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". 2065 | 2066 | 2067 | 2068 | Hints: 2069 | Use zlib.compress() and zlib.decompress() to compress and decompress a string. 2070 | 2071 | 2072 | Solution: 2073 | ```py 2074 | 2075 | import zlib 2076 | s = 'hello world!hello world!hello world!hello world!' 2077 | t = zlib.compress(s) 2078 | print t 2079 | print zlib.decompress(t) 2080 | ``` 2081 | 2082 | ## Q. 2083 | Please write a program to print the running time of execution of "1+1" for 100 times. 2084 | 2085 | 2086 | 2087 | Hints: 2088 | Use timeit() function to measure the running time. 2089 | 2090 | Solution: 2091 | ```py 2092 | 2093 | from timeit import Timer 2094 | t = Timer("for i in range(100):1+1") 2095 | print t.timeit() 2096 | ``` 2097 | 2098 | ## Q. 2099 | Please write a program to shuffle and print the list [3,6,7,8]. 2100 | 2101 | 2102 | 2103 | Hints: 2104 | Use shuffle() function to shuffle a list. 2105 | 2106 | Solution: 2107 | ```py 2108 | 2109 | from random import shuffle 2110 | li = [3,6,7,8] 2111 | shuffle(li) 2112 | print li 2113 | ``` 2114 | 2115 | ## Q. 2116 | Please write a program to shuffle and print the list [3,6,7,8]. 2117 | 2118 | 2119 | 2120 | Hints: 2121 | Use shuffle() function to shuffle a list. 2122 | 2123 | Solution: 2124 | ```py 2125 | 2126 | from random import shuffle 2127 | li = [3,6,7,8] 2128 | shuffle(li) 2129 | print li 2130 | ``` 2131 | 2132 | 2133 | 2134 | ## Q. 2135 | Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. 2136 | 2137 | Hints: 2138 | Use list[index] notation to get a element from a list. 2139 | 2140 | Solution: 2141 | ```py 2142 | 2143 | subjects=["I", "You"] 2144 | verbs=["Play", "Love"] 2145 | objects=["Hockey","Football"] 2146 | for i in range(len(subjects)): 2147 | for j in range(len(verbs)): 2148 | for k in range(len(objects)): 2149 | sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) 2150 | print sentence 2151 | ``` 2152 | 2153 | 2154 | Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. 2155 | 2156 | Hints: 2157 | Use list comprehension to delete a bunch of element from a list. 2158 | 2159 | Solution: 2160 | ```py 2161 | 2162 | li = [5,6,77,45,22,12,24] 2163 | li = [x for x in li if x%2!=0] 2164 | print li 2165 | ``` 2166 | 2167 | ## Q. 2168 | By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. 2169 | 2170 | Hints: 2171 | Use list comprehension to delete a bunch of element from a list. 2172 | 2173 | Solution: 2174 | ```py 2175 | 2176 | li = [12,24,35,70,88,120,155] 2177 | li = [x for x in li if x%5!=0 and x%7!=0] 2178 | print li 2179 | ``` 2180 | 2181 | 2182 | ## Q. 2183 | By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. 2184 | 2185 | Hints: 2186 | Use list comprehension to delete a bunch of element from a list. 2187 | Use enumerate() to get (index, value) tuple. 2188 | 2189 | Solution: 2190 | ```py 2191 | 2192 | li = [12,24,35,70,88,120,155] 2193 | li = [x for (i,x) in enumerate(li) if i%2!=0] 2194 | print li 2195 | ``` 2196 | 2197 | 2198 | ## Q. 2199 | By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0. 2200 | 2201 | Hints: 2202 | Use list comprehension to make an array. 2203 | 2204 | Solution: 2205 | ```py 2206 | 2207 | array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] 2208 | print array 2209 | ``` 2210 | 2211 | ## Q. 2212 | By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. 2213 | 2214 | Hints: 2215 | Use list comprehension to delete a bunch of element from a list. 2216 | Use enumerate() to get (index, value) tuple. 2217 | 2218 | Solution: 2219 | ```py 2220 | 2221 | li = [12,24,35,70,88,120,155] 2222 | li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] 2223 | print li 2224 | 2225 | ``` 2226 | 2227 | 2228 | 2229 | ## Q. 2230 | By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. 2231 | 2232 | Hints: 2233 | Use list's remove method to delete a value. 2234 | 2235 | Solution: 2236 | ```py 2237 | 2238 | li = [12,24,35,24,88,120,155] 2239 | li = [x for x in li if x!=24] 2240 | print li 2241 | ``` 2242 | 2243 | 2244 | ## Q. 2245 | With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. 2246 | 2247 | Hints: 2248 | Use set() and "&=" to do set intersection operation. 2249 | 2250 | Solution: 2251 | ```py 2252 | 2253 | set1=set([1,3,6,78,35,55]) 2254 | set2=set([12,24,35,24,88,120,155]) 2255 | set1 &= set2 2256 | li=list(set1) 2257 | print li 2258 | ``` 2259 | 2260 | 2261 | With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. 2262 | 2263 | Hints: 2264 | Use set() to store a number of values without duplicate. 2265 | 2266 | Solution: 2267 | ```py 2268 | 2269 | def removeDuplicate( li ): 2270 | newli=[] 2271 | seen = set() 2272 | for item in li: 2273 | if item not in seen: 2274 | seen.add( item ) 2275 | newli.append(item) 2276 | 2277 | return newli 2278 | 2279 | li=[12,24,35,24,88,120,155,88,120,155] 2280 | print removeDuplicate(li) 2281 | ``` 2282 | 2283 | 2284 | ## Q. 2285 | Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. 2286 | 2287 | Hints: 2288 | Use Subclass(Parentclass) to define a child class. 2289 | 2290 | Solution: 2291 | ```py 2292 | 2293 | class Person(object): 2294 | def getGender( self ): 2295 | return "Unknown" 2296 | 2297 | class Male( Person ): 2298 | def getGender( self ): 2299 | return "Male" 2300 | 2301 | class Female( Person ): 2302 | def getGender( self ): 2303 | return "Female" 2304 | 2305 | aMale = Male() 2306 | aFemale= Female() 2307 | print aMale.getGender() 2308 | print aFemale.getGender() 2309 | 2310 | ``` 2311 | 2312 | 2313 | ## Q. 2314 | Please write a program which count and print the numbers of each character in a string input by console. 2315 | 2316 | Example: 2317 | If the following string is given as input to the program: 2318 | 2319 | abcdefgabc 2320 | 2321 | Then, the output of the program should be: 2322 | 2323 | a,2 2324 | c,2 2325 | b,2 2326 | e,1 2327 | d,1 2328 | g,1 2329 | f,1 2330 | 2331 | Hints: 2332 | Use dict to store key/value pairs. 2333 | Use dict.get() method to lookup a key with default value. 2334 | 2335 | Solution: 2336 | ```py 2337 | 2338 | dic = {} 2339 | s=raw_input() 2340 | for s in s: 2341 | dic[s] = dic.get(s,0)+1 2342 | print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) 2343 | ``` 2344 | 2345 | 2346 | ## Q. 2347 | Please write a program which accepts a string from console and print it in reverse order. 2348 | 2349 | Example: 2350 | If the following string is given as input to the program: 2351 | 2352 | rise to vote sir 2353 | 2354 | Then, the output of the program should be: 2355 | 2356 | ris etov ot esir 2357 | 2358 | Hints: 2359 | Use list[::-1] to iterate a list in a reverse order. 2360 | 2361 | Solution: 2362 | ```py 2363 | 2364 | s=raw_input() 2365 | s = s[::-1] 2366 | print s 2367 | ``` 2368 | 2369 | 2370 | ## Q. 2371 | Please write a program which accepts a string from console and print the characters that have even indexes. 2372 | 2373 | Example: 2374 | If the following string is given as input to the program: 2375 | 2376 | H1e2l3l4o5w6o7r8l9d 2377 | 2378 | Then, the output of the program should be: 2379 | 2380 | Helloworld 2381 | 2382 | Hints: 2383 | Use list[::2] to iterate a list by step 2. 2384 | 2385 | Solution: 2386 | ```py 2387 | 2388 | s=raw_input() 2389 | s = s[::2] 2390 | print s 2391 | ``` 2392 | 2393 | 2394 | ## Q. 2395 | Please write a program which prints all permutations of [1,2,3] 2396 | 2397 | 2398 | Hints: 2399 | Use itertools.permutations() to get permutations of list. 2400 | 2401 | Solution: 2402 | ```py 2403 | 2404 | import itertools 2405 | print list(itertools.permutations([1,2,3])) 2406 | ``` 2407 | 2408 | ## Q. 2409 | Write a program to solve a classic ancient Chinese puzzle: 2410 | We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? 2411 | 2412 | Hint: 2413 | Use for loop to iterate all possible solutions. 2414 | 2415 | Solution: 2416 | ```py 2417 | 2418 | def solve(numheads,numlegs): 2419 | ns='No solutions!' 2420 | for i in range(numheads+1): 2421 | j=numheads-i 2422 | if 2*i+4*j==numlegs: 2423 | return i,j 2424 | return ns,ns 2425 | 2426 | numheads=35 2427 | numlegs=94 2428 | solutions=solve(numheads,numlegs) 2429 | print solutions 2430 | ``` 2431 | 2432 | 2433 | -------------------------------------------------------------------------------- /task_handler/task0.py: -------------------------------------------------------------------------------- 1 | SHIP DOCKING 2 | -------------------------------------------------------------------------------- /task_handler/task1.py: -------------------------------------------------------------------------------- 1 | UNLOADING VESSEL 2 | -------------------------------------------------------------------------------- /task_handler/task2.py: -------------------------------------------------------------------------------- 1 | TRUCK LOADING CONTAINER 2 | -------------------------------------------------------------------------------- /task_handler/task3.py: -------------------------------------------------------------------------------- 1 | CUSTOMS CHECK 2 | -------------------------------------------------------------------------------- /task_handler/task4.py: -------------------------------------------------------------------------------- 1 | RE-FUELING SHIP 2 | -------------------------------------------------------------------------------- /task_handler/taskhandler.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import sys 3 | from StringIO import StringIO 4 | 5 | 6 | class TaskHandler(object): 7 | 8 | def __init__(self): 9 | 10 | """ 11 | Ships must dock first, then vessel can be unloaded, then a truck can 12 | load a container, and lastly it needs to go through a customs check. 13 | The refueling process can happen anytime after a ship docks. 14 | """ 15 | 16 | self._task_order = {'RE-FUELING SHIP': ['SHIP DOCKING'], 17 | 'UNLOADING VESSEL': ['SHIP DOCKING'], 18 | 'TRUCK LOADING CONTAINER': ['UNLOADING VESSEL'], 19 | 'CUSTOMS CHECK': ['TRUCK LOADING CONTAINER'] 20 | } 21 | 22 | 23 | self.task_list = {'SHIP DOCKING': 0, 24 | 'RE-FUELING SHIP': 0, 25 | 'UNLOADING VESSEL': 0, 26 | 'TRUCK LOADING CONTAINER': 0, 27 | 'CUSTOMS CHECK': 0 28 | } 29 | 30 | 31 | def tasks_remaining(self): 32 | """ Gets total number of tasks remaining. """ 33 | 34 | return sum(self.task_list.values()) 35 | 36 | 37 | def add_task(self, tasks_array): 38 | """ Adds an array of tasks to existing task list. """ 39 | 40 | for task_file in tasks_array: 41 | task = open(task_file).read().rstrip() 42 | self.task_list[task] = self.task_list.get(task) + 1 43 | 44 | 45 | def execute_tasks(self): 46 | """ Executes tasks in sensible order. """ 47 | 48 | for task in self.task_list.keys(): 49 | 50 | if task not in self._task_order: 51 | while self.task_list[task] > 0: 52 | print task + ' COMPLETED' 53 | self.remove_task(task) 54 | 55 | else: 56 | while self.task_list[task] > 0: 57 | self.check_dependencies(task) 58 | print task + ' COMPLETED' 59 | self.remove_task(task) 60 | 61 | 62 | 63 | def check_dependencies(self, task): 64 | """ Checks for any task dependencies. """ 65 | 66 | dependencies_remaining = [] 67 | 68 | if task in self._task_order: 69 | dependencies = self._task_order[task] 70 | 71 | for dependency in dependencies: 72 | dependencies_remaining.append(dependency) 73 | 74 | if dependencies_remaining == []: 75 | return 76 | else: 77 | for dependency in dependencies_remaining: 78 | self.check_dependencies(dependency) 79 | 80 | 81 | 82 | def remove_task(self, task): 83 | """ Removes a task from the task list once it has been completed. """ 84 | 85 | self.task_list[task] -= 1 86 | 87 | 88 | def __repr__(self): 89 | 90 | return '<{} tasks remaining>'.format(self.tasks_remaining()) 91 | 92 | 93 | 94 | class TestingTaskHandler(unittest.TestCase): 95 | 96 | def setUp(self): 97 | self.job = TaskHandler() 98 | self.job.add_task(['task0.py', 'task1.py', 'task4.py', 'task2.py', 'task3.py', 'task3.py', 'task4.py', 'task2.py', 'task1.py']) 99 | self.held = sys.stdout 100 | sys.stdout = StringIO() 101 | 102 | def test_add_tasks(self): 103 | self.assertEqual(self.job.tasks_remaining(), 9) 104 | self.assertEqual(self.job.task_list, {'SHIP DOCKING': 1, 'UNLOADING VESSEL': 2, 'CUSTOMS CHECK': 2, 'TRUCK LOADING CONTAINER': 2, 'RE-FUELING SHIP': 2}) 105 | 106 | def test_remove_task(self): 107 | self.job.remove_task('SHIP DOCKING') 108 | self.assertEqual(self.job.tasks_remaining(), 8) 109 | self.assertEqual(self.job.task_list, {'SHIP DOCKING': 0, 'UNLOADING VESSEL': 2, 'CUSTOMS CHECK': 2, 'TRUCK LOADING CONTAINER': 2, 'RE-FUELING SHIP': 2}) 110 | 111 | def test_execute_tasks(self): 112 | self.job.execute_tasks() 113 | self.assertEqual(self.job.tasks_remaining(), 0) 114 | self.assertEqual(sys.stdout.getvalue(), 115 | 'SHIP DOCKING COMPLETED\nUNLOADING VESSEL COMPLETED\nUNLOADING VESSEL COMPLETED\nCUSTOMS CHECK COMPLETED\nCUSTOMS CHECK COMPLETED\nTRUCK LOADING CONTAINER COMPLETED\nTRUCK LOADING CONTAINER COMPLETED\nRE-FUELING SHIP COMPLETED\nRE-FUELING SHIP COMPLETED\n') 116 | 117 | 118 | 119 | if __name__ == '__main__': 120 | unittest.main() 121 | --------------------------------------------------------------------------------