How to write the Fibonacci Sequence?

前端 未结 30 2336
醉酒成梦
醉酒成梦 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: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.

提交回复
热议问题