Avatar of booji

booji's solution

to Go Counting in the Python Track

Published at Jun 01 2019 · 0 comments
Test suite

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.

|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.


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):
        except AttributeError:
            self.assertRaisesRegex = self.assertRaisesRegexp

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

if __name__ == '__main__':
import itertools
from collections import defaultdict

NONE = ''

class Board:
    """Count territories of each player in a Go game

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

    def __init__(self, board):
        self.board = [list(row) for row in board]
        self.row = len(self.board)
        self.col = len(self.board[0])

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

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

            (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.
        if 0 > x or x > self.col-1:
            raise ValueError("Position needs to be inside board dimensions")
        if 0 > y or y > self.row-1:
            raise ValueError("Position needs to be inside board dimensions")

        if self.board[y][x] != " ":
            return NONE, set()

        unchecked = [(x,y)]
        visited = []
        territory = set()
        border_stones = set()
        while unchecked:
            pos = unchecked.pop()
            for nx,ny in [(-1,0),(1,0),(0,-1),(0,1)]:
                nx, ny = pos[0]+nx,pos[1]+ny
                if (nx,ny) in visited or nx < 0 or ny < 0 or nx > self.col-1 or ny > self.row-1:
                if self.board[ny][nx] == " ":

        if len(border_stones) != 1:
            return NONE, territory

        if stone == 'B':
            return BLACK, territory
        elif stone == 'W':
            return WHITE, territory
            raise ValueError('Wrong board markings')

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


            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.
        visited = set()
        res = {NONE: set(), WHITE: set(), BLACK: set()}
        for x,y in itertools.product(range(self.col),range(self.row)):
            if self.board[y][x] == " " and (x,y) not in visited:
                stone, territory = self.territory(x,y)

        return res

    def __str__(self):
        res = '\n'
        for key, value in territories.items():
            if key == NONE:
                key = ' '
            elif key == WHITE:
                key = '□'
            elif key == BLACK:
                key = "■"
            for x,y in value:
        for x,y in itertools.product(range(self.col),range(self.row)):
            if board[y][x] == 'W':
                board[y][x] = '○'
            elif board[y][x] == 'B':
                board[y][x] = '●'

        res +=  '  │'+('│').join([str(i).zfill(2) for i in range(self.col)])+'│\n'
        res += ('──'+'┼──'*(self.col)+'┤\n')
        for i,row in enumerate(board):
            res += f'{i:02d}│ ' + ('│ ').join(row) + '│'
            if i == len(board)-1:
                res += '\n──'+'┴──'*(self.col)+'┘\n'
                res += '\n──'+'┼──'*(self.col)+'┤\n'
        res += f"Black: {len(territories[BLACK])}\n"
        res += f"White: {len(territories[WHITE])}\n"
        return res

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?