[英]Tail recursion for a function
I have a homework problem that gives a recursive function and I have to implement it using tail-recursion.我有一个作业问题,它给出了递归 function,我必须使用尾递归来实现它。 The function is
function 是
f(0) = 1 f(0) = 1
f(n) = 1+2*f(n-1) f(n) = 1+2*f(n-1)
I am not the best at tail-recursion and i tried to look up examples but all i find are examples witht the fibonacci sequence and it doesnt help much.我不是最擅长尾递归的,我试图查找示例,但我发现的只是斐波那契数列的示例,它没有多大帮助。
All i really have is我真正拥有的是
def f(n,s=1):
if n == 0:
return s
else:
return f(n-1, "i dont know what to put here")
I understand that tail recursion basically computes the function every call through i just dont know how to implement it.我知道尾递归基本上计算 function 每次调用我只是不知道如何实现它。
Edit: I made a typo f(n) is supposed to be 1 + 2*f(n-1)编辑:我打错了 f(n) 应该是 1 + 2*f(n-1)
For tail recursion, you track the sum as you go:对于尾递归,您可以像 go 一样跟踪总和:
$ cat foo.py
import sys
def f(n,s=1):
if n == 0:
return s
return f(n-1, 1+2*s)
r = int(sys.argv[1])
print(f(r))
Output: Output:
$ seq 0 10 | xargs -I% python foo.py %
1
3
7
15
31
63
127
255
511
1023
2047
Tail recursion is just a recursive function that only calls itself at the end of the function, so according to the specs of your function, it should just be something like:尾递归只是一个递归 function,它只在 function 的末尾调用自己,所以根据你的 ZC1C425268E68385D1AB5074C17A94F14 的规范,它应该是这样的:
def f(n):
if n == 0:
return 1
return 1 + f(n - 1)
It can be as simple as:它可以很简单:
def f(n):
return 1 if n==0 else 1 + 2*f(n-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.