首先,前綴表示法不需要任何括號 - 您純粹通過字符串中元素的排序來控制操作的優先級。例如,如果您想要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