Sample Solutions for Homework 1 Part A: 1) def, if, elif, while, for, and, not, lambda, return, in, and = are all reserved. 2) 1 + 2 + 3 + 4 + 5 ==> 27 (integer) 17/2 ==> 8 (integer) 17%2 ==> 1 (integer) 3 == (1 + 2) ==> True (boolean) "Let's play Python!" ==> "Let's play Python!" (string) "Isn't that "Python\"?" ==> 'Isn\'t that "Python"?' (string) range(4) ==> [0, 1, 2, 3] (list) [0,1].extend([2,3]) ==> (no return value) [0,1].append([2,3]) ==> (no return value) ['a', 'b'] + ['c', 'd'] ==> ['a', 'b', 'c', 'd'] (list) 3) def exify(l): if isinstance(l,list): if l: return [exify(l[0])] + exify(l[1:]) else: return [] else: return 'X' 4) # iterative def findcubes(): result = range(16) for i in range(16) n = i+1 result[i] = n*n*n ; return result # recursive def findcubes(n = 15): if n: return findcubes(n-1) + [n*n*n] else: return [] # functional (not required but useful to see): def findcubes(): return map(lambda n: n*n*n, range(1,16)) In this particular case, the iterative solution is longer than the recursive solution (130 chars vs. 92). But the iterative solution uses only 62 characters. (Here we are counting spaces as characters). Part B: def add_trios(l): # I'm going to assume l is a list of integers # whose length is a multiple of 3. if l: return [l[0] + l[1] + l[2]] + add_trios(l[3:]) else: return [] def double_nums(l): if l: if isinstance(l[0],(int,long,float,complex)): return [l[0]*2] + double_nums(l[1:]) else: return [l[0]] + double_nums(l[1:]) else: return [] def consonants_to_x(l): if l: if not l[0] in ['a','e','i','o','u','A','E','I','O','U']: return ['x'] + consonants_to_x(l[1:]) else: return [l[0]] + consonants_to_x(l[1:]) else return [] def nest_numbers(l): if l: if isinstance(l[0],(int,long,float,complex)): return [[l[0]]] + nest_numbers(l[1:]) else: return [l[0]] + nest_numbers(l[1:]) else: return []