Python 将此函数从递归转换为迭代 +1这就是我的想法,但最终采用列表法:(在没有for循环的情况下如何进行?我们不应该知道:P@user3147711,我添加了使用while循环而不是for循环的代码。最好使用for进行迭代。首先,它更可能确保终止。其次,它更可读
将此函数从递归转换为迭代Python 将此函数从递归转换为迭代 +1这就是我的想法,但最终采用列表法:(在没有for循环的情况下如何进行?我们不应该知道:P@user3147711,我添加了使用while循环而不是for循环的代码。最好使用for进行迭代。首先,它更可能确保终止。其次,它更可读,python,recursion,stack,iteration,Python,Recursion,Stack,Iteration,将此函数从递归转换为迭代 +1这就是我的想法,但最终采用列表法:(在没有for循环的情况下如何进行?我们不应该知道:P@user3147711,我添加了使用while循环而不是for循环的代码。最好使用for进行迭代。首先,它更可能确保终止。其次,它更可读。@IoannisFilippidis,您最好提到OP通知他/她。好吧,好吧……这只是第一个期中材料,我们不应该知道列表或for循环(只知道一段时间)。有没有比@falsetru和@thefourtheye更简单的方法? def g(n): "
+1这就是我的想法,但最终采用列表法:(在没有for循环的情况下如何进行?我们不应该知道:P@user3147711,我添加了使用
while
循环而不是for
循环的代码。最好使用for
进行迭代。首先,它更可能确保终止。其次,它更可读。@IoannisFilippidis,您最好提到OP通知他/她。好吧,好吧……这只是第一个期中材料,我们不应该知道列表或for循环(只知道一段时间)。有没有比@falsetru和@thefourtheye更简单的方法?
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
"""
if n<=3:
return n
else:
return g(n-1)+2*g(n-2)+3*g(n-3)
def g_iter(n):
"""Return the value of G(n), computed iteratively.
>>> g_iter(1)
1
>>> g_iter(2)
2
>>> g_iter(3)
3
>>> g_iter(4)
10
>>> g_iter(5)
22
"""
"*** YOUR CODE HERE ***"
def g(n):
if n <= 3:
return n
a, b, c = 1, 2, 3
for i in range(n - 3):
a, b, c = b, c, c + 2 * b + 3 * a
return c
def g(n):
if n <= 3:
return n
a, b, c = 1, 2, 3
while n > 3:
a, b, c = b, c, c + 2 * b + 3 * a
n -= 1
return c