Python中元组的斐波那契数列

1 投票
6 回答
9231 浏览
提问于 2025-04-18 03:30

要写一个叫做make_fibonacci的函数,这个函数需要一个参数n,能够生成并返回一个包含前n+1个斐波那契数的元组,前提是n必须大于等于0。从这里的其他问题来看,

def make_fibonacci(n):
    a, b = 0, 1
    for i in range(d):
        a, b = b, a+b

但是因为我需要把斐波那契数放在一个元组里,比如说

make_fibonacci(10)  
>>> (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55)

非常感谢!

6 个回答

1

这个内容完全是关于元组的,和列表没有关系。

概念知识两个元组可以相加

def get_fibonacci(n):  # n = no. of terms to be taken in tuple fibonacci_sequence
    a, b = 0, 1
    fibonacci_sequence = (a, b)
    for i in range(n-2):
        a, b = b, a+b
        fibonacci_sequence += (b,)  # Comma is needed at the end to accept a tuple with a single value
    print fibonacci_sequence
get_fibonacci(10)

注意:这个是在Python控制台v2.7.12上测试过的,可能在Python 3.x及以后的版本上不适用。如果你发现它可以正常工作,那就太好了,请纠正这个说法。欢迎任何积极的修改!

2

你可以使用一个列表来实现这个功能:

def make_fibonacci(n):
    result = [0]
    a, b = 0, 1
    for i in range(n-1):
        a, b = b, a+b
        result.append(b)
    return tuple(result)


>>> print make_fibonacci(10)
(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
2
def fib(n):
    tup=[]
    a,b = 0,1
    while b<n:
        tup=tup+[b,]
        a,b = b,a+b
    print tup

你需要在元组后面添加内容,然后如果想的话就打印出来。

3

这里有一个简单的解决方案,就是先把数据放到一个列表里,然后再把它转成一个元组返回。

def make_fibonacci(n):
    a = [0, 1]
    [a.append(a[-1]+a[-2]) for i in xrange(n)]
    return tuple(a)
1

你可以把它添加到一个列表里:

def make_fibonacci(n):
    fib = []
    a, b = 0, 1
    for i in range(n):
        a, b = b, a+b
        fib.append(a)
    return tuple(fib)


make_fibonacci(10)

撰写回答