Advertisement
Davitkova

more_exercises_04_balanced_brackets

May 26th, 2024
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. number_of_lines = int(input())
  2. string_of_brackets = ""
  3.  
  4. # read the input and append only brackets to a string
  5. for line in range(number_of_lines):
  6.     current_input = input()
  7.     if current_input == ")" or current_input == "(":
  8.         string_of_brackets += current_input
  9.  
  10. # First check if the number of entered brackets is even. If not, print string is UNBALANCED and exit
  11. if len(string_of_brackets) % 2 != 0:
  12.     print("UNBALANCED")
  13.     exit()
  14.  
  15. # There are no nested brackets by definition.
  16. # Check if odd positions are opening brackets. If any of them is not, print UNBALANCED and exit
  17. for opening_bracket in string_of_brackets[::2]:
  18.     if opening_bracket != "(":
  19.         print("UNBALANCED")
  20.         exit()
  21.  
  22. # Check if even positions are closing brackets. If any of them is not, print UNBALANCED and exit
  23. for closing_bracket in string_of_brackets[1::2]:
  24.     if closing_bracket != ")":
  25.         print("UNBALANCED")
  26.         exit()
  27.  
  28. # if all conditions passed, the string is balanced
  29. print("BALANCED")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement