Created
October 12, 2020 13:29
-
-
Save les-peters/ed5c5e052650159f8bde95991d4807e0 to your computer and use it in GitHub Desktop.
Lisp math simulator
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 | |
question = """ | |
Given a basic Lisp-like string expression, parse it (where the available | |
functions are add, subtract, multiply, and divide, and they all take in 2 values). | |
""" | |
def babyLisp(str): | |
ops = { | |
'add': '+', | |
'subtract': '-', | |
'multiply': '*', | |
'divide': '/', | |
'power': '**', | |
'modulo': '%' | |
} | |
loop = True | |
while loop is True: | |
loop = False | |
for op in ops: | |
p = '(\(' + op + ' (\d+) (\d+)\))' | |
c = re.compile(p) | |
m = c.search(str) | |
if m: | |
loop = True | |
str = re.sub(p, eval("'{}'.format(int(int(m.group(2)) " + ops[op] + " int(m.group(3))))"), str, count=1) | |
return str | |
print(babyLisp('(add 1 2)')) | |
print(babyLisp('(multiply 4 (add 2 3))')) | |
print(babyLisp('(subtract 8 3)')) | |
print(babyLisp('(multiply 3 4)')) | |
print(babyLisp('(add 3 (multiply 2 3))')) | |
print(babyLisp('(divide 36 9)')) | |
print(babyLisp('(power 3 4)')) | |
print(babyLisp('(modulo 12 5)')) | |
print(babyLisp('(add (add 1 2) (add 3 4))')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment