Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
edited by

Hello all. I'm actually new to python and I also came across of this exercise, checking whether the brackets in a given string are matching or not.

Using various stack commands I've seen many examples. Here, I also attempted a different approach. Anyone give me some suggestion, where I went wrong in the below code?

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 of my code is just to add up "(" & ")" brackets into two different lists, then comparing the length of the list.

1 Answer

0 votes
by (16.4k points)

We can slightly modify your code, check the below code. This code will clean up 'for' loop & replaces the lists with a simple counter variable. In case, If the count drops below zero it will return false, so that matched (")(") will returns "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

Interested to learn more about Python? Come & Join:- Python training course

Browse Categories

...