Avatar of siebenschlaefer

siebenschlaefer's solution

to Go Counting in the Python Track

Published at Mar 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()
BLACK, WHITE, NONE = 'B', 'W', ''


class Board:
    def __init__(self, board):
        self.board = board

    def territory(self, x, y):
        is_valid = lambda x, y: \
            0 <= y < len(self.board) and 0 <= x < len(self.board[y])
        if not is_valid(x, y):
            raise ValueError('out of range')
        if self.board[y][x] in (BLACK, WHITE):
            return (NONE, set())
        owner = set()
        stack = [(x, y)]
        territory = set(stack)
        while stack:
            x, y = stack.pop()
            for x, y in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
                if not is_valid(x, y):
                    continue
                if self.board[y][x] in (BLACK, WHITE):
                    owner.add(self.board[y][x])
                elif (x, y) not in territory:
                    stack.append((x, y))
                    territory.add((x, y))
        return (owner.pop() if len(owner) == 1 else NONE, territory)

    def territories(self):
        result = {owner: set() for owner in (BLACK, WHITE, NONE)}
        for y in range(len(self.board)):
            for x in range(len(self.board[y])):
                owner, territory = self.territory(x, y)
                result[owner].update(territory)
        return result

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?