'Using python to implement the tail recursion function
For a function p(0) = 10000, p(n) = p(n-1) + 0.02*p(n-1),
the code should be like this:
def p(n,v=10000):
if n == 0:
return v
else:
return p(n-1,1.02*v)
But if p(0) = 10000, p(n) = p(n-1) + 10**(n-1),
then how to write this tail recursion?
Solution 1:[1]
This should solve your problem
def p(n):
if n==0:
return 10000
else: # n!=0
return p(n-1) + 0.02 * p(n-1)
print(p(0)) # The result is 10000
print(p(1)) # The result is 10200.0
the first if will be the base of the recursion which is p(0) and the else will be the recursion function
Solution 2:[2]
Here's the tali recursion code for the function that you wanted
def p(n,v=10000):
if n == 0:
return v
else:
return p(n-1, v + 10**(n-1))
Here, we use the v as the value from the previous function recursion call, and then add the 10**(n-1) to it.
Solution 3:[3]
Well.. you already have tail recursion with the if n == 0: return v. You just need to rework the non constant return value. Try this:
def p(n, v=10000):
if n == 0:
return v
else:
return p(n - 1, v) + 10**(n - 1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LoopFree |
| Solution 2 | Flaze07 |
| Solution 3 | flakes |
