Files
2nd/10_Wiki/Topics/Other/Iteration.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

196 lines
6.0 KiB
Markdown

---
id: wiki-2026-0508-iteration
title: Iteration
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Iterative Development, Loop, Iterate]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [methodology, agile, python, control-flow, generators]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: python
framework: general
---
# Iteration
## 매 한 줄
> **"매 small step, 매 feedback, 매 adjust, 매 repeat"**. Iteration 매 dual concept — (1) programming control flow (`for`, `while`, generators) 와 (2) development methodology (small increments + feedback loop). 2026 LLM-assisted 시대 매 iteration 매 even tighter — 매 minute 매 cycle 가능.
## 매 핵심
### 매 Programming iteration
- **Eager**: `for x in list` — 매 list 매 fully materialized.
- **Lazy**: generator, iterator — 매 on-demand pull.
- **Async**: `async for x in stream` — 매 I/O 의 overlap.
- **Parallel**: `joblib`, `multiprocessing.Pool.imap` — 매 CPU-bound iteration.
### 매 Methodology iteration
- **Loop**: hypothesis → build → measure → learn.
- **Cadence**: daily (LLM-assisted), weekly (sprint), monthly (release).
- **Artifact per cycle**: shippable increment.
- **Feedback source**: tests, users, metrics, code review.
### 매 응용
1. Data pipeline (process N rows lazily).
2. ML hyperparameter search (iteratively narrow).
3. Agile sprint (2-week cycle).
4. LLM agentic loop (think → act → observe → repeat).
## 💻 패턴
### Pattern 1: Generator (lazy iteration)
```python
def read_jsonl(path: str):
"""매 1GB+ file 의 stream — 매 memory O(1)."""
import json
with open(path) as f:
for line in f:
yield json.loads(line)
for record in read_jsonl("events.jsonl"):
process(record)
```
### Pattern 2: Itertools combinators
```python
from itertools import islice, chain, groupby, accumulate
# 매 first 100 records 만
head = list(islice(read_jsonl("big.jsonl"), 100))
# 매 multiple sources 의 concat
combined = chain(read_jsonl("a.jsonl"), read_jsonl("b.jsonl"))
# 매 group by user
sorted_records = sorted(combined, key=lambda r: r["user_id"])
for user_id, group in groupby(sorted_records, key=lambda r: r["user_id"]):
handle_user(user_id, list(group))
```
### Pattern 3: Async iteration (2026)
```python
import asyncio
import httpx
async def fetch_pages(urls: list[str]):
async with httpx.AsyncClient() as client:
async def fetch(url):
r = await client.get(url)
return url, r.text
for coro in asyncio.as_completed([fetch(u) for u in urls]):
yield await coro
async def main():
async for url, html in fetch_pages(URLS):
print(url, len(html))
```
### Pattern 4: Iterative refinement (algorithm)
```python
def newton_sqrt(n: float, tol: float = 1e-10, max_iter: int = 50) -> float:
x = n / 2
for _ in range(max_iter):
x_new = 0.5 * (x + n / x)
if abs(x_new - x) < tol:
return x_new
x = x_new
return x
```
### Pattern 5: LLM agentic loop (2026)
```python
from anthropic import Anthropic
client = Anthropic()
def agent_loop(task: str, max_iter: int = 10):
history = [{"role": "user", "content": task}]
for i in range(max_iter):
msg = client.messages.create(
model="claude-opus-4-7",
max_tokens=4000,
tools=TOOLS,
messages=history,
)
history.append({"role": "assistant", "content": msg.content})
if msg.stop_reason == "end_turn":
return msg
# tool_use → execute → observation → next iter
observations = execute_tools(msg.content)
history.append({"role": "user", "content": observations})
raise RuntimeError("매 max_iter 의 reach")
```
### Pattern 6: Sprint retrospective
```python
def retro(sprint_data: dict) -> dict:
return {
"what_worked": sprint_data["green_items"],
"what_didnt": sprint_data["red_items"],
"experiments_next": [
f"Try {hypothesis}" for hypothesis in sprint_data["new_ideas"]
],
"metrics_delta": {
k: sprint_data["after"][k] - sprint_data["before"][k]
for k in sprint_data["before"]
},
}
```
### Pattern 7: Bounded iteration with timeout
```python
import time
def iterate_with_budget(items, budget_sec: float):
start = time.time()
for item in items:
if time.time() - start > budget_sec:
print(f"매 budget 매 expire — {item} 의 stop")
return
yield process(item)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Large file processing | Generator (lazy). |
| Multiple I/O calls | Async iteration. |
| CPU-bound loop | `multiprocessing` 또는 vectorize. |
| Numerical convergence | While + tolerance check. |
| Product development | 2-week sprint + retrospective. |
| LLM agent | think-act-observe loop with max_iter cap. |
**기본값**: Programming 매 generator-first; methodology 매 1-week iteration with measurable hypothesis.
## 🔗 Graph
- 부모: [[Agile]]
- 응용: [[Generator]] · [[Sprint]]
- Adjacent: [[Lean-Startup]]
## 🤖 LLM 활용
**언제**: Agentic systems (think-act-observe), iterative refinement of code via LLM feedback, sprint planning summaries.
**언제 X**: Single-shot generation, tasks where each iteration is 1+ hours of human work (cycle too slow).
## ❌ 안티패턴
- **Eager when lazy works**: `list(huge_generator)` — 매 OOM.
- **Unbounded loop**: no max_iter — 매 infinite loop bug.
- **No feedback in iteration**: 매 build without measure — methodology 매 broken.
- **Perfect first iteration**: 매 ship at 70% — feedback 의 wait.
## 🧪 검증 / 중복
- Verified: PEP 234 (iterators), Eric Ries "Lean Startup" (2011), "Continuous Delivery" (Humble & Farley).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content covering both programming and methodology iteration with LLM agentic loop |