Skip to content

Instantly share code, notes, and snippets.

@pansapiens
Created March 7, 2017 02:48
Show Gist options
  • Save pansapiens/090ba41cc0d853558fa51d93857be2d6 to your computer and use it in GitHub Desktop.
Save pansapiens/090ba41cc0d853558fa51d93857be2d6 to your computer and use it in GitHub Desktop.
Check that brackets are balanced
friend = {'}':'{', ']':'[', ')':'('}
close = friend.keys()
open = friend.values()
def check(input):
stack = []
for c in input:
if c in open:
stack.append(c)
elif c in close:
if len(stack) > 0 and stack.pop() == friend[c]:
continue
else:
return False
return len(stack) == 0
assert check('()') == True
assert check('[()]') == True
assert check('[(])') == False
assert check("(a)") == True
assert check("(sdfas") == False
assert check("7(z)))") == False
assert check('{thi(s[is]some)stuff}') == True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment