Skip to content

Instantly share code, notes, and snippets.

@anfedorov
Last active August 29, 2015 14:03
Show Gist options
  • Save anfedorov/9eca3dc5676578d81297 to your computer and use it in GitHub Desktop.
Save anfedorov/9eca3dc5676578d81297 to your computer and use it in GitHub Desktop.
def verify_balanced(s):
"""Verifies that all '{', '[', and '(' characters have closing partners.
Returns:
the index of an out of first unbalanced character or `None`
Doctests:
>>> verify_balanced('asdf (foo) [bar] [[baz], {}, ()]')
None
>>> verify_balanced('asdf )foo [bar] [[baz], {}, ()]')
5
"""
opening = '{[('
closing = '}])'
stack = []
for i, c in enumerate(s):
if c in opening:
stack.append((i, opening.index(c)))
elif c in closing:
if len(stack) == 0:
return i
j, x = stack.pop()
if x != closing.index(c):
return j
if len(stack) > 0:
j, x = stack.pop()
return j
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment