diff --git a/.idea/vcs.xml b/.idea/vcs.xml index dd86497..35eb1dd 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,6 +2,5 @@ - \ No newline at end of file diff --git a/Shunting Yard/solution.py b/Shunting Yard/solution.py index 683e70e..facb0f4 100644 --- a/Shunting Yard/solution.py +++ b/Shunting Yard/solution.py @@ -1,3 +1,4 @@ +from algo.LineCheck import is_valid from algo.Queue import Queue from algo.Stack import Stack @@ -12,6 +13,7 @@ def get_priority(elem): return {"+": 0, "-": 0, "*": 1, "/": 1, "^": 2}.get(elem, -1) def infix_to_postfix(self, line: str): + assert is_valid(line) for elem in line.split(): if elem.isnumeric(): self.__queue.push(elem) diff --git a/Shunting Yard/tests.py b/Shunting Yard/tests.py index 8e61da5..c7fb64d 100644 --- a/Shunting Yard/tests.py +++ b/Shunting Yard/tests.py @@ -41,3 +41,9 @@ def test_algo(self): for expr, expected in test_cases: self.assertEqual(Solution().infix_to_postfix(expr), expected) + + def test_invalid_string(self): + self.assertRaises( + AssertionError, Solution().infix_to_postfix, "(1 + ((2)) /) 52)" + ) + self.assertRaises(AssertionError, Solution().infix_to_postfix, ")(") diff --git a/algo/LineCheck.py b/algo/LineCheck.py new file mode 100644 index 0000000..1866b30 --- /dev/null +++ b/algo/LineCheck.py @@ -0,0 +1,18 @@ +from .Stack import Stack + + +def is_valid(bracket_sequence): + stack = Stack() + brackets_dict = { + "[": "]", + "{": "}", + "(": ")", + } + for bracket in bracket_sequence: + if bracket not in ("[", "{", "(", ")", "}", "]"): + continue + if bracket in brackets_dict: + stack.push(bracket) + elif len(stack) == 0 or bracket != brackets_dict[stack.pop()]: + return False + return len(stack) == 0 diff --git a/algo/tests.py b/algo/tests.py index 0194ea3..a63f9d7 100644 --- a/algo/tests.py +++ b/algo/tests.py @@ -3,6 +3,8 @@ from .Queue import Queue from .Stack import Stack +# from .LineCheck import is_valid + class TestQueue(unittest.TestCase): def setup(self):