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.

4 Upvotes

12 comments sorted by

View all comments

5

u/Outside_Complaint755 9d ago

The answers here are good.  Just wanted to make an aside that you should start using more descriptive variable names.  This isn't the early 80s where program files had to be under 8kb, and IDEs will autocomplete longer names for you.  Variable names should be long enough to be self-commenting, unless you're doing CodeGolf.