【发布时间】:2021-05-04 14:46:51
【问题描述】:
我想在 while 循环中使用 for 循环来将列表的最后 3 个数字相加并生成一个新数字以附加到现有列表中。但是,代码不会在 while 循环中进入 for 循环,我不知道为什么。
函数应该做什么:
- 输入数字列表(作为签名)
- 将列表中的最后 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