我正在尝试制作一个程序来检查以确保文本在括号方面是平衡的(所以(),[],{}而不是(),[,{})。当它平衡时,我可以让它工作,当它缺少右括号时它不平衡(如前面的例子)。如果我在左侧缺少一个括号((),],{}),我无法做到的是不平衡。我知道它试图从一个空堆栈中弹出,但不知道如何应对。我的老师在她的 Stack 课程中说,如果它试图弹出到一个空的堆栈,则会自动引发异常,我无法更改她的课程,这是问题所在,否则无论如何我都会将其设为 false不要陷入这种混乱。那么在引发该错误之前,是否有人对如何执行此操作有任何想法?这是代码:
from ListNode import *
from Stack import Stack
ch = 0
s = 0
check = True
def parbalance():
stack = Stack()
user = input("Enter a file name: ")
file = open(user)
lines = file.readlines()
for char in lines:
for ch in char:
#print(ch)
if ch in "([{":
stack.push(ch)
if ch in ")]}":
popStack = stack.pop()
if ch == "(" and popStack != ")":
check = False
elif ch == "[" and popStack != "]":
check = False
elif ch == "{" and popStack != "}":
check = False
if stack.is_empty():
check = True
print("true")
else:
check = False
print("false")
parbalance()
如果有帮助,这是她的 Stack 类:
from ListNode import *
class Stack:
def __init__(self):
self.top = None
def push(self, item):
temp = ListNode(item)
temp.set_link(self.top)
self.top = temp
#self.top = ListNode(item, self.top)
def pop(self):
if self.top == None:
raise Exception("Trying to pop from an empty stack")
temp = self.top
self.top = temp.get_link()
return temp.get_item()
def destroy(self):
self.top = None
def is_full(self):
return False
def is_empty(self):
return self.top == None