【问题标题】:Balanced Parentheses Program Python: Match Function Returning Incorrect Value平衡括号程序 Python:匹配函数返回不正确的值
【发布时间】: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


    【解决方案1】:

    使用stack.append(i) 而不是stack.append([i]) 将元素i 添加到双端队列:

    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)  # <- HERE!
                print(i)
    
            # ...
    

    如果您想通过附加可迭代参数 ([i]) 中的元素来扩展双端队列,请使用 extend

    stack.extend([i])
    

    更多信息请参见Python documentation

    【讨论】:

      猜你喜欢
      • 2010-10-07
      • 1970-01-01
      • 2011-12-15
      相关资源
      最近更新 更多