Files
2nd/10_Wiki/Topics/Other/Iteration.md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24:15 +09:00

6.0 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-iteration Iteration 10_Wiki/Topics verified self
Iterative Development
Loop
Iterate
none A 0.9 applied
methodology
agile
python
control-flow
generators
2026-05-10 pending
language framework
python 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)

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

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)

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)

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)

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

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

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

🤖 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