Avatar of mike-cramblett

mike-cramblett's solution

to Go Counting in the Python Track

Published at Jan 22 2019 · 0 comments
Instructions
Test suite
Solution

Count the scored points on a Go board.

In the game of go (also known as baduk, igo, cờ vây and wéiqí) points are gained by completely encircling empty intersections with your stones. The encircled intersections of a player are known as its territory.

Write a function that determines the territory of each player. You may assume that any stones that have been stranded in enemy territory have already been taken off the board.

Write a function that determines the territory which includes a specified coordinate.

Multiple empty intersections may be encircled at once and for encircling only horizontal and vertical neighbours count. In the following diagram the stones which matter are marked "O" and the stones that don't are marked "I" (ignored). Empty spaces represent empty intersections.

+----+
|IOOI|
|O  O|
|O OI|
|IOI |
+----+

To be more precise an empty intersection is part of a player's territory if all of its neighbours are either stones of that player or empty intersections that are part of that player's territory.

For more information see wikipedia or Sensei's Library.

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run the appropriate command below (why they are different):

  • Python 2.7: py.test go_counting_test.py
  • Python 3.4+: pytest go_counting_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest go_counting_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/go-counting directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see Running the Tests.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

go_counting_test.py

import unittest
import go_counting


# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0

board5x5 = [
    "  B  ",
    " B B ",
    "B W B",
    " W W ",
    "  W  "
]


class GoCountingTest(unittest.TestCase):
    def test_black_corner_territory_on_5x5_board(self):
        board = go_counting.Board(board5x5)
        stone, territory = board.territory(x=0, y=1)
        self.assertEqual(stone, go_counting.BLACK)
        self.assertSetEqual(territory, {(0, 0), (0, 1), (1, 0)})

    def test_white_center_territory_on_5x5_board(self):
        board = go_counting.Board(board5x5)
        stone, territory = board.territory(x=2, y=3)
        self.assertEqual(stone, go_counting.WHITE)
        self.assertSetEqual(territory, {(2, 3)})

    def test_open_corner_territory_on_5x5_board(self):
        board = go_counting.Board(board5x5)
        stone, territory = board.territory(x=1, y=4)
        self.assertEqual(stone, go_counting.NONE)
        self.assertSetEqual(territory, {(0, 3), (0, 4), (1, 4)})

    def test_a_stone_and_not_a_territory_on_5x5_board(self):
        board = go_counting.Board(board5x5)
        stone, territory = board.territory(x=1, y=1)
        self.assertEqual(stone, go_counting.NONE)
        self.assertSetEqual(territory, set())

    def test_invalid_because_x_is_too_low(self):
        board = go_counting.Board(board5x5)
        with self.assertRaisesWithMessage(ValueError):
            board.territory(x=-1, y=1)

    def test_invalid_because_x_is_too_high(self):
        board = go_counting.Board(board5x5)
        with self.assertRaisesWithMessage(ValueError):
            board.territory(x=5, y=1)

    def test_invalid_because_y_is_too_low(self):
        board = go_counting.Board(board5x5)
        with self.assertRaisesWithMessage(ValueError):
            board.territory(x=1, y=-1)

    def test_invalid_because_y_is_too_high(self):
        board = go_counting.Board(board5x5)
        with self.assertRaisesWithMessage(ValueError):
            board.territory(x=1, y=5)

    def test_one_territory_is_the_whole_board(self):
        board = go_counting.Board([" "])
        territories = board.territories()
        self.assertSetEqual(territories[go_counting.BLACK], set())
        self.assertSetEqual(territories[go_counting.WHITE], set())
        self.assertSetEqual(territories[go_counting.NONE], {(0, 0)})

    def test_two_territories_rectangular_board(self):
        input_board = [
            " BW ",
            " BW "
        ]
        board = go_counting.Board(input_board)
        territories = board.territories()
        self.assertSetEqual(territories[go_counting.BLACK], {(0, 0), (0, 1)})
        self.assertSetEqual(territories[go_counting.WHITE], {(3, 0), (3, 1)})
        self.assertSetEqual(territories[go_counting.NONE], set())

    def test_two_region_rectangular_board(self):
        input_board = [" B "]
        board = go_counting.Board(input_board)
        territories = board.territories()
        self.assertSetEqual(territories[go_counting.BLACK], {(0, 0), (2, 0)})
        self.assertSetEqual(territories[go_counting.WHITE], set())
        self.assertSetEqual(territories[go_counting.NONE], set())

    # Utility functions
    def setUp(self):
        try:
            self.assertRaisesRegex
        except AttributeError:
            self.assertRaisesRegex = self.assertRaisesRegexp

    def assertRaisesWithMessage(self, exception):
        return self.assertRaisesRegex(exception, r".+")


if __name__ == '__main__':
    unittest.main()
WHITE, BLACK, EMPTY, NONE = 'W','B','E',''
class Board:
    """Count territories of each player in a Go game

    Args:
        board (list[str]): A two-dimensional Go board
    """

    def __init__(self, board):
        self.board = board
        self.players = [BLACK,WHITE,EMPTY]
        self.piece_list = dict(zip(self.players,[[],[],[]]))
        self.max_y = len(self.board) -1
        self.max_x = len(self.board[0]) -1
        
        for j,row in enumerate(self.board):
            for i, piece in enumerate(row):
                if piece == ' ':
                        self.piece_list[EMPTY].append((i,j))
                else:        
                    for player in self.players[:2]:
                        if piece == player:
                            self.piece_list[player].append((i,j))
                            

    def territory(self, x, y):
        """Find the owner and the territories given a coordinate on
           the board

        Args:
            x (int): Column on the board
            y (int): Row on the board

        Returns:
            (str, set): A tuple, the first element being the owner
                        of that area.  One of "W", "B", "".  The
                        second being a set of coordinates, representing
                        the owner's territories.
        """
        found = []
        owner  = NONE
        
        if x > self.max_x or y > self.max_y or x < 0 or y < 0:
            raise ValueError("Bad point {},{}".format(x,y))

        point = (x,y)
        checking = []
        
        if point in self.piece_list[EMPTY]:
            checking.append(point)
            owners = []
            already_checked = []
            while len(checking) > 0:
                
                check = checking.pop(0)
                found.append(check)
                owners_found, to_check = self.check_directions(check[0],check[1])
                already_checked.append(check)
                
                owners += owners_found
                for possible in to_check:
                    if possible not in already_checked:
                        checking.append(possible)

            if len(set(owners)) == 1:
                owner = owners[0]
        
        
        return (owner,set(found))


    def check_directions(self,x,y):
        directions = [(0,1),(1,0),(0,-1),(-1,0)]
        emptys = []
        owners = []
        for (x_d,y_d) in directions:
            check_point = (x+x_d,y+y_d)
            if 0 <= check_point[0] <= self.max_x and 0 <= check_point[1] <= self.max_y:
                if check_point in self.piece_list[EMPTY]:
                    emptys.append(check_point)
                else:
                    for player in self.players[:2]:
                        if check_point in self.piece_list[player]:
                            owners.append(player)
        return (owners,emptys)


    def territories(self):
        """Find the owners and the territories of the whole board

        Args:
            none

        Returns:
            dict(str, set): A dictionary whose key being the owner
                        , i.e. "W", "B", "".  The value being a set
                        of coordinates owned by the owner.
        """
        return_keys = self.players[:2]+[NONE]
        return_terrs = dict(zip(return_keys,[[],[],[]]))
        
        for empty in self.piece_list[EMPTY]:
            owner, terr_found = self.territory(empty[0],empty[1])
            return_terrs[owner].append(empty)
        
        for player in return_keys:
            return_terrs[player] = set(return_terrs[player])

        return return_terrs

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?