Created
March 7, 2017 02:48
-
-
Save pansapiens/090ba41cc0d853558fa51d93857be2d6 to your computer and use it in GitHub Desktop.
Check that brackets are balanced
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
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