Starting from:

$40

CSE505 – Assignment 2 – Problem 2 Solved

CSE505 – Assignment 2 – Problem 2 

Problem 1 was posted in A2.pdf.  Below is Problem 2.  Problem 3 will be posted later.    

 

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.   

 

What to Submit 

 

Prepare a top-level directory named A2_UBITId1_UBITId2 if the assignment was done by two students (list UBITId’s in alphabetic order);  otherwise, name it as A2_UBITId if the assignment is done solo.  In this directory place the files A2_problem1.pdf and A2_problem2.py, as well as your solution from problem 3 (TBA).     

 

Compress the directory and submit the compressed file using the online submission procedure – instructions posted at Resources → Assignments → Online_Submission.pdf.   Only one submission per team is required. 

 

                                           

More products