Skip to content Skip to sidebar Skip to footer

Applying `functools.lru_cache` To Lambda

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 &g

Solution 1:

Try fib = functools.lru_cache()(lambda n: fib(n - 1) + fib(n - 2) if n > 1 else 1)

I believe that calling lru_cache returns a function, which takes a function and returns a function. To supply a max size, use fib = functools.lru_cache(100)(lambda n: fib(n - 1) + fib(n - 2) if n > 1 else 1)

Solution 2:

a small example with the most stupid function i could think of:

from functools import lru_cache

@lru_cache(maxsize=32)defidentity(x):
    return x

identity2 = lru_cache(maxsize=32)(lambda x: x)

the first version is the decorator version where you can see the first agument of lru_cache. from there it is easy to see how to get the syntax for a lambda expression right.

Post a Comment for "Applying `functools.lru_cache` To Lambda"