What Is a Dry Run? Trace an Algorithm with a State Table



☰

Start NorthStar

Python DSA Notes

What Is a Dry Run? Trace an Algorithm with a State Table

Use a small input and a trace table to locate the first state that differs from what the algorithm should produce.

Python DSA 笔记

Dry Run 是什么?用状态表逐步检查算法

用小输入和状态表逐步执行算法,找到实际状态第一次偏离预期的位置。

Share this article

Copy the link, open your phone share sheet, scan the QR code for WeChat, or send by email.




Email

A program that runs can still update its state incorrectly. A dry run uses a small concrete input and executes the algorithm by hand, recording each event, branch, state change, and check.

The Core Idea

A dry run turns “the answer is wrong” into a precise statement such as “position first diverges from the expected value in step two.”

A Reusable Trace Table

Step Input / Event State Before Branch / Action State After Check
1 current input relevant values rule that ran updated values expected or not

Record only state that affects the future, plus the output you are checking.

Worked Example

In Shell Game, suppose the pebble starts at 1 and shells 1 and 2 are swapped. The correct next position is 2. With two independent if statements, the first condition moves 1 to 2 and the second condition immediately moves 2 back to 1. A two-row micro-trace exposes the exact failure.

The fix is an exclusive branch:

if position == a:
    position = b
elif position == b:
    position = a

A Five-Step Routine

  1. State the input, output, and loop invariant or state meaning.
  2. Choose a small input that triggers the important branch.
  3. Select the few state columns that determine future behavior.
  4. Execute one statement at a time without skipping “obvious” work.
  5. Stop at the first difference between expected and actual state.

Choose Useful Inputs

Include the smallest legal case, one case for each branch, cases around boundaries, and one ordinary example with a known answer. For a swap, test the state at the first endpoint, the second endpoint, and neither endpoint.

Dry Run vs. Other Tools

Dry runs clarify expectations; print statements reveal actual execution; debuggers inspect variables and call stacks; unit tests preserve known behavior. They work together. A dry run tells you what to inspect with the other tools.

Common Mistakes

  1. Recording only the final value instead of every meaningful transition.
  2. Copying execution without an independent expected result.
  3. Choosing an example too large to inspect clearly.
  4. Continuing long after the first incorrect state appears.

Copyable Template

Goal:
Input:
Expected output:

| Step | Event | State Before | Action | State After | Check |
|------|-------|--------------|--------|-------------|-------|

Practice Questions

  1. Trace the indices produced by range(n) for n = 0, 1, and 3.
  2. Compare “add then test” with “test then add” in a running-sum loop.
  3. Write one swap-table row for each possible relation between the pebble and the swapped shells.
  4. Turn the first mismatch in your table into a focused debugging question.

代码能够运行,不代表状态更新正确。Dry Run 的做法是选一个小输入,不靠直觉跳步,而是把每一次读取、判断、更新和输出都写进状态表。它能把“答案不对”变成“第 2 步的 position 更新错了”。

一句话结论

Dry Run 就是用具体输入手动执行算法,并在每一步记录关键状态、动作、预期结果和实际结果。

为什么只看代码不够?

人在阅读熟悉的代码时,很容易看到“想写的逻辑”,而不是“实际执行的逻辑”。以下错误尤其适合用 Dry Run 发现:

  • 更新顺序颠倒;
  • 条件分支连续命中;
  • 循环边界多一次或少一次;
  • 变量没有重置;
  • 累计值在错误时机改变;
  • 当前状态与上一轮状态混在一起。

一张好状态表需要哪些列?

最通用的模板是:

Step Input / Event State Before Branch / Action State After Check
1 本轮输入 更新前关键变量 执行了哪条规则 更新后关键变量 是否符合预期

列不必越多越好。只记录会影响后续执行的状态,以及当前要验证的输出。

完整例子:Shell Game

石子开始在位置 1,第一轮交换 1 和 2,然后猜位置 1。正确执行应当是:

Step Event Before Action After Guess Score
1 swap 1 2 1 position == a, move to b 2 1 0

这行表同时确认了两件事:交换后位置是 2;计分发生在交换之后。

Dry Run 怎样抓住 double-if bug?

错误代码:

if position == a:
    position = b
if position == b:
    position = a

把一轮拆成两个判断:

Micro-step Condition Before After
1 position == a 1 2
2 position == b 2 1

第二行立即暴露问题:第一次更新改变了第二个条件的真假。正确做法是让两个分支互斥:

if position == a:
    position = b
elif position == b:
    position = a

Dry Run 的五步流程

1. 先写算法契约

说明输入是什么、输出是什么、每轮开始和结束时状态应表示什么。

2. 选一个小而有区分力的输入

不要只选“最顺”的例子。优先选择会触发关键分支、边界或状态变化的输入。

3. 确定关键状态列

例如索引、当前位置、累计分、当前最优值、队列内容。临时变量只有在它能解释错误时才需要记录。

4. 一条语句一条语句执行

不要心算跳过“显然”的步骤。条件的真假、更新前后值和循环次数都要明确。

5. 在第一个分歧处停止

一旦实际状态与预期状态不同,先解释这个最早分歧。后面的错误通常只是它的连锁反应。

怎样选择测试输入?

至少准备四类:

  1. 最小合法输入;
  2. 能触发每个分支的输入;
  3. 边界附近输入;
  4. 一个你知道正确答案的普通样例。

对于 Shell Game,还应分别测试石子在 a、在 b、不在两者之中的情况。

Dry Run、print 和 debugger 有什么区别?

工具 最适合 优点 局限
Dry Run 理解算法与预演逻辑 强迫你说清状态和预期 长输入很费时
print 快速观察真实运行 简单直接 输出过多时难追踪
Debugger 逐句运行复杂程序 可看调用栈和变量 仍需要知道该观察什么
Unit test 防止已知行为回归 可重复、自动化 失败后仍要定位原因

Dry Run 不是替代其他工具,而是帮助你决定“该观察哪些状态”。

常见误区

只写变量最终值

最终值只能说明错了,不能说明从哪一步开始错。

表格复制代码,却没有预期列

没有独立预期,表格可能只是把错误执行抄一遍。至少要有一个 Check 或“应该是多少”的判断。

输入太大

先缩到仍能复现错误的最小例子。五行状态往往比五十行日志更有用。

错误发生后继续算很久

定位第一个错误状态更重要。修正它,再重新 Dry Run。

可复制模板

Goal / 目标:
Input / 输入:
Expected output / 预期输出:

| Step | Event | State Before | Action | State After | Check |
|------|-------|--------------|--------|-------------|-------|

练习

  1. 为 for i in range(n) 写出 n = 0、1、3 的索引表。
  2. 追踪 running sum,说明“先加再判断”和“先判断再加”的区别。
  3. 为 Shell Game 的三种位置关系各写一行状态表。
  4. 找出一个能在第一轮暴露 double-if bug 的最小输入。
  5. 把状态表整理成一个高质量 Debugging Question。

Questions or feedback?

Have a question about this article or want to suggest an improvement? Send us a private message.

Send Feedback

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

Back to Python DSA Notes
返回Python DSA 笔记

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top