简体   繁体   中英

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([[[], []], [], [[], []]]))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM