🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of d-m-3

d-m-3's solution

to Rectangles in the Python Track

Published at Sep 09 2020 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Count the rectangles in an ASCII diagram like the one below.

   +--+
  ++  |
+-++--+
|  |  |
+--+--+

The above diagram contains 6 rectangles:



+-----+
|     |
+-----+
   +--+
   |  |
   |  |
   |  |
   +--+
   +--+
   |  |
   +--+




   +--+
   |  |
   +--+


+--+
|  |
+--+

  ++
  ++


You may assume that the input is always a proper rectangle (i.e. the length of every line equals the length of the first line).

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 pytest rectangles_test.py

Alternatively, you can tell Python to run the pytest module: python -m pytest rectangles_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/rectangles 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.

rectangles_test.py

import unittest

from rectangles import rectangles

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


class RectanglesTest(unittest.TestCase):
    def test_no_rows(self):
        self.assertEqual(rectangles([]), 0)

    def test_no_columns(self):
        self.assertEqual(rectangles([""]), 0)

    def test_no_rectangles(self):
        self.assertEqual(rectangles([" "]), 0)

    def test_one_rectangle(self):
        self.assertEqual(rectangles(["+-+", "| |", "+-+"]), 1)

    def test_two_rectangles_without_shared_parts(self):
        self.assertEqual(rectangles(["  +-+", "  | |", "+-+-+", "| |  ", "+-+  "]), 2)

    def test_five_rectangles_with_shared_parts(self):
        self.assertEqual(rectangles(["  +-+", "  | |", "+-+-+", "| | |", "+-+-+"]), 5)

    def test_rectangle_of_height_1_is_counted(self):
        self.assertEqual(rectangles(["+--+", "+--+"]), 1)

    def test_rectangle_of_width_1_is_counted(self):
        self.assertEqual(rectangles(["++", "||", "++"]), 1)

    def test_1x1_square_is_counted(self):
        self.assertEqual(rectangles(["++", "++"]), 1)

    def test_only_complete_rectangles_are_counted(self):
        self.assertEqual(rectangles(["  +-+", "    |", "+-+-+", "| | -", "+-+-+"]), 1)

    def test_rectangles_can_be_of_different_sizes(self):
        self.assertEqual(
            rectangles(
                [
                    "+------+----+",
                    "|      |    |",
                    "+---+--+    |",
                    "|   |       |",
                    "+---+-------+",
                ]
            ),
            3,
        )

    def test_corner_is_required_for_a_rectangle_to_be_complete(self):
        self.assertEqual(
            rectangles(
                [
                    "+------+----+",
                    "|      |    |",
                    "+------+    |",
                    "|   |       |",
                    "+---+-------+",
                ]
            ),
            2,
        )

    def test_large_input_with_many_rectangles(self):
        self.assertEqual(
            rectangles(
                [
                    "+---+--+----+",
                    "|   +--+----+",
                    "+---+--+    |",
                    "|   +--+----+",
                    "+---+--+--+-+",
                    "+---+--+--+-+",
                    "+------+  | |",
                    "          +-+",
                ]
            ),
            60,
        )


if __name__ == "__main__":
    unittest.main()
import itertools

def rectangles(strings):
    plus_positions = {}
    for line_nb, line in enumerate(strings):
        plus_positions[line_nb] = []
        for i, char in enumerate(line):
            if char == "+":
                plus_positions[line_nb].append(i)
    count = 0
    for l1, l2 in itertools.combinations(plus_positions.keys(), 2):
        intersection = list(set(plus_positions[l1]).intersection(plus_positions[l2]))
        for c1, c2 in itertools.combinations(intersection, 2):
            count += is_complete_rectangle(strings, l1, l2, c1, c2)
    return count

def is_complete_rectangle(strings, l1, l2, c1, c2):
    # Check the two horizontal lines of the rectangle
    for char in (strings[l1][c1 + 1:c2] + strings[l2][c1 + 1:c2]):
        if not (char == "-" or char == "+"):
            return False
    # Check the two vertical lines of the rectangle
    for row in strings[l1 + 1:l2]:
        if not (row[c1] == "|" or row[c1] == "+") or not (row[c2] == "|" or row[c2] == "+"):
            return False
    return True

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?