Created
April 3, 2014 07:45
-
-
Save eirenik0/9949990 to your computer and use it in GitHub Desktop.
The balanced parentheses problem shown above is a specific case of a more general situation that arises in many programming languages. The general problem of balancing and nesting different kinds of opening and closing symbols occurs frequently. For example, in Python square brackets, [ and ], are used for lists; curly braces, { and }, are used …
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
| def parChecker(symbolString): | |
| s = Stack() | |
| balanced = True | |
| index = 0 | |
| while index < len(symbolString) and balanced: | |
| symbol = symbolString[index] | |
| if symbol in "([{": | |
| s.push(symbol) | |
| else: | |
| if s.isEmpty(): | |
| balanced = False | |
| else: | |
| top = s.pop() | |
| print(top,symbol,index) | |
| if not matches(top,symbol): | |
| balanced = False | |
| index = index + 1 | |
| if balanced and s.isEmpty(): | |
| return True | |
| else: | |
| return False | |
| def matches(open,close): | |
| opens = "([{" | |
| closers = ")]}" | |
| return opens.index(open) == closers.index(close) | |
| print(parChecker('{{([][])}()}')) | |
| print(parChecker('[{()]')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment