# Demo 3:字符串重写 > 第 13 章 拓扑、统计物理与采样 · [本章演示](index.md) · [代码演示总索引](../index.md) **可视化**:双图 —— 经典步数 vs Grover 迭代 **对应教程**:[第 13 章 拓扑、统计物理与采样 中相关小节](https://tutorial.chenzhaoyun.com/quantum-tutorial/ch13-topology-statistical-physics/) · 依赖安装:`pip install "unified-quantum[visualization,simulation]"` ## 实现要点 重写规则 (固定一组): a → bc b → a c → a 我们关心匹配查询: 给定起始串 S, 经典法必须逐步展开每条规则 (O(|S|·|R|) per step); 量子 Grover 匹配只测 √M 个候选 (M=|prefix|·|R|). 对比: - 经典 "单步展开" 时间 (模拟, 扫 4 个 |S| 长度) - 量子 Grover 迭代次数 (~ π/4 √M) 画柱图对比, 并对一组具体 query 演示 Grover 找到目标子串的命中概率. ## 完整源码 ```{literalinclude} 03_string_rewriting.py :language: python :linenos: :caption: demos/ch13-topology-statistical-physics/03_string_rewriting.py ``` ## 运行结果 ![Demo 3:字符串重写](03_string_rewriting.png) ## 运行方式 ```bash # 仓库根目录执行;输出 PNG 到 demos/ch13-topology-statistical-physics/03_string_rewriting.png,关键统计到 stdout .venv/bin/python3 demos/ch13-topology-statistical-physics/03_string_rewriting.py ``` --- [← 本章演示](index.md) · [↑ 代码演示总索引](../index.md) · [⌂ 教程门户](https://tutorial.chenzhaoyun.com/)