I've been seeing some great answers, and decided to add my own approach. Summary: I used dictionaries to count and store occurrences of brackets, then performed a simple calculation to find the number complete and incomplete. Depending on your personal knowledge, this approach may be easier to understand. I added lots of comments to explain steps. Enjoy.
txt = input("Enter any Breackets : ")
# creating two dictionaries, so we can keep track of the totals for each bracket type
open_dict = {'(': 0, '{': 0, '[': 0}
close_dict = {')': 0, '}': 0, ']': 0}
# loops through each character in the input string, 'txt'
for each in txt:
# if the character/symbol is in the open brace dictionary, update its value at that key
if each in open_dict:
open_dict[each] += 1
# else if the character/symbol is in the closed brace dictionary, update its value at that key
elif each in close_dict:
close_dict[each] += 1
# now we are done counting how many of each open and closing brace is in the 'txt'
# we will now want to use these numbers in the dictionaries to calculate how many are complete and incomplete
complete = 0
incomplete = 0
# we use zip() to loop through elements in 'open_dict' and 'close_dict' at the same time
for opened, closed in zip(open_dict, close_dict):
# find the greater of the two values
# ... for example it could compare '(': 2 with ')': 1 so 2 would be 'high' and 1 would be 'low'
high = max(open_dict[opened], close_dict[closed])
# find the lesser of the two values
low = min(open_dict[opened], close_dict[closed])
# we add low to the total complete
# ... for example if we had 3 open and 3 close, 3 is 'low'.
# 3 open 3 close means there are 3 complete
# ... for example if we had 5 open and 2 close, 2 is 'low'.
# 2 subtracted from 5 means (5 - 2 = 3) so 3 are incomplete and 2 are complete
complete += low
# we calculate the incomplete by high - low
# ... for example if we had 3 open and 3 close, 3 is 'high' and 3 is 'low'.
# 3 open 3 close (or 3 - 3 = 0) means there are 0 incomplete
# ... for example if we had 5 open and 2 close, 3 is 'high' and 2 is 'low.
# 2 subtracted from 5 means (5 - 2 = 3) so 3 are incomplete and 2 are complete
incomplete += high - low
print("Complete: %d, Incomplete: %d" % (complete, incomplete))
Example Input:
(()}
Output:
Complete: 1, Incomplete: 2
I like this approach because we can also quite easily become more precise, and print how many of each bracket are complete and incomplete:
(replace the last for loop
with this block of code)
for opened, closed in zip(open_dict, close_dict):
high = max(open_dict[opened], close_dict[closed])
low = min(open_dict[opened], close_dict[closed])
complete = low
incomplete = high - low
print("%s%s: Complete: %d, Incomplete: %d" % (opened, closed, complete, incomplete))
Example Input:
(()}
Output:
(): Complete: 1, Incomplete: 1
{}: Complete: 0, Incomplete: 1
[]: Complete: 0, Incomplete: 0