#229 · Grids and matrices · Beginner · 30 XP · about 6 min
A square grid of numbers is given as a list of rows, each row a list of integers, with as many rows as columns. Write diagonal_sum(grid) that adds up the numbers on its two diagonals: the one from the top-left corner down to the bottom-right corner, and the one from the top-right corner down to the bottom-left corner.
When the grid has an odd size, the two diagonals cross in the centre cell: count that cell once. Return the total as an integer.
diagonal_sum([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # returns 25 diagonal_sum([[1, 2], [3, 4]]) # returns 10 diagonal_sum([[7]]) # returns 7
In the first grid the diagonals are 1, 5, 9 and 3, 5, 7. The 5 sits on both, so the total is 1 + 5 + 9 + 3 + 7 = 25.
First solves only, ranked by stars and then time.