0.) (Note: remember, computer scientists always start counting from 0!) Try to guess what Python will do for the following expressions. Check your answer using the Python interpreter.
>>> for item in (1, 2, 3, 4, 5): ... print(item * item) ... >>> len((1, 2, 3, 4, 5)) >>> (1, 3, 9) * 3 >>> len((1, 5, 10) * 2) >>> len(1, 2, 3, 4) >>> (1, 2, 3) + (4, 3, 2, 1) >>> ((1, 2, 3) + (4, 3, 2, 1))[4]
1.) For each of the following tuples, give the correct expression to get 7.
>>> x = (1, 3, (5, 7), 9) >>> #YOUR EXPRESSION INVOLVING x HERE 7 >>> y = ((7,),) >>> #YOUR EXPRESSION INVOLVING y HERE 7 >>> z = (1, (2, (3, (4, (5, (6, 7)))))) >>> #YOUR EXPRESSION INVOLVING z HERE 7
2.) Write the reverse procedure which operates on tuples. For a description of its behavior, see the docstring given below:
def reverse(seq): """Takes an input tuple, seq, and returns a tuple with the same items in reversed order. Does not reverse any items in the tuple and does not modify the original tuple. Arguments: seq -- The tuple for which we return a tuple with the items reversed. >>> x = (1, 2, 3, 4, 5) >>> reverse(x) (5, 4, 3, 2, 1) >>> x (1, 2, 3, 4, 5) >>> y = (1, 2, (3, 4), 5) >>> reverse(y) (5, (3, 4), 2, 1) """ "*** Your code here. ***"
3.) Try to guess what the following print. Check your solution using the Python interpreter.
>>> tuple(map(lambda x: x * x, (1, 2, 3, 4, 5, 6)))
>>> tuple(filter(lambda x: x % 2 == 0, (1, 2, 3, 4, 5, 6)))
>>> def is_even(x): ... return x % 2 == 0 ... >>> def square(x): ... return x * x ... >>> tuple(map(square, filter(is_even, (1, 2, 3, 4, 5, 6))))
4.) Write the sizes procedure using map. This procedure will take a sequence of tuples and will return a sequence of the sizes of each of the tuples in the original input.
def sizes(seq): """Takes an input sequence of tuples, seq, and returns a sequence with the corresponding lengths of each tuple in seq. Arguments: seq -- A sequence of tuples. >>> sizes(((1,), (2, 3), (4, 5, 6))) (1, 2, 3) """ "*** Your code here. ***"
5.) Write the odd_len_only procedure using filter. This procedure will take a sequence of tuples and return a sequence containing only those tuples in the original sequence which had an odd length.
def odd_len_only(seq): """Takes an input sequence of tuples, seq, and returns a sequence with only the tuples which had odd length. Arguments: seq -- A sequence of tuples. >>> odd_len_only(((1,), (2, 3), (4, 5, 6))) ((1,), (4, 5, 6)) """ "*** Your code here. ***"
6.) It'd be convenient to have a procedure tuple_to_rlist, which takes a tuple and converts it to the equivalent rlist. Finish the implementation below. (Hint: an easy solution uses reverse from earlier in the lab).
def tuple_to_rlist(tup): """Takes an input tuple, tup, and returns the equivalent representation of the sequence using an rlist. Arguments: tup -- A sequence represented as a tuple. >>> tuple_to_rlist((1, 2, 3, 4, 5, 6)) (1, (2, (3, (4, (5, (6, None)))))) """ "*** Your code here. ***"