【发布时间】:2022-01-10 03:14:30
【问题描述】:
我想使用堆栈来检查包含嵌套括号的表达式的有效性。 我写了下面的代码,但是当我的输入是 [{[]} 时,代码不会返回任何内容,但我希望返回“左括号多于右括号”。 同样当我的输入是()时,响应而不是“平衡”是“不匹配”! 我写的代码有什么错误?
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
return
def pop(self):
self.items.pop()
def match(left, right):
if left == '[' and right == ']':
return True
elif left == '{' and right == '}':
return True
elif left == '(' and right == ')':
return True
else:
return False
def validity(text):
st = Stack()
for i in text:
if i in '[{(':
st.push(i)
if i in ']})':
if st.is_empty():
print('right parentheses is more than left one')
return False
else:
compare = st.pop()
if not match(compare, i):
print('mismatched')
return False
if st.is_empty():
print('balanced')
else:
print('left parentheses are more than right ones')
for j in range(4):
example = input('plz enter text ')
validity(example)
【问题讨论】:
-
你的
validity函数不是很连贯:有时它返回一个布尔值,有时它打印一些东西。你应该澄清这一点。