python - Reversing an order of integers produced by recursion -


i have basic recursion function print out line of numbers given 1 input number.

def formula1(distance):     if distance == 1:         print(int(distance))         return     elif (distance % 2) == 0:         print(int(distance), end=" ")         return formula1(distance / 2)     elif (distance % 2) == 1:         print(int(distance), end=" ")         return formula1(3*distance + 1) 

i have print number in reverse now, without being string or list. i'm unsure how do this, declaring new temporary variable overwritten. , defining variable in parameters wouldn't think...

in above function print() lines have removed, i'm not sure replace without trying figure out whole calculation backwards.

example, formula1 (5) prints out 5 16 8 4 2 1 need print out 1 2 4 8 16 5

you need ensure recursive call made prior call print:

def formula1(distance):     if distance == 1:         print(distance, end=" ")         return     elif (distance % 2) == 0:         v = formula1(distance // 2)         print(distance, end=" ")         return v     else:         v = formula1(3 * distance + 1)         print(distance, end=" ")         return v 

each call formula1 has own local scope, assignments v distinct , preserved once recursive call returns.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -