ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Sep 21 2020
·
0 comments

Instructions

Test suite

Solution

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

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")
```

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`

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

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.

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
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 copy
def rectangles(strings):
"""
I solve the Ex using dual space (discrete Hough transform)
a rectangle is defined by the top left and bottom right corners denoted:
b,l,t,r
The range of l,r is the length of the string denoted a
The range of b,t is the length of the list of strings, denoted b
so the dual space is a x b x a x b (x - cross-product)
"""
if not strings:
return 0
if not strings[0]:
return 0
sz = (len(strings), len(strings[0]))
dual = create_dual(strings, sz)
rect_counter = count_rectangles(dual, strings, sz)
return rect_counter
def create_dual(strings, sz):
dual = n_dim_list([sz[0], sz[1], sz[0], sz[1]], 0)
for r_i, row in enumerate(strings):
for c_i, v in enumerate(row):
if v == '+':
for b, l, t, r in compute_potential_dual_rectangle(r_i, c_i, sz):
dual[b][l][t][r] += 1
return dual
def count_rectangles(dual, strings, sz):
rect_counter = 0
for b, l, t, r in next_potential_rectangle_from_dual(dual, sz):
rect_counter += verify_rect(strings, b, l, t, r)
return rect_counter
def compute_potential_dual_rectangle(r_0, c_0, sz):
for r_1 in range(sz[0]):
for c_1 in range(sz[1]):
if not (r_1 == r_0 and c_1 == c_0):
left = min(c_0, c_1)
right = max(c_0, c_1)
bottom = min(r_0, r_1)
top = max(r_0, r_1)
yield bottom, left, top, right
def next_potential_rectangle_from_dual(dual, sz):
for bottom in range(sz[0]):
for left in range(sz[1]):
for top in range(sz[0]):
for right in range(sz[1]):
if dual[bottom][left][top][right] == 4:
yield bottom, left, top, right
def verify_rect(strings, bottom, left, top, right):
bott_line = all([c == '+' or c == '-' for c in strings[bottom][left:right + 1]])
top_line = all([c == '+' or c == '-' for c in strings[top][left:right + 1]])
left_line = all([c == '+' or c == '|' for c in [strings[i][left] for i in range(bottom, top + 1)]])
right_line = all([c == '+' or c == '|' for c in [strings[i][right] for i in range(bottom, top + 1)]])
return 1 if all([bott_line, top_line, left_line, right_line]) else 0
def n_dim_list(dims, init_val):
if not dims:
return []
lst = [init_val for _ in range(dims[-1])]
for d in dims[::-1][1::]:
lst = [copy.deepcopy(lst) for _ in range(d)]
return lst
```

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?

Level up your programming skills with 3,443 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments