StealthPython - 4 months ago 35

Python Question

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.

Example,

formula1 (5) prints out

`5 16 8 4 2 1`

I need it to print out

`1 2 4 8 16 5`

Answer

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.