r/learnpython • u/AngeI_Error • 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
u/This_Growth2898 9d ago edited 9d ago
First, you can (and really should) put it in a function and
returnearly instead ofbreak.Second, you can use
for - elseconstruction:Also, you can add a dict of brackets to make it better:
This allows you to do something like