Can someone explain the code snippet below? I'm a bit confused by the syntax @memoize
. When/how is it called? What does it do?
import functools
def memoize(fn):
known = dict()
@functools.wraps(fn)
def memoizer(*args):
if args not in known:
known[args] = fn(*args)
return known[args]
return memoizer
@memoize
def fibonacci(n):
'''Returns the nth number of the Fibonacci sequence'''
assert(n >= 0), 'n must be >= 0'
return n if n in (0, 1) else fibonacci(n-1) + fibonacci(n-2)
if __name__ == '__main__':
print(fibonacci(10))