1
I’m trying to create a recursive algorithm to find the depth of a list, which is the largest number of nested lists
, But this is complicated, I can’t find it. I understand the path that the algorithm has to take, but I still don’t understand clearly how to do it and how to implement it. If someone could help me understand better how to do it, it would be cool.
What I’ve realized so far is that every time an element is a list, we have to increase a counter variable, but I’m not sure how to relate this variable to recursive calls.
I would like to know the process to reach the solution and not a solution, because then I would understand better how recursion works...
I’ve seen some recursive solutions on stackoverflow, as for example this:
def flat(l):
depths = []
for item in l:
if isinstance(item, list):
depths.append(flat(item))
if len(depths) > 0:
return 1 + max(depths)
return 1
But still it is not easy to understand why of all the calls and all the steps...
You could have read it, right? When I showed you the second code, it was meant for you to look, analyze, and adapt as one more implementation. Is easy to adapt.
– Victor Martins