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])