Problem Description
This problem is taken from the game Minesweeper on Windows. The input is a static board of mines and blank locations (* and .)
Like this:
The objective is to create an output file with the same game board only with the blanks replaced with a count of the adjacent count.
Like this: Solution
I think the intention of this problem was to solve a 2D array problem. Well, there's not really arrays in Python, so I used a list of lists. (Lists are pretty much arrays)
The tricky thing about this problem was thinking of a way to iterate the list and perform the calculation without writing out of bounds. Here's how I did it:
Couple things, I used list comprehensions to initialize the list of empty lists like this: self.game_space = [[] for i in range(self.rows)]
Then I could just append to the lists like this and didn't need to know the number of columns of the game board to do it.
This is the more Pythonic way to do this (I think). Adding the index variable and enumerate keyword allows using the lists as iterators in the for loops. You could use nested for loops with counters like i and j along with the range() function. That would look more like C++ but is not the thing. (I guess I could have skipped the elif part, but I like how this reads) def process_gameboard(self, input_game): #convert strings to ints, use 88 as the sentinal for * for index, row in enumerate(input_game): for char in row: if char == "*": self.game_space[index].append(88) elif char == ".": self.game_space[index].append(0) else: None
See the full code on my Github
0 Comments
Leave a Reply. |
Archives
December 2022
Categories |