1. Identify the recursive structure of the input (in this case, always a nested list), and write...
Question:
1. Identify the recursive structure of the input (in this case, always a nested list), and write down the code template for nested lists:
def f(obj: Union[int, list]) -> ...:
if isinstance(obj, int):
...
else:
...
for sublist in obj:
... f(sublist) ...
...
2. Implement the base case(s) directly (in this case, a single integer).
3. Write down a concrete example with a somewhat complex argument, (in this case, a nested list with around 3 sub-nested lists), and then write down the relevant recursive calls and what they should return.
4. Determine how to combine the recursive calls to compute the correct output. Make sure you can express this in English first, and then implement your idea.
HINT: The implementations here should be similar to ones you've seen before in the readings or comprehension questions.
"""
from typing import Union
def num_positives(obj: Union[int, list]) -> int:
"""Return the number of positive integers in .
Remember, 0 is *not* positive.
>>> num_positives(17)
1
>>> num_positives(-10)
0
>>> num_positives([1, -2, [-10, 2, [3], 4, -5], 4])
5
"""
count = 0
if (obj == int) and (obj > 1):
count += 1
else:
for item in obj:
count += num_positives(item)
return count
def nested_max(obj: Union[int, list]) -> int:
"""Return the maximum integer stored in nested list .
Return 0 if is an empty list.
Precondition: all integers in are positive.
>>> nested_max(17)
17
>>> nested_max([1, 2, [1, 2, [3], 4, 5], 4])
5
"""
def max_length(obj: Union[int, list]) -> int:
"""Return the maximum length of any list in nested list .
The *maximum length* of a nested list is defined as:
1. 0, if is a number.
2. The maximum of len(obj) and the lengths of the nested lists contained
in , if is a list.
>>> max_length(17)
0
>>> max_length([1, 2, [1, 2], 4])
4
>>> max_length([1, 2, [1, 2, [3], 4, 5], 4])
5
"""
pass
if __name__ == '__main__':
import doctest
doctest.testmod()
import python_ta
python_ta.check_all()
Building Java Programs A Back To Basics Approach
ISBN: 9780135471944
5th Edition
Authors: Stuart Reges, Marty Stepp