我想编一个括号检查器程序。但我想让它数一数不匹配的括号。我在用python。在这个问题上我怎么用stack呢?你知道吗
我试过一些代码,但没有成功,因为它不能计算错误的括号。你知道吗
if __name__ == "__main__":
# text = sys.stdin.read()
text = str(input())
stackie = []
num = 0
opening_brackets_stack = []
for i, next in enumerate(text):
if next == '(' or next == '[' or next == '{':
# Process opening bracket, write your code here
stackie.append(next)
pass
if next == ')' or next == ']' or next == '}':
# Process closing bracket, write your code here
if next == ")" :
if '(' in stackie :
stackie.remove("(")
else:
num += 1
if next == "]" :
if '[' in stackie :
stackie.remove("[")
else:
num += 1
if next == "}" :
if '{' in stackie :
stackie.remove("{")
else:
num += 1
pass
我想如果你想写一个classical bracket parser,逻辑中的一个错误是调用堆栈上的
remove
,而不是比较pop
。你知道吗要确定它什么时候按预期工作,什么时候不按预期工作并不容易,所以一些测试用例和它们的预期行为有很大的帮助,比如说,对于
'(asd(gdgd)[dfdf])'
、'[(asd(gdgd)[dfdf])'
和'(asd(gdg{d)[df}df])'
,您希望得到什么作为输出?你知道吗以这段代码为例:
根据之前的样本,我们得到:
这个解决方案停留在第一个不匹配的括号上,主要是因为这个问题比以人类的方式找到所有不匹配的括号要容易得多。后者在规则大小的文本中计算起来相当复杂,仍然不能确定是否能给出所需的结果。你知道吗
除非这是绝对不可行的,否则在我看来,通过修复括号错误来迭代工作是更可取的。你知道吗
我附上了下面的解决方案,希望它是自我描述,将做你想要的。你知道吗
相关问题 更多 >
编程相关推荐