Syntax error Check if concatenation of two strings is balanced or not in Python

Check if concatenation of two strings is balanced or not in Python



Suppose we have two bracket sequences s and t with only these characters '(' and ')'. We have to check whether the concatenated string of s and t is balanced or not. The concatenation can be done by s | t or t | s.

So, if the input is like s = "()()))", t = "()(()(", then the output will be True because if we concatenate t | s, then we will get "()(()(()()))", which is balanced.

To solve this, we will follow these steps −

  • Define a function is_balanced_parenthesis() . This will take string
  • stack := a new list
  • for i in range 0 to size of string, do
    • if string[i] is same as '(', then
      • push string[i] into stack
    • otherwise,
      • if stack is empty, then
        • return False
      • otherwise,
        • pop from stack
  • if stack is not empty, then
    • return False
  • return True
  • From the main method do the following −
  • if is_balanced_parenthesis(s + t) is true, then
    • return True
  • return is_balanced_parenthesis(t + s)

Let us see the following implementation to get better understanding −

Example

 Live Demo

def is_balanced_parenthesis(string):
   stack = []
   for i in range(len(string)):
      if string[i] == '(':
         stack.append(string[i])
      else:
         if len(stack) == 0:
            return False
         else:
            stack.pop()
   if len(stack) > 0:
      return False
   return True
def solve(s, t):
   if is_balanced_parenthesis(s + t):
      return True
   return is_balanced_parenthesis(t + s)
s = "()()))"
t = "()(()("
print(solve(s, t))

Input

"()()))", "()(()("

Output

True
Updated on: 2020-12-30T13:45:41+05:30

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements