Python Problem 2
This problem is taken from the game Minesweeper on Windows. The input is a static board of mines and blank locations (* and .)
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.
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
Leave a Reply.