StealthPython - 1 year ago 79
Python Question

# Reversing a order of integers produced by recursion, in the recursion

I have a basic recursion function that will essentially print out a line of numbers given one 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 to print the number in reverse now, without it being a string or list. I'm really unsure how do do this, declaring a new temporary variable would just get overwritten. And defining a variable in the parameters wouldn't help I don't think...

In the above function obviously the print() lines would have to be removed, but I'm not sure what to replace it with without trying to figure out the whole calculation backwards.

Edit:
Example,
formula1(5) prints out 5 16 8 4 2 1
I need it to print out 1 2 4 8 16 5

Also please stop ripping on my code, I don't care how bad it looks, if you have something constructive to say then please, but otherwise don't comment.

You just need to ensure that the recursive call is made prior to the call to `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 to `formula1` has its own local scope, so the assignments to `v` are distinct and preserved once a recursive call returns.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download