I am learning data structures in Python and working on stacks. I am trying to create a code that uses stacks to match the parenthesis in an expression, however I am not getting the right answer. This needs to be done without the use of Python libraries.
class Stack():
def __init__(self): # Initialize a new stack
self._items = []
self._size = 0
self._top = -1
def push(self, new_item): # Append the new item to the stack
self._items.append(new_item)
self._top += 1
self._size += 1
self._items[self._top] = new_item
def pop(self): # Remove and return the last item from the stack
old_item = self._items[self._top]
self._top -= 1
self._size -= 1
return old_item
def size(self): # Return the total number of elements in the stack
return len(self._items)
def isEmpty(self): # Return True if the stack is empty and False if it is not empty
if self._items == 0:
return True
else:
return False
def peek(self): # Return the element at the top of the stack or return None if the stack is
empty if self.isEmpty(): return None else: return self._items[self._top]
def check_Par(exp):
opening = ['(', '[', '{']
closing = [')', ']', '}']
balanced = True
s = Stack()
for x in exp:
if x in opening:
s.push(x)
elif x in closing:
position = s.pop()
if closing.index(x) and opening.index(position):
balanced = True
else:
balanced = False
pass
if s.isEmpty():
balanced = False
return balanced
exp1 = "(2)+(-5)" # True
exp2 = "((2))*((3))" # True
exp3 = "(4))]" #False
print(check_Par(exp1))
print(check_Par(exp2))
print(check_Par(exp3))
I get an error for line 14 IndexError: list index out of range
Also, I know the for loop is not completed and I am having a hard time fix it. Any advice it would be greatly appreciated. Lois
listdirectly instead of making your ownstackclass. You can uselist.appendandlist.pop.s.pop()gets called whens._top < 0 and s._size == 0at some point.