CodeBlanks Logo Icon CodeBlanks

Challenge 3

Sort an array with bubble sort and print it.

Challenge 3: Stack with parentheses

In this challenge you will balance parentheses using a stack. Every opened parenthesis must be closed.

String: '(())' is balanced, '(()' is not. Push open parens, pop on close.

Practice Balance parentheses

Write balance_parens(s). Balance with a stack, return True if balanced. Print True with print(balance_parens('(())')).

Starter code

solution.py
def balance_parens(s):
    # Balance parentheses

Sample solution

solution.py
def balance_parens(s):
    # Balance parentheses
    stack = []
    for ch in s:
        if ch == '(':
            stack.append(ch)
        elif ch == ')':
            if len(stack) == 0:
                return False
            stack.pop()
    return len(stack) == 0
print(balance_parens('(())'))

Expected output

True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Challenge 3: match the terms

Term Meaning
stack Parenthesis
push Open paren
pop Close paren
empty Balanced

2 Which parenthesis string is balanced?

  • (()
  • ())(
  • )(
  • (()) Correct answer

Explanation: (()) is balanced.

3 Balanced

Question
A balanced stack is ____ at the end.
Answer
A balanced stack is empty at the end.

Explanation: empty is right.

All lessons in Beginner