def paren(s, cnt=0):
if s == '':
return True
if s[0] == '(':
return paren(s[1:], cnt 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
return cnt == 0
So this code works for all cases if there is the same number of "(" and ")". But for example it doesn't work for "))(( ". how can I modify the code for this to work that for every opening bracket there is a closing one, then it returns True.
CodePudding user response:
Check if at any point c < 0
, and fix the return
for when s == ''
def paren(s, cnt=0):
if c < 0: return False
elif s == '': return c == 0
elif s[0] == '(':
return paren(s[1:], cnt 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
# here, there's a non-parentheses character. I'll assume you want to ignore these
# if they're impossible, just remove this line
return parent(s[1:], cnt)
CodePudding user response:
def paren(s):
_s = s.replace('()','')
if not _s:
return True
elif _s==s:
return False
return paren(_s)
print(paren(')()('))
CodePudding user response:
To check that for every opening bracket there is a closing bracket, you can simply check if the final value of cnt is 0. If it is, then it means that there was an equal number of opening and closing brackets, so the string is balanced. Here is one way you could modify the code to do this:
def paren(s, cnt=0):
if s == '':
# If the string is empty, return True if the count is 0,
# otherwise return False
return cnt == 0
if s[0] == '(':
# If the first character is an opening bracket, increment the count
return paren(s[1:], cnt 1)
elif s[0] == ')':
# If the first character is a closing bracket, decrement the count
return paren(s[1:], cnt - 1)
# If the first character is neither an opening nor closing bracket,
# just recurse on the rest of the string
return paren(s[1:], cnt)
This code should work for the example you gave, "))(( ". When it reaches the first closing bracket, cnt will be decremented to -1. When it reaches the next closing bracket, cnt will be decremented again to -2. When it reaches the first opening bracket, cnt will be incremented to -1. Finally, when it reaches the last opening bracket, cnt will be incremented again to 0. When the string is empty, cnt will be 0, so the function will return True.