(Feb-10-2021, 10:34 PM)deanhystad Wrote: I don't know if there is an error in you logic or your code. As written, the code only returns a value if n == 0. This occurs only one time and is followed by the recursion unwinding. This is easier to see if I move the print statements around.
[output]convert(4562, 0)
convert(1521, 1)
convert(507, 2)
convert(169, 3)
convert(56, 4)
convert(19, 5)
convert(6, 6)
convert(2, 7)
convert(1, 8)
convert(0, 9)
b [-1, 0, 0, 1, -1, 1, 0, -1, 1]
a [-1, 0, 0, 1, -1, 1, 0, -1, 1]
...
Notice that after line 13 (print('b', new) is executed once followed by line 11 (print('a', new)) executing 9 times. There is no return after line 11.
Should convert look like this?
def convert(n,m): print(f'convert({n}, {m})') a = ((n+1) % 3)-1 if n: new.append(a) convert((n+1)//3,m+1) print('a', new) else: print('b', new) return new
But, control enters only one time in the else part.
Then there is a print of correct 'new', on line #13.
Seemingly, if line#13 gives correct output, then inside that else conditional will get on line #14 correct return too.
But, that doesn't occur and it behaves as if line #14 is not having updated value of new.
However, your modification to move return at end of all recursive calls works.
Not sure still why need return at the end of all recursive calls, when return at n==0 should give correct output, particularly when line #13 works correctly.
>> There can be only one reason, that in a recursion there can be no 'return call' till last case is executed.
But, know nothing like that. As per me, can exit by return anytime.