Created
August 7, 2019 12:33
-
-
Save vincent-prz/ff7769b0638349d59823bbd3401821ab 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
import re | |
def _parse_sequence(sequence): | |
remainder_to_parse = sequence | |
tokens = [] | |
while len(remainder_to_parse) > 0: | |
match2 = re.match(r"^(\(.*\))", remainder_to_parse) | |
if match2 is not None: | |
token = match2.group(1) | |
else: | |
token = remainder_to_parse.split()[0] | |
tokens.append(token) | |
remainder_to_parse = remainder_to_parse[len(token) + 1 :] | |
return [parse(token) for token in tokens] | |
def parse(input_text): | |
match = re.match(r"^\((.*)\)$", input_text) | |
if match is not None: | |
return _parse_sequence(match.group(1)) | |
if input_text.isdigit(): | |
return int(input_text) | |
return input_text | |
if __name__ == "__main__": | |
print(parse(input())) |
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
import unittest | |
from lisp_parser import parse | |
class TestLispParser(unittest.TestCase): | |
def test_parse_single_digit(self): | |
self.assertEqual(parse("(1)"), [1]) | |
def test_parse_addition(self): | |
self.assertEqual(parse("(+ 1 2)"), ["+", 1, 2]) | |
def test_parse_nested_expression(self): | |
self.assertEqual(parse("(list (+ 1 2) 9)"), ["list", ["+", 1, 2], 9]) | |
def test_parse_example(self): | |
self.assertEqual( | |
parse("(first (list 1 (+ 2 3) 9))"), ["first", ["list", 1, ["+", 2, 3], 9]] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment