Advertisement
OpataJoshua

Untitled

Jan 14th, 2023
870
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1.  
  2. #User function Template for python3
  3.  
  4. class Solution:
  5.    
  6.     #Function to check if brackets are balanced or not.
  7.     def ispar(self,x):
  8.         # code here
  9.         startChars = ['{', '[', '(']
  10.         metStartingChars = []
  11.         charMap = {
  12.             "{":"}","[":"]","(":")"
  13.         }
  14.         if (len(x) % 2 != 0 ) or (x[0] not in startChars) :
  15.             return False
  16.        
  17.         for char in x:
  18.             # if char is a starting character lets expect an ending for it
  19.             if char in startChars:
  20.                 metStartingChars.append(char)
  21.            
  22.             # else if ending character? it be the ending character iof the last starting character we met
  23.             else:
  24.                 lastestStart = metStartingChars[-1] if 0 < len(metStartingChars) else None
  25.                 if charMap.get(lastestStart, None) == char :
  26.                     metStartingChars.pop()
  27.                 else:
  28.                     return False
  29.            
  30.         return not metStartingChars
  31.    
  32.    
  33. #{
  34.  # Driver Code Starts
  35. #Initial Template for Python 3
  36.  
  37. import atexit
  38. import io
  39. import sys
  40.  
  41. #Contributed by : Nagendra Jha
  42.  
  43.  
  44. _INPUT_LINES = sys.stdin.read().splitlines()
  45. input = iter(_INPUT_LINES).__next__
  46. _OUTPUT_BUFFER = io.StringIO()
  47. sys.stdout = _OUTPUT_BUFFER
  48.  
  49. @atexit.register
  50.  
  51. def write():
  52.     sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
  53.  
  54.  
  55. if __name__ == '__main__':
  56.     test_cases = int(input())
  57.     for cases in range(test_cases) :
  58.         #n = int(input())
  59.         #n,k = map(int,imput().strip().split())
  60.         #a = list(map(int,input().strip().split()))
  61.         s = str(input())
  62.         obj = Solution()
  63.         if obj.ispar(s):
  64.             print("balanced")
  65.         else:
  66.             print("not balanced")
  67. # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement