I am trying to use recursion to find the depth of an "expression", i.e., how many layers of nested tuples there are: For example,
depth(('+', ('expt', 'x', 2), ('expt', 'y', 2))) => 2
depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4
Basically, I figured that I need to check (working from out to in) for each element being an instance of a tuple, and then if so, recursively call the depth function. But I need to find a way of figuring out which set of recursive calls has the greatest depth, and that's where I'm stuck. Here's what I have so far:
def depth3(expr):
if not isinstance(expr, tuple):
return 0
else:
for x in range(0, len(expr)):
# But this doesn't take into account a search for max depth
count += 1 + depth(expr[x])
return count
Thoughts on a good way to approach this?
You're on the right track, but instead of finding the "total" depth with count += 1 + depth(expr[x])
, use max
to find the maximum:
def depth(expr):
if not isinstance(expr, tuple):
return 0
# this says: return the maximum depth of any sub-expression + 1
return max(map(depth, expr)) + 1
print depth(("a", "b"))
# 1
print depth(('+', ('expt', 'x', 2), ('expt', 'y', 2)))
# 2
print depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2))))
# 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With