使用python实现尾递归功能
对于函数 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该可以解决您的问题,
第一个 if 将是递归的基础,即 p(0)
else 将是递归函数
This should solve your problem
the first if will be the base of the recursion which is p(0)
and the else will be the recursion function
这是您在此处想要的功能的TALI递归代码
,我们将V作为先前函数递归调用的值,然后将10 **(n-1)添加到其中。
Here's the tali recursion code for the function that you wanted
Here, we use the v as the value from the previous function recursion call, and then add the 10**(n-1) to it.
好吧..您已经有了
if n == 0: return v
的尾递归。您只需要修改非常量返回值即可。试试这个: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: