Created
October 17, 2010 14:56
-
-
Save stucchio/630918 to your computer and use it in GitHub Desktop.
Coroutine paren matcher
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
def matchparen(): | |
ct = 0 | |
msg = None | |
result = None | |
while (msg != True): | |
msg = (yield ct) | |
if msg == '(': | |
ct += 1 | |
if msg == ')': | |
if ct <= 0: | |
result = 'PARSE FAIL' | |
break | |
else: | |
ct -= 1 | |
if result is None and ct == 0: | |
result = "SUCCESS" | |
else: | |
result = "PARSE FAIL" | |
while True: | |
yield result | |
#A set of matched parenthesis | |
parser = matchparen() | |
parser.next() | |
for m in "(()foo(()bar))": | |
parser.send(m) | |
print parser.send(True) | |
#A set of unmatched parenthesis | |
parser = matchparen() | |
parser.next() | |
for m in "(()foo(()ba)r))": | |
parser.send(m) | |
print parser.send(True) | |
#A set of unmatched parenthesis | |
parser = matchparen() | |
parser.next() | |
for m in "(()foo(()ba)r)(": | |
parser.send(m) | |
print parser.send(True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment