Read the question, write Python on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read one line of brackets — only (), [], and {} — and print yes if they are balanced, otherwise no.
A stack is the tool: push opening brackets, pop when a closer matches the top.
Input. One line of bracket characters (may be empty).
Output. yes or no.
Examples
Input
()[]{}Output
yes
Input
([)]
Output
no
Input
((
Output
no
Hint
- pairs = {')': '(', ']': '[', '}': '{'}.
- If the stack is empty when a closer arrives, or leftovers remain at the end, it is no.
Show correct code
Peek only after you have tried. You can still Check your own version.
s = input().strip()
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
ok = True
for ch in s:
if ch in '([{':
stack.append(ch)
elif ch in pairs:
if not stack or stack[-1] != pairs[ch]:
ok = False
break
stack.pop()
print('yes' if ok and not stack else 'no')
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.