[SOLVED] CSE505 Problem2-Python generator called flatten

30.00 $

Category:
Click Category Button to View Your Next Assignment | Homework

You will receive the following solution file(s) instantly after successful payment:

zip file icon A2_Problem2-h2nyn9.zip (169.9 KB)
Assignment Instructions Updated Recently? Submit Below and we will provide new Solution!
Submit New Instructions
🔒 Securely Powered by:
Secure Checkout
Rate this product

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.

 

  • A2_Problem2-h2nyn9.zip