I
I
igoodmood2016-04-07 21:29:18
Python
igoodmood, 2016-04-07 21:29:18

How to properly implement a function by recursion?

I want to implement a function in python that finds out the depth of an array.
I ask you to help with the elimination of errors, what exactly is wrong.

count = 0
p = 0
flag = True
def depth(s):
    count = 0
    p = 0
    if type(s) == list:
        count += 1
        return depth(s[0])
    else:
        if p < count:
            p = count
        flag = False
        count = 0
        return depth(s[1:])
    return p

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Movchan, 2016-04-07
@Alexander1705

def depth(arr):
    if hasattr(arr, '__getitem__'):
        return max(depth(i) for i in arr) + 1
    else:
        return 0

PS You can use map:
def depth(arr):
    if hasattr(arr, '__getitem__'):
        return max(map(depth, arr)) + 1
    else:
        return 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question