Home > Software design >  Using python to implement the tail recursion function
Using python to implement the tail recursion function

Time:03-31

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?

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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.

  • Related