Vishesh Vishesh - 1 year ago 52
Python Question

Python program to check matching of simple parentheses

I am a Python newbie and 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 havent 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 + ["("]
if l == ")":
clo = clo + [")"]
return(ope, clo)
if len(ope)==len(clo):
return True
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.

Thanks for your time!

Answer Source

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