Reputation: 46
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
Upvotes: 1
Views: 977
Reputation: 54
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:
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."
Upvotes: 1
Reputation: 588
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")
Upvotes: 0