Advanced · 2D lists · 180 of 264
Magic square
A magic square has every row, every column and both diagonals adding up to the same number.
Input: n, then n lines of n whole numbers. Output: magic or not magic
Examples
Input
3 2 7 6 9 5 1 4 3 8
Output
magic
Input
3 1 2 3 4 5 6 7 8 9
Output
not magic
Input
1 5
Output
magic
2 more tests check other inputs when you press Check.
Stuck? The idea behind 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)].