Reputation: 301
I've written a recursive function to gauge, e.g. list depth and for some reason it returns unexpected results.
I have two functions: 1. checks if the object is iterable 2. gauges the depth of the object, e.g. list
I think I'm missing something in the second function but I couldn't wrap my head around why exactly variable n
when returned from else
turns into a funny result.
I set print
to see how n
gets changed in every stage and it seemed working as expected but when returned from else
it turns into a wrong number.
Here are two functions' code:
def isiterable(obj):
'''
takes in an obj and returns 1 if iterable or 0 if not
strings are discarded as iterable
:param obj: any object
:return: int
'''
if isinstance(obj, str):
return 0
else:
try:
iter(obj)
return 1
except TypeError as err:
return 0
my second function is recursive where I'm experiencing problems
def get_depth(a, n=0):
if isiterable(a):
return n + f(a[0], n+1)
else:
return n
I've three examples:
a = [[[1,2], [3,4]], [[5,6],[7,8]]]
b = [[1,2], [2,3]]
c = [2]
I'm expecting get_depth
to return 3 for list a
, 2 for list b
and 1 for list c
.
for some reason results for a
get doubled and return 6. In b
case it is 3 instead of 2.
Many thanks
Upvotes: 0
Views: 78
Reputation: 13541
You don't need to add n
when you return from get_depth
.
def get_depth(a, n=0):
if isiterable(a):
return get_depth(a[0], n+1)
else:
return n
Because, when a
have more depth, you will calculate the get_depth
function again witn n+1
which is already count the depth correctly and the extras are not needed.
Btw, you have to think about what if this case?
d = [1, 2, [3, 4]]
I can modify a bit such as:
def get_depth(a, n=0):
if isiterable(a):
temp = []
for i in range(0, len(a)):
temp.append(get_depth(a[i], n+1))
return max(temp)
else:
return n
Upvotes: 1