Skip to content

Commit

Permalink
Merge pull request #6 from m4tveevm/dev
Browse files Browse the repository at this point in the history
Added check for correctness of bracket sequence
  • Loading branch information
m4tveevm authored Oct 17, 2024
2 parents 0700db9 + 7d2598a commit fb89a11
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 1 deletion.
1 change: 0 additions & 1 deletion .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Shunting Yard/solution.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from algo.LineCheck import is_valid
from algo.Queue import Queue
from algo.Stack import Stack

Expand All @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions Shunting Yard/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, ")(")
18 changes: 18 additions & 0 deletions algo/LineCheck.py
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions algo/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from .Queue import Queue
from .Stack import Stack

# from .LineCheck import is_valid


class TestQueue(unittest.TestCase):
def setup(self):
Expand Down

0 comments on commit fb89a11

Please sign in to comment.