Search code examples
pythonrecursionindentation

Python balanced parenthesis error with index and indentation


I recently got into python and I ran into this problem while coding a solution to check if a series of parentheses are balanced or not. I've checked different posts about indentations, but that doesn't seem to help.It gives me an index out of range error on elif line, which I don't get since its accessing the first and last character. Any help and feedback would be appreciated.

def nest_paren(s):
  if s == " ":
    return True
  elif len(s) % 2 == 1 or s[0] != '(' or s[-1] != ')':
    return False
  return nest_paren(s[1:-1])

nest_paren(s="(())")  # This should return True
nest_paren(s="((())") # This should return False

Solution

  • Your base case is not correct. You need to handle the empty string, not a string with a space in it.

    Change if s == " ": to if s == "": and it should work.

    I'm assuming that you are only supposed to accept a single set of nested parentheses, of the form (...(())...). If you need to also recognize where there are several adjacent sets of non-nested balanced parentheses (like in (())()), you'll need a more sophisticated algorithm. Here's a simple way to do it with an iteration over the string, rather than recursion:

    def nest_paren(s):
        open_count = 0
        for c in s:
            if c == '(':
                open_count += 1
            elif c == ')'
                open_count -= 1
                if open_count < 0:
                    return False
            else:  # non-parenthesis character, you could ignore these instead
                return False
        return open_count == 0