Junior — Senior
Determining the balance of brackets in a string
livecode
Task condition
It is necessary to write a function areBracketsBalanced that takes a string expr, which may contain only the characters ()[]{}. The function should return True if all brackets are opened and closed correctly, otherwise – False.
def areBracketsBalanced(expr):
stack = []
for char in expr:
if char in ["(", "{", "["]:
stack.append(char)
else:
if not stack:
return False
current_char = stack.pop()
if current_char == "(":
if char != ")":
return False
if current_char == "{":
if char != "}":
return False
if current_char == "[":
if char != "]":
return False
return not stack