i python newbie , came across exercise of checking whether or not simple brackets "(", ")" in given string matched evenly.
i have seen examples here using stack command havent encountered yet.so attempted different approach. can tell me going wrong?
def matched(str): ope = [] clo = [] 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 pile "(" , ")" 2 separate lists , compare length of lists. had version had appended lists ope , clo relevant held either ( or ) respectively.
thanks time!
a more elegant way below. cleans loop , replaces lists simple counter variable. returns false if counter drops below 0 matched(")(")
return false
.
def matched(str): count = 0 in str: if == "(": count += 1 elif == ")": count -= 1 if count < 0: return false return count == 0
Comments
Post a Comment