简体   繁体   English

Python中的递归:超过最大深度

[英]Recursion in Python: Max Depth Exceeded

I am confused how to do recursion in python, when to return and when to update a global variable. 我很困惑如何在python中进行递归,何时返回以及何时更新全局变量。

Consider this question: https://leetcode.com/problems/nested-list-weight-sum-ii/ 考虑以下问题: 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. 给定一个嵌套的整数列表,返回列表中所有整数的总和,并按其深度加权,其中叶级整数的权重为1,而根级整数的权重最大。

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? 在这里更新md时如何递归?

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. 相反,或者您只是在原始输入列表上连续​​调用maxDepth ,而无需实际遍历嵌套列表的层次结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM