Memoisation
Not met yet
Some recursive functions ask the same question many times: a file tree printer that shows every folder's size measures each folder again for every folder above it. Memoisation writes each answer down the first time, filed by its arguments, and reads it back after that. The answers don't change, only the work: from millions of calls to a few dozen. Use a dictionary, or put @functools.cache above the def. Its arguments must be things a dictionary could use as keys, so not lists.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks checking a memo dictionary is enough to speed a function up, without writing each new answer into it.
- Thinks functools.cache keeps only the most recent answer, rather than one answer for every set of arguments.
- Thinks functools.cache only keeps the answers to calls made from outside the function, not the recursive calls inside it.
- Thinks memoisation speeds up any recursive function, even one that never asks the same question twice.
- Thinks memoising a function changes the answers it gives, rather than only how much work it does.
- Thinks functools.cache works with any arguments, including lists, rather than only with arguments that can be hashed.