For combinatorial iteration: permutations, combinations, cartesian products, without storing all results in memory.
Use itertools for memory-efficient iteration over combinatorial structures.
from itertools import permutations, combinations, product, chain
# Permutations: all orderings
list(permutations('ABC'))
# [('A','B','C'), ('A','C','B'), ('B','A','C'), ...]
# Combinations: all subsets of size k
list(combinations('ABCD', 2))
# [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]
# Product: cartesian product
list(product('AB', '12'))
# [('A','1'), ('A','2'), ('B','1'), ('B','2')]
# Chain: concatenate iterables
list(chain([1,2], [3,4], [5]))
# [1, 2, 3, 4, 5]
# All are lazy - generate on demand
for perm in permutations(range(10)): # 3.6M permutations
if is_valid(perm):
break # Stop early, don't generate rest
from itertools import permutations, combinations, product
# TSP: try all tours (TSP.ipynb)
def brute_force_tsp(cities):
start, *rest = cities
return min(
([start] + list(perm) for perm in permutations(rest)),
key=tour_length
)
# Card hands (Probability.ipynb)
deck = [r + s for r in 'A23456789TJQK' for s in 'SHDC']
hands = combinations(deck, 5) # 2.6M hands, lazy
# Dice rolls (Probability.ipynb)
def roll(n, sides=6):
"""Distribution of sums from rolling n dice."""
from collections import Counter
die = range(1, sides + 1)
return Counter(sum(roll) for roll in product(die, repeat=n))
# Expression building (Countdown.ipynb)
for L, R in product(left_expressions, right_expressions):
for op in ['+', '-', '*', '/']:
combine(L, op, R)
# Splits of a sequence
def splits(sequence):
"""All ways to split sequence into two non-empty parts."""
return ((sequence[:i], sequence[i:])
for i in range(1, len(sequence)))
product(range(6), repeat=3) for 3 diceislice(permutations(...), 100) for first 100npx skills add jimmc414/iterate-with-itertools下载完整 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