Python Forum
Why not getting return on line #16?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why not getting return on line #16?
#7
(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.
Reply


Messages In This Thread
Why not getting return on line #16? - by jahuja73 - Feb-10-2021, 03:18 PM
RE: Why not getting return on line #16? - by jahuja73 - Feb-11-2021, 03:38 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Read characters of line and return positions Gizzmo28 2 2,065 Nov-04-2020, 09:27 AM
Last Post: perfringo
  Return JSON records in single line using python 2.7 anandmn85 0 2,822 May-14-2018, 09:16 AM
Last Post: anandmn85

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020