How to write the Fibonacci Sequence?

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

    A more detailed explanation of how Memoization works for Fibonacci sequence.

    # Fibonacci sequence Memoization
    
    fib_cache = {0:0, 1:1}
    
    def fibonacci(n):
        if n < 0:
            return -1
        if fib_cache.has_key(n):
            print "Fibonacci sequence for %d = %d cached" % (n, fib_cache[n])
            return fib_cache[n]
        else:
            fib_cache[n] = fibonacci(n - 1) + fibonacci(n - 2)
        return fib_cache[n]
    
    if __name__ == "__main__":
        print fibonacci(6)
        print fib_cache
        # fibonacci(7) reuses fibonacci(6) and fibonacci(5)
        print fibonacci(7)
        print fib_cache
    

提交回复
热议问题