Python Json树-表达式求值
我有一个json表示以下格式的数学表达式,需要对其求值Python Json树-表达式求值,python,json,algorithm,data-structures,tree,Python,Json,Algorithm,Data Structures,Tree,我有一个json表示以下格式的数学表达式,需要对其求值 { "operator":"+", "params": ["60" , { "operator":"/", "params":[ "alias3",
{
"operator":"+",
"params": ["60" , {
"operator":"/",
"params":[
"alias3",
{
"operator":"+",
"params":["alias1","alias2"]
}
]
}]
}
上述结构的示例如下所示:
{
"operator":"abs",
"params": [
{
"operator":"/",
"params":[
{
"operator": "*",
"params":
[
"100",
{
"operator": "/",
"params": ["2000", "40"]
}
]
},
{
"operator":"+",
"params":[
"30",
{
"operator": "*",
"params": [
"25",
{
"operator": "-",
"params": ["60", "15"]
}
]
}
]
}
]
}
]
}
注:
- 使用的运算符为+、-、*、/、abs
- 除了abs()之外,每个操作符都有2个参数
- 在任何给定级别,上述任何操作员都可以在场
abs((100*(2000/40))/(30+(25*(60-15))
,计算结果为4.329
请帮助我评估这个json表达式树
我找到的解决方案是:
这个问题几乎类似于表达式树的计算。但是,输入是json格式的。这就是我努力读取json数据的地方。
当输入为树(使用节点)格式时,Psuedo代码如下-这将是一个递归函数
Let t be the syntax tree
If t is not null then
If t.info is operand then
Return t.info
Else
A = solve(t.left)
B = solve(t.right)
return A operator B
where operator is the info contained in t
我尝试使用相同的psuedo代码并从json读取输入。
但是,我无法找到正确的根和叶的情况下退出递归函数。
通过查看json,可以注意到,叶的大小写将是“string”,而非叶的大小写将是“dictionary”。但,问题是“运算符”也是字符串,并且运算符永远不会是叶子。任何帮助或建议都将不胜感激。提前感谢。您可以检查叶的
类型,以确定是否必须将其解析为float或dict,从而使用递归
您可以使用操作符上的一些if
来确定要应用的操作。(这里我使用operator包来避免一些ifs)
您可以使用递归函数,其中params
由函数本身映射。基本情况是函数的参数不是字典(而是基元类型)
字典文本允许将运算符名称转换为实际的运算符函数,而splash运算符同样可以很好地处理一元运算符和二元运算符,为动态检索的函数提供所有“已解决”的参数(1或2)
Let t be the syntax tree
If t is not null then
If t.info is operand then
Return t.info
Else
A = solve(t.left)
B = solve(t.right)
return A operator B
where operator is the info contained in t
from operator import add, sub, mul, truediv
def solve(tree):
if type(tree) is not dict:
return float(tree) # convert string to float
return {
"+": add,
"-": sub,
"*": mul,
"/": truediv,
"abs": abs
}[tree["operator"]](*map(solve, tree["params"]))