Created
March 13, 2019 17:14
-
-
Save mplanchard/5ebd907531e72701c61ca43c05ac1d6c to your computer and use it in GitHub Desktop.
2D Array Problem
This file contains 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
test_array = [ | |
[1, 2, 3, 4], | |
[5, 6, 7, 8], | |
[9, 10, 11, 12], | |
] | |
# [2][0] | |
# [1][0] [2][1] | |
# [0][0] [1][1] [2][2] | |
# [0][1] ... | |
# [0][2] | |
# [0][3] | |
def coord_on_array(array, x, y): | |
return ( | |
x >= 0 | |
and y >= 0 | |
and y < len(array) | |
and x < len(array[y]) | |
) | |
def get_starting_coords(array): | |
y = len(array) - 1 | |
x = 0 | |
while coord_on_array(array, x, y): | |
yield x, y | |
y -= 1 | |
y += 1 | |
while coord_on_array(array, x, y): | |
x += 1 | |
yield x, y | |
def get_diagonal_for_starting_coord(array, x, y): | |
while coord_on_array(array, x, y): | |
yield array[y][x] | |
x += 1 | |
y += 1 | |
def print_diagonals(array): | |
"""Print the diagonals from an array.""" | |
for x, y in get_starting_coords(array): | |
diag = get_diagonal_for_starting_coord(array, x, y) | |
for item in diag: | |
print(item, end=' ') | |
print() | |
print_diagonals(test_array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment