Created
September 3, 2013 13:25
-
-
Save landau/6423883 to your computer and use it in GitHub Desktop.
Well formed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import argv | |
def is_left(a): | |
if a == '[' or a == '(' or a == '{': return True | |
return False | |
def is_right(a): | |
if a == ']' or a == '}' or a == ')': return True | |
return False | |
def is_match(left, right): | |
if left == '(' and right == ')': return True | |
if left == '{' and right == '}': return True | |
if left == '[' and right == ']': return True | |
return False | |
for string in open(argv[1], 'r'): | |
string = string.rstrip() | |
l = len(string) | |
if l % 2 != 0: | |
print 'False' | |
continue | |
is_formed = True | |
stack = [] | |
for char in string: | |
if is_right(char): | |
if len(stack) < 1: | |
is_formed = False | |
break | |
open_char = stack.pop() | |
if not is_match(open_char, char): | |
is_formed = False | |
break | |
else: | |
# left char | |
stack.append(char) | |
print str(is_formed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment