(Feb-11-2021, 03:48 PM)deanhystad Wrote: Yes. That is the purpose of my code. To demonstrate why your convert function returns None when called with a non-zero value for n. Is the reason clear now?
Your convert function, as you wrote it, has two potential outcomes. If the value of n == 0 the function returns new. If n is any value other than 0, commit does not return a value, so the value of the function call is None. I tried to highlight this by writing convert0() to return new, and convert6(), convert2() and convert1() not returning a value. This is exactly how your code works. convert(0) returns new. convert(6), convert(2) and convert(1) do not return a value.
When your main code calls convert(4562) it does not return a value. 4562 is not 0, so the code executes the branch that executes the recursion, not the branch that returns a value. It operates just like convert(6) or convert6().
I seem very slow learner, as unable to grasp still.
For the final attempt have modified my code to see that output is 'None' many times.
#https://ideone.com/XKyhyR n = 4562; rev = 0 new= [] m = 0 def convert(n,m): print "round #:", m,"n :", n a = ((n+1) % 3)-1 if n: new.append(a); print 'new :', new print 'call convert(', (n+1)//3,',',m+1,'):', convert((n+1)//3,m+1) print 'after convert(' , n, ',' ,m, ')','\n' else: print 'n==',n, 'new: ::: ', new return new print convert(n,m), "<<---- None returned ? " sum = 0 def value(l): sum = 0 for i in range(0, len(new),1): sum += new[i]*(3**i) print "sum :" , sum return sum print value(new),Output:
round #: 0 n : 4562
new : [-1]
call convert( 1521 , 1 ): round #: 1 n : 1521
new : [-1, 0]
call convert( 507 , 2 ): round #: 2 n : 507
new : [-1, 0, 0]
call convert( 169 , 3 ): round #: 3 n : 169
new : [-1, 0, 0, 1]
call convert( 56 , 4 ): round #: 4 n : 56
new : [-1, 0, 0, 1, -1]
call convert( 19 , 5 ): round #: 5 n : 19
new : [-1, 0, 0, 1, -1, 1]
call convert( 6 , 6 ): round #: 6 n : 6
new : [-1, 0, 0, 1, -1, 1, 0]
call convert( 2 , 7 ): round #: 7 n : 2
new : [-1, 0, 0, 1, -1, 1, 0, -1]
call convert( 1 , 8 ): round #: 8 n : 1
new : [-1, 0, 0, 1, -1, 1, 0, -1, 1]
call convert( 0 , 9 ): round #: 9 n : 0
n== 0 new: ::: [-1, 0, 0, 1, -1, 1, 0, -1, 1]
[-1, 0, 0, 1, -1, 1, 0, -1, 1]
after convert( 1 , 8 )
None
after convert( 2 , 7 )
None
after convert( 6 , 6 )
None
after convert( 19 , 5 )
None
after convert( 56 , 4 )
None
after convert( 169 , 3 )
None
after convert( 507 , 2 )
None
after convert( 1521 , 1 )
None
after convert( 4562 , 0 )
None <<---- None returned ?
sum : -1
sum : -1
sum : -1
sum : 26
sum : -55
sum : 188
sum : 188
sum : -1999
sum : 4562
4562