Diagonal Sums
Advanced · Stretch · from Python Comprehensions: List, Dict, Set, and Generator in One Guide
From the lesson: Python Comprehensions: List, Dict, Set, and Generator in One Guide
Imagine you have a list of 100 numbers and you want a new list containing only the even ones, each doubled. With a regular loop, that takes four lines. With a Python comprehension, it takes one.
Read the lessonA grid is a list of rows, all the same length, but it does not have to be square. Number the diagonals by adding the row and the column: the cell in row r, column c lies on diagonal r + c. Write a function diagonal_sums(grid) that returns the sum of each diagonal, from diagonal 0 (the top-left cell) to the last one (the bottom-right cell).
grid = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
diagonal_sums(grid) # [1, 6, 15, 14, 9]Here 6 is 2 + 4, and 15 is 3 + 5 + 7. An empty grid has no diagonals. Try to build the answer with comprehensions.
Return the answer instead of printing it: Check calls diagonal_sums() with its own grids, some of them hidden.
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| diagonal_sums([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) | [1, 6, 15, 14, 9] |
| diagonal_sums([[1, 2], [3, 4]]) | [1, 5, 4] |
More List Comprehension exercises
- Double Every NumberBeginner
- Filter Even NumbersBeginner
- Predict the Output: if vs if-elseIntermediate
- Create a Dict ComprehensionIntermediate
- Unique Vowels with a Set ComprehensionIntermediate
- Fix the Bug: Wrong Comprehension SyntaxIntermediate
- Refactor a Loop into a ComprehensionIntermediate
- Flatten a MatrixAdvanced
All Python exercises · 50 practice problems · Data Structures quiz