返回错误结果的序列的递归求和

时间:2019-04-02 16:15:13

标签: python recursion

我正在尝试检索算术序列的前n个项之和:
a(n) = n(n-1) + 4 where n(1) = 5 因此,前两个项(5,9)的总和为14。但是,我的代码未返回此值。相反,我得到了13。我想念什么?

def main():
    sequence(3,0)
    print("in main")


# 5,9,13,17,21,...
# Sum of first 2 = 14
# Sum of first 3 = 27
def sequence(n, sum):
    if (n == 1):
        return 5
    else:
        a = sequence(n-1, sum) + 4
        sum += a
        print(sum)
        return a


if __name__ == '__main__': 
    try:
        main()
    finally:
        print("done")

3 个答案:

答案 0 :(得分:2)

具有以下内容的算术序列(或级数):

  • 给定的开始学期:我们称其为 f irst
  • 一个增量值(在任意两个连续项之间):我们称它为 d iff

是一组有序的数字(术语),每个术语可以写为:

Tk = Tk - 1 + d,然后从这里:

Tk = T1 + (k - 1) * d(尽管我觉得有点不自然,T1是第1个 st 元素,所以索引从 1 开始,以便序列中的 n th 元素具有索引 n )。 mark0

所以:

T1 = f + (1 - 1) * d

T2 = f + (2 - 1) * dT1 + d

T3 = f + (3 - 1) * dT2 + d

T4 = f + (4 - 1) * d

....

Tn - 1 = f + (n - 2) * d

Tn = f + (n - 1) * d

总结所有内容,位于 = 符号的右侧:

  • f 出现 n
  • d 出现(n - 1) + (n - 2) + ... + 2 + 1,它是直到n - 1的数字之和,可以使用 Gauss 计算的公式:(n - 1) * n // 2
  • 对于这种特殊情况,f = 5d = 4

因此,使用此算术序列属性,您无需计算每个项,因此无需递归。

有关更多详细信息,请选中[Wikipedia]: Arithmetic progression

翻译为 Python

>>> def sum_arithmetic_sequence(first, diff, count):
...     return count * first + ((count - 1) * count // 2) * diff
...
>>>
>>> sum_arithmetic_sequence(5, 4, 1)
5
>>> sum_arithmetic_sequence(5, 4, 2)
14
>>> sum_arithmetic_sequence(5, 4, 3)
27
>>> sum_arithmetic_sequence(5, 4, 4)
44

或(来自 mark0 ):

>>> def sequence_sum(n):  # I'd add the first and diff arguments as well to keep it general, but for simplicity's sake I'll hardcode them to 5 and 4
...     if n == 1:
...         return 5
...     return 5 + (n - 1) * 4 + sequence_sum(n - 1)
...
>>>

答案 1 :(得分:1)

您应该尝试将其分解以了解它。

sequence(3, 0)

# first iteration
a = sequence(2, 0) + 4
# second iteration
a = sequence(1, 0) + 4
# third iteration
return 5

# Now let's work our way backwards

a = 5 + 4 -> 9
a = 9 + 4 -> 13

因此,您为什么得到13。这是否足以使您朝正确的方向前进?这是另一个提示,请注意,您返回的是数字序列,而不是数字和。

答案 2 :(得分:0)

您的问题似乎至少有两个令人困惑的问题。首先,您将序列公式表示为:

a(n) = n(n-1) + 4

但是要获得您要描述的结果,公式必须为:

a(n) = a(n-1) + 4

第二,您似乎将序列与序列的求和混淆了。让我们(递归地)生成序列,然后(也递归地)对序列进行连续求和:

def sum_sequence(sequence):

    first, rest = sequence[0], sequence[1:]

    if rest:
        second, rest = rest[0], rest[1:]
        rest = sum_sequence([first + second] + rest)

    return [first] + rest

def generate_sequence(n):
    if n == 1:
        return 5

    return generate_sequence(n - 1) + 4

if __name__ == '__main__':

    sequence = [generate_sequence(n) for n in range(1, 11)]

    print(*sequence, sep=", ", end=", ...\n")

    sums = sum_sequence(sequence)

    print(*sums, sep=", ", end=", ...\n")

输出

% python3 test.py
5, 9, 13, 17, 21, 25, 29, 33, 37, 41, ...
5, 14, 27, 44, 65, 90, 119, 152, 189, 230, ...
%