Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

recursion - 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
question from:https://stackoverflow.com/questions/65852202/python-balanced-parenthesis-error-with-index-and-indentation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...