Last active
April 28, 2020 16:06
-
-
Save mynameisvinn/ee9fcd1d2ef4bc4846c46ee8bb850f8b to your computer and use it in GitHub Desktop.
recurse center, pair programming
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 create_tokens(source): | |
"""convert source to tokens. | |
convert a string "(first (list 1 (+ 2 3) 9))" into a python list | |
['(', 'first', '(', 'list', '1', '(', '+', '2', '3', ')', '9', ')', ')']. | |
this conversion allows us to recursively inspect each element in the list. | |
""" | |
return source.replace('(',' ( ').replace(')',' ) ').split() | |
def create_ast(tokens): | |
"""convert tokens to ast. | |
For example, if your code is given "(first (list 1 (+ 2 3) 9))", it could | |
return a nested array like ["first", ["list", 1, ["+", 2, 3], 9]]. | |
""" | |
# pop off first token and examine, first in first out | |
token = tokens.pop(0) | |
# whenever we encounter an open parenthesis, we create a new list | |
if '(' == token: | |
L = [] | |
while tokens[0] != ')': # break when we see a closed paren | |
L.append(create_ast(tokens)) # recursively read tokens | |
tokens.pop(0) # pop off ')' since we dont need it for our ast | |
return L | |
# base case | |
else: | |
return atom(token) | |
def atom(token): | |
""" | |
if we have a string "2", convert it to a python integer 2. otherwise, keep | |
it as a python string. | |
""" | |
try: | |
return int(token) | |
except ValueError: | |
return str(token) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment