How to write the Fibonacci Sequence?

2018-12-31 05:36发布

I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening.

startNumber = int(raw_input("Enter the start number here "))
endNumber = int(raw_input("Enter the end number here "))

def fib(n):
    if n < 2:
        return n
    return fib(n-2) + fib(n-1)

print map(fib, range(startNumber, endNumber))

Someone pointed out in my Part II (which was closed for being a duplicate - https://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome.


I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?).

What I have so far is no actual coding but rather:

  • Write Fib sequence formula to infinite
  • Display startNumber to endNumber only from Fib sequence.

I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.

30条回答
路过你的时光
2楼-- · 2018-12-31 06:21

These all look a bit more complicated than they need to be. My code is very simple and fast:

def fibonacci(x):

    List = []
    f = 1
    List.append(f)
    List.append(f) #because the fibonacci sequence has two 1's at first
    while f<=x:
        f = List[-1] + List[-2]   #says that f = the sum of the last two f's in the series
        List.append(f)
    else:
        List.remove(List[-1])  #because the code lists the fibonacci number one past x. Not necessary, but defines the code better
        for i in range(0, len(List)):
        print List[i]  #prints it in series form instead of list form. Also not necessary
查看更多
大哥的爱人
3楼-- · 2018-12-31 06:21

Fibonacci sequence is: 1, 1, 2, 3, 5, 8, ....

That is f(1) = 1, f(2) = 1, f(3) = 2, ..., f(n) = f(n-1) + f(n-2).

My favorite implementation (simplest and yet achieves a light speed in compare to other implementations) is this:

def fibonacci(n):
    a, b = 0, 1
    for _ in range(1, n):
        a, b = b, a + b
    return b

Test

>>> [fibonacci(i) for i in range(1, 10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]

Timing

>>> %%time
>>> fibonacci(100**3)
CPU times: user 9.65 s, sys: 9.44 ms, total: 9.66 s
Wall time: 9.66 s

Edit: an example visualization for this implementations.

查看更多
大哥的爱人
4楼-- · 2018-12-31 06:22

OK.. after being tired of referring all lengthy answers, now find the below sort & sweet, pretty straight forward way for implementing Fibonacci in python. You can enhance it it the way you want by getting an argument or getting user input…or change the limits from 10000. As you need……

def fibonacci():
    start = 0 
    i = 1 
    lt = []
    lt.append(start)
    while start < 10000:
        start += i
        lt.append(start)
        i = sum(lt[-2:])
        lt.append(i)
    print "The Fibonaccii series: ", lt

This approach also performs good. Find the run analytics below

In [10]: %timeit fibonacci
10000000 loops, best of 3: 26.3 ns per loop
查看更多
忆尘夕之涩
5楼-- · 2018-12-31 06:23

Using for loop and print just the result

def fib(n:'upto n number')->int:
    if n==0:
        return 0
    elif n==1:
        return 1
    a=0
    b=1
    for i in range(0,n-1):
        b=a+b
        a=b-a
    return b

Result

>>>fib(50)
12586269025
>>>>
>>> fib(100)
354224848179261915075
>>> 

Print the list containing all the numbers

def fib(n:'upto n number')->int:
    l=[0,1]
    if n==0:
        return l[0]
    elif n==1:
        return l
    a=0
    b=1
    for i in range(0,n-1):
        b=a+b
        a=b-a
        l.append(b)
    return l

Result

>>> fib(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
查看更多
伤终究还是伤i
6楼-- · 2018-12-31 06:25

Why not simply do the following?

x = [1,1]
for i in range(2, 10):  
    x.append(x[-1] + x[-2]) 
print(', '.join(str(y) for y in x))
查看更多
闭嘴吧你
7楼-- · 2018-12-31 06:25

This is quite efficient, using O(log n) basic arithmetic operations.

def fib(n):
    return pow(2 << n, n + 1, (4 << 2*n) - (2 << n) - 1) % (2 << n)

This one uses O(1) basic arithmetic operations, but the size of the intermediate results is large and so is not at all efficient.

def fib(n):
    return (4 << n*(3+n)) // ((4 << 2*n) - (2 << n) - 1) & ((2 << n) - 1)

This one computes X^n in the polynomial ring Z[X] / (X^2 - X - 1) using exponentiation by squaring. The result of that calculation is the polynomial Fib(n)X + Fib(n-1), from which the nth Fibonacci number can be read.

Again, this uses O(log n) arithmetic operations and is very efficient.

def mul(a, b):
        return a[0]*b[1]+a[1]*b[0]+a[0]*b[0], a[0]*b[0]+a[1]*b[1]

def fib(n):
        x, r = (1, 0), (0, 1)
        while n:
                if n & 1: r = mul(r, x)
                x = mul(x, x)
                n >>= 1
        return r[0]
查看更多
登录 后发表回答