python-checkio/ElectronicStation/brackets.py

29 lines
1.2 KiB
Python
Raw Normal View History

2020-01-02 17:30:27 +01:00
def checkio(expression):
OPENING_BRACKETS = ["(", "[", "{"]
CLOSING_BRACKETS = [")", "]", "}"]
current_bracket = []
for letter in expression:
if letter in CLOSING_BRACKETS:
if len(current_bracket) == 0:
return False
else:
last_bracket = current_bracket[-1:][0]
if OPENING_BRACKETS.index(last_bracket) == CLOSING_BRACKETS.index(letter):
current_bracket.pop()
else:
return False
if letter in OPENING_BRACKETS:
current_bracket.append(letter)
return len(current_bracket) == 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"
assert checkio("(((([[[{{{3}}}]]]]))))") == False, "No brackets, no problem"