Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep list count - count lists within lists

I am trying to get the length of a list, but that list can contain other lists that are deeply nested (e.g. [[[[[[[]]]]]]]).

But you have to get any non list elements in the count as well: [1, 2, [3, 4]] would output 5 (1, 2, 3, 4 and a list). ["a", "b", ["c", "d", ["e"]]] would output 7.

It first comes to mind to use recursion to solve this problem. I wrote this:

def deep_count(arr, count=0):
    if any(type(i) == list for i in arr):
        for i in arr:
            if type(i) == list:
                count += len(arr)
            else:
                count += 1
        return deep_count(arr[1:], count)
    return count

It's outputting 9 instead of 7. And if it's just nested lists like [[[]]] it only outputs 1.

like image 294
taylorSeries Avatar asked Jun 09 '26 14:06

taylorSeries


1 Answers

There doesn't seem to be a need for supplying an initial value, you can just use arr as the only parameter, then just get the count and if the current element is a list then also add that list's count.

def f(arr):
    count = len(arr)
    for element in arr:
        if isinstance(element, list):
            count += f(element)
    return count

>>> f([1, 2, [3, 4]])
5
>>> f(["a", "b", ["c", "d", ["e"]]])
7
like image 122
Jab Avatar answered Jun 11 '26 05:06

Jab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!