Last answered:

22 Mar 2024

Posted on:

22 Mar 2024

1

Resolved: Can anyonne tell me if the following code fails in any conditions ?

Assumption  - the string which is being checked only contains brackets

class stacks(object):
    def __init__(self):
        self.stack = []
    def push(self,item):
        self.stack.append(item)
    def pop(self):
        if not self.stack:
            return None
        else:
            return self.stack.pop()
    def peek(self):
        if not self.stack:
            return None
        else:
            return self.stack[-1]
    def is_empty(self):
        if not self.stack:
            return True
        else:
            return False
    def show(self):
        if not self.stack:
            return []
        else:
            return self.stack

x = stacks()
check_msg = '{[({})])'
def check_balanced(msg):
    closing = []
    for l in msg:
        if l=='{' or l=='(' or l=='[':
            x.push(l)
        else:
            closing.append(l)
    for i in closing:
        if x.peek() == '(' and i==')':
            n = x.pop()
        elif x.peek() == '{' and i=='}':
            n = x.pop()
        elif x.peek() == '[' and i==']':
            n = x.pop()
    if x.is_empty():
        print(f'{msg} has balanced brackets')
    else:
        print(f'{msg} has not balanced brackets')
check_balanced(check_msg)

 

1 answers ( 1 marked as helpful)
Posted on:

22 Mar 2024

0

I have tested the code and found wrong result for the input string - '][[({})]]'

I have identified the issue arises when i check the length of the list (closing) as it does not remove all the elements from the stack in this case


Submit an answer