Skip to content

Instantly share code, notes, and snippets.

@gchiam
Last active November 18, 2019 10:41
Show Gist options
  • Save gchiam/aef949acfae22e8c7e74b763ad3b6842 to your computer and use it in GitHub Desktop.
Save gchiam/aef949acfae22e8c7e74b763ad3b6842 to your computer and use it in GitHub Desktop.
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