2 (a) Define a Python generator, called flatten, that takes as input a list of integers with arbitrary levels of nesting and yields one by one the integers in the list in left-to-right order. For example, a call such as
flatten([[[2],4],[[[[[6],8]]]],[[10],[[11]]]])
should yield one by one the values 2, 4, 6, 8, 10 and 11. Test flatten by executing:
inlist = [[[2],4],[[[[[6],8]]]],[[9],[[10]]]]
for x in flatten(inlist):
if x%2 != 0:
break
print(x)
The printed list should be the numbers 2, 4, 6, and 8 with one number on each line.
Place your definition of flatten and the above tester code in a file A2_problem.py. You may run Python on timberlake by a command such as:
/util/bin/python flatten.py
(b) Follow a systematic approach using higher-order procedures (as described in Lecture 11) in order to re-write your definition of flatten and the tester code by eliminating all generators, including the built-in list generator. Name the re-written generator as flatten2. Be sure to apply the optimization that minimizes the number of thunk functions used.
Augment the file A2_problem.py with the definition of flatten2 and the re-written tester code. Check that flatten2 and the re-written tester code have the same input-output behavior as the original one.
Reviews
There are no reviews yet.