How to check if the parentheses and brackets are balanced?

Question:

I need to write a function that given a string with parenthesis and/or square brackets it is able to evaluate if they appear in the correct order. For example, in this string ‘([b])(aa)’ you can see that every time a parenthesis or square bracket is open, it is closed in the correct position. However, a string like ‘[(a])’ it is not closing the parenthesis or square brackets in the correct order as it should be ‘[(a)]’.

The function should return True or False depending on this correct position of both elements. I have tried the following code, but this logic seems to be infinite and it is not working if I have more than two parenthesis or square brackets opened.

def parenthesis(string):
  for a in range(len(string)):
    if string[a] == "(":
      for b in range(a,len(string)):
        if string[b] == "[":
          for c in range(b,len(string)):
            if string[c] == "]":
              for d in range(c,len(string)):
                if string[d] == ")":
                  return True
        elif string[b] == ")":
          return True
        else:
          return False

If I run the function over the string "([b])(aa)" it is returning false as output.

parenthesis("([b])(aa)")

How can I rewrite this function so it evaluates all the parenthesis and square brackets combinations properly?

Asked By: MatmataHi

||

Answers:

This is one of the stack implementations I know:

def is_balanced(s):
    stack = []
    for char in s:
        if char == "(" or char == "{" or char == "[":
            stack.append(char) 
        elif len(stack) <= 0:
            return False
        elif char == ")" and stack.pop() != "(":
            return False
        elif char == "]" and stack.pop() != "[":
            return False
        elif char == "}" and stack.pop() != "{":
            return False
    if len(stack) == 0:
        return True
    return False
Answered By: DontDownvote

This version is more DRY than the prior answer:

def is_balanced(parens: str) -> bool:
    # Link: https://stackoverflow.com/a/73341167/
    parens_map ={'(':')','{':'}','[':']'}
    stack = []
    for paren in parens:
        if paren in parens_map:  # is open
            stack.append(paren)
        elif paren in parens_map.values():  # is close
            if (not stack) or (paren != parens_map[stack.pop()]):
                return False
    return not stack
Answered By: Asclepius
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.