Last active
December 11, 2015 05:39
-
-
Save jonathanmarvens/4554092 to your computer and use it in GitHub Desktop.
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 isBalanced (string): | |
if isinstance(string, basestring) is False: | |
return True | |
STRUCTURE_OPN = 1 | |
STRUCTURE_CLS = 2 | |
structures = { | |
'(': (')', STRUCTURE_OPN), | |
')': ('(', STRUCTURE_CLS), | |
'[': (']', STRUCTURE_OPN), | |
']': ('[', STRUCTURE_CLS), | |
'{': ('}', STRUCTURE_OPN), | |
'}': ('{', STRUCTURE_CLS), | |
} | |
structure_stack = [] | |
string_length = len(string) | |
for i in range(string_length): | |
if string[i] in structures: | |
structure = string[i] | |
if structures[structure][1] is STRUCTURE_OPN: | |
structure_stack.append(structure) | |
elif structures[structure][1] is STRUCTURE_CLS: | |
if len(structure_stack) is not 0: | |
if structure_stack.pop() != structures[structure][0]: | |
return False | |
else: | |
return False | |
return (len(structure_stack) is 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment