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 memorynpx skills add jimmc414/cache-recursive-calls下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer