【问题标题】:tribonacci sequence python code skips for loop within while looptribonacci序列python代码在while循环中跳过for循环
【发布时间】:2021-05-04 14:46:51
【问题描述】:

我想在 while 循环中使用 for 循环来将列表的最后 3 个数字相加并生成一个新数字以附加到现有列表中。但是,代码不会在 while 循环中进入 for 循环,我不知道为什么。

函数应该做什么:

  1. 输入数字列表(作为签名)
  2. 将列表中的最后 3 个数字相加并生成下一个要附加的数字
  3. 继续第 2 步,直到列表长度 == n
#my code

def tribonacci(signature, n):
    total = 0
    for i in range(len(signature)):
        num = signature[i]
        total += num
    signature.append(total)
    
    while len(signature) < n:
        for j in range(-1,-4):
            num = signature[j]
            total += num
        signature.append(num)
    return signature
#Some sample test code:
 
print(tribonacci([1, 1, 1], 10))
print("Correct output: " + "[1, 1, 1, 3, 5, 9, 17, 31, 57, 105]")

print(tribonacci([0, 0, 1], 10))
print("Correct output: " + "[0, 0, 1, 1, 2, 4, 7, 13, 24, 44]")

print(tribonacci([300, 200, 100], 0))
print("Correct output: " + "[]")

更新!

按照建议,我通过创建 total_2 = 0 来重置 while 循环中的总计数。我还在范围中添加了 -1,并将 while 循环块中的 .append(num) 更改为 .append(total_2 )。


def tribonacci(signature, n):
    total = 0
    for i in range(len(signature)):
        num = signature[i]
        total += num
    signature.append(total)
    
    while len(signature) < n:
        total_2 = 0
        for j in range(-1,-4, -1):
            num = signature[j]
            total_2 += num
        signature.append(total_2)
    return signature

但是,此代码在 n = 0 的第 3 次打印测试代码中不起作用。其中一位用户共享了一个更短的代码,该代码适用于所有测试代码。

【问题讨论】:

    标签: python-3.x for-loop while-loop


    【解决方案1】:

    试试range(-1,-4,-1)。你需要告诉python向后退。

    仅供参考,我已通过一些改进实现了您的功能:

    def tribonacci(signature, n):
        signature = signature[:n]
        while len(signature) < n:
            signature.append(sum(signature[-3:]))
        return signature
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多