Starting from:
$30

$24

Exercise #7 Solution

More Complicated Recursion




In a le called ex7.py you must complete the following functions:




rsum: Return the sum of all elements in a given list




rmax: Return the maximum number in a given list




second smallest: Return the second smallest number in a given list 1




sum max min: Return the sum of the maximum and minimum elements in a given list







Wait a second... isn't this the same set of functions from last week? Almost... but here's the di erence.




We're no longer working with just lists of integers. We're working with nested lists of integers.




In particular, the lists for all four functions can be de ned as lists of Ls where L is de ned as either being an integer, the empty list, or a list of Ls.




Some example lists would be:




[1, 2, 3]




[1, [2, 3]]




[[1], [2, [3]], []]




As with the prevoius exercise, you must implement these functions recursively, you may not use loops anywhere in your code and you cannot rely on any built-in functions2. You should also be following the same rules of e ciency (you shouldn't pass through any list twice).




If you really planned your previous exercise properly, this shouldn't be a massive change, but make sure you really understand the problem before you start writing any code3. Remember, algorithm rst, code second.




What to Submit




As always, your code should not use import, input or print anywhere. Make sure your function and le names are exactly as speci ed in this handout.




















































1This can be equal to the smallest number in the list, e.g., second smallest([1, 1, 3]) should return 1




Except possibly for isinstance... hint hint...
Remember that if you struggled with the previous exercise, you can always go to practicals to get help from the TAs



1

More products