华为机试:仿 LISP 运算_仿lisp运算华为机试-CSDN博客https://blog.csdn.net/weixin_44052055/article/details/125902077看到这一篇博文, 感觉这个题目挺有意思的.
今天也做一个Python版本的. 后面可能会逐步把它实现成一个Lisp解释器.
import re
# 解析字符串(源代码), 生成树法树(AST)
def parse(expt):
expt = re.sub("\(", " ( ", expt)
expt = re.sub("\)", " ) ", expt)
res = []
for i in expt.strip().split():
if i != ')':
if re.match("^[0-9]+$", i):
i = int(i)
elif re.match("^[0-9][0-9.]*$", i):
i = float(i)
res.append(i)
if i == ')':
tmp = []
while res[-1] != '(':
tmp.insert(0, res.pop())
res[-1] = tmp
if '(' in res:
print('parse error: 括号不匹配')
raise ValueError()
return res
同时也写了一个测试代码.
from lisp_interpreter import *
# \testcases\test_demo1.py
def test_parse():
code1 = '(+ 2 (+ 3 4))'
code2 = '(lambda (x) (+ x 1))'
res1 = parse(code1)
res2 = parse(code2)
print('\n', res1, '\n', res2)
assert res1 == [['+', 2, ['+', 3, 4]]]
assert res2 == [['lambda', ['x'], ['+', 'x', 1]]]
测试运行PASS, 解析正确.
欢迎对Lisp感兴趣的同学一起讨论.
标签:tmp,re,LISP,res,res1,expt,parse,Python,机试 From: https://blog.csdn.net/weixin_46766770/article/details/144704002