Skip to content

Instantly share code, notes, and snippets.

@praveenvvstgy
Created November 10, 2014 12:16
Show Gist options
  • Save praveenvvstgy/34dc2a771501c30bc78f to your computer and use it in GitHub Desktop.
Save praveenvvstgy/34dc2a771501c30bc78f to your computer and use it in GitHub Desktop.
Check for balanced parentheses in an expression
def braces_validator(string):
openers = "({["
closers = ")}]"
stack = []
for char in string:
if char in openers:
stack.append(openers.index(char))
elif char in closers:
if len(stack) == 0 or stack.pop() != closers.index(char):
return False
return len(stack) == 0
# Testing
print braces_validator("(((((({ [ ] ( ) }")
print braces_validator("{ [ ( ] ) }))))))")
print braces_validator("")
print braces_validator("({[]})")
print braces_validator("({[]})]")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment