0

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?

1
  • Note that python does not have tail call optimization, so forcing code to be tail recursive is generally a waste. Do you really need this restriction (e.g. for an exercise) or do you just need any recursive solution? Commented Mar 31, 2022 at 5:27

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

It works, while I want to write tail recursion. Anyway, thank you so much.
1

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.

Comments

0

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)

1 Comment

I really appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.