@
rickyleegee 本来我的意思是直接
expr_str = """(2*3)+(4-2)"""
ans = eval(expr_str)
后来发现你好像是在做 python 题学习递归,假期要结束了,刚好蛋疼给你写了个答案:
# -*- coding: utf-8 -*-
import json
def is_raw_type(d : dict) -> bool:
type_words = ['int']
for k in d.keys():
if k not in type_words:
return False
return True
def is_basic_expr(d : dict) -> bool:
op_words = ['plus', 'times', 'minus']
if len(d.keys()) != 1:
return False
else:
k,v = d.copy().popitem()
if k in op_words:
if isinstance(v,dict):
return is_raw_type(v)
if isinstance(v,list):
return (sum([not is_raw_type(kv) for kv in v]) == 0)
def calc_parser(d : dict):
if is_raw_type(d):
return d
elif is_basic_expr(d):
k,v = d.popitem()
if k == "plus":
return {'int':sum([int(sub_v['int']) for sub_v in v])}
elif k == "minus":
return {'int':v[0]['int']-v[1]['int']}
elif k == "times":
s = 1
for sub_v in v:
s = int(s*sub_v['int'])
return {'int':s}
else:
return {'int':0}
elif len(d.keys()) == 1:
e = d.copy()
k,v = d.popitem()
e[k] = [calc_parser(sub_v) for sub_v in v]
return calc_parser(e)
test = """{ "root": { "description": "This is your first nested expression, and it evaluates to 8. If you have difficulties understanding it, it reads (2*3)+(4-2).", "plus": [{ "times": [{ "int": 2 }, { "int": 3 }] }, { "minus": [{ "int": 4 }, { "int": 2 }] }] } }"""
d_with_description = json.loads(test)
for k,v in d_with_description['root'].items():
if k != 'description':
d = {k:v}
print(calc_parser(d))
这也是为了证明题中自己发明的那种自定义 json 语法格式多蛋疼~