我正在尝试解决一个需要我编写一个函数的练习,该函数将一个整数作为输入,然后返回一个tribonacci项列表直到输入值。我大部分时间都“成功”,但也会输出一个额外的术语。这是我的代码:
def tribonacci(m):
tribs = [0, 0, 1]
if m == 0 or m == 1:
tribs = [0, 0]
elif m == 2:
tribs = [0, 0, 1]
else:
while tribs[-1] < m:
tribs.append(tribs[-1] + tribs[-3] + tribs[-2])
return tribs
我知道问题是while循环运行额外的迭代,因为最后一个元素仍然不大于m。但是,我无法立即看到如何解决这个问题。我会采用while-else循环,但我希望看到其他一些建议。
答案 0 :(得分:0)
只需将即将生成的术语与m进行比较,如下所示:
def tribonacci(m):
tribs = [0, 0, 1]
if m == 0 or m == 1:
tribs = [0, 0]
elif m == 2:
tribs = [0, 0, 1]
else:
while tribs[-1] + tribs[-3] + tribs[-2] < m:
tribs.append(tribs[-1] + tribs[-3] + tribs[-2])
return tribs