300. Python Program to Print a Number Spiral
HardPhase 3 · Challenge
This one takes several steps and some thought, but every tool is one you know: a list, for loops, if and %. Fill a 3 by 3 grid on paper first and say each turn out loud.
Overview
A spiral walks around the edge of a grid and then curls inwards. It is a classic puzzle, because you must decide when to turn.
Problem Statement
Linh designs a snail-shell puzzle for a maths club. Read a whole number n and fill a grid of n rows and n columns with the numbers 1 to n * n:
- Start in the top-left corner with 1, and move to the right.
- Write the next number in the next square.
- When the next square is outside the grid, or already has a number, turn clockwise first. Clockwise means right, then down, then left, then up, then right again.
Print the grid one row per line. Every number takes the same room: as many characters as n * n has digits. A shorter number gets spaces in front of it. One more space separates the numbers in a row. For example, when n is 4, n * n is 16, so each number takes 2 characters and 5 is printed as a space and 5.
Examples
Example 1. Input 4 gives:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Why: 1 to 4 go right along the top row. 5 to 7 go down the right side. 8 to 10 go left along the bottom, and 11 and 12 go up. Then the walk turns right again and fills the middle with 13 to 16.
Example 2. Input 3 gives:
1 2 3
8 9 4
7 6 5
Why: n * n is 9, which has 1 digit, so no number needs a space in front. The walk goes right, down, left and up, and 9 ends in the middle.
Input
One whole number n (1 to 10). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
n lines, each with n numbers. The spaces at the start of a line matter: the tests check them. A space at the end of a line is fine: the tests ignore it. The tests try 7 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.