Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

I got the school assignment, where I need to count several lists in f.e. this list:

['a', ['house', [2], 3], [], [[[2]]], 'b']


I wanted to do without using global.
I tried doing this:


def zoznam_prvkov(zoznam):
    z = []
    for i in range(len(zoznam)):
        if isinstance(zoznam[i], list) == False:
            z.append(zoznam[i])
        else:
            zoznam_prvkov(zoznam[i])
    return z

But that returns only [1, 2, 3, 6, 8] 

1 Answer

0 votes
by (36.8k points)

If the item is not the list, then return 0, otherwise count it as the list and sum up your counts of all the items:

def count_lists(x):

    if not isinstance(x, list):

        return 0

    return 1 + sum(count_lists(item) for item in x)

Want to be a Data Science expert? Come and join this Data Science Courses

 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...