Last active
August 29, 2015 14:07
-
-
Save domluna/4a7bcaef02feecdde4a3 to your computer and use it in GitHub Desktop.
Matching parens
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 match(s, pairs): | |
| stack = [] | |
| closers = set(pairs.values()) | |
| for c in s: | |
| if c in pairs: | |
| stack.append(pairs[c]) | |
| elif c in closers: | |
| # we can end early if either is true | |
| if not stack or c != stack.pop(): | |
| return False | |
| return not stack | |
| # from the example | |
| m = { | |
| '{':'}', | |
| '[':']', | |
| '(': ')' | |
| } | |
| # tests | |
| print match(')()', m) == False | |
| print match('({[]})', m) == True | |
| print match('aaaaaa({[]}aaaaaaaaaaaaaaa)', m) == True | |
| print match('aaaaaa({[]}aaaaaaaaaaaaaaa', m) == False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment