Program to check balanced brackets for equation

Question:

I am trying to write a program which checks balanced brackets for equation, my program is checking the brackets but its only looking for brackets and only give the right answer for the bracket but different answer for equation

My expected output is

exp1 = "(2+3)+(1-5)" # True
exp2 = "((3*2))*(7/3))" # False
exp3 = "(3*5))]" # False

My program below:

def is_valid(myStr):
  """ Check the orders of the brackets
      Returns True or False
  """
  opening = ['(', '[', '{']
  closing = [')', ']', '}']
  stack = []
  for i in myStr:
    if i in opening:
        stack.append(i)
    elif i in closing:
        pos = closing.index(i)
        if ((len(stack) > 0) and
            (opening[pos] == stack[len(stack)-1])):
            stack.pop()
        else:
            return False
    if len(stack) == 0:
        return True
    else:
        return False
  return 

My program returning me False for all above equations, where am I doing wrong.

Asked By: AHF

||

Answers:

Found few bugs and improvements.

PS: It’s better not to use i,j as variable but some meaningful names such as ele, element etc.

def is_valid(myStr):
    """ Check the orders of the brackets
      Returns True or False
  """
    opening = ['(', '[', '{']
    closing = [')', ']', '}']
    stack = []
    for i in myStr:
        if i in opening:
            stack.append(i)
        elif i in closing:
            pos = closing.index(i)
            if ((len(stack) > 0) and
                    (opening[pos] == stack[-1])):
                stack.pop()
            else:
                stack.append(i)
        else:
            pass
    if len(stack) == 0:
        return True
    else:
        return False


print(is_valid('(2+3)+(1-5)'))
print(is_valid('((3*2))*(7/3))'))
print(is_valid('(3*5))]'))
# True
# False
# False
Answered By: Neeraj

The last if-else statements in your program checking if the stack length is 0 should be outside the for loop. I have changed the code for your reference and checked it with your examples. It worked fine.

def is_valid(myStr):
opening = ['(', '[', '{']
closing = [')', ']', '}']

stack = []
for i in myStr:
    if i in opening:
        stack.append(i)
        print(stack)
    elif i in closing:
        pos = closing.index(i)
        if ((len(stack) > 0) and
            (opening[pos] == stack[len(stack)-1])):
            stack.pop()
        else:
            return False
if len(stack) == 0:
    return True
else:
    return False
Answered By: Shivam Roy

in Javascript;

const brackets = new Map()
brackets.set('{', '}');
brackets.set('(', ')');
brackets.set('[', ']');
function baz(str) {
  let temp = []
  for (let i = 0; i < str.length; i++) {
    if (brackets.has(str[i])) {
      temp.push(str[i])  
    }
   else if (brackets.get(temp?.findLast((item) => item)) === str[i]) {
      temp.pop()
    }
    else {
      temp.push(str[i])
    }
  }    
    return !!temp.length
}
baz('({[([]())]})')
baz('{[]}')
baz('{(])}')
baz('{([)]}')

Answered By: talatatac
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.