Advertisement
djangopdx

is_matched.py

Sep 18th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. #!/bin/python
  2. """ hackerrank coding challenge to determine if a string of brackets is balanced or not """
  3.  
  4.  
  5. def is_opposite(char1, char2):
  6.     # if char1 is the opposite kind of bracket as char2 then return True
  7.     # but this only works if char1 is of variety "LEFT bracket"
  8.     # this means that order counts
  9.     if char1 == "{" and char2 == "}":
  10.         return True
  11.     elif char1 == "[" and char2 == "]":
  12.         return True
  13.     elif char1 == "(" and char2 == ")":
  14.         return True
  15.     else:
  16.         return False
  17.  
  18. def is_matched(expression):
  19.     stack_string = []
  20.     expression = [ x for x in expression ]
  21.     # make the input string, expression, into a list object
  22.     while len(expression) != 0:
  23.         current_char = expression.pop(0)
  24.         # above code pops one character from the left side of the input
  25.         if current_char in '{[(':
  26.             stack_string.append(current_char)
  27.         elif current_char in ')}]' and len(stack_string) == 0:
  28.             return False
  29.         elif current_char in ')}]':
  30.             if is_opposite(stack_string[-1],current_char):
  31.                 stack_string.pop()
  32.         else:
  33.             return False
  34.     if len(stack_string) == 0:
  35.         return True
  36.     else:
  37.         return False
  38.  
  39. t = int(raw_input().strip())
  40. for a0 in xrange(t):
  41.     expression = raw_input().strip()
  42.     if is_matched(expression) == True:
  43.         print "YES"
  44.     else:
  45.         print "NO"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement