I am confused how to do recursion in python, when to return and when to update a global variable.
Consider this question: https://leetcode.com/problems/nested-list-weight-sum-ii/
Given a nested list of integers, return the sum of all integers in the list weighted by their depth, where the leaf level integers have weight 1, and the root level integers have the largest weight.
Input: [[1,1],2,[1,1]]
Here is my solution:
class Solution:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
md = 0
def maxdepth(nestedList, m):
for i in nestedList:
if i.isInteger() == False:
md = max (m + 1, md)
maxdepth(nestedList, m+1)
return md
def depthSum(nestedList, maxdepth):
s = 0
for i in nestedList:
t = i.isInteger()
if t:
s += i.getInteger() * maxdepth
else:
s += depthSum(i.getList(), maxdepth-1)
return s
m = maxdepth(nestedList, 1)
return depthSum(nestedList, m)
Recursion Error: Maximum Recursion Depth Exceeded.
How to do recursion while updating md here?
For one thing, I would say that in the last line of this part
def maxdepth(nestedList, m):
for i in nestedList:
if i.isInteger() == False:
md = max (m + 1, md)
maxdepth(nestedList, m+1)
you probably want to be doing
maxdepth(i, m+1)
instead, or you'll just be continually calling maxDepth
on the original input list without actually traversing the hierarchy of nested lists.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.