Python checking the parentheses are equal on both sides

Question:

I wrote a code but dont know how to make it find the extra unbalanced parentheses this is my code

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))

For example if i input ()()() the code will say it is balanced but if i input something like this (())) it will say it is not balanced. what i want to add is that it would say code is balanced or not and says the first position of the side that is not balanced like CODE IS NOT BALANCED ")" POSTITION 3 and i would like to do it for the other side aswell if it is not balanced ((()) CODE IS NOT BALANCED "(" POSTITION 1

Asked By: Kamel Avad

||

Answers:

Try this:
In every iteration, the innermost bracket gets replaced with empty string. If the final string is empty, its balanced otherwise not.

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")
Answered By: SM1312

I quickly wrote something that could sort your problem. Sorry for it being a little untidy. I made it a little more elaborate aswell (not mixing bracket types etc.).

The relevant parts, that I guess could have helped you a lot are the following:

  • The enumerate function will let you iterate over something, giving both the value and the position of a given entry (here a tutorial example: https://www.geeksforgeeks.org/enumerate-in-python/)
  • f-strings are a great way to incorporate variables in your strings. Just put an f infront of your string and put your variables in curly brackets.

So if you want to try for yourself I would advise checking out enuemrate and f-strings. Otherwise you can use the below function.

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."
Answered By: KRS
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.