#!/usr/bin/python


class Stack:
	def __init__(self):
		self.items=[]

	def push(self,item):
		self.items.append(item)

	def pop(self):
		return self.items.pop()

	def isEmpty(self):
		return (self.items ==[])


def cal_str(string):
	import re
	tokens = re.split("([^0-9])",string)
	#print tokens
	#print tokens[0]
	stack = Stack()
	index=0
	while index<len(tokens):
		if tokens[index] == ' ' or tokens[index]=='':
			index=index+1
			continue
		if tokens[index]=='+':
			sum=int(stack.pop()) +int(stack.pop())
			stack.push(sum)
		elif tokens[index]=='*':
			product=int(stack.pop()) * int(stack.pop())
			stack.push(product)
		else:
			stack.push(tokens[index])
		index=index+1

	return stack.pop()
if __name__ =='__main__':
        print cal_str("15 3 + 2 *")



因为书上没有将STR转换为int,因此,失败,实际中应该转为float,而且,运算远远没有这么简单,只是理解下栈的应用。
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐