GCSE · 9 exercises
Python 2d lists
A list of lists is a grid: grid[row][col]. Read one row per line, each turned into numbers.
Loop over rows, then over the columns inside each row. zip(*grid) turns rows into columns.
grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
print(*row)
print(grid[1][2]) # 6Watch for: [[0] * 3] * 2 makes two names for the same row: changing one changes both. Build rows with a comprehension: [[0] * 3 for _ in range(2)].
Exercises
- Transpose a matrixSwap the rows and the columns of a matrix.Advanced
- Matrix multiplicationMultiply an n by m matrix A by an m by p matrix B.Advanced
- Rotate a pictureRotate a grid of characters 90 degrees clockwise.Advanced
- Spiral orderPrint the numbers of a matrix in spiral order: along the top row, down the rightAdvanced
- Row and column totalsPrint the matrix with the sum of each row added at the end of the row, and a lastAdvanced
- Magic squareA magic square has every row, every column and both diagonals adding up to the sameAdvanced
- Count the islandsA map shows land (#) and water (.).Advanced
- Who won?Look at a finished tic-tac-toe board and say who won: X, O, or draw if nobody hasAdvanced
- Minesweeper numbersReplace every empty square (.) of a minesweeper field with the number of mines (*)Advanced