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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…