简体   繁体   中英

Fibonacci Sequence in tuple Python

To be writing a make_fibonacci that accepts a parameter n which generates and returns a tuple containing the first n+1 terms of the fibonacci sequence, where n>= 0. From the other questions here,

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

but since I need the range of the fibonacci in a tuple, like

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

Thanks a lot!

here's a naive solution, construct as a list and return a tuple

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

You need to append to tuple and then print it if you like

You can do that using a list:

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)

You can append it to a list:

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)

This one purely works on tuples and is free from lists.

Conceptual Knowledge : Two Tuples Can Be Added

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)

Note : This has been tested on Python Console v2.7.12, and it might not work on Python 3.x and later versions. If you find it working, well and fine, please correct this statement. Positive Modifications are always Welcome!

fib = (0,1,1)
print(fib)
for i in range(10):
    fib = fib + (fib[i+1] + fib[i+2],)
print(fib)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM