How to write the Fibonacci Sequence?

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

    If you're a fan of recursion you can cache the results easily with the lru_cache decorator (Least-recently-used cache decorator)

    from functools import lru_cache
    
    
    @lru_cache()
    def fib(n):
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            return fib(n-1) + fib(n-2)
    

    If you need to cache more than 128 values you can pass maxsize as an argument to the lru_cache (e.g. lru_cache(maxsize=500). If you set maxsize=None the cache can grow without bound.

提交回复
热议问题