Hackbright Code Challenges

Balanced Parentheses: Solution

Balanced Parentheses: Solution

Problem

Balanced Parentheses

Whiteboard

Medium

Concepts

Conditionals, Loops

Download

balanced-parentheses-solution.zip


We should fail in two possible ways:

  • if we close a parentheses when none are open

  • if we end up with stray open parentheses

Our solution keeps track of how many parentheses are open and fails on either of those conditions. Otherwise, it returns True:

balancedparentheses.py
def has_balanced_parens(phrase):
    """Does a string have balanced parentheses?"""

    # START SOLUTION

    parens = 0

    for char in phrase:

        if char == "(":
            parens = parens + 1

        elif char == ")":
            parens = parens - 1

            if parens < 0:
                # We can never close more than we have open
                return False

    # Make sure we have none left

    if parens > 0:
        return False

    else:
        return True

Our Balanced Brackets problem is related but harder, as it requires checking other types of opening-and-closing marks. Give it a try!