Created
October 12, 2013 09:46
-
-
Save cldotdev/6948045 to your computer and use it in GitHub Desktop.
Code Fragment 6.4: Function for matching delimiters in an arithmetic expression.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| class Empty(Exception): | |
| pass | |
| class ArrayStack: | |
| def __init__(self): | |
| self._data = [] | |
| def __len__(self): | |
| return len(self._data) | |
| def is_empty(self): | |
| return len(self._data) == 0 | |
| def push(self, e): | |
| self._data.append(e) | |
| def top(self): | |
| if self.is_empty(): | |
| raise Empty('Stack is empty') | |
| return self._data[-1] | |
| def pop(self): | |
| if self.is_empty(): | |
| raise Empty('Stack is empty') | |
| return self._data.pop() | |
| def is_matched(expr): | |
| lefty = '({[' | |
| righty = ')}]' | |
| S = ArrayStack() | |
| for c in expr: | |
| if c in lefty: | |
| S.push(c) | |
| elif c in righty: | |
| if S.is_empty(): | |
| return False | |
| if righty.index(c) != lefty.index(S.pop()): | |
| return False | |
| return S.is_empty() | |
| print(is_matched('{[()]}')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment