""" ################################################################################ MIDTERM EXAM ASSIGNMENT RULES ################################################################################ - You are strictly forbidden to share answers with your classmates. - You are not allowed to search for answers on the Internet. You are not allowed to ask for answers in forums or other online communication systems. - Note that, when you find an answer on the web, somebody else will also find it and use it. This means, both of you will submit the exact same answer. This, then, means cheating, no matter you know the other person or not. - If your answers are similar to some other student's answers, you will enter manual cheat check process. We don't care whether you know the other person or not, we don't care whether he/she is your friend or not, we don't care who delivered and who received. Both parties get a discipline penalty if found guilty. - You are not allowed to import any packages. If there are any imports in your submission, we will remove them before grading. - If your file doesn't run, then you will get 0 points. Make sure that your indentation and syntax are correct. - Do not change the below function definitions. In other words, DO NOT CHANGE the function names and the parameters of the functions. You are only allowed to write code within the function scope. - Do not print anything on the screen unless you are asked to. Some questions require you to RETURN a value. Printing that value on the screen is not equal to returning the value. - Do not submit any testing code. - Do not try to take user input using Python input() function! The automated tests will provide inputs to your functions for grading not some user. - For problems with EXCEPTIONS, you MUST use try-except block(s) to handle all of the possible exceptions. If-else solutions for handling the exceptions WILL NOT BE GIVEN FULL CREDIT! ################################################################################ DO NOT FORGET TO FILL THE LINES BELOW: My full name : _______________ My student ID : _______________ My department : _______________ """ """ ################################################################################ Question 1: (15 points) Topics: lists, tuples ################################################################################ The Manhattan distance between two points (x1,y1) and (x2,y2) is given as |x1-x2| + |y1-y2|, where |x| denotes the absolute value of x. Write a Python function named max_manhattan(points), that takes a LIST of points where each point is represented by a 2-element TUPLE containing x and y coordinates, and RETURNs a TUPLE containing indices of the two points whose manhattan distance is the LARGEST among the given points. --- Sample test cases --- For example, calling max_manhattan([(0,0), (1,1), (2,-2)]) returns (0,2) because the manhattan distance between the points (0,0) and (2,-2) is 4, and that is the maximum in the given set. Calling max_manhattan([(0,0),(1,0),(0,2),(-3,0)]) returns (2,3) because the maximum distance occurs between the points at positions 2 and 3: (0,2)-(-3,0) """ def max_manhattan(points): # Remove the return line below before you answer this question. If you will NOT answer # this question, then do NOT remove this line below. return "I have not solved this question" """ ################################################################################ Question 2: (20 points) Topics: lists, tuples, dictionaries, exceptions ################################################################################ Write a Python function updateInventory(inventory, transactions) that takes two arguments as follows: 1. a DICTIONARY storing inventory counts of a store's items. For example: {"tshirt":29, "pants":14, "shirt":7, "shoes":5} 2. a LIST of TUPLES, where each tuple contains an item name and an integer amount, representing a transaction on that item (how many pieces of that item have been added to the inventory or sold to customers). For example: [("tshirt", 4), ("pants", -2)] This means the number of tshirts in the inventory will be increased by 4, and the number of pants will be decreased by 2. Output: Your function must RETURN the resulting inventory DICTIONARY after applying all transactions in the list. The resulting inventory dictionary for the given sample input arguments above would be: {"tshirt":33, "pants":12, "shirt":7, "shoes":5} Potential problems and EXCEPTIONS and how to handle them: a) If an item in the transactions list does not exist in the inventory (KeyError), then you must ADD it to the inventory. b) If the amount of an item drops to 0 in the inventory after a transaction, then that item must be REMOVED from the inventory (so that the dictionary does not hold a key for that item anymore). c) If the transaction indicates that more items are being sold then there are such items in the inventory, your function should RETURN an error message instead of the new inventory in the following format: "The transaction (item, amount) cannot be completed. Not enough items." where (item, amount) is a tuple from the transactions list that caused this problem. d) If the amount in some (item, amount) tuple given in the transactions list is not a proper integer value, so TypeError exception is raised when you try to add or subtract the amount to/from the inventory, your function should RETURN an error message instead of the new inventory in the following format: "The transaction (item, amount) cannot be completed. Bad transaction amount." where (item, amount) is a tuple from the transactions list that caused this problem. e) If anything else goes wrong and any other exception is raised, your function should RETURN an error message instead of the new inventory in the following format: "The transactions cannot be completed. Something went wrong." Exceptions Rules: You MUST use try-except block(s) to handle all of the possible exceptions discussed above. If-else solutions for handling the exceptions WILL NOT BE GIVEN FULL CREDIT! ------------ Sample test case 1 --------------- inventory = {"tshirt":29, "pants":14, "shirt":7, "shoes":5} transactions = [("shoes", 3), ("tshirt", -23)] print(updateInventory(inventory, transactions)) --------------- Expected output --------------- {'tshirt': 6, 'pants': 14, 'shirt': 7, 'shoes': 8} ------------ Sample test case 2 --------------- inventory = {"tshirt":29, "pants":14, "shirt":7, "shoes":5} transactions = [("shoes", -5), ("ties", 12)] print(updateInventory(inventory, transactions)) --------------- Expected output --------------- {'tshirt': 29, 'pants': 14, 'shirt': 7, 'ties': 12} ------------ Sample test case 3 --------------- inventory = {"tshirt":29, "pants":14, "shirt":7, "shoes":5} transactions = [("shoes", -12), ("tshirt", -23), ("pants", 2)] print(updateInventory(inventory, transactions)) --------------- Expected output --------------- The transaction ('shoes', -12) cannot be completed. Not enough items. ------------ Sample test case 4 --------------- inventory = {"tshirt":29, "pants":14, "shirt":7, "shoes":5} transactions = [("shoes", -5), ("pants", "four")] print(updateInventory(inventory, transactions)) --------------- Expected output --------------- The transaction ('pants', 'four') cannot be completed. Bad transaction amount. """ def updateInventory(inventory, transactions): # Remove the return line below before you answer this question. If you will NOT answer # this question, then do NOT remove this line below. return "I have not solved this question" """ ################################################################################ Question 3: (15 points) Topics: Strings, lists, iterations ################################################################################ Write a Python function longest_consecutive_subsequence(nums) that takes a sequence of numbers as input argument and RETURNs the LIST of longest subsequence of the consecutive numbers within the input sequence of numbers. The input argument "nums" will be a variable of type string containing integer values separeated by a comma. Note that input numbers may have duplicates. You must remove the duplicate numbers first, and then search for the longest subsequence of the consecutive numbers. ------------ Sample test case 1 --------------- print(longest_consecutive_subsequence("23,2,4,5,6,7,11,23")) --------------- Expected output --------------- [4, 5, 6, 7] ------------ Sample test case 2 --------------- print(longest_consecutive_subsequence("-4,-5,-4,-3,0,1")) --------------- Expected output --------------- [-5, -4, -3] """ def longest_consecutive_subsequence(nums): # Remove the return line below before you answer this question. If you will NOT answer # this question, then do NOT remove this line below. return "I have not solved this question" """ ################################################################################ Question 4: (15 points) Topics: lists, dictionaries ################################################################################ Write a Python function group_by_category_and_price(items) which takes a list of food items where each of them is given as a dictionary object containing "name", "category" and "price" attributes, and groups them by category and price respectively. The function must return a dictionary involving sub-dictionaries where the input elements are grouped according to the category and prices. A sample input and its corresponding output are given below: items = [ {"name": "apple", "category": "fruit", "price": 0.5}, {"name": "banana", "category": "fruit", "price": 0.25}, {"name": "carrot", "category": "vegetable", "price": 0.1}, {"name": "broccoli", "category": "vegetable", "price": 0.15}, {"name": "chicken", "category": "meat", "price": 2.5}, {"name": "beef", "category": "meat", "price": 3.5}, {"name": "orange", "category": "fruit", "price": 0.5}, {"name": "lettuce", "category": "vegetable", "price": 0.2}, {"name": "lamb", "category": "meat", "price": 2.0}, ] result = group_by_category_and_price(items) print(result) The expected output: { 'fruit': { 0.5: [{'name': 'apple', 'category': 'fruit', 'price': 0.5}, {'name': 'orange', 'category': 'fruit', 'price': 0.5}], 0.25: [{'name': 'banana', 'category': 'fruit', 'price': 0.25}] }, 'vegetable': { 0.1: [{'name': 'carrot', 'category': 'vegetable', 'price': 0.1}], 0.15: [{'name': 'broccoli', 'category': 'vegetable', 'price': 0.15}], 0.2: [{'name': 'lettuce', 'category': 'vegetable', 'price': 0.2}] }, 'meat': { 2.0: [{'name': 'lamb', 'category': 'meat', 'price': 2.0}], 2.5: [{'name': 'chicken', 'category': 'meat', 'price': 2.5}], 3.5: [{'name': 'beef', 'category': 'meat', 'price': 3.5}] } } """ def group_by_category_and_price(items): # Remove the return line below before you answer this question. If you will NOT answer # this question, then do NOT remove this line below. return "I have not solved this question" """ ################################################################################ Question 5: (20 points) Topics: lists, dictionaries ################################################################################ A list of dictionaries each having a category and value pair will be given as a function argument. Your task is to write a Python function that takes this list object and produces and PRINTs some statistics as explained in the example below. Your function must compute and PRINT the MEAN and STANDARD DEVIATION for each unique category by considering the given values per each category type. It is FORBIDDEN to import and utilize any ready statistics library. Sample input and usage: items = [ {'category': 'fruit', 'value': 7.5}, {'category': 'fruit', 'value': 3.5}, {'category': 'fruit', 'value': 4.5}, {'category': 'vegetable', 'value': 1.5}, {'category': 'vegetable', 'value': 2.5}, {'category': 'meat', 'value': 10.0}, {'category': 'meat', 'value': 12.0}, {'category': 'meat', 'value': 8.0}, ] getstatistics(items) --------------- Expected output --------------- Fruit: Mean=5.17, Std=2.08 Vegetable: Mean=2.00, Std=0.71 Meat: Mean=10.00, Std=2.00 """ def getstatistics(items): # Remove the return line below before you answer this question. If you will NOT answer # this question, then do NOT remove this line below. return "I have not solved this question" """ ################################################################################ Question 6: (15 points) Topics: dictionaries, exceptions ################################################################################ Write a Python function mergeDictionaries(dict1, dict2) that takes two dictionaries dict1 and dict2 as arguments and merges them into a new dictionary and RETURNs this new dictionary. If the same key exists in both dictionaries, then the LARGER value is stored as the value of the key in the new dictionary. Potential problems and EXCEPTIONS and how to handle them: a) If the same key exists in both dictionaries but the two values are not comparable, a TypeError exception will be raised when you try to compare them. In such case, your function should RETURN an error message instead of the new dictionary in the following format: "Merging failed due to a comparability issue for key ." where is the key that caused this problem. b) If anything else goes wrong and any other exception is raised, your function should RETURN an error message instead of the new dictionary in the following format: "Merging failed due to an unknown issue." Exceptions Rules: You MUST use try-except block(s) to handle all of the possible exceptions. If-else solutions for handling the exceptions WILL NOT BE GIVEN FULL CREDIT! ------------ Sample test case 1 --------------- d1 = {1:1, 2:2, 3:3} d2 = {1:0, 2:1, 3:2} print(mergeDictionaries(d1, d2)) --------------- Expected output --------------- {1: 1, 2: 2, 3: 3} ------------ Sample test case 2 --------------- d1 = {1:1, 2:2, 3:3} d3 = {7:3, 8:2, 9:4, 10:1, 11:0} print(mergeDictionaries(d1, d3)) --------------- Expected output --------------- {1: 1, 2: 2, 3: 3, 7: 3, 8: 2, 9: 4, 10: 1, 11: 0} ------------ Sample test case 3 --------------- d1 = {1:1, 2:2, 3:3} d4 = {1:5, 2:'value'} print(mergeDictionaries(d1, d4)) --------------- Expected output --------------- Merging failed due to a comparability issue for key 2. ------------ Sample test case 4 --------------- d1 = {1:1, 2:2, 3:3} d2 = {1:0, 2:1, 3:2} print(mergeDictionaries(d1, "d2")) --------------- Expected output --------------- Merging failed due to an unknown issue. """ def mergeDictionaries(dict1, dict2): # Remove the return line below before you answer this question. If you will NOT answer # this question, then do NOT remove this line below. return "I have not solved this question"