So I made a recursive lambda in Python for the Fibonacci sequence. I used recursion because it was easiest to implement with lambda.
fib = lambda n: fib(n - 1) + fib(n - 2) if n > 1 else 1
Because using recursion, the same Fibonacci values were calculated many times, I thought using a cache decorator would help, and I knew that functools.lru_cache
was an easy option.
I know you can't apply the decorator to the function using @functools.lru_cache
to a lambda like a normal function, but when I tried this:
fib = functools.lru_cache((lambda n: fib(n - 1) + fib(n - 2) if n > 1 else 1), maxsize = None)
I got an error saying that functools.lru_cache
wouldn't accept a function object as an argument.
>>> fib = functools.lru_cache((lambda n: fib(n - 1) + fib(n - 2) if n > 1 else 1), maxsize = None)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
fib = functools.lru_cache((lambda n: fib(n - 1) + fib(n - 2) if n > 1 else 1), maxsize = None)
TypeError: lru_cache() got multiple values for argument 'maxsize'
I checked the docs, and it looks like functools.lru_cache
only accepts a maxsize
and a typed
argument, which default to 128
and False
respectively.
Is there a cleverer way to assign the decorator to the function rather than just defining the function without lambda and then applying the decorator?