前缀表达式求值(Prefix expressions)

这篇博客介绍如何计算前缀表达式,并提供了一个使用Python实现的代码示例。程序通过读取输入文件,逐行处理前缀表达式,根据运算符进行计算,最终输出表达式的结果。

Description:

You are given a prefix expression. Write a program to evaluate it.

Input sample:

The first argument will be an input file with one prefix expression per line. e.g.

* + 2 3 4
Your 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 '/' 

Output sample:

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)



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值