You are given a prefix expression. Write a program to evaluate it.
The first argument will be an input file with one prefix expression per line. e.g.
* + 2 3 4Your program has to read this and insert it into any data structure you like. Traverse that data structure and evaluate the prefix expression. Each token is delimited by a whitespace. You may assume that the only valid operators appearing in test data are '+','*' and '/'
Print to stdout, the output of the prefix expression, one per line. e.g.
20
对于一个前缀表达式的求值而言,首先要从右至左扫描表达式,从右边第一个字符开始判断,如果当前字符是数字则一直到数字串的末尾再记录下来,如果是运算符,则将右边离得最近的两个“数字串”作相应的运算,以此作为一个新的“数字串”并记录下来。一直扫描到表达式的最左端时,最后运算的值也就是表达式的值。例如,前缀表达式“- 1 + 2 3“的求值,扫描到3时,记录下这个数字串,扫描到2时,记录下这个数字串,当扫描到+时,将+右移做相邻两数字串的运算符,记为2+3,结果为5,记录下这个新数字串,并继续向左扫描,扫描到1时,记录下这个数字串,扫描到-时,将-右移做相邻两数字串的运算符,记为1-5,结果为-4,所以表达式的值为-4。(来自百度百科http://baike.baidu.com/view/3095092.htm#3)
import sys
def compute_prefix(line):
ll = line.split()
ll.reverse()
#print ll
help = []
operators = ['+','*','/']
n = len(ll)
for i in range(n):
if ll[i] in operators:
tmp = str(eval(help.pop()+ll[i]+help.pop()))
help.append(tmp)
else:
help.append(ll[i])
#print help
print help[0]
if __name__ == "__main__":
argv = sys.argv
inf = open(argv[1],'r')
while True:
line = inf.readline()
if len(line) == 0:
break
compute_prefix(line)