Balanced Brackets
Medium · 55 XPWrite is_balanced(s) returning True when every bracket ()[]{} is closed in the right order. Print the result for four test strings.
Target output
{[()]} True
{[(])} False
((())) True
(] False
Blank · autosaved
PYbalanced-brackets.py
Push opening brackets onto a stack; on a closer, the popped item must be its partner. The stack must be empty at the end.
def is_balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
for test in ("{[()]}", "{[(])}", "((()))", "(]"):
print(f"{test} {is_balanced(test)}")
Run your code to check it…