-
-
Save anfedorov/9eca3dc5676578d81297 to your computer and use it in GitHub Desktop.
This file contains 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 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