Reputation: 63
I am doing my lab homework for python and I am stuck on one of the questions. Any help would be greatly appreciated.
So the task is to find whether a string has balanced brackets or not. This means that each closing bracket should be in order.
Balanced bracket example:
(<>){}
Unbalanced bracket example:
())
(<)> (this one is mistmatched)
)(<>
The part I am stuck on is; how can I return the last element of the stack to compare?
def balanced_brackets(text):
s = Stack()
opening_bracket_list = ["(", "[", "{"]
closing_bracket_dict = {")":"(", "]" : "[", "}" : "{"}
text_list = list(text)
for element in text_list:
if element in opening_bracket_list:
s.push(element)
if element in closing_bracket_dict:
if (last element of the stack) == closing_bracket_dict[element]:
s.pop()
else:
return False
if s == []:
return True
As you can see, I split the text into a string and use a for loop. If its an opening bracket, I push it into the stack, if its a closing element, I check if the last element of the stack matches the value from the dictionary. If no it return False
, if yes it returns True
.
Any other suggestions to help the code would also be greatly appreciated. I use code runner for this and I can only use a stack and specifically a function (not a class) for this lab question
Upvotes: 1
Views: 1755
Reputation: 1
The above mentioned code shows Run time error for inputs like ")". To overcome this situation, we could just the closing dictionary and check whether the stack is empty and the popping element corresponds to the opening element.
def ispar(x):
# code here
s = []
bracket_dict = {")":"(", "]" : "[", "}" : "{"}
for element in x:
if element in bracket_dict.values():
s.append(element)
if element in bracket_dict:
if not s or s[-1] != bracket_dict[element]:
return False
s.pop()
return not s
Upvotes: 0
Reputation: 11
If s
is your stack then you can use s[-1]
to get the stack element without popping it.
If the stack is empty and if you try to access s[-1]
it will show index out of range. Hence use len(s)
to check the length of the string.
Upvotes: 0
Reputation: 281330
Usually, there's a peek()
operation that gets the top element without removing it. If peek()
isn't supported, it can be simulated by pop
ping the top element and push
ing it back on. You don't need to do any of that here, though, because you can just pop
the element to compare it:
for element in text_list:
if element in opening_bracket_list:
s.push(element)
elif element in closing_bracket_dict:
if s.pop() != closing_bracket_dict[element]:
return False
You'll also need to return True
at the end if everything matched.
Upvotes: 4