I´;我目前正在python上开发一个平衡括号算法,can´;我不知道是什么´;这是不对的
这是我到目前为止所使用的代码,我已经尝试了一些,但是没有成功,我觉得这可能是一个我遗漏的简单错误。我的一个朋友有相同的任务,代码非常相似,但他的工作非常完美,而我的工作却不完美。I´;我目前正在python上开发一个平衡括号算法,can´;我不知道是什么´;这是不对的,python,python-3.x,brackets,Python,Python 3.x,Brackets,这是我到目前为止所使用的代码,我已经尝试了一些,但是没有成功,我觉得这可能是一个我遗漏的简单错误。我的一个朋友有相同的任务,代码非常相似,但他的工作非常完美,而我的工作却不完美。 代码接受方括号的任意组合,并检查它们是否平衡,如果平衡,则应输出成功,如果不平衡,则应输出方括号不平衡的索引(从索引1开始)。 例如: 代码本身没有任何错误代码,但无论是否平衡,它始终显示“Success”。 相反,我得到的是: Input: ()) Output: Success // 您的代码正在打印“Succe
代码接受方括号的任意组合,并检查它们是否平衡,如果平衡,则应输出成功,如果不平衡,则应输出方括号不平衡的索引(从索引1开始)。 例如: 代码本身没有任何错误代码,但无论是否平衡,它始终显示“Success”。 相反,我得到的是:
Input: ())
Output: Success
//
您的代码正在打印“Success”,因为您告诉它,在完成后,它应该始终打印Success
if __name__ == "__main__":
# A bunch of stuff unrelated to program flow...
print ('Success')
您可能只希望在到达文本末尾时,队列中没有任何内容时成功
if __name__ == "__main__":
text = sys.stdin.read()
char_code = 0
opening_brackets_stack = []
for i, next in enumerate(text):
if next == '(' or next == '[' or next == '{':
char_code += 1
opening_brackets_stack.append(next)
stack_pop = opening_brackets_stack.pop()
if next == ')' or next == ']' or next == '}':
char_code += 1
if not Match(stack_pop, next):
print(char_code)
else:
char_code += 1
if not opening_brackets_stack: # <-- new line
print ('Success')
描述出了什么地方出了问题,如果你收到了一条错误信息,就发布它。(所有这些,包括堆栈跟踪。)我还假设您给这个程序一些输入。请指出您提供的输入,以及您期望该输入的输出,以及您实际获得的输出。为什么要为此使用类?这没有意义…@DiegoJoseQuanCampos您还没有提供一个示例案例(“我给出输入x,期望输出y,但得到输出z”),这使得这个问题脱离了主题。你能修改吗?我添加了更多的信息,如果不完整,很抱歉。Joran,这段代码将用于我作业的另一部分,需要一个类。删除它是为了澄清这帮了我很大的忙,也给了我一个新的视角来看待我的任务。谢谢
if __name__ == "__main__":
# A bunch of stuff unrelated to program flow...
print ('Success')
if __name__ == "__main__":
text = sys.stdin.read()
char_code = 0
opening_brackets_stack = []
for i, next in enumerate(text):
if next == '(' or next == '[' or next == '{':
char_code += 1
opening_brackets_stack.append(next)
stack_pop = opening_brackets_stack.pop()
if next == ')' or next == ']' or next == '}':
char_code += 1
if not Match(stack_pop, next):
print(char_code)
else:
char_code += 1
if not opening_brackets_stack: # <-- new line
print ('Success')
# this will let us check for an expected closing bracket more easily
opening_brackets = "([{"
closing_brackets = ")]}"
mapping = dict(zip(opening_brackets, closing_brackets))
stack = []
for i, ch in enumerate(text):
if ch in opening_brackets:
# throw the closing bracket on the stack
matching_closer = mapping[ch]
stack.append(matching_closer)
elif ch == stack[-1]:
# if the character closes the last-opened bracket
stack.pop() # pop it off
elif ch in closing_brackets:
# this is an unmatched closing bracket, making the brackets
# imbalanced in this expression
print("FAILED")
sys.exit(1) # closes the program immediately with a retcode of 1
else:
# not a bracket, continue as normal
# this is technically a NOP and everything from the `else` can be
# omitted, but I think this looks more obvious to the reader.
continue
if not stack: # empty stack means matched brackets!
print("SUCCESS")
else:
print("FAILED")