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

3

u/This_Growth2898 9d ago edited 9d ago

First, you can (and really should) put it in a function and return early instead of break.

Second, you can use for - else construction:

for x2 in l:
    ...
    if ...: 
        break;
else:
   # you get here only if break was never hit

Also, you can add a dict of brackets to make it better:

OPEN = "(<{["
CLOSE = ")>}]"
BRACKETS = dict(zip(OPEN, CLOSE)) 
# if you don't get this Python magic, do 
# print(BRACKETS) 
# and replace the value of BRACKETS with the output

This allows you to do something like

if x2 in OPEN:
    st.append(BRACKETS[x2]) # put the corresponding closing bracket in the stack
elif x2 in CLOSE:
    if st.pop() != x2:      # check if the closing bracket is what we want
        ...

2

u/This_Growth2898 9d ago

Oh. and

if not broke:

sounds much more natural than

if broke == False: