Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...