我想编写括号检查器程序。但我希望它计算不匹配的括号。我正在使用 python 。以及如何在这个问题中使用堆栈?
我已经尝试了一些代码,但它没有用,因为它不能计算错误的括号。
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
最佳答案
我附上了以下解决方案,希望它是 self 描述的并且会做你想做的。
def check_closed_brackets(open_bracket, nonclosed_opening_brackets, nonopened_closing_brackets):
if len(nonclosed_opening_brackets) == 0: # There are no opened brackets remaining so the close must be invalid
nonopened_closing_brackets.append(element)
else: # Open brackets exist lets check them
if element == ")" :
if nonclosed_opening_brackets[len(nonclosed_opening_brackets) -1] == '(':
nonclosed_opening_brackets.remove("(")
else:
nonopened_closing_brackets.append(element)
if element == "]" :
if nonclosed_opening_brackets[len(nonclosed_opening_brackets) -1] == '[':
nonclosed_opening_brackets.remove("[")
else:
nonopened_closing_brackets.append(element)
if element == "}" :
if nonclosed_opening_brackets[len(nonclosed_opening_brackets) -1] == '{':
nonclosed_opening_brackets.remove("{")
else:
nonopened_closing_brackets.append(element)
if __name__ == "__main__":
# text = sys.stdin.read()
text = str(input())
nonclosed_opening_brackets = []
nonopened_closing_brackets = []
for i, element in enumerate(text):
if element == '(' or element == '[' or element == '{':
nonclosed_opening_brackets.append(element)
if element == ')' or element == ']' or element == '}':
check_closed_brackets(element, nonclosed_opening_brackets, nonopened_closing_brackets)
print('Number of Opened Brackets that are not closed: {0}'.format(len(nonclosed_opening_brackets)))
print('Number of Closed Brackets that are not opened: {0}'.format(len(nonopened_closing_brackets)))
关于python - 我想在 python 中制作括号检查器来计算错误的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57408040/