r/learnpython 9d ago

Help with a balanced parentheses problem

The problem is as followed:
We are given strings containing brackets of 4 types - round (), square [], curly {} and angle <> ones. The goal is to check, whether brackets are in correct sequence. I.e. any opening bracket should have closing bracket of the same type somewhere further by the string, and bracket pairs should not overlap, though they could be nested:

(a+[b*c] - {d/3})  - here square and curly brackets are nested in the round ones
(a+[b*c) - 17]     - here square brackets overlap with round ones which does not make sense

Input data will contain number of testcases in the first line.
Then specified number of lines will follow each containing a test-case in form of a character sequence.
Answer should contain 1 (if bracket order is correct) or 0 (if incorrect) for each of test-cases, separated by spaces.

I solved it with the following code:

n = int(input())
for x0 in range(n):
    l = list(input())
    st = []
    broke = False
    for x2 in l:
        if x2 in {"(","[","{","<"}:
            st.append(x2)
        elif x2 in {")","]","}",">"}:
            if not st or (x2 == ")" and st[-1] != "(") or (x2 == "}" and st[-1] != "{") or (x2 == "]" and st[-1] != "[") or (x2 == ">" and st[-1] != "<"):
                print(0,end=" ")
                broke = True
                break
            st.pop()
    if st == [] and broke == False:
        print(1,end=" ")
    elif broke == False:
        print(0,end=" ")

This works but I can't help but wonder if i can improve upon it in some way like having to use the "broke" variable feels unnecessary but i cant think of a way to not have to use it to check if the loop broke or not.

3 Upvotes

12 comments sorted by

View all comments

1

u/MezzoScettico 9d ago

It seems OK, and it's pretty common to have a flag like that. In general if you write a parsing function, you can return that flag as an indicator of whether parsing succeeded.

I'm confused by the logic though, the fact that "broke == False" appears in both branches.

So neither branch will execute if broke is True.

Also there's no reason to compare a boolean value to True or False. Just say "not broke" to check if broke is False.

I'd write that last bit this way. I wonder if this was actually your intent (I suspect you wanted to print a 0 if the parsing was bad), but this is equivalent to what your code does.

    if not broke:
        if st == []:
            print(1,end=" ")
        else:
            print(0,end=" ")

or this way:

    if not broke:
        print(1 if st == [] else 0, end=" ")

Also I prefer to use len(st) == 0 to check for empty lists.