Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Brackets by pburakov
def checkio(expression):
# Opening brackets will be in brackets.values() list
# Closing brackets will be in brackets.keys() list
brackets = {
'}': '{',
')': '(',
']': '['
}
# List in opened brackets in order they're encountered in the string.
# Successfully closed brackets will be deleted from this list
brackets_order = []
expression.split()
for char in expression:
# Bracket was opened
if char in brackets.values():
brackets_order.append(char)
# Bracket was closed
if char in brackets.keys():
if len(brackets_order) > 0 and brackets[char] == brackets_order[-1]:
# Successful closure - delete last used bracket from the list
del brackets_order[-1]
else:
# Exit with False if it's not the same bracket that was opened last
return False
# Making sure no brackets left unclosed
return len(brackets_order) == 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"
Nov. 12, 2015