Skip to content

Instantly share code, notes, and snippets.

@jonathanmarvens
Last active December 11, 2015 05:39
Show Gist options
  • Save jonathanmarvens/4554092 to your computer and use it in GitHub Desktop.
Save jonathanmarvens/4554092 to your computer and use it in GitHub Desktop.
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