'Developing a function to print a grid in python
I Just started programming with python and I've been tasked in printing a grid in python that looks as follows (image is attached). I'm really stumped on how i would achieve this through defining a function:
def display_game(game, grid_size):
The argument (game) is the strings that represent the cells in the game i.e (~), whilst the grid_size represents the size of the grid, i.e 7 would correspond to a 7x7 grid.
I know string splicing, for loops and print statements would be viable, i just don't know how to piece it together.
Any help would be much appreciated, Cheers.
Solution 1:[1]
There you go:
def display_game(game, grid_size):
header_row = ''
row = ''
for x in range(1,grid_size+1):
header_row = header_row + '|' + str(x)
row = row + '|' + game
print(header_row + '|')
print('-' * (len(row)+1))
char = 64
for x in range(1,grid_size+1):
char = char +1
print(chr(char) + row + '|')
display_game('~', 7)
This should give the following output:
Solution 2:[2]
def display_game(game, grid_size):
c = 65
# First row
print(f" ", end='')
for j in range(grid_size):
print(f"| {j+1} ", end='')
print("| ")
print((7*4+4)*"-")
# Other rows
for i in range(grid_size):
print(f"{chr(c+i)} ", end='')
for j in range(grid_size):
print(f"| {game} ", end='')
print("| ")
print((7*4+4)*"-")
display_game('~', 7)
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------
A | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
B | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
C | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
D | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
E | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
F | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
G | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chadee Fouad |
Solution 2 | Freddy Mcloughlan |