I got a recursive function, which reverses an integer. The reversed Integer can not start with zero, e.g.: 12340 becomes 4321.
res = 0
base = 1
def reverse(n):
global res
global base
if n > 0:
reverse(n // 10)
res = res + (n % 10) * base
base = base * 10
return res
this code works, but only once and hence I want to get rid of the global variables. I thought of a helper function, inside of the reverse(n) function, but I could not get it to work properly. I have tried for almost an hour and would love to see the solution eventually.
It's totally possible with a helper method:
def reverse_recursive(i: int) -> int:
def helper(i: int, result_up_to_now: int) -> int:
if i == 0:
return result_up_to_now
return helper(i // 10, result_up_to_now * 10 + (i % 10))
return helper(i, 0)
assert reverse_recursive(123456789) == 987654321
And even without one:
def reverse_recursive_nohelper(i: int, result_up_to_now=0) -> int:
if i == 0:
return result_up_to_now
return reverse_recursive_nohelper(i // 10, result_up_to_now * 10 + (i % 10))
assert reverse_recursive_nohelper(123456789) == 987654321
But the latter one could of course be misused/misunderstood by someone.
Just for comparison, the non-recursive version:
def reverse_straight(i: int) -> int:
result = 0
while i != 0:
result = result*10 + i % 10
i //= 10
return result
assert reverse_straight(123456789) == 987654321
global only on the agg_res variable for the result.
Anyway agg_res is reinitialized at the end of the calculation (no influence on the second re-use)
agg_res=0
def reverse(n, res=0, base=1):
global agg_res
ls = len(str(n))
if n > 0:
reverse(n // 10, res, base)
res = res + (n % 10)
base = base * (10**(ls-1))
agg_res += res*base
else :
agg_res=0
# First time
reverse(5786)
print(agg_res)
# 6875
# Second time
reverse(5786)
print(agg_res)
# 6875
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With