I came across this exercise of checking whether or not the simple brackets “(“, “)” in a given string are matched evenly.
I have seen examples here using the stack command which I haven’t encountered yet. So I attempted a different approach. Can anyone tell me where I am going wrong?
def matched(str): ope = [] clo = [] for i in range(0,len(str)): l = str[i] if l == "(": ope = ope + ["("] else: if l == ")": clo = clo + [")"] else: return(ope, clo) if len(ope)==len(clo): return True else: return False
The idea is to pile up “(” and “)” into two separate lists and then compare the length of the lists. I also had another version where I had appended the lists ope and clo with the relevant I which held either ( or ) respectively.
Advertisement
Answer
A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that matched(")(")
will return False
.
def matched(str): count = 0 for i in str: if i == "(": count += 1 elif i == ")": count -= 1 if count < 0: return False return count == 0