1412
1412

Reputation: 133

How to use recursion to calculate the max length of a nested list?

Here is the code that counts the maximum length in a nested list.

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

The code is wrong as I don't know how to correctly combine len() function and recursion. What should I do?

Upvotes: 1

Views: 3566

Answers (4)

Victoria June
Victoria June

Reputation: 1

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)

This would work perfectly. Some of the code above isn't giving the right answer.

Upvotes: 0

David Perez
David Perez

Reputation: 488

This is the closest to your code:

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

Upvotes: 0

Peter M. Elias
Peter M. Elias

Reputation: 1194

How's this?

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)

... and if you want to be more Pythonic and duck-type it ...

def nested_list(l):
    try:
        lens = [len(l)]
    except TypeError:
        return 0

    for x in l:
        lens.append(nested_list(x))
    return max(lens)

Upvotes: 1

Bhargav Rao
Bhargav Rao

Reputation: 52071

You are not using recursion here at all. Recursion invovles calling a method inside the same method. One way of doing this can be as follows. Note that there are three cases here,

  1. When the obj is only an integer, you need to return 0
  2. When the obj is a list with integers you need to return the length of the list
  3. When the obj is a heterogeneous list, you need to recurse.

A code example can be

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

Upvotes: 1

Related Questions