Skip to content

Instantly share code, notes, and snippets.

@hillscottc
Created May 31, 2014 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hillscottc/c6bc47eff9e6cd2bc731 to your computer and use it in GitHub Desktop.
Save hillscottc/c6bc47eff9e6cd2bc731 to your computer and use it in GitHub Desktop.
Stack to balance brackets.
from pythonds.basic.stack import Stack
def parChecker(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in "([{":
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
top = s.pop()
if not matches(top,symbol):
balanced = False
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
def matches(open,close):
opens = "([{"
closers = ")]}"
return opens.index(open) == closers.index(close)
print(parChecker('{{([][])}()}'))
print(parChecker('[{()]'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment