DanaFosmer.com
  • Test Engineering
  • Electrical Engineering
  • Projects and Code
  • Archives
  • About

Python Problem 2

12/29/2022

0 Comments

 

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:
Picture
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:
Picture

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:
  1. Read in a string list of lists
  2. Convert the strings to integers to enable the math. So, if there was a period I convert to 0, if there was a * I convert to an 88 as a sentinel value for *. (You can actually mix types in a list in Python, so maybe that was a waste of time)
  3. Then I added a buffer on all sides of the 2D list, such that a 4x4 game board is now 6x6. That way I could iterate through the 2D list and every time I found an 88 call a method to add 1 to every adjacent cell of the table.
  4. Convert the 88s to * and everything to strings in order to write to a file

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
    March 2016
    March 2014
    July 2011

    Categories

    All
    Python

  • Test Engineering
  • Electrical Engineering
  • Projects and Code
  • Archives
  • About