Skip to content

Instantly share code, notes, and snippets.

@landau
Created September 3, 2013 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save landau/6423883 to your computer and use it in GitHub Desktop.
Save landau/6423883 to your computer and use it in GitHub Desktop.
Well formed
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