Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of lists using recursion?

This is what I've tried:

def recursive_list_counter(l):
    sum = 0
    for e in l:
        if type(e) == type([]):
            #print e
            sum += 1
            recursive_list_counter(e)
    return sum 

# should be 6 if I count the first also
recursive_list_counter([[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6])

I want to use recursion to retrieve the number of lists within a list, counting the original list also.

like image 529
user2144553 Avatar asked Nov 27 '22 09:11

user2144553


2 Answers

Your recursive call ignores what is returned. Add the return value:

def recursive_list_counter(l):
    sum = 0
    for e in l:
        if isinstance(e, list):
            sum += 1
            sum += recursive_list_counter(e)
    return sum 

Note that the outer list is ignored in the count, so the call returns 5, not 6.

Furthermore, you should use isinstance() to test if an object is of a given type.

If you want to see 6, count the current list in the function, and leave counting nested lists to the recursive call:

def recursive_list_counter(l):
    sum = 1
    for e in l:
        if isinstance(e, list):
            sum += recursive_list_counter(e)
    return sum 
like image 104
Martijn Pieters Avatar answered Dec 05 '22 15:12

Martijn Pieters


For your given example, if all you have are numbers within lists, you can try converting to string and counting the number of [

>>> li = [[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6]
>>> str(li).count('[') 
6
like image 36
Anshul Goyal Avatar answered Dec 05 '22 15:12

Anshul Goyal