#!/usr/bin/python
#coding=utf-8
import sys
sys.path.append('/home/administrator/python_dir/tools')
from Stack import Stack
num_stack = Stack()
operator_stack = Stack()
brackets_stack = Stack()
import char_tools
def execute_express(press):
i=0;
while i < len(press):
char = press[i]
if char_tools.str_is_number(press[i]):
j=exe_num(press,i)
if j > i and j != -1:
num_stack.push(press[i:j])
i=j
else:
num_stack.push(press[i])
i = i+1
elif char_tools.str_is_operator(press[i]):
operator_stack.push(press[i])
i = i+1
elif press[i] == '(':
brackets_stack.push(press[i])
i = i+1
elif press[i] == ')':
if brackets_stack.isEmpty() or operator_stack.isEmpty():
print '有错误'
raise RuntimeError('有错误')
else:
value = exe_num_value(num_stack.pop(),num_stack.pop(),operator_stack.pop())
num_stack.push(value)
i = i+1
else:
i = i+1
def exe_num_value(num0,num1,operator):
value = None
if operator == '+':
value = int(num0)+int(num1)
elif operator == '-':
value = int(num1)-int(num0)
elif operator == '*':
value = int(num1)*int(num0)
elif operator == '/':
value = int(num1)/int(num0)
else :
print '出现错误!\t\n'
raise RuntimeError('有错误')
return value
def exe_num(press,i):
while i <len(press):
if char_tools.str_is_number(press[i]):
i = i+1
continue
else:
return i
return -1
if __name__ == '__main__':
print '算数表达式计算'
execute_express('((*2 2)+(+ 1 2 ))')
print num_stack.pop()