【问题标题】:How to use recursion to calculate the max length of a nested list?如何使用递归计算嵌套列表的最大长度?
【发布时间】:2016-03-02 20:05:09
【问题描述】:

这是计算嵌套列表中最大长度的代码。

def max_length(obj):
    """
    Return the maximum length of obj or any of its sublists, if obj is a list.
    otherwise return 0.

    @param object|list obj: object to return length of
    @rtype: int

    >>> max_length(17)
    0
    >>> max_length([1, 2, 3, 17])
    4
    >>> max_length([[1, 2, 3, 3], 4, [4, 5]])
    4
    """
    if isinstance(obj,int):
        return 0
    else:
        return max([len(x) for x in obj])

代码错误,因为我不知道如何正确组合len() 函数和递归。我该怎么办?

【问题讨论】:

  • 你没有为一个递归调用该方法;)所以没有递归。

标签: python list python-3.x recursion maxlength


【解决方案1】:

您根本没有在这里使用递归。递归涉及在同一方法内调用方法。这样做的一种方式可以如下。注意这里分三种情况,

  1. obj只是integer时,需要返回0
  2. objlistintegers 时,您需要返回length 的list
  3. obj 是异构list 时,您需要递归

一个代码示例可以是

>>> def max_length(obj):
...     if isinstance(obj,int):
...         return 0
...     elif all(isinstance(i,int) for i in obj):
...             return len(obj)
...     else:
...         return max(max_length(i) for i in obj)
... 
>>> max_length(17)
0
>>> max_length([1, 2, 3, 17])
4
>>> max_length([[1, 2, 3, 3], 4, [4, 5]])
4

【讨论】:

    【解决方案2】:

    怎么样?

    def nested_list(l):
        if type(l) is not list:
            return 0
    
        lens = [len(l)]
    
        for x in l:
            lens.append(nested_list(x))
        return max(lens)
    

    ...如果您想更 Pythonic 并使用鸭式输入...

    def nested_list(l):
        try:
            lens = [len(l)]
        except TypeError:
            return 0
    
        for x in l:
            lens.append(nested_list(x))
        return max(lens)
    

    【讨论】:

      【解决方案3】:

      这是最接近您的代码的:

      def max_length(obj): if isinstance(obj,int): return 0 else: return max(len(obj), max([max_length(i) for i in obj]))

      【讨论】:

        【解决方案4】:
        result = []
        if isinstance(obj, int):
            result.append(0)
        else:
            for sublist in obj:
                result.append(max_length(sublist))
                result.append(len(obj))
        return max(result)
        

        这会很完美。上面的一些代码没有给出正确的答案。

        【讨论】:

          猜你喜欢
          • 2011-08-07
          • 1970-01-01
          • 1970-01-01
          • 2019-03-05
          • 2012-01-30
          • 1970-01-01
          • 1970-01-01
          • 2020-06-01
          • 1970-01-01
          相关资源
          最近更新 更多