Accel Thinking

Python Learning 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.

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.