Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Brackets by PythOff
def searchClosing(exp, i, typ):
numTyp = [0, 0, 0]
for j in range (exp.index(i) + 1, len(exp)):
if exp[j] == typ[0]:
if numTyp[0] == 0:
return True
else:
numTyp[0] += 1
elif exp[j] == typ[1]:
if numTyp[1] == 0:
return False
else:
numTyp[1] += 1
elif exp[j] == typ[2]:
if numTyp[2] == 0:
return False
else:
numTyp[2] += 1
elif exp[j] == typ[3]:
numTyp[0] -= 1
elif exp[j] == typ[4]:
numTyp[1] -= 1
elif exp[j] == typ[5]:
numTyp[2] -= 1
return False
def checkio(expression):
numRound = 0
numSquare = 0
numCurly = 0
for i in expression:
if i == '(':
if searchClosing(expression, i, ")]}([{") == False:
return False
numRound += 1
elif i == '[':
if searchClosing(expression, i, "])}[({") == False:
return False
numSquare += 1
elif i == '{':
if searchClosing(expression, i, "}]){[(") == False:
return False
numCurly += 1
elif i == ')':
numRound -= 1
elif i == ']':
numSquare -= 1
elif i == '}':
numCurly -= 1
return (numRound == 0 and numSquare == 0 and numCurly == 0)
#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"
Oct. 21, 2016