Last active
November 18, 2019 10:41
-
-
Save gchiam/aef949acfae22e8c7e74b763ad3b6842 to your computer and use it in GitHub Desktop.
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
MAPPING = { | |
'{': '}', | |
'(': ')', | |
'[': ']', | |
} | |
def is_open(c): | |
return c in MAPPING | |
def is_close(c): | |
return c in MAPPING.values() | |
def is_matched(c1, c2): | |
return MAPPING.get(c1) == c2 | |
def func(s, c): | |
if not s: | |
return c | |
if is_open(c): | |
return s + c | |
if is_close(c) and is_matched(s[-1], c): | |
return s[:-1] | |
raise ValueError() | |
def is_matched(s): | |
try: | |
return not bool(reduce(func, s, '')) | |
except ValueError: | |
return False | |
if __name__ == '__main__': | |
valids = ( | |
'', | |
'()', | |
'[]', | |
'{}', | |
'([]{})', | |
'([]{()})', | |
) | |
invalids = ( | |
'(', | |
']', | |
'(()', | |
'([)', | |
'())', | |
'()]', | |
'({}]', | |
) | |
for s in valids: | |
print s, is_matched(s) | |
for s in invalids: | |
print s, is_matched(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment