Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/python
- """ hackerrank coding challenge to determine if a string of brackets is balanced or not """
- def is_opposite(char1, char2):
- # if char1 is the opposite kind of bracket as char2 then return True
- # but this only works if char1 is of variety "LEFT bracket"
- # this means that order counts
- if char1 == "{" and char2 == "}":
- return True
- elif char1 == "[" and char2 == "]":
- return True
- elif char1 == "(" and char2 == ")":
- return True
- else:
- return False
- def is_matched(expression):
- stack_string = []
- expression = [ x for x in expression ]
- # make the input string, expression, into a list object
- while len(expression) != 0:
- current_char = expression.pop(0)
- # above code pops one character from the left side of the input
- if current_char in '{[(':
- stack_string.append(current_char)
- elif current_char in ')}]' and len(stack_string) == 0:
- return False
- elif current_char in ')}]':
- if is_opposite(stack_string[-1],current_char):
- stack_string.pop()
- else:
- return False
- if len(stack_string) == 0:
- return True
- else:
- return False
- t = int(raw_input().strip())
- for a0 in xrange(t):
- expression = raw_input().strip()
- if is_matched(expression) == True:
- print "YES"
- else:
- print "NO"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement