Jerry Thomas
Jerry Thomas

Reputation: 9

python finding depth of a list using recursion

I need to find the depth of a list using recursion but and I can't use global variables or have more than one parameter. this is the code that I have but I'm getting the error where I can't call depth because I cant use a global variable and when I call it inside the function when the recursion happens it just resets the variable

def how_deep(list_of_lists):
    for i in list_of_lists:
        if type(i) == list:
            how_deep(i)
            depth += 1
        else:
            print(depth)


if __name__ == '__main__':
    print(how_deep([[[], [], [], [[[]]]], []],))
    print(how_deep([]))
    print(how_deep([[], []]))
    print(how_deep([[[]], [], [[]], [[[]]]]))
    print(how_deep([[[[], [[]], [[[]]], [[[[]]]]]]]))
    print(how_deep([[[], []], [], [[], []]]))

Upvotes: 0

Views: 412

Answers (1)

flakes
flakes

Reputation: 23614

As you loop through each item you want to record its maximum depth and return the maximum depth of an individual child in the list. You could do something like this:

def how_deep(list_of_lists):
    if not isinstance(list_of_lists, list):
        return 0
    return max(map(how_deep, list_of_lists), default=0) + 1

Upvotes: 4

Related Questions