Skip to content

Instantly share code, notes, and snippets.

@kosugi
Created February 14, 2014 19:13
Show Gist options
  • Select an option

  • Save kosugi/9007121 to your computer and use it in GitHub Desktop.

Select an option

Save kosugi/9007121 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# http://www.checkio.org/mission/brackets/
# 普通こうでは!?
from itertools import dropwhile
pairs = '{} [] ()'.split()
def parse_term(s):
t = ''.join(dropwhile(str.isdigit, s))
if s != t:
return t
for pair in pairs:
if t[0] == pair[0]:
t = parse_expr(t[1:])
if t[0] == pair[1]:
return t[1:]
raise Exception('term')
def parse_expr(s):
s = parse_term(s)
while True:
if s == '' or s[0] not in '+-/*':
return s
s = parse_term(s[1:])
def checkio(s):
try:
if '' == parse_expr(s):
return True
except:
pass
return False
checkio("((5+3)*2+1)") == True
checkio("{[(3+1)+2]+}") == False
checkio("(3+{1-1)}") == False
checkio("[1+1]+(2*2)-{3/3}") == True
checkio("(({[(((1)-2)+3)-3]/3}-3)") == False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment