5. [2 points Lists of lists! In Python, you can test whether a variable referenc
ID: 3589075 • Letter: 5
Question
5. [2 points Lists of lists! In Python, you can test whether a variable references a list or not using the isinstance function. Here's an example >>> isinstance(a, list) True >>> isinstance(b, list) False In this problem, we will see that elements of a list can also be lists. For example [[1,2, [3,4,[5, 6] is a list whose first element is the list [1,21 and whose second element is the list [3,4, [5]], and whose third element is the number 6. The lists [1,21 and [3,4, [5111 are said to be nested in the list [I1,2], [3,4,[5 6]. The list [5] is nested in [ 3,4, [5]] In nested sum.py, write a recursive function nested sum(numlist) that returns the sum of all the numbers in the numlist, including all numbers nested inside of the numlist. You may assume this list does not contain strings. That is, all data in the list, or nested within, is numerical. Implement nested_sum (numlist) according to the following recursive algorithm I. Set total equal to 0 I For each element x in numlist, do the following A. B. Ifx is not a list, then add x to total If x is a list, then 1. 2. Set nested_list equal to x Recursively compute the sum of this nested_list and store this result in subtotal 3. Add subtotal to total. III Return total Note that this algorithm has a loop but is still recursive. The recursive step is inside the loop, which means this function might use recursion more than once Example Usage python3 -i nested sum. py >>> nested_sum ([[1,2, 3,4, [5]], 6]) 21 '@IMlao1(023.35422Explanation / Answer
def nested_sum(numlist):
total = 0
for x in numlist:
if not isinstance(x, list):
total += x
else:
nested_list = x
subtotal = nested_sum(nested_list)
total += subtotal
return total
print(nested_sum([[1, 2], [3, 4, [5]], 6]))
# code link: https://paste.ee/p/0Vngw
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.