Total the two diagonals
A scoring sheet is a square grid, and the bonus is whatever sits on the two diagonals.
- The grid is square.
- Add every cell on the top-left to bottom-right diagonal, and every cell on the other one.
- On an odd-sized grid the centre belongs to both diagonals, and is counted once.
- An empty grid totals zero.
diagonal_total(sheet: list<list<int>>) → int
Where you start
def diagonal_total(sheet: list[list[int]]) -> int:
Worked examples
| Call | Result |
|---|---|
diagonal_total([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) | 25 |
diagonal_total([[1, 2], [3, 4]]) | 10 |
diagonal_total([[5]]) | 5 |
diagonal_total([]) | 0 |
Hint
Walk one index down the grid. At row i the two diagonal cells are column i and column (last - i) — and on an odd grid those meet in the middle.
Reference solution in Python
def diagonal_total(sheet: list[list[int]]) -> int:
total = 0
n = len(sheet)
for i in range(n):
total += sheet[i][i]
if i != n - 1 - i:
total += sheet[i][n - 1 - i]
return total