Created
May 31, 2014 15:08
-
-
Save hillscottc/c6bc47eff9e6cd2bc731 to your computer and use it in GitHub Desktop.
Stack to balance brackets.
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
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