-2

The code takes in any combination of brackets and checks if they are balanced or not. If they are balanced it should output success; if they aren't balanced it should output the index (starting at index 1) where the brackets are not balanced. Example:

Input: ())
Output: 3
\\
Input: ()
Output: Success

The code always displays "Success" regardless of it being balanced or not. Instead i get this:

Input: ())
Output: Success
import sys

def Match(self, c):
    if self == '[' and c == ']':
       return True
    if self == '{' and c == '}':
       return True
    if self == '(' and c == ')':
       return True
    else:    
       return False

if __name__ == "__main__":
    text = sys.stdin.read()
    char_code = 0
    opening_brackets_stack = []
    for i, next in enumerate(text):
        if next == '(' or next == '[' or next == '{':
             char_code += 1
             opening_brackets_stack.append(next)
             stack_pop = opening_brackets_stack.pop()

        if next == ')' or next == ']' or next == '}':
             char_code += 1
             if not Match(stack_pop, next):
                 print(char_code)
        else:
            char_code += 1
    print ('Success')
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • 1
    Describe what goes wrong, and if you get an error message, post it. (All of it, including stack trace.) – user2357112 Feb 06 '18 at 17:26
  • I'm also assuming you give this program some input. Please indicate the input you give, and also the output you would expect for that input, and the output you actually get. – SethMMorton Feb 06 '18 at 17:30
  • 1
    why are you using a class for this? it doesnt make sense... – Joran Beasley Feb 06 '18 at 17:33
  • @DiegoJoseQuanCampos you still haven't provided a sample case ("I give input x and expect output y, but get output z instead") which makes this question off-topic. Can you edit to correct? – Adam Smith Feb 06 '18 at 19:56
  • 1
    I added some more information, sorry if it was incomplete. And Joran, the code is going to be utilized for another part of my assignment and was going to need a class. Deleted it for clarity – Diego Jose Quan Campos Feb 06 '18 at 19:58
  • I'd suggest looking at the line `stack_pop = opening_brackets_stack.pop()` and thinking about whether it's in the right place. – Mark Dickinson Feb 06 '18 at 20:04

2 Answers2

1

Your code is printing "Success" because you've told it that after it finishes it should always print success

if __name__ == "__main__":
    # A bunch of stuff unrelated to program flow...
    print ('Success')

You probably only want success if you've reached the end of your text with nothing in the queue.

if __name__ == "__main__":
    text = sys.stdin.read()
    char_code = 0
    opening_brackets_stack = []
    for i, next in enumerate(text):
        if next == '(' or next == '[' or next == '{':
             char_code += 1
             opening_brackets_stack.append(next)
             stack_pop = opening_brackets_stack.pop()

        if next == ')' or next == ']' or next == '}':
             char_code += 1
             if not Match(stack_pop, next):
                 print(char_code)
        else:
            char_code += 1
    if not opening_brackets_stack:  # <-- new line
        print ('Success')

Except this won't solve your problem either, since you've never properly checked if you have an unmatched closing bracket, only an unmatched opening bracket. Consider this, instead:

# this will let us check for an expected closing bracket more easily
opening_brackets = "([{"
closing_brackets = ")]}"
mapping = dict(zip(opening_brackets, closing_brackets))

stack = []
for i, ch in enumerate(text):
    if ch in opening_brackets:
        # throw the closing bracket on the stack
        matching_closer = mapping[ch]
        stack.append(matching_closer)
    elif ch == stack[-1]:
        # if the character closes the last-opened bracket
        stack.pop()  # pop it off
    elif ch in closing_brackets:
        # this is an unmatched closing bracket, making the brackets
        # imbalanced in this expression
        print("FAILED")
        sys.exit(1)  # closes the program immediately with a retcode of 1
    else:
        # not a bracket, continue as normal
        # this is technically a NOP and everything from the `else` can be
        # omitted, but I think this looks more obvious to the reader.
        continue
if not stack:  # empty stack means matched brackets!
    print("SUCCESS")
else:
    print("FAILED")
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

Code can contain any brackets from the set []{}(), where the opening brackets are [,{, and ( and the closing brackets corresponding to them are ],}, and ). For convenience, the text editor should not only inform the user that there is an error in the usage of brackets, but also point to the exact place in the code with the problematic bracket. First priority is to find the first unmatched closing bracket which either doesn’t have an opening bracket before it, like ] in ](), or closes the wrong opening bracket, like } in ()[}. If there are no such mistakes, then it should find the first unmatched opening bracket without the corresponding closing bracket after it, like ( in {}([]. If there are no mistakes, text editor should inform the user that the usage of brackets is correct. Apart from the brackets, code can contain big and small latin letters, digits and punctuation marks. More formally, all brackets in the code should be divided into pairs of matching brackets, such that in each pair the opening bracket goes before the closing bracket, and for any two pairs of brackets either one of them is nested inside another one as in (foo[bar]) or they are separate as in f(a,b)-g[c]. The bracket [ corresponds to the bracket ], { corresponds to }, and ( corresponds to ).

# python3
from collections import namedtuple

Bracket = namedtuple("Bracket", ["char", "position"])

def are_matching(left, right):
    return (left + right) in ["()", "[]", "{}"]

def find_mismatch(text):
    opening_brackets_stack = []
    mismatch_pos = None
    for i, next in enumerate(text):
        if next in "([{":
            # Process opening bracket, write your code here
            opening_brackets_stack.append(next)
            if len(opening_brackets_stack) < 2:
                mismatch_pos = Bracket(next, i + 1).position

        if next in ")]}":
            # Process closing bracket, write your code here
            if len(opening_brackets_stack) == 0:
                return Bracket(next, i + 1).position
            
            top = opening_brackets_stack.pop()
            
            if not are_matching(top, next):
                return Bracket(next, i + 1).position
            
    if len(opening_brackets_stack) == 0:
        return "Success"
    return mismatch_pos
        
def main():
    text = input()
    mismatch = find_mismatch(text)
    # Printing answer, write your code here
    print(mismatch)

if __name__ == "__main__":
    main()

Nayanexx.py
  • 121
  • 1
  • 5