简体   繁体   English

使用python实现尾递归function

[英]Using python to implement the tail recursion function

For a function p(0) = 10000, p(n) = p(n-1) + 0.02*p(n-1) ,对于 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) ,但是如果p(0) = 10000, p(n) = p(n-1) + 10**(n-1) ,

then how to write this tail recursion?那么这个尾递归怎么写呢?

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第一个 if 将是递归的基础,即 p(0),else 将是递归 function

Here's the tali recursion code for the function that you wanted这是您想要的 function 的 tali 递归代码

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.在这里,我们使用 v 作为先前 function 递归调用的值,然后将 10**(n-1) 添加到它。

Well.. you already have tail recursion with the if n == 0: return v .嗯..你已经有了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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM