使用python实现尾递归功能

发布于 2025-01-17 23:24:00 字数 287 浏览 2 评论 0原文

对于函数 p(0) = 10000, p(n) = p(n-1) + 0.02*p(n-1)

代码应该是这样的:

def p(n,v=10000):
    if n == 0:
         return v
    else:
         return p(n-1,1.02*v)

但是如果 p(0) = 10000, p(n) = p(n-1) + 10**(n-1)

那么这个尾递归怎么写呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

何必那么矫情 2025-01-24 23:24:00

这应该可以解决您的问题,

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

第一个 if 将是递归的基础,即 p(0)
else 将是递归函数

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

雨落□心尘 2025-01-24 23:24:00

这是您在此处想要的功能的TALI递归代码

def p(n,v=10000):
    if n == 0:
         return v
    else:
         return p(n-1, v + 10**(n-1))

,我们将V作为先前函数递归调用的值,然后将10 **(n-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.

泪眸﹌ 2025-01-24 23:24:00

好吧..您已经有了 if n == 0: return v 的尾递归。您只需要修改非常量返回值即可。试试这个:

def p(n, v=10000):
    if n == 0:
         return v
    else:
         return p(n - 1, v) + 10**(n - 1)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文