Comet wants a rock count before Pip rolls out. "There are only a few rocks," she says. "I can see them. Four, I think."
Wren taps the field sketch. "What does the evidence say?" he asks. "I trust a count that checks every cell. How many cells is that?"
Nova projects the field with a small light that sweeps along the top row, then the next. "How can I help?" she asks. "One loop for the rows and one for the columns inside it. Count how often the inner line runs."
Comet laughs. "Fine. Lead programmer, make the computer check every cell."
Nested loops walk a grid. The outer loop picks a row, and the inner loop visits every column in that row.
This order, row by row and left to right, is row-major order. The field below is made-up data from the FieldSim story.
# walk.py
FIELD = [
"..*..#",
".#....",
"...#*.",
"*.....",
"..#..*",
]
rows_walked = 0
checks = 0
rocks = 0
for r in range(len(FIELD)):
rows_walked += 1
for c in range(len(FIELD[r])):
checks += 1
if FIELD[r][c] == "#":
rocks += 1
print("rock at", (r, c))
print("Rows walked:", rows_walked)
print("Cells checked:", checks)
print("Rocks:", rocks) rock at (0, 5) rock at (1, 1) rock at (2, 3) rock at (4, 2) Rows walked: 5 Cells checked: 30 Rocks: 4
A statement execution count is how many times a line runs. Counting it by tracing lets you compare loops informally.
walk.py counts for us: rows_walked += 1 runs once per row, and checks += 1 runs once per cell.
| Line in walk.py | Runs | Why |
|---|---|---|
| rows_walked += 1 | 5 times | once for each row |
| checks += 1 | 30 times | once for each cell |
| rocks += 1 | 4 times | once for each # |
# row_counts.py
FIELD = [
"..*..#",
".#....",
"...#*.",
"*.....",
"..#..*",
]
for r in range(len(FIELD)):
open_cells = 0
for c in range(len(FIELD[r])):
if FIELD[r][c] != "#":
open_cells += 1
print("Row", r, "open:", open_cells) Row 0 open: 5 Row 1 open: 5 Row 2 open: 5 Row 3 open: 6 Row 4 open: 5
| Statement | True or false? |
|---|---|
| In walk.py the outer loop walks the rows. | ? |
| The inner loop finishes a whole row before the next row starts. | ? |
| The line checks += 1 runs 6 times in walk.py. | ? |
| Row-major order means column by column, top to bottom. | ? |
Every cell, in order, and the counts to prove it. Tomorrow the grid becomes a class in its own file.