Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Matching Brackets in the Python Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Given a string containing brackets [], braces {}, parentheses (), or any combination thereof, verify that any and all pairs are matched and nested correctly.

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 matching_brackets_test.py

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

Source

Ginna Baker

Submitting Incomplete Solutions

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

matching_brackets_test.py

import unittest

from matching_brackets import is_paired

# Tests adapted from `problem-specifications//canonical-data.json` @ v2.0.0


class MatchingBracketsTest(unittest.TestCase):
    def test_paired_square_brackets(self):
        self.assertEqual(is_paired("[]"), True)

    def test_empty_string(self):
        self.assertEqual(is_paired(""), True)

    def test_unpaired_brackets(self):
        self.assertEqual(is_paired("[["), False)

    def test_wrong_ordered_brackets(self):
        self.assertEqual(is_paired("}{"), False)

    def test_wrong_closing_bracket(self):
        self.assertEqual(is_paired("{]"), False)

    def test_paired_with_whitespace(self):
        self.assertEqual(is_paired("{ }"), True)

    def test_partially_paired_brackets(self):
        self.assertEqual(is_paired("{[])"), False)

    def test_simple_nested_brackets(self):
        self.assertEqual(is_paired("{[]}"), True)

    def test_several_paired_brackets(self):
        self.assertEqual(is_paired("{}[]"), True)

    def test_paired_and_nested_brackets(self):
        self.assertEqual(is_paired("([{}({}[])])"), True)

    def test_unopened_closing_brackets(self):
        self.assertEqual(is_paired("{[)][]}"), False)

    def test_unpaired_and_nested_brackets(self):
        self.assertEqual(is_paired("([{])"), False)

    def test_paired_and_wrong_nested_brackets(self):
        self.assertEqual(is_paired("[({]})"), False)

    def test_paired_and_incomplete_brackets(self):
        self.assertEqual(is_paired("{}["), False)

    def test_too_many_closing_brackets(self):
        self.assertEqual(is_paired("[]]"), False)

    def test_math_expression(self):
        self.assertEqual(is_paired("(((185 + 223.85) * 15) - 543)/2"), True)

    def test_complex_latex_expression(self):
        self.assertEqual(
            is_paired(
                "\left(\begin{array}{cc} \frac{1}{3} & x\\ \mathrm{e}^{x} &... x^2 \end{array}\right)"
            ),
            True,
        )


if __name__ == "__main__":
    unittest.main()
def is_empty(stack):
    return stack == []

class CheckBrackets:
    BRACKETS = {'{': '}',
               '[': ']',
               '(': ')'}
    OPENING_BRACKET = set(BRACKETS.keys())
    CLOSING_BRACKET = set(BRACKETS.values())

    def __init__(self, inp):
        self.inp = inp

    def is_paired(self):
        stack = []
        for bracket in self.get_brackets(self.inp):
            if self.is_opening_bracket(bracket):
                stack.append(bracket)
            elif self.is_closing_bracket(bracket) and self.closes_existing_bracket(bracket, stack):
                stack.pop()
            else:
                return False # This is an invalid closing bracket

        return is_empty(stack) # There are more open brackets left to close

    def closes_existing_bracket(self, char, stack):
        return stack and self.matching_brackets(stack[-1], char)

    def matching_brackets(self, opener, closer):
        return self.BRACKETS[opener] == closer

    def get_brackets(self, string):
        return [char for char in string if self.is_bracket(char)]

    def is_opening_bracket(self, bracket):
        return bracket in self.OPENING_BRACKET

    def is_closing_bracket(self, bracket):
        return bracket in self.CLOSING_BRACKET

    def is_bracket(self, char):
        return self.is_opening_bracket(char) or self.is_closing_bracket(char)


def is_paired(inp):
    return CheckBrackets(inp).is_paired()

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of cjchallis

Interesting to frame it in terms of a class.

I think you can gain some clarity but splitting up lines 15-16, and you can eliminate lines 17 and 18 by refactoring. I would make line 15 simply if char in self.CLOSERS:, which echoes line 13 and thus clearly organizes the code into the two important cases. Then, in line 16 check for if not stack or not self.corresponding_brackets(stack.pop(), char)) and return False if either condition is met.

This will also generalize the code to ignore non-bracket characters, so a test of 3 * (5+4) will pass.

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?