Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Brackets by marcelina.gorzelana
def checkio(expr):
res = True
br = {'{' : 0, '[' : 1, '(' : 2, '}' : 3, ']' : 4, ')' : 5}
opened = []
op = 0
cl = 0
for symb in expr:
if br.get(symb, 6) < 6:
n = br.get(symb, 6)
if n < 3:
opened.append(symb)
op += 1
else:
if len(opened) > 0:
l = len(opened) - 1
if n%3 == (br.get(opened[l]) % 3):
opened.pop()
cl += 1
else:
res = False
break
else:
if n >=3:
res = False
break
if op < cl:
res = False
break
if op != cl:
res = False
return res
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("((5+3)*2+1)") == True, "Simple"
assert checkio("{[(3+1)+2]+}") == True, "Different types"
assert checkio("(3+{1-1)}") == False, ") is alone inside {}"
assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators"
assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant"
assert checkio("2+3") == True, "No brackets, no problem"
assert checkio("(((1+(1+1))))]") == False, "Last"
Nov. 21, 2016