Sub topic 16
Turning Pseudocode into a Working Program
This chapter assumes you can read the pseudocode conventions used so far in the tutorial and can build a trace table. It also assumes you can write and run a short Python program with functions, lists, and loops. The examples use Python, but the method works for any language.
Pseudocode that has been desk checked is a specification you already trust. Translation should keep that trust. The aim is a program that does exactly what the traced pseudocode does, on the same inputs, step for step. Most translation bugs come from small mismatches between the pseudocode's conventions and the language's rules. Index bases, loop bounds, and operator meanings cause most of them.
A Repeatable Translation Workflow
Treat translation as a procedure with checkpoints. Do not rewrite the algorithm from memory.
The trace tables from earlier chapters become your first test cases. If the program and the hand trace disagree, at least one of them is wrong. You can locate the divergence by printing the same columns the trace table recorded.
Mapping Constructs One to One
Most pseudocode constructs have a direct counterpart. The table lists the ones used in this tutorial with their Python equivalents and the detail that most often goes wrong.
| Pseudocode | Python | Watch for |
|---|---|---|
| `x ← 5` | `x = 5` | `=` in pseudocode conditions means comparison, which is `==` in Python |
| `IF c THEN ... END IF` | `if c:` plus an indented block | The end of the indented block replaces `END IF` |
| `FOR i ← a TO b` | `for i in range(a, b + 1)` | `TO` is inclusive, and `range` excludes its stop value |
| `WHILE c DO ... END WHILE` | `while c:` | There is no do-until form, so use `while True` with `break` |
| `a AND b`, `a OR b`, `NOT a` | `a and b`, `a or b`, `not a` | Both languages short-circuit here, but check this in other languages |
| `x ≤ y`, `x ≠ y` | `x <= y`, `x != y` | |
| `a DIV b`, `a MOD b` | `a // b`, `a % b` | Python's `//` rounds toward negative infinity, and C and Java truncate toward zero |
| `a ÷ b` or `a / b` | `a / b` | In Python this always gives a float |
| `RETURN v` | `return v` | |
| `A[i]` on a 1-based array | `a[i - 1]` | See the next section |
| `length(A)` or parameter `n` | `len(a)` | Python lists carry their length, so `n` is often dropped |
Handling the Index Shift
The pseudocode in this tutorial uses 1-based arrays, and Python uses 0-based lists. You have two consistent options.
- Shift every index. Subtract 1 from every array subscript and rewrite the loop bounds to match. This gives idiomatic code, but you must apply the shift everywhere.
- Pad the list. Put a dummy value at index 0 and keep the pseudocode's indices unchanged. This keeps the translation literal, which helps when you are checking it against a trace. It is awkward to use from other code.
Shifting is the usual choice. Do it in a fixed order:
- Mark which variables are indices, meaning they are used inside
A[...]. Mark which are counters or values, meaning they are used in arithmetic or returned. - Shift only the indices.
- Rewrite each loop's bounds so the shifted index covers the same elements as before.
For example, FOR i ← 2 TO n visits elements 2 through n. After the shift those are positions 1 through n − 1, so the loop becomes range(1, n).
FindMax, Translated and Checked
The pseudocode starts at max ← A[1] and loops FOR i ← 2 TO n. In Python, A[1] becomes a[0], and the loop covers positions 1 through len(a) - 1. Also, max is a built-in in Python, so the variable gets a different name.
def find_max(a):
max_val = a[0]
for i in range(1, len(a)):
if a[i] > max_val:
max_val = a[i]
return max_val
print(find_max([3, 7, 2, 9])) # 9, matching the trace tableThe original pseudocode required a non-empty array. Python will raise IndexError on find_max([]). That is a reasonable result, because the precondition was violated. Decide whether to keep that behavior or check for an empty list and raise a clearer error.
InsertionSort and the Short-Circuit Guard
Insertion sort shows every index pitfall at once.
def insertion_sort(a):
for j in range(1, len(a)): # FOR j ← 2 TO n
key = a[j]
i = j - 1
while i >= 0 and a[i] > key: # WHILE i ≥ 1 AND A[i] > key
a[i + 1] = a[i]
i -= 1
a[i + 1] = key
data = [5, 2, 4, 6, 1, 3]
insertion_sort(data)
print(data) # [1, 2, 3, 4, 5, 6]There are three details to check against the pseudocode:
- The guard shifts too.
i ≥ 1becomesi >= 0. If you copyi >= 1unchanged, the first element is never compared, and[2, 1]stays unsorted. - Short-circuiting still matters. When
ireaches −1, Python'sandstops before evaluatinga[i]. If you swap the two operands,a[-1]is evaluated. Python does not raise an error for this. It silently reads the last element, so the program can give wrong results without crashing. In C, the same mistake reads memory outside the array. i + 1needs no change. Expressions built from a shifted index are already shifted.
The pseudocode procedure changes A in place, and so does the Python function, because lists are passed by object reference. If your target language passes arrays by value, return the sorted array instead.
Recursion and Language Limits
Recursive pseudocode translates directly:
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(3)) # 6, matching the call trace
print(fact(20)) # 2432902008176640000Pseudocode assumes unlimited memory and unbounded integers, but real languages have limits. CPython's default recursion limit is about 1000 frames, so fact(5000) raises RecursionError. Python integers never overflow. In Java, a long overflows after fact(20), and an int overflows after fact(12). When the pseudocode's assumptions exceed the language's limits, either change the algorithm (for example, to a loop) or document the input range it supports.
Testing Against Your Traces
Convert each hand trace into an assertion. Then add the edge cases you chose while desk checking.
def find_max(a):
max_val = a[0]
for i in range(1, len(a)):
if a[i] > max_val:
max_val = a[i]
return max_val
def sum_to(n):
total = 0
i = 1
while i <= n:
total = total + i
i = i + 1
return total
def insertion_sort(a):
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i >= 0 and a[i] > key:
a[i + 1] = a[i]
i -= 1
a[i + 1] = key
# Cases taken from the hand traces
assert find_max([3, 7, 2, 9]) == 9
assert sum_to(3) == 6
# Edge cases
assert find_max([4]) == 4 # single element, loop body never runs
assert find_max([9, 1, 2]) == 9 # maximum in the first position
assert find_max([-5, -2, -8]) == -2 # all negative values
assert sum_to(0) == 0 # empty range
assert sum_to(1) == 1
for case in ([], [1], [2, 1], [1, 2, 3], [3, 2, 1], [2, 2, 1]):
copy = list(case)
insertion_sort(copy)
assert copy == sorted(case), case
print("all tests passed")If an assertion fails, do not start editing at random. Add a print of the trace-table columns inside the loop, such as print(j, i, key, a). Then compare the output row by row with your hand trace. The first row that differs shows where the translation went wrong.
Exercise
The 1-based pseudocode FOR k ← 1 TO n - 1 DO IF A[k] > A[k + 1] THEN swap A[k] and A[k + 1] makes one pass of bubble sort. Translate the loop header and the comparison into 0-based Python for a list a of length n.
Show answer
for k in range(0, n - 1): with if a[k] > a[k + 1]:. The 1-based values of k run from 1 to n − 1. After the shift they run from 0 to n − 2, which is range(0, n - 1). The largest value of k + 1 is n − 1, which is the last valid index.
Exercise
A student translates the insertion sort guard as while a[i] > key and i >= 0:. On which input does this first behave differently from the correct version, and why does Python not raise an error?
Show answer
Any input where the key is smaller than every element before it, for example [2, 1]. When i becomes −1, a[-1] is evaluated before the bounds check. Python treats negative indices as counting from the end of the list, so it reads the last element instead of raising IndexError. Depending on that value, the loop may continue past the start of the list, producing wrong output without a crash.
Exercise
In the sum loop, i starts at 1 and the condition is i ≤ n. Should you translate this to i = 0 and while i < n to "make it 0-based"? Explain.
Show answer
No. Here i is a value being added to the total, not an array index, so the index shift does not apply. With i = 0 and i < n, the loop adds 0 through n − 1 and returns 3 for n = 3 instead of 6. That is the off-by-one bug the desk check found. Keep i = 1 and while i <= n.