Skip to content

Instantly share code, notes, and snippets.

@domluna
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save domluna/4a7bcaef02feecdde4a3 to your computer and use it in GitHub Desktop.

Select an option

Save domluna/4a7bcaef02feecdde4a3 to your computer and use it in GitHub Desktop.
Matching parens
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