I am trying to use recursion to find the depth of an “expression”, i.e. the number of layers of nested tuples: for example,
depth(('+', ('expt', 'x', 2), ('expt', 'y', 2))) => 2 depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4
Basically, I decided that I needed to check (working from outside in) for each element that is an instance of a tuple, and then, if so, call the depth function recursively. But I need to find a way to figure out which set of recursive calls has the greatest depth, and what I'm stuck with. Here is what I still have:
def depth3(expr): if not isinstance(expr, tuple): return 0 else: for x in range(0, len(expr)):
Thoughts on a good way to approach this?