Created
February 18, 2019 10:21
-
-
Save dolohow/32e570564c95e2262389bdba6da9e714 to your computer and use it in GitHub Desktop.
Parenthesis parser
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
def parse(string): | |
tokens = [] | |
for char in string: | |
try: | |
if char == '(': | |
tokens.append('(') | |
elif char == '[': | |
tokens.append('[') | |
elif char == ']': | |
if tokens.pop() != '[': | |
return False | |
elif char == ')': | |
if tokens.pop() != '(': | |
return False | |
except IndexError: | |
return False | |
return not len(tokens) | |
assert(parse('()')) | |
assert(parse('()()')) | |
assert(parse('(())')) | |
assert(not parse('((())')) | |
assert(not parse('((]))')) | |
assert(parse('(([]))')) | |
assert(not parse('(([))]')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment