Skip to content

Instantly share code, notes, and snippets.

@eirenik0
Created April 3, 2014 07:45
Show Gist options
  • Save eirenik0/9949990 to your computer and use it in GitHub Desktop.
Save eirenik0/9949990 to your computer and use it in GitHub Desktop.
The balanced parentheses problem shown above is a specific case of a more general situation that arises in many programming languages. The general problem of balancing and nesting different kinds of opening and closing symbols occurs frequently. For example, in Python square brackets, [ and ], are used for lists; curly braces, { and }, are used …
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()
print(top,symbol,index)
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