首先,前缀表示法不需要任何括号 - 您纯粹通过字符串中元素的排序来控制操作的优先级。例如,如果您想要2*(1+4)*3
,您的前缀表达式将变为"* * 2 + 1 4 3"
。
2*1+4*3
将成为"+ * 2 1 * 4 3"
。使用split(),这会给你一个运算符和操作数的列表,['+', '*', '2', '1', '*', '4', '3']
。这将处理空白跳过。然后为了评估它,递归地遍历列表:如果找到一个运算符,从当前位置开始从列表中获取下两个操作数;如果你找到一个常数,就返回它。每次您从列表中拉出某些东西时,请推进当前位置。
opns = {
'+' : lambda a,b: a+b,
'-' : lambda a,b: a-b,
'*' : lambda a,b: a*b,
'/' : lambda a,b: a/b,
}
def prefix_eval(expr, posn=0):
# save current element from expression
current = expr[posn]
# advance parsing position
posn += 1
if current in ['+','-','*','/']:
# binary operator, get next two operands
op1,posn = prefix_eval(expr, posn)
op2,posn = prefix_eval(expr, posn)
# evaluate operation from current, on operands
return opns[current](op1,op2), posn
else:
# not an operator, must be a numeric value
return float(current),posn
print prefix_eval("+ * 2 1 * 4 3".split())[0]
print prefix_eval("* * 2 + 1 4 3".split())[0]
打印
14.0
30.0
输出是否包含除数字和基本操作之外的其他内容?如果是,那么遗传程序的名称是什么? (你的意思是任何机会都有遗传编程吗?) – Matt
你的“表达式树数据结构”是什么样的?你想从头开始分析器,还是使用更强大的库?你为什么想要将解析和评估分成两个文件? – poke