kongguyinzhe
kongguyinzhe

Reputation: 11

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?

Upvotes: 0

Views: 264

Answers (3)

Flaze07
Flaze07

Reputation: 43

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.

Upvotes: 1

LoopFree
LoopFree

Reputation: 149

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

Upvotes: 1

flakes
flakes

Reputation: 23674

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)

Upvotes: 0

Related Questions