How to write the Fibonacci Sequence?

前端 未结 30 2359
醉酒成梦
醉酒成梦 2020-11-22 00:32

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

相关标签:
30条回答
  • 2020-11-22 01:12

    there is a very easy method to realize that!

    you can run this code online freely by using http://www.learnpython.org/

    # Set the variable brian on line 3!
    
    def fib(n):
    """This is documentation string for function. It'll be available by fib.__doc__()
    Return a list containing the Fibonacci series up to n."""
    result = []
    a = 0
    b = 1
    while a < n:
        result.append(a)  # 0 1 1 2 3 5  8  (13) break
        tmp_var = b       # 1 1 2 3 5 8  13
        b = a + b         # 1 2 3 5 8 13 21
        a = tmp_var       # 1 1 2 3 5 8  13
        # print(a)
    return result
    
    print(fib(10))
    # result should be this: [0, 1, 1, 2, 3, 5, 8]
    
    0 讨论(0)
  • 2020-11-22 01:13

    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
    
    0 讨论(0)
  • 2020-11-22 01:14

    The idea behind the Fibonacci sequence is shown in the following Python code:

    def fib(n):
       if n == 1:
          return 1
       elif n == 0:   
          return 0            
       else:                      
          return fib(n-1) + fib(n-2)         
    

    This means that fib is a function that can do one of three things. It defines fib(1) == 1, fib(0) == 0, and fib(n) to be:

    fib(n-1) + fib(n-2)

    Where n is an arbitrary integer. This means that fib(2) for example, expands out to the following arithmetic:

    fib(2) = fib(1) + fib(0)
    fib(1) = 1
    fib(0) = 0
    # Therefore by substitution:
    fib(2) = 1 + 0
    fib(2) = 1
    

    We can calculate fib(3) the same way with the arithmetic shown below:

    fib(3) = fib(2) + fib(1)
    fib(2) = fib(1) + fib(0)
    fib(2) = 1
    fib(1) = 1
    fib(0) = 0
    # Therefore by substitution:
    fib(3) = 1 + 1 + 0
    

    The important thing to realize here is that fib(3) can't be calculated without calculating fib(2), which is calculated by knowing the definitions of fib(1) and fib(0). Having a function call itself like the fibonacci function does is called recursion, and it's an important topic in programming.

    This sounds like a homework assignment so I'm not going to do the start/end part for you. Python is a wonderfully expressive language for this though, so this should make sense if you understand math, and will hopefully teach you about recursion. Good luck!

    Edit: One potential criticism of my code is that it doesn't use the super-handy Python function yield, which makes the fib(n) function a lot shorter. My example is a little bit more generic though, since not a lot of languages outside Python actually have yield.

    0 讨论(0)
  • 2020-11-22 01:14

    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]
    
    0 讨论(0)
  • 2020-11-22 01:15

    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))
    
    0 讨论(0)
  • 2020-11-22 01:15

    this is an improvement to mathew henry's answer:

    def fib(n):
        a = 0
        b = 1
        for i in range(1,n+1):
                c = a + b
                print b
                a = b
                b = c
    

    the code should print b instead of printing c

    output: 1,1,2,3,5 ....

    0 讨论(0)
提交回复
热议问题