Reputation: 13
I feel like i'm going at it all wrong. I am recursing at the depth of a list as if it was a Tree. This causes problems because It's an arbitrary list that can have strings, ints ... Here's what I have
def visit_depth(list_, depth):
if depth == 0:
return 1
elif depth >0:
return sum([visit_depth(l, depth - 1) for l in list_])
else:
return 0
Upvotes: 1
Views: 47
Reputation: 198556
This causes problems because It's an arbitrary list that can have strings, ints
Guard against them.
def deep_len(obj, depth=0):
if isinstance(obj, list):
if depth == 0:
return len(obj)
else:
return sum(deep_len(elem, depth - 1) for elem in obj)
else:
return 0
deep_len([1,2,[2,5],[3]], 0)
# => 4 (this list itself has 4 elements)
deep_len([1,2,[2,5],[3]], 1)
# => 3 (going 1 level down there's just 3 elements)
deep_len([1,2,[2,5],[3]], 2)
# => 0 (there is no 2 levels down)
Upvotes: 5