【发布时间】:2021-11-13 07:39:02
【问题描述】:
所以我正在尝试“括号是否平衡?”在 Python 中编写程序,当我的平衡函数正常工作时,我创建的用于检查括号是否匹配的函数返回了不正确的值。我将附上整个代码、cmets 和所有内容,以便您查看。我尝试的第一种方法是使用条件 if/else 语句。对于这种方法,即使括号匹配,我也会一直得到 False 。对于第二种方法,我不断收到 TypeError: 。这是我的代码。
from collections import deque
stack = deque()
#dir(堆栈)
#使用堆栈查看输入字符串是否有一组平衡的括号
#function 告诉哪些括号应该匹配。以后会用到
def is_match(paren1, paren2):
#dictionary for more efficiency rather than a bunch of conditionals
#match_dict = {
# ')': '(',
# ']': '[',
# '}': '{'
#}
if paren1 == '(' and paren2 == ')':
return True
if paren1 == '[' and paren2 == ']':
return True
if paren1 == '{' and paren2 == '}':
return True
else:
return False
#print(match_dict[paren1] == paren2)
#return match_dict[paren1] == paren2
def is_balanced(string):
#start with an iterative for loop to index through the string
for i in string:
#check to see if the index of the string is an open parentheses, if so, append to stack
if i in '([{':
stack.append([i])
print(i)
#if index is not in substring, check to see if string is empty
else:
if len(stack) == 0:
return 'not balanced'
else:
match = stack.pop()
if is_match(match, i) == True:
return 'balanced'
else:
return 'not balanced'
字符串 = ('([{}])')
is_balanced(字符串)
【问题讨论】:
标签: python dictionary return compare parentheses