Python - fibonacci

发布时间 2023-06-13 14:14:33作者: ZhangZhihuiAAA

So is there ever a good place to use mutable defaults? Yes! Mutable defaults can be very useful for caching and/or recursive algorithms:

def fibonacci(n, cache={0:0, 1:1}):
    if n in cache:
        return cache[n]
    else:
        value = fibonacci(n-1) + fibonacci(n-2)
        cache[n] = value
        return value