I have this homework problem in recursion: checking for valid parentheses. The question asks me to write a function that gets a string and a counter as an input and return whether the parentheses were opened and closed properly.
def is_valid_paren(s, cnt=0):
lst1 = list(s)
if lst1 == [] and cnt ==0:
return True
if lst1[0] == '(':
cnt+=1
return is_valid_paren(lst1[1:], cnt)
elif lst1[0] == ')':
cnt-=1
return is_valid_paren(lst1[1:], cnt)
else:
return is_valid_paren(lst1[1:], cnt)
This is my code, however I keep getting a list index out of range error when I try running it on some strings. Any help on why I get this error message would be greatly appreciated, Thanks!
"))(("to count as "valid", you probably want to check thatcntis greater than zero in theelifbranch, before you recurse.