Step 01 Beginner Problems — Patterns
Pattern 22 — Number Pattern
A square of numbers arranged in concentric layers like an onion: the outermost ring is all n, the next ring in is n - 1, and the value drops by one per layer until the single center cell holds 1. For n = 4 the square is 7x7, and the figure reads identically along every row, column, and line of symmetry.
4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4
How to think about it
The grid has size 2n - 1 (so there is a single center cell). For the cell at (i, j), compute its distance to the nearest edge: dist = min(i, j, size - 1 - i, size - 1 - j). Edge cells have dist 0, the next ring dist 1, and the center dist n - 1. The printed value is n - dist. That is the whole pattern — no row or column formula, just 'how deep is this cell?'. Every ring of constant dist is a square frame of the kind Pattern 21 draws, and the frames nest inside each other.
Code
Two nested loops walk the (2n - 1) x (2n - 1) grid. For each cell the code takes the minimum of the four distances to the edges and prints n minus that distance. The min-of-four-distances idiom is the entire algorithm — everything else is the standard grid-printing skeleton from Pattern 1.
def pattern(n):
size = 2 * n - 1
for i in range(size):
row = []
for j in range(size):
dist = min(i, j, size - 1 - i, size - 1 - j)
row.append(str(n - dist))
print(" ".join(row))Key points
- Grid size is 2n - 1, not n — the input counts layers, and layers need a center.
- Cell value = n - min(i, j, size-1-i, size-1-j): distance to the nearest edge decides everything.
- Each constant-value ring is a hollow square — Pattern 21 nested inside itself.
- The center cell is always 1 and the border is always n — instant sanity checks.
- The figure has four-way symmetry: rows read the same as columns.