Sub topic 16
Turning Pseudocode into a Working Program
This chapter assumes you can read Python, know the difference between 0-based and 1-based indexing, and have already hand-traced FindMax and InsertionSort in earlier chapters. Here you will translate those pseudocode algorithms into Python and use your trace tables to check the result.
A Repeatable Translation Process
Translation works best when it is mechanical. You already made the design decisions during stepwise refinement and desk checking. The job now is to carry them over without adding new bugs.
Construct-by-Construct Mapping
| Pseudocode | Python | Watch out for |
|---|---|---|
| `x ← 5` | `x = 5` | Do not confuse `=` with `==` |
| `IF a > b THEN ... END IF` | `if a > b:` plus indentation | Indentation is the block |
| `FOR i ← 1 TO n` (1-based) | `for i in range(n):` (0-based) | `TO` includes `n`. `range` stops before its end value |
| `FOR i ← 2 TO n` (1-based) | `for i in range(1, n):` | Shift both bounds down by one |
| `WHILE i ≥ 1` (1-based index) | `while i >= 0:` | The lowest valid index changes |
| `A[i]` (1-based) | `a[i]` (0-based) | Shift once, consistently |
| `RETURN x` | `return x` | Procedures without a return become functions returning `None` |
Example: FindMax
The pseudocode starts at A[1] and loops i from 2 to n. After shifting down by one, the loop starts at a[0] and runs i from 1 to n - 1, which is range(1, len(a)).
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])) # 9The output matches the final row of your trace table. The name max_val also avoids shadowing Python's built-in max.
Example: InsertionSort
In this version the outer bound shifts, and the guard i ≥ 1 becomes i >= 0. Python's and short-circuits, so a[i] is never read when i is -1. Without the short-circuit, a[-1] would quietly read the last element, because negative indexes are legal in Python.
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
return a
print(insertion_sort([5, 2, 4, 1])) # [1, 2, 4, 5]Checking Against Your Trace
Reuse the inputs you traced by hand, including the edge cases. If an output disagrees, add a print of the loop variables in the same order as your trace table's columns. The first row that differs shows you where the translation went wrong.
Also check the preconditions you assumed. FindMax requires a non-empty array, and find_max([]) raises IndexError. Decide whether to document that requirement or add a check for it.
Exercise
Translate this 1-based pseudocode loop to Python with 0-based indexing: total ← 0; FOR i ← 1 TO n DO total ← total + A[i] END FOR. What is the most likely bug if you write for i in range(1, n):?
Show answer
Correct version: total = 0 then for i in range(n): total = total + a[i]. Writing range(1, n) shifts only the lower bound. It skips a[0] and still stops at a[n - 1], so it adds up all elements except the first.
Exercise
In insertion_sort, what goes wrong if the condition is written a[i] > key and i >= 0?
Show answer
When i reaches -1, a[-1] is evaluated first and reads the last element instead of stopping the loop. Comparisons can then go wrong and elements can be shifted incorrectly. The bounds check must come first so short-circuiting protects the access.