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

myFirstCode's solution

to Rectangles in the Python Track

Published at Aug 24 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()
# A Python program to print all
# combinations of given length
from itertools import combinations


class Rectangle:
    """
    A---B
    |   |
    C---D
    """

    def __init__(self, dots: tuple):
        self.D: list = max(dots)
        self.A: list = min(dots)
        self.B: list = self.__find_b(dots)
        self.C: list = self.__find_c(dots)

    def __find_b(self, dots: tuple) -> list:
        for dot in dots:
            if self.A[0] == dot[0] and \
                    self.A[1] < dot[1] and \
                    self.D[1] == dot[1]:
                return dot

    def __find_c(self, dots: tuple) -> list:
        for dot in dots:
            if self.D[0] == dot[0] and \
                    self.D[1] > dot[1] and \
                    self.A[1] == dot[1]:
                return dot

    def __eq__(self, other):
        return self.A == other.A and \
               self.B == other.B and \
               self.C == other.C and \
               self.D == other.D

    @staticmethod
    def is_rectangle(dots: tuple, strings: list) -> bool:

        rec = list()
        D: list = max(dots)
        A: list = min(dots)
        if A[0] == D[0] or A[1] == D[1]:
            return False

        rec.append(D)
        rec.append(A)

        # find B
        for dot in dots:
            if A[0] == dot[0] and \
                    A[1] < dot[1] and \
                    D[1] == dot[1] and \
                    dot not in rec:
                B = dot
                rec.append(dot)

        # find C
        for dot in dots:
            if D[0] == dot[0] and \
                    D[1] > dot[1] and \
                    A[1] == dot[1] and \
                    dot not in rec:
                C = dot
                rec.append(dot)

        # true rectangle has 4 corners/dots only
        if len(rec) != 4:
            return False

        # vertical lines should be consist of '+'/'|' only
        for row in strings[A[0] + 1: C[0]]:
            if row[A[1]] == ' ' or \
                    row[B[1]] == ' ' or \
                    row[A[1]] == '-' or \
                    row[B[1]] == '-':
                return False

        # horizontal line should be consist of '+'/'-' only
        for c in strings[A[0]][A[1]: B[1]]:
            if c == ' ':
                return False

        # horizontal line should be consist of '+'/'-' only
        for d in strings[C[0]][C[1]: D[1]]:
            if d == ' ':
                return False

        return True


def rectangles(strings: list) -> int:
    """
    Count the rectangles in an ASCII diagram

    :param strings: ASCII diagram
    :return: rectangles counter
    """

    all_rectangles = list()
    # get all coordinates for possible rectangle angle/dot (dot == '+')
    all_dots = list()
    for i_row, row in enumerate(strings):
        for i_col, col in enumerate(row):
            if col == '+':
                all_dots.append([i_row, i_col])

    # get all possible combinations of 4 dots
    comb = combinations(all_dots, 4)

    # check if combination is true rectangle
    for c in comb:
        flag = Rectangle.is_rectangle(c, strings)
        if flag:
            r = Rectangle(c)
            if r not in all_rectangles:
                all_rectangles.append(r)

    # count total rectangles and return the number
    return len(all_rectangles)

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?