Midterm exam 1 solutions: 1. - False. s[4] is "n" while s[-7] is "a" - True. - False. After first two statements: list1 -> [1, 1, 2, 3, 5] list2 ---^ list1[2] = 0 does: list1 -> [0, 1, 2, 3, 5] list2 ---^ list1 = [1,2,3] does: list1 -> [1, 2, 3] list2 -> [0, 1, 2, 3, 5] finally, list1[0] = 3 does: list1 -> [3, 2, 3] list2 -> [0, 1, 2, 3, 5] - False. It would print: None 3 with the "None" coming from trying to print what is returned from the call to identity(3), which is None. 2. Many different implementations, but here's one: import random def random_remove(s): result = "" for char in s: if random.randint(0,1) == 1: result += char return result 3. a. i. valid ii. not valid, ints cannot be added with strings iii. valid, tuples can be iterated over iv. not valid, cannot iterate over 10 in the for loop v. valid, strings can be iterated over just like lists and tuples, with an iteration for each character vi. valid, just a list with one string in it b. i. 4 ii. 3 iii. Any odd number will result in an infinite loop. Some people also noted that floats would do it as well. c. i. 21 = 6 + 5 + 4 + 3 + 2 + 1 + 0 ii. Infinite recursion. It never changes the sign of num in the elif statement, so it will still just keep calling rec_mystery with the exact same negative number. If the line was: return -rec_mystery(-num) then it would have returned -21 4. There are three major errors: - raw_input returns a string, but we need an int - when dividing by 2, we could be unintentionally rounding, so we need to make sure we're doing float division - cannot add a string and an int in the print statement (area will be an int or float) The fixed code would be something like: def triangle_stats(): num = int(raw_input("Enter a side length: ") area = (num ** 2)/2.0 print "The area of the triangle is: " + str(area) 5. a. def is_odd(num): return num % 2 == 1 b. Again, many different ways, but here's one: def only_one(some_list, test_function): count_true = 0 for val in some_list: if test_function(val): count_true += 1 return count_true == 1