Created
December 13, 2009 12:30
-
-
Save bebraw/255398 to your computer and use it in GitHub Desktop.
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
class Operation: | |
def __eq__(self, other): | |
return self.__class__ == other.__class__ | |
def matches(self, line): | |
def zip_strs(a, b): | |
def separate(str): | |
return [char for char in str] | |
return zip(separate(a), separate(b)) | |
self.match_args = [] | |
for syntax_part, line_part in zip_strs(self.syntax, line): | |
if syntax_part == '%': | |
arg = line_part | |
self.match_args.append(arg) | |
elif syntax_part != line_part: | |
return False | |
return True | |
def match(self): | |
return self.__class__(*self.match_args) | |
class Pen(Operation): | |
syntax = 'P %' | |
def __init__(self, number=0): | |
self.number = int(number) | |
def __eq__(self, other): | |
return self.number == other.number | |
class Down(Operation): syntax = 'D' | |
class Up(Operation): syntax = 'U' | |
class Direction(Operation): | |
def __init__(self, amount=0): | |
self.amount = int(amount) | |
def __eq__(self, other): | |
return self.amount == other.amount | |
class East(Direction): syntax = 'E %' | |
class North(Direction): syntax = 'N %' | |
class South(Direction): syntax = 'S %' | |
class West(Direction): syntax = 'W %' | |
class Parser: | |
def __init__(self, operations): | |
self.operations = operations | |
def parse(self, line): | |
ret = [] | |
for line in code.splitlines(): | |
ret.append(self.parse_line(line)) | |
return ret | |
def parse_line(self, line): | |
for operation in self.operations: | |
if operation.matches(line): | |
return operation.match() | |
code = '''P 2 # select pen 2 | |
D # pen down | |
W 2 # draw west 2cm | |
N 1 # then north 1 | |
E 2 # then east 2 | |
S 1 # then back south | |
U # pen up''' | |
operations = (Pen(), Down(), West(), North(), East(), South(), Up(), ) | |
parser = Parser(operations) | |
result = parser.parse(code) | |
assert result[0] == Pen(2) | |
assert result[1] == Down() | |
assert result[2] == West(2) | |
assert result[3] == North(1) | |
assert result[4] == East(2) | |
assert result[5] == South(1) | |
assert result[6] == Up() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment