This exercise asked you to refactor this code snippet to refactor (taken from a correct but very repeated solution to exercise 24 on this website):
Hint: Think about a way to refactor this using functions where generating an 8x8 or a 19x19 grid is a single change to a function call!
What we can see right away is the repeated structure of the vertical and horizontal lines. Our strategy therefore is going to be to write one function for the vertical lines, and one function for the horizontal lines.
This way, with these two functions, we can print the grid in a repeatable way for a square grid, just by changing a single variable (grid_size
):
The cool part about this function split is that to make an asymmetrical grid, we instead use two variables grid_size_x
and grid_size_y
to control how many squares in the x
and y
direction we want, without having to change any of our printing code:
prints out:
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
Happy coding!