Last active
August 29, 2015 14:03
-
-
Save s16h/1af01f0c83fa7d439052 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
#!/usr/bin/python | |
def has_balanced_delimiters(string, delimiters={'(': ')', '[': ']', '{': '}'}): | |
""" | |
Parses a string to determine if it contains balanced delimiters. | |
A balanced delimiter string starts with an opening character ((, [, {), ends | |
with a matching closing character (), ], } respectively). A balanced | |
delimiter string may contain any number of balanced delimiters. | |
""" | |
stack = [] | |
for char in string: | |
if char in delimiters: | |
stack.append(char) | |
if char in delimiters.values(): | |
if stack and char == delimiters[stack[-1]]: | |
stack.pop() | |
else: | |
return False | |
return False if stack else True | |
if __name__ == '__main__': | |
strings = [ | |
'(){}', | |
'([{}])', | |
'({})', | |
'([)]', | |
'(', | |
')', | |
'([})', | |
'())', | |
'[(2 + 2) * (42 - 42)] / {3.14}', | |
'[(2 + 2) * (42 - 42)] / {3.14' | |
] | |
for string in strings: | |
print '"{}" {} balanced delimiters'.format( | |
string, 'has' if has_balanced_delimiters(string) else 'does not have') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment