0

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([[[], []], [], [[], []]]))
1
  • i have to keep the if name equals main portion the same or else i would just add another parameter Commented Dec 2, 2021 at 5:31

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

4 Comments

yeah i would use that but i cant use the isinstance keyword either this class is killing me
@JerryThomas then just change not isinstance(list_of_lists, list) to type(list_of_lists) != list
@JerryThomas Or if you know the elements will always be lists, then you can remove that if check altogether.
@JerryThomas you could also wrap it in try: ... except TypeError: return 0 to avoid the check. That would actually be slightly faster in the nominal case where everything is a list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.