相关原理
理论部分请参照上面的博客,写的很清楚。
好的我们来看代码
举个栗子
(9-((1+3)*2))/2
结果是0.5
def infix_to_prefix(expression):
assert type(expression)==list
expression.reverse()
priority={'+':0,'-':0,'*':1,'/':1}
operator_list=[]#运算符的英文是operator
operand_list=[]#操作数的英文是operand
for each_element in expression:
if each_element not in priority and each_element not in ['(',')']:
operand_list.append(each_element)#操作数直接push到操作数栈
else:
if each_element not in ['(',')']:
#表明此时是运算符,不是括号
if len(operator_list)==0 or operator_list[-1]==')':
#如果运算符栈为空,或者栈顶元素是右括号,那么直接push
operator_list.append(each_element)
elif priority[each_element]>=priority[operator_list[-1]]:
#如果这个运算符的优先级大于栈顶运算符的优先级,直接push
operator_list.append(each_element)
else:
#此时需要将运算符栈顶的运算符弹出来放到操作数栈中
operand_list.append(operator_list.pop())
else:
#此时是括号
if each_element==')':
#右括号直接入栈
operator_list.append(each_element)
else:
assert each_element=='('
#左括号的时候从运算符栈中弹出运算符,直到遇到右括号为止,将这对括号中间的运算符放到操作数栈中
while(operator_list[-1]!=')'):
operand_list.append(operator_list.pop())
operator_list.pop()
while(len(operator_list)!=0):
operand_list.append(operator_list.pop())
operand_list.reverse()
return operand_list
上面的函数已经将中缀表达式转化为了前缀表达式,相关原理那篇博文已经说的很清楚了。
但是那篇博客没有介绍如何根据前缀表达式计算结果,这里我说一下
- 定义一个栈,从右向左扫描前缀表达式
- 如果是操作数,则将操作数压入栈中
- 如果是运算符,则从栈中取出来两个操作数,计算结果,再放回栈中
下面我们根据前缀表达式计算结果
def compute_prefix_expression(prefix):
stack=list()
for i in range(len(prefix)-1,-1,-1):
element=prefix[i]
if element not in ['+','-','*','/']:
stack.append(element)
else:
a=stack.pop()
b=stack.pop()
stack.append(str(eval(a+element+b)))
assert len(stack)==1
return eval(stack[0])
结果: