nested lists sum of depth python

Question:

I am practicing recursion, and I want to return depth (starting from 1) for each element of the list (I already accomplished it), but also the weighted sum of the depth of nested list * the value.

For example, [1, [4]] -> (1 * 1) + (4 * 2) = 1 + 8 = 9

I am using the variable res to store the sum, but its restarting its counter every time it changes to a new list of lists. Is there a way to keep track of the sum as I did with the list?


nestedList = [[1,1],2,[1,1]]


def depth_checker(nested_list, depth=1, output=[], res=0):

  for i in nested_list:
    if not isinstance(i, list):
      output.append(depth)
      print(i, depth)
      res = res + (i * depth)
      print(res)
    elif isinstance(i, list):
      depth_checker(i, depth + 1, output, res)
  
  
  
  return (res, output)

Output

depth_checker(nestedList)


OUTPUT >>

1 2
2
1 2
4
2 1
2
1 2
4
1 2
6

(2, [2, 2, 1, 2, 2]])


Expected Output:

(10, [2, 2, 1, 2, 2])

Asked By: matt.aurelio

||

Answers:

The problem is the difference between the implementation of a list and an integer. When you make the recursive call to depth_checker, any changes to output will be reflected in the original variable. However changes made to res will not modify the variable passed in. Lists are mutable, integers aren’t.

Your simplest option is to change your code to return the value res in all cases. Then modify the last line to be res = depth_checker(....) so that it gets updated

Answered By: Frank Yellin

You can do something like this:

def depth_checker(nested_list, depth=1):
    res = 0
    for obj in nested_list:
        if isinstance(obj, list):
            res += depth_checker(obj, depth + 1)
        else:
            res += obj * depth
    return res


print(depth_checker([2, 2, 1, 2, 2])) # 9
Answered By: funnydman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.