livepython.net

218. Python Program to Check If Brackets Are Balanced

HardPhase 3 · Challenge

This one takes a few steps. It uses a list with append() and pop(), a for loop and a small dictionary. You know all of them. Try a short example on paper first.

Overview

Checking brackets is a classic interview question. Code editors do this check every time you type a bracket.

Problem Statement

Tariq is writing a small code editor. It should warn Tariq when the brackets in a line do not match.

There are three kinds of brackets: ( ), [ ] and { }. The brackets in a line are balanced when:

  • Each opening bracket (, [ or { has a closing bracket of the same kind after it: ), ] or }.
  • Each closing bracket has an opening bracket of the same kind before it.
  • The bracket opened last is closed first. So ([]) is balanced, but ([)] is not.

All other characters do not matter: skip them. A line with no brackets is balanced.

A stack helps here. A stack is a list where you add and take items only at the end, like a pile of plates: the last plate you put on is the first one you take off. append() puts an item on top, and pop() takes the top item off.

Read one line. Print Balanced or Not balanced.

Examples

Example 1. Input (a[b]{c}) gives:

Balanced

Why: [b] and {c} open and close inside the round brackets. Then the last ) closes the first (.

Example 2. Input ([)] gives:

Not balanced

Why: the [ was opened last, so it must be closed first. But a ) comes before the ].

Input

One line of text, 1 character or more. It can have letters, digits, spaces, brackets and other characters. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line: Balanced or Not balanced. The tests try 9 different inputs, also lines with an extra opening or closing bracket.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 13 · Dictionaries
solution.py
# write your code here

EXPECTED OUTPUT

1Balanced

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.