Advanced · 2D lists · 179 of 264
Row and column totals
Print the matrix with the sum of each row added at the end of the row, and a last row with the sum of each column (and the grand total).
Input: r and c, then r lines of c whole numbers. Output: r + 1 lines of c + 1 numbers.
Examples
Input
2 2 1 2 3 4
Output
1 2 3 3 4 7 4 6 10
Input
1 3 5 5 5
Output
5 5 5 15 5 5 5 15
One more test checks 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)].