DiYane

Balanced Brackets

Jul 28th, 2023
1,019
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.49 KB | None | 0 0
  1. def is_balanced(expression):
  2.     stack = []
  3.     for char in expression:
  4.         if char == "(":
  5.             stack.append(char)
  6.         elif char == ")":
  7.             if not stack or stack[-1] != "(":
  8.                 return False
  9.             stack.pop()
  10.  
  11.     return len(stack) == 0
  12.  
  13. n = int(input())
  14. expression = ""
  15.  
  16. for _ in range(n):
  17.     line = input().strip()
  18.     expression += line
  19.  
  20. result = is_balanced(expression)
  21. if result:
  22.     print("BALANCED")
  23. else:
  24.     print("UNBALANCED")
  25.  
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment