算术表达式字符串求值

问题: 计算字符串“10+12*13-30/20”的值

思路:

第一步:从左到右解析字符串,将数值与运算符放入数组

第二步:先计算乘除法,将求值放入队列

第三步:依次出队列,计算最终值

python代码实现如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
cal_string = '10+12*13-30/20'
#分隔字符串
symbol = ['+', '-', '*', '/']
one_word = ''
data = []
for c in cal_string:
    if c not in symbol:
        one_word += c
    else:
    	data.append(int(one_word))
    	data.append(c)
    	one_word = ''
data.append(one_word)
print data

#计算乘除,将运算完的值入队列
hign_symbol = ['*', '/']
queue = []
cur_symbol = ''
for one in data:
    if cur_symbol == '':
	if one in hign_symbol:
	    cur_symbol = one		
        else:
	    queue.append(one)
    else:
	last_one = queue.pop()
	if cur_symbol == '*':
	    new_one = float(last_one) * float(one)		    
            queue.append(new_one)
	else:
	    new_one = float(last_one) / float(one)
	    queue.append(new_one)
	cur_symbol = ''
print queue

#将队列数据出队列,计算最后值
result = 0
cur_symbol = ''
for one in queue:
    if one != '+' and one != '-':
	if cur_symbol == '':
	    result = one
	else:
	    if cur_symbol == '+':
		result = result + one
	    else:
		result = result - one
    else:
	cur_symbol = one
print result
输出结果:

[10, '+', 12, '*', 13, '-', 30, '/', '20']
[10, '+', 156.0, '-', 1.5]
164.5



猜你喜欢

转载自blog.csdn.net/xal0610/article/details/80010331