I need to know if there’s a more concise way of writing this function, it seems like there should be a better way of doing this. The function adapts to the size of the grid, and you can use boolean parameters to decide if you want the x and y-axes labeled.
test = [
['A', 'B', 'C', 'D'],
['E', 'F', 'G', 'H'],
['I', 'J', 'K', 'L'],
['M', 'N', 'O', 'P']
]
# print an ASCII grid around the given 2D array
# axis booleans decide whether or not to print row/column labels
def print_grid(grid, xAxis=False, yAxis=False):
if xAxis:
column_labels = ' | '.join(str(i + 1) for i in range(len(grid[0])))
print(f"{' | ' if yAxis else '| '}{column_labels} |")
for row_num, row in enumerate(grid):
row_str = ' | '.join(str(i) for i in row)
print(f"{'---' if yAxis else ''}{'+---' * len(grid[0])}+")
print(f"{' ' + str(row_num + 1) + ' ' if yAxis else ''}| {row_str} |")
print(f"{'---' if yAxis else ''}{'+---' * len(grid[0])}+")
print_grid(test, False, False)
print()
print_grid(test, True, False)
print()
print_grid(test, False, True)
print()
print_grid(test, True, True)
Expected output:
+---+---+---+---+
| A | B | C | D |
+---+---+---+---+
| E | F | G | H |
+---+---+---+---+
| I | J | K | L |
+---+---+---+---+
| M | N | O | P |
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
| A | B | C | D |
+---+---+---+---+
| E | F | G | H |
+---+---+---+---+
| I | J | K | L |
+---+---+---+---+
| M | N | O | P |
+---+---+---+---+
---+---+---+---+---+
1 | A | B | C | D |
---+---+---+---+---+
2 | E | F | G | H |
---+---+---+---+---+
3 | I | J | K | L |
---+---+---+---+---+
4 | M | N | O | P |
---+---+---+---+---+
| 1 | 2 | 3 | 4 |
---+---+---+---+---+
1 | A | B | C | D |
---+---+---+---+---+
2 | E | F | G | H |
---+---+---+---+---+
3 | I | J | K | L |
---+---+---+---+---+
4 | M | N | O | P |
---+---+---+---+---+
New contributor
Kai B. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4