Python 检查两边的括号是否相等,如果不相等,找出多余的并说出它们的位置

Python Check whether the parentheses are equal on both sides and if they are not find the extra ones and say their positions

我写了一个代码,但不知道如何让它找到额外的不平衡括号这是我的代码

def checkBalance(str1):
count = 0
for i in str1:
    if i == "(" or i == "{" or i == "[":
        count += 1
    elif i == ")" or i == "}" or i == "]":
        count -= 1
    if count < 0:
        return False and str1.find(")")
return count == 0 

str1 = input("Enter a string of brackets: ")
print("Given string is balanced :", checkBalance(str1))

例如,如果我输入 ()()(),代码会说它是平衡的,但如果我输入类似这样的内容 (())),它会说它不平衡,我想添加的是它会说代码是否平衡,并说不平衡的边的第一个位置,如 CODE IS NOT BALANCED ")" POSTITION 3 和如果另一个不平衡,我也想这样做 ((()) CODE IS NOT BALANCED "(" POSTITION 1

试试这个: 在每次迭代中,最里面的括号被替换为空字符串。如果最终字符串为空,则其平衡不平衡。

def checkBalance(check_string):
    brackets = ['()', '{}', '[]']
    while any(item in check_string for item in brackets):
        for br in brackets:
            check_string = check_string.replace(br, '')
    return not check_string
   
str1 = input("Enter a string of brackets: ")
print("Given string:", str1, "is", "Balanced" if checkBalance(str1) else "Not balanced")

我很快写了一些可以解决您的问题的东西。抱歉有点乱。我也把它做得更精致一点(不混合括号类型等)。

以下相关部分,我想可能对您有很大帮助:

  • enumerate 函数可让您遍历某些内容,给出给定条目的值和位置(此处为教程示例:https://www.geeksforgeeks.org/enumerate-in-python/
  • f-strings 是将变量合并到字符串中的好方法。只需在字符串前面加上一个 f,然后将变量放在大括号中即可。

因此,如果您想自己尝试,我建议您查看 enuemrate 和 f-strings。否则你可以使用下面的函数。

def checkBalance(str1: str) -> str:
    """ Checks if there is unmatched brackets.
    
    :param str: The string that shall be checked
    ...
    :returns: A message detailing if and where brackets are unmatched.
    """
    
    brackets = {"curly": {"open": "{",
                          "close": "}",
                          "count": 0},
                "round": {"open": "(",
                          "close": ")",
                          "count": 0},
                "square": {"open": "[",
                           "close": "]",
                           "count": 0}
    }
    
    for pos, i in enumerate(str1):
        for bracket in brackets:
            if i == brackets[bracket]["open"]:
                brackets[bracket]["count"] += 1
    
                for name in brackets:
                    if name != bracket:
                        if brackets[name]["count"] != 0:
                            return f"Error, opening {bracket} bracket before {name} bracket shut at position {pos}."
    
            if i == brackets[bracket]["close"]:
                brackets[bracket]["count"] -= 1
                if brackets[bracket]["count"] < 0:
                    return f"Error, closing {bracket} bracket at position {pos} without opening bracket"
    
    return_val = ""
    for name, info in brackets.items():
        if info["count"] > 0:
            return_val += f"You have {info['count']} unmatched opening {name} brackets \n"
    
    if return_val != "":
        return return_val
    
    return "No problems with your brackets."