Avatar of ubalot

ubalot's solution

to Go Counting in the Python Track

Published at Jan 08 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()
from typing import Dict, Iterable, List, Set, Tuple

BLACK = 'B'
WHITE = 'W'
NONE = ' '


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

    Args:
        board (list[str]): a 2-dimensional Go board
    """

    def __init__(self, board: List[str]):
        self.board: List[str] = board
        self.width: int = len(board)
        self.height: int = len(board[0])

        positions: Set[Tuple[int, int, str]] = set(self._enumerate_board())
        b_positions: Set[Tuple[int, int]] = self.create_player_positions(positions, BLACK)
        w_positions: Set[Tuple[int, int]] = self.create_player_positions(positions, WHITE)
        all_positions: Set[Tuple[int, int]] = set((x, y) for x, y, _ in positions)
        n_positions: Set[Tuple[int, int]] = all_positions - b_positions - w_positions
        self._players_positions = {
            BLACK: b_positions,
            WHITE: w_positions,
            NONE: n_positions
        }

        self._n_forest: List[Set[Tuple[int, int]]] = self._get_none_forest(n_positions)
        self._territories_map: List[Tuple[Set[Tuple[int, int]], str]] = self._map_territories()
        self._players_map: Dict[str, Set[Tuple[int, int]]] = self._create_players_map()

    def territory(self, x: int, y: int) -> Tuple[str, set]:
        """ Find the owner and the territories given a coordinate on
            the board. """
        if x < 0 or y < 0 or x >= self.height or y >= self.width:
            raise ValueError(f"Wrong input: cell ({x}, {y}) doesn't exists.")

        position: Tuple[int, int] = (x, y)
        for positions, player in self._territories_map:
            if position in positions:
                return player, positions
        return NONE, set()

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

    def _enumerate_board(self) -> Tuple[int, int, chr]:
        """ Return each cell coordinates and content. """
        yield from ((x, y, c) for y, row in enumerate(self.board) for x, c in enumerate(row))

    @staticmethod
    def create_player_positions(positions: List[Tuple[int, int, chr]],
                                player_char: chr) -> Set[Tuple[int, int]]:
        """ Return all positions for a given player. """
        return set((x, y) for x, y, c in positions if c == player_char)

    def _possible_neighbours(self, position: Tuple[int, int]) -> Tuple[int, int]:
        """ Return all cells that are near to the given one. """
        p_x, p_y = position

        if p_y - 1 >= 0:
            yield p_x, p_y - 1
        if p_x - 1 >= 0:
            yield p_x - 1, p_y
        if p_x + 1 < self.height:
            yield p_x + 1, p_y
        if p_y + 1 < self.width:
            yield p_x, p_y + 1

    def _get_none_forest(self,
                         none_positions: Iterable[Tuple[int, int]]) -> List[Set[Tuple[int, int]]]:
        """ Given a set of positions, return a forest of positions that are in the same area. """
        n_positions: List[Tuple[int, int]] = sorted(list(none_positions))
        forest: List[List[Tuple[int, int]]] = []

        while n_positions:
            position = n_positions.pop(0)
            inserted = False
            for group in forest:
                for elem in group:
                    if position in self._possible_neighbours(elem):
                        group.append(position)
                        inserted = True
            if not inserted:
                forest.append([position])
        return [set(group) for group in forest]

    def _map_territories(self) -> List[Tuple[Set[Tuple[int, int]], str]]:
        """ Return group of territories (as set of tuples) with the owner (as string). """
        territories_map: List[Tuple[Set[Tuple[int, int]], str]] = []

        for group in self._n_forest:
            border = []

            for position in group:
                possible_neighbours: List[Tuple[int, int]] = (
                    list(self._possible_neighbours(position)))
                for pos in self._players_positions[BLACK]:
                    if pos in possible_neighbours:
                        border.append(BLACK)
                for pos in self._players_positions[WHITE]:
                    if pos in possible_neighbours:
                        border.append(WHITE)

            if WHITE in border and BLACK in border:
                territories_map.append((group, NONE))
            elif WHITE in border:
                territories_map.append((group, WHITE))
            elif BLACK in border:
                territories_map.append((group, BLACK))
            else:
                territories_map.append((group, NONE))

        return territories_map

    def _create_players_map(self) -> Dict[str, Set[Tuple[int, int]]]:
        """ Return a dictionary with players as keys and all the territories owned as values """
        players_map: Dict[str, Set[Tuple[int, int]]] = {
            BLACK: set(),
            WHITE: set(),
            NONE: set()
        }

        for positions, player in self._territories_map:
            if player == BLACK:
                players_map[BLACK] |= positions
            elif player == WHITE:
                players_map[WHITE] |= positions
            elif player == NONE:
                players_map[NONE] |= positions

        return players_map

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?