Python bootcamp · Lab 42

Matching brackets

mediumStacks15 minLesson: Stacks

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

Example 1
Input
()[]{}
Output
yes
Example 2 — Wrong closer for the inner opener.
Input
([)]
Output
no
Example 3
Input
((
Output
no
Hint
  1. pairs = {')': '(', ']': '[', '}': '{'}.
  2. 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.