I am trying to use stacks to check parenthesis, but the following code cannot output the right result; after checking it several times, I still cannot find the mistakes; any hint or help is appreciated a lot! thanks!
open_list = ["[","{","("]
close_list = ["]","}",")"]
def check(mystr):
stack1 = []
for i in mystr:
if i in open_list:
stack1.append(i)
elif i in close_list:
stack1.append(i)
for i in stack1:
index1 = open_list.index(i)
expected_result = close_list[index1]
if expected_result == stack1[-1]:
stack1.remove(i)
stack1.pop(-1)
else:
print(i)
print(stack1, stack1, sep = 'n')
return 'unbalanced'
if len(stack1) == 0:
return 'balanced'
else:
print(stack1)
return 'unbalanced'
# example
list1 = '{a + [b - (c * [e / f] + g) - h] * i}'
# output
(
['[', '(', '[', ']', ')', ']']
['[', '(', '[', ']', ')', ']']
unbalanced
3
Modifying the list you are iterating will cause to skip elements, in the first iteration of the second loop in the check function you will have expected_result
== stack1[-1]
, but in the second iteration i
is the second value in the list which now that is modified it will be ‘(‘ instead of ‘[‘.
You can simplify the logic by only adding the open symbols into the stack and every time you find a close symbol you compare to see if the last open saved is it’s pair, if not it’s unbalanced.
def check(mystr):
stack1 = []
for i in mystr:
if i in open_list:
stack1.append(i)
elif i in close_list:
if not stack1 or stack1[-1] != open_list[close_list.index(i)]:
return 'unbalanced'
else:
stack1.pop(-1)
if len(stack1) == 0:
return 'balanced'
else:
print(stack1)
return 'unbalanced'
1