with one click
cache-recursive-calls
// For dynamic programming: overlapping subproblems, recursive solutions with repeated computations, memoization to avoid redundant work.
// For dynamic programming: overlapping subproblems, recursive solutions with repeated computations, memoization to avoid redundant work.
| name | cache-recursive-calls |
| description | For dynamic programming: overlapping subproblems, recursive solutions with repeated computations, memoization to avoid redundant work. |
Use @functools.cache (Python 3.9+) or @functools.lru_cache(None) to memoize.
from functools import cache
@cache
def fib(n):
"""Fibonacci with memoization: O(n) instead of O(2^n)."""
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
# Or with size limit
from functools import lru_cache
@lru_cache(maxsize=1000)
def expensive_lookup(key):
# ... expensive computation
return result
from functools import cache
# TSP with dynamic programming (TSP.ipynb)
@cache
def shortest_segment(A, Bs, C):
"""Shortest path from A through all cities in Bs to C."""
if not Bs:
return [A, C]
return min(
(shortest_segment(A, Bs - {B}, B) + [C] for B in Bs),
key=segment_length
)
# Key insight: Bs must be frozenset (hashable)
cities = frozenset(['NYC', 'LA', 'CHI', 'HOU'])
tour = shortest_segment('START', cities, 'START')
# Expression counting (Countdown.ipynb)
@cache
def expressions(numbers):
"""All expressions makeable from numbers."""
if len(numbers) == 1:
return {numbers[0]: str(numbers[0])}
table = {}
for Lnums, Rnums in splits(numbers):
for L, R in product(expressions(Lnums), expressions(Rnums)):
for op in ops:
# Combine L and R with op
...
return table
# Word segmentation (ngrams.py)
@cache
def segment(text):
"""Best word segmentation of text."""
if not text:
return []
candidates = ([first] + segment(rest)
for first, rest in splits(text))
return max(candidates, key=word_probability)
cache is unbounded, lru_cache has size limitfunc.cache_info() shows hits/missesfunc.cache_clear() frees memoryConducts iterative deep research on any topic using web search, progressive exploration, and structured synthesis. Use when asked for comprehensive research, deep investigation, thorough analysis, or multi-source exploration of any topic. Triggers: research, investigate, deep dive, comprehensive analysis, explore thoroughly, find everything about.
For cross-cutting concerns: add behavior without modifying functions, caching, timing, logging, validation wrappers.
For performance work: measure before changing, profile to find bottlenecks, compare before and after.
For symbolic computation: ASTs, mathematical expressions, code that manipulates code structure, expression transformations.
For ordered processing: A* search, Dijkstra, event simulation, task scheduling. Efficient min/max extraction with heap-based queue.
For persistent state: closures capture outer variables, alternative to classes for simple state, factory functions that remember context.