Nov-22-2020, 01:33 PM
Yes, recursive algorithms are always difficult to understand.
When I have a program of which I do not understand the results, I add print statements to them so I can follow what happens from step to step. Like this:
When I have a program of which I do not understand the results, I add print statements to them so I can follow what happens from step to step. Like this:
def sumtree(l): tot = 0 print(f"New instance of sumtree({l})") for x in l: if not isinstance(x, list): tot += x # print(tot) else: tot += sumtree(x) # print('xxx') print(f"End of sumtree({l}), returning: {tot}") return tot o = [1, [2, [3, 4], 5], 6, [7, 8]] print(sumtree(o))
Output:New instance of sumtree([1, [2, [3, 4], 5], 6, [7, 8]])
New instance of sumtree([2, [3, 4], 5])
New instance of sumtree([3, 4])
End of sumtree([3, 4]), returning: 7
End of sumtree([2, [3, 4], 5]), returning: 14
New instance of sumtree([7, 8])
End of sumtree([7, 8]), returning: 15
End of sumtree([1, [2, [3, 4], 5], 6, [7, 8]]), returning: 36
36
Does this make clear what happens?