SimeonTs

SUPyF2 D.Types and Vars More Exercises - 05. Balanced Bracke

Sep 27th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. """
  2. Data Types and Variables - More Exercises
  3. Check your code: https://judge.softuni.bg/Contests/Practice/Index/1723#4
  4.  
  5. SUPyF2 D.Types and Vars More Exercises - 05. Balanced Brackets
  6.  
  7. Problem:
  8. You will receive n lines. On those lines, you will receive one of the following:
  9. • Opening bracket – “(“,
  10. • Closing bracket – “)” or
  11. • Random string
  12. Your task is to find out if the brackets are balanced.
  13. That means after every closing bracket should follow an opening one.
  14. Nested parentheses are not valid, and if two consecutive opening brackets exist,
  15. the expression should be marked as unbalanced.
  16.  
  17. Input
  18. • On the first line, you will receive n – the number of lines, which will follow
  19. • On the next n lines, you will receive “(”, “)” or another string
  20.  
  21. Output
  22. You have to print “BALANCED”, if the parentheses are balanced and “UNBALANCED” otherwise.
  23.  
  24. Constraints
  25. • n will be in the interval [1…20]
  26. • The length of the stings will be between [1…100] characters
  27.  
  28. Examples
  29. Input:
  30. 8
  31. (
  32. 5 + 10
  33. )
  34. * 2 +
  35. (
  36. 5
  37. )
  38. -12
  39. Output:
  40. BALANCED
  41.  
  42. Input:
  43. 6
  44. 12 *
  45. )
  46. 10 + 2 -
  47. (
  48. 5 + 10
  49. )
  50.  
  51. Output:
  52. UNBALANCED
  53. """
  54. n = int(input())
  55. opened = 0
  56. closed = 0
  57.  
  58. for i in range(n):
  59.     line = input()
  60.     if line == "(":
  61.         opened += 1
  62.         if (opened - closed) > 1:
  63.             print("UNBALANCED")
  64.             exit(0)
  65.     elif line == ")":
  66.         closed += 1
  67.         if (opened - closed) != 0:
  68.             print("UNBALANCED")
  69.             exit(0)
  70.  
  71. if opened == closed:
  72.     print("BALANCED")
  73. else:
  74.     print("UNBALANCED")
Add Comment
Please, Sign In to add comment