-1
txt = input("Enter any Brackets : ")

j = 0
k = 0
for i in txt:
    if i == "(" or i == "{" or i == "[":
        j += 1
    if i == ")" or i == "}" or i == "]":
        k += 1
if j < k and j != 0 and k != 0:
    print("complete" + str(j))
    print("incomplete" + str(k - j))
elif j > k and j != 0 and k != 0:
    print("complete" + str(k))
    print("incomplete" + str(j - k))
elif j == k and j != 0 and k != 0:
    print("complete"+str(k))

output:

Enter bracket : (()}
complete2

but the expected output is:

complete 1 and incomplete 1
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41

5 Answers5

0

First of all you are just incrementing two numbers on the basis of brackets no matter what type of bracket it is;

if i == "(" or i == "{" or i == "[":
        j += 1
if i == ")" or i == "}" or i == "]":
    k += 1

So here whether i am giving parenthesis as input or square brackets, if they are opening ones, it is going to increment j and if they are closing ones, it is going to increment k.

So if i give ( and ] as input, though they are different but first will increment j, so j now will be equal to 1. And same will happen with k because of second part ]. Thus k will also be equal to 1.

Thus the condition j == k will be true even when the brackets are not same. Thus returning complete.

You should instead create a dict where you will track all different types of brackets seperately.

This is what i came up with. (Though there is a little bug here which is my code does not detect the order of the brackets.)

txt = input("Enter any Brackets: ")

res = {
    '(': 0,
    ')': 0,
    '{': 0,
    '}': 0,
    '[': 0,
    ']': 0
    }
for i in txt:
    if i == '(':
        res['('] += 1
    if i == ')':
        res[')'] += 1
    if i == '{':
        res['{'] += 1
    if i == '}':
        res['}'] += 1
    if i == '[':
        res['['] += 1
    if i == ']':
        res[']'] += 1

if res['('] == res[')'] and res['{'] == res['}'] and res['['] == res[']']:
    print('complete: ', res['('] + res['{'] + res['['])

else:
    print('Brackets are not complete. Please check')
Irfan wani
  • 4,084
  • 2
  • 19
  • 34
0

Check out this code: For another logic go with is code.
Here logic is that count number of each bracket and them subtract them from their alternative which is number of incomplete. Opposite of that is complete.

txt = input("Enter any Breackets : ")

list1 = ['(', '[', '{', ')', ']', '}']
ind = []

for i in txt:  
    ind.append(list1.index(i))

ind.sort()
count = list(ind.count(i) for i in range(6))
incomplete = sum([abs(count[i]-count[i+3]) for i in range(3)])
print('Complete', (len(txt)-incomplete)//2)
print('Incomplete', incomplete)

Output: Please change output-format as per your requirement.

Enter any Breackets : ((]]{}
Complete 1
Incomplete 4
Davinder Singh
  • 2,060
  • 2
  • 7
  • 22
0

You used or in your if conditions inside the for loop so j and k values are increased each time a bracket is found.

It is as if you are trying to check brackets but do not care if they are {}, [] or ().

I would suggest you use different loops for each type of bracket (it will make your code a lot bigger but will be much simpler) or you could try to use a list and keep the brackets as the elements and then compare the list items.

Karthik J
  • 51
  • 6
0

You are checking for all bracket types in a single if statement, essentially equating ( with { and so on. What you should do is to separate each type of opening and closure separately and keep count of each type individually.

Python has matching and counting as a built-in function you can use with String.count('pattern') so I used that for cleaner code.

Also, since we are tracking openings and closures in the same time we can determine whether the mismatches are of opening or closure types.

Here's my solution to your problem:

txt = input("Enter brackets : ")

opened_parentheses = txt.count('(')
closed_parentheses = txt.count(')')
opened_braces = txt.count('{')
closed_braces = txt.count('}')
opened_brackets = txt.count('[')
closed_brackets = txt.count(']')

parentheses = opened_parentheses - closed_parentheses
braces = opened_braces - closed_braces
brackets = opened_brackets - closed_brackets

report = ''

if opened_parentheses > 0 or closed_parentheses > 0:
    if parentheses == 0:
        report += f'{closed_parentheses} complete parentheses \n'
    elif parentheses < 0:
        report += f'{abs(parentheses)} parentheses missing openings\n'
    else:
        report += f'{parentheses} parentheses missing closure\n'
else:
    report += 'no parentheses\n'

if opened_braces > 0 or closed_braces > 0:
    if braces == 0:
        report += f'{closed_braces} complete braces \n'
    elif braces < 0:
        report += f'{abs(braces)} braces missing openings\n'
    else:
        report += f'{braces} braces missing closure\n'
else:
    report += 'no braces\n'

if opened_brackets > 0 or closed_brackets > 0:
    if brackets == 0:
        report += f'{closed_brackets} complete brackets \n'
    elif brackets < 0:
        report += f'{abs(brackets)} brackets missing openings\n'
    else:
        report += f'{brackets} brackets missing closure\n'
else:
    report += 'no brackets\n'

print(report)

As a good follow-up practice, you can improve upon this by implementing a method to determine incorrect patterns like (([))] which will be counted as all-complete, but do not make sense.

M.H. Tajaddini
  • 776
  • 4
  • 20
0

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
ObjectJosh
  • 601
  • 3
  • 14