Created
August 13, 2025 07:06
-
-
Save bru32/c6f47dbd51ec47e3eef26b9f478a4189 to your computer and use it in GitHub Desktop.
Generator that yields 2D list values.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Diagonal array generator. | |
| Start at top right corner going diagonally up | |
| and end in the bottom left corner. | |
| Bruce Wernick | |
| 13 August 2025 | |
| """ | |
| def diag(arr): | |
| nr = len(arr) | |
| nc = len(arr[0]) | |
| for k in range(nr+nc-1): | |
| for c in range(nc-1,-1,-1): | |
| for r in range(nr-1,-1,-1): | |
| if (r - c) + nc - 1 == k: | |
| yield(arr[r][c]) | |
| # Usage: | |
| arr = [[1,2,3], | |
| [4,5,6], | |
| [7,8,9]] | |
| # expect: 3,6,2,9,5,1,8,4,7 | |
| for a in diag(arr): | |
| print(a, end=",") | |
| print("\n") | |
| arr = [[ 1, 2, 3, 4], | |
| [ 5, 6, 7, 8], | |
| [ 9,10,11,12], | |
| [13,14,15,16], | |
| [17,18,19,20], | |
| [21,22,23,24], | |
| [25,26,27,28]] | |
| for a in diag(arr): | |
| print(a, end=",") | |
| print("\n") | |
| arr = [[ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12], | |
| [13,14,15,16,17,18,19,20,21,22,23,24], | |
| [25,26,27,28,29,30,31,32,33,34,35,36]] | |
| for a in diag(arr): | |
| print(a, end=",") | |
| print("\n") | |
| # Use a list comprehension to create a list of any size | |
| rows, cols = 14, 4 | |
| arr = [[1+c+r*cols for c in range(cols)] for r in range(rows)] | |
| for a in diag(arr): | |
| print(a, end=",") | |
| print("\n") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment