在元组中生成斐波那契数列

1 投票
3 回答
749 浏览
提问于 2025-04-18 02:47
def make_fibonacci(n):
    if n == 0:
        return (0,)
    count = 1
    while n > count:
        a , b = 0, 1
        c = a +b
        a,b = b,c
        count += 1
        return (b,c)
    return (0,) + (b,c)

这是我的代码,但我得不到想要的结果。

make_fibonacci(5)

(0, 1, 1, 2, 3, 5)

哪里出错了?

3 个回答

0

这是你代码的简化版本,不需要用到递归

def make_fibonacci(n):
    result = [0,1]
    if n < 1:
        return [0]
    count = 1
    while count < n:
        count += 1
        result.append(result[-1]+result[-2])
    return result

>>> print make_fibonacci(5)
[0, 1, 1, 2, 3, 5]
2

你在 while 循环里用了 return,所以它当然不会继续循环下去了。

看起来你是想做一些递归的操作,但实际上并没有真正去做递归,也就是没有在函数内部调用 make_fibonacci() 自己。

我建议你放弃使用元组的想法,先专注于建立一个普通的数字列表,等完成后再转换成元组。

0

像这样使用

def make_fibonacci(n):
    if n == 0:
        return (0,)
    count = 1
    x = [0]
    a, b = 0, 1
    while n >= count:
        count += 1
        a, b = b, a+b
        x += [a]

    return tuple(x)

if __name__ == '__main__':
    print make_fibonacci(5)

输出结果是:

(0, 1, 1, 2, 3, 5)

撰写回答