我试图写一个算法,使用堆栈来检查表达式是否有平衡的括号,但我一直遇到这个错误


def is_matched(expression):
left_bracket = "[({"
right_bracket = "])}"
my_stack = Stack(len(expression))
# our solution methodology is to go through the expression and push all of the the open brackets onto the stack and then
# with the closing brackets - each time we encounter a closing bracket we will pop the stack and compare
for character in expression:
if character in left_bracket:
my_stack.push(character)
elif character in right_bracket:
# first check to see that the stack is not empty i.e we actually have some opneing brackets in the expression
if my_stack.is_empty():
return False
# now we need to check that the type of braket we pop is the equivalent of it's closing bracket in the expression
if right_bracket.index(character) != left_bracket.index(my_stack.pop):
return False
return my_stack.is_empty()
print(is_matched("()"))
if right_bracket.index(character) != left_bracket.index(my_stack.pop):
TypeError: expected a string or other character buffer object
python-BaseException

这是我的堆栈实现:

class Stack:
def __init__(self, capacity):
"""Builds a stack with given capacity > 0."""
if capacity <= 0:
raise Exception("The capacity must be positive")
self.the_array = [None] * capacity
self.top = -1  # the index of the top element
def size(self):
"""Returns the size, i.e. the number
of elements in the container."""
return self.top + 1
def is_empty(self):
"""Returns True if and only if the container is empty."""
return self.size() == 0
def is_full(self):
"""Returns True if and only if the container is full."""
return self.size() >= len(self.the_array)
def push(self, item):
"""Places the given item at the top of the stack
if there is capacity, or raises an Exception."""
if self.is_full():
raise Exception("The stack is full")
self.top += 1
self.the_array[self.top] = item
def pop(self):
"""Removes and returns the top element of the stack,
or raises an Exception if there is none."""
if self.is_empty():
raise Exception("The stack is empty")
item = self.the_array[self.top]
# removes a reference to this item,
# helps with memory management and debugging
self.the_array[self.top] = None
self.top -= 1
return item
def reset(self):
"""Removes all elements from the container."""
while not self.is_empty():
self.pop()
assert (self.is_empty)

它应该在第二次迭代时弹出堆栈,并注意到左右括号的索引是相同的,然后进入最后一次迭代,它意识到堆栈为空并返回True,但它没有这样做,而是抛出typeError。

任何帮助都是感激的。

谢谢

在这一行:

if right_bracket.index(character) != left_bracket.index(my_stack.pop):

你实际上需要调用pop方法,因为pop是一个方法,而不是一个属性。

因此它应该是这样的:

if right_bracket.index(character) != left_bracket.index(my_stack.pop()):

最新更新