實戰:自動拼寫檢查

Vibe Prompt

「幫我用 FastAPI 建立一個拼寫檢查 API:輸入單字,回傳最相似的 5 個正確拼寫。」

# spell_checker.py
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="拼寫檢查 API")

def edit_distance(s1, s2):
    m, n = len(s1), len(s2)
    dp = [[0]*(n+1) for _ in range(m+1)]
    for i in range(m+1): dp[i][0] = i
    for j in range(n+1): dp[0][j] = j
    for i in range(1, m+1):
        for j in range(1, n+1):
            if s1[i-1] == s2[j-1]:
                dp[i][j] = dp[i-1][j-1]
            else:
                dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
    return dp[m][n]

DICTIONARY = ["coding", "coding", "vibe", "tutor", "python", "algorithm",
              "react", "next", "docker", "kubernetes", "fastapi", "tailwind"]

class SpellRequest(BaseModel):
    word: str
    top_k: int = 5

class SpellResponse(BaseModel):
    original: str
    suggestions: list

@app.post("/spell-check", response_model=SpellResponse)
def spell_check(req: SpellRequest):
    scored = [(w, edit_distance(req.word, w)) for w in DICTIONARY]
    scored.sort(key=lambda x: x[1])
    suggestions = [{"word": w, "distance": d} for w, d in scored[:req.top_k]]
    return SpellResponse(original=req.word, suggestions=suggestions)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

本日總結

完成了 DP 課程!你現在可以解決:

  • ✅ 0/1 背包
  • ✅ LCS
  • ✅ 編輯距離
  • ✅ 用 Vibe Coding 把 DP 包裝成 API

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!