Python 我如何迭代地编写这个递归函数?

Python 我如何迭代地编写这个递归函数?,python,function,recursion,iteration,Python,Function,Recursion,Iteration,在Python中: def g(n): if n <=3: return n return g(n-1) + 2 * g(n-2) + 3 * g(n-3) def g(n): 如果n这看起来类似于斐波那契级数问题,并且以迭代方式实现是非常重要的。这看起来也像是家庭作业,所以我将发布斐波那契迭代的步骤,你应该能够将其应用到你的问题中 如果您不知道,斐波那契的定义如下: def fib(n): 如果n这看起来类似于斐波那契级数问题,

在Python中:

def g(n):  
    if n <=3:        
        return n   
    return g(n-1) + 2 * g(n-2) + 3 * g(n-3)
def g(n):

如果n这看起来类似于斐波那契级数问题,并且以迭代方式实现是非常重要的。这看起来也像是家庭作业,所以我将发布斐波那契迭代的步骤,你应该能够将其应用到你的问题中

如果您不知道,斐波那契的定义如下:

def fib(n):

如果n这看起来类似于斐波那契级数问题,并且以迭代方式实现是非常重要的。这看起来也像是家庭作业,所以我将发布斐波那契迭代的步骤,你应该能够将其应用到你的问题中

如果您不知道,斐波那契的定义如下:

def fib(n):

如果n这太有趣了,无法解决

def g(n, *, _cache=[0, 1, 2, 3]):
    for _ in range(n - len(_cache) + 1):
        _cache.append(sum(i * _cache[-i] for i in (1, 2, 3)))
    return _cache[n]

希望您已经找到了解决方案。

这太有趣了,无法解决

def g(n, *, _cache=[0, 1, 2, 3]):
    for _ in range(n - len(_cache) + 1):
        _cache.append(sum(i * _cache[-i] for i in (1, 2, 3)))
    return _cache[n]
def g(n):
    if n <= 3:
        return n
    a, b, c = 1, 2, 3
    for i in range(3, n):
        a, b, c = b, c, (a * 3 + b * 2 + c)
    return c
希望您已经找到了解决方案。

def g(n):
def g(n):
    if n <= 3:
        return n
    a, b, c = 1, 2, 3
    for i in range(3, n):
        a, b, c = b, c, (a * 3 + b * 2 + c)
    return c
如果n
def g(n):

如果n您的递归函数可以理解为

To find the value of g(30), find the value of g(29), g(28), and g(27)
  To find the value of g(29), find the value of g(28), g(27), and g(26)
    To find the value of g(28), find the value of g(27), g(26), and g(25)
      ...
        (repeat until all sub-finds have completed)
迭代函数将从另一端开始

I know the values of g(1), g(2), and g(3) -> calculate g(4)
I know the values of g(2), g(3), and g(4) -> calculate g(5)
I know the values of g(3), g(4), and g(5) -> calculate g(6)
...
(repeat until the desired g(n) is reached)

递归函数可以理解为

To find the value of g(30), find the value of g(29), g(28), and g(27)
  To find the value of g(29), find the value of g(28), g(27), and g(26)
    To find the value of g(28), find the value of g(27), g(26), and g(25)
      ...
        (repeat until all sub-finds have completed)
迭代函数将从另一端开始

I know the values of g(1), g(2), and g(3) -> calculate g(4)
I know the values of g(2), g(3), and g(4) -> calculate g(5)
I know the values of g(3), g(4), and g(5) -> calculate g(6)
...
(repeat until the desired g(n) is reached)

作业n的最大值是多少?你知道如何计算前三个,对吗?那么如何根据前面的三个来计算任何后续的数字呢?也许我有点困惑,因为它是纯文本的,但是你有两个相邻的返回语句。你能把这个格式化得更好吗?很难理解没有最大值。我刚刚重新格式化了Ryan,对不起,这是正确的。迭代函数很容易定义,因为这个函数使用求和。家庭作业?n的最大值是多少?你知道如何计算前三个,对吗?那么如何根据前面的三个来计算任何后续的数字呢?也许我有点困惑,因为它是纯文本的,但是你有两个相邻的返回语句。你能把这个格式化得更好吗?很难理解没有最大值。我刚刚重新格式化了Ryan,对不起,这是正确的。可以很容易地定义迭代函数,因为该函数使用求和。这证明应该有一个模糊化的python竞赛。它可能是模糊化的,但由于缓存的使用,该函数也非常有效。这真的不是什么冒犯,我喜欢;)这证明了应该有一个模糊化python竞赛。它可能是模糊化的,但由于缓存的使用,该函数也非常有效。这真的没有冒犯,我喜欢;)