python实现逆波兰计算表达式实例详解

yipeiwu_com5年前Python基础

本文实例讲述了python实现逆波兰计算表达式的方法。分享给大家供大家参考。具体分析如下:

逆波兰表达式又叫做后缀表达式。在通常的表达式中,二元运算符总是置于与之相关的两个运算对象之间,所以,这种表示法也称为中缀表示。波兰逻辑学家J.Lukasiewicz于1929年提出了另一种表示表达式的方法。按此方法,每一运算符都置于其运算对象之后,故称为后缀表示。

# -*- coding: utf-8 -*-
symbol_priority = {}
symbol_priority[0] = ['#']
symbol_priority[1] = ['(']
symbol_priority[2] = ['+', '-']
symbol_priority[3] = ['*', '/']
symbol_priority[4] = [')']
def comparePriority(symbol, RPN_stack, symbol_stack):
  '''Compare priority between two symbols'''
  global symbol_priority
  if len(symbol_stack) > 0:
    symbol_pop = symbol_stack.pop()
  else:
    return
  for list in symbol_priority.values():
    if (symbol in list) and (symbol_pop in list):
      '''same priority'''
      symbol_stack.append(symbol_pop)
      symbol_stack.append(symbol)
      return
    elif symbol in list:
      '''symbol is smaller'''
      RPN_stack.append(symbol_pop)
      #recusion call
      comparePriority(symbol, RPN_stack, symbol_stack)
      return
    elif symbol_pop in list:
      '''symbol is bigger'''
      symbol_stack.append(symbol_pop)
      symbol_stack.append(symbol)
      return
    else:
      continue
    symbol_stack.append(symbol_pop)
    return
def scanEveryone(input_string, RPN_stack, symbol_stack):
  for ch in input_string:
    if ch.isdigit():
      RPN_stack.append(ch)
    else:
      if len(symbol_stack) > 0:
        if ch == '(':
          symbol_stack.append(ch)
        elif ch == ')':
          while True:
            symbol_pop = symbol_stack.pop()
            if symbol_pop == '(':
              break
            else:
              RPN_stack.append(symbol_pop)
        else:
          comparePriority(ch, RPN_stack, symbol_stack)
      else:
        symbol_stack.append(ch)
def scanInput(RPN_stack, symbol_stack):
  input_string = raw_input()
  input_string += '#'
  scanEveryone(input_string, RPN_stack, symbol_stack)
def calRPN(RPN_stack):
  value_stack = []
  RPN_stack.append('#')
  for value in RPN_stack:
    if value == '#':
      return value_stack.pop()
      break
    if value.isdigit():
      value_stack.append(value)
    else:
      right_value = value_stack.pop()
      left_value = value_stack.pop()
      cal_string = left_value + value + right_value
      value_stack.append(str(eval(cal_string)))
def main():
  RPN_stack = []
  symbol_stack = []
  scanInput(RPN_stack, symbol_stack)
  print calRPN(RPN_stack)
if __name__ == '__main__':
  main()

calRPN.py

# -*- coding: utf-8 -*-
symbol_priority = {}
symbol_priority[0] = ['#']
symbol_priority[1] = ['(']
symbol_priority[2] = ['+', '-']
symbol_priority[3] = ['*', '/']
symbol_priority[4] = [')']
def comparePriority(symbol, RPN_stack, symbol_stack):
  '''Compare priority between two symbols'''
  global symbol_priority
  if len(symbol_stack) > 0:
    symbol_pop = symbol_stack.pop()
  else:
    return
  for list in symbol_priority.values():
    if (symbol in list) and (symbol_pop in list):
      '''same priority'''
      symbol_stack.append(symbol_pop)
      symbol_stack.append(symbol)
      return
    elif symbol in list:
      '''symbol is smaller'''
      RPN_stack.append(symbol_pop)
      #recusion call
      comparePriority(symbol, RPN_stack, symbol_stack)
      return
    elif symbol_pop in list:
      '''symbol is bigger'''
      symbol_stack.append(symbol_pop)
      symbol_stack.append(symbol)
      return
    else:
      continue
    symbol_stack.append(symbol_pop)
    return
def scanEveryone(input_string, RPN_stack, symbol_stack):
  for ch in input_string:
    if ch.isdigit():
      RPN_stack.append(ch)
    else:
      if len(symbol_stack) > 0:
        if ch == '(':
          symbol_stack.append(ch)
        elif ch == ')':
          while True:
            symbol_pop = symbol_stack.pop()
            if symbol_pop == '(':
              break
            else:
              RPN_stack.append(symbol_pop)
        else:
          comparePriority(ch, RPN_stack, symbol_stack)
      else:
        symbol_stack.append(ch)
def scanInput(RPN_stack, symbol_stack):
  input_string = raw_input()
  input_string += '#'
  scanEveryone(input_string, RPN_stack, symbol_stack)
def calRPN(RPN_stack):
  value_stack = []
  RPN_stack.append('#')
  for value in RPN_stack:
    if value == '#':
      return value_stack.pop()
      break
    if value.isdigit():
      value_stack.append(value)
    else:
      right_value = value_stack.pop()
      left_value = value_stack.pop()
      cal_string = left_value + value + right_value
      value_stack.append(str(eval(cal_string)))
def main():
  RPN_stack = []
  symbol_stack = []

  scanInput(RPN_stack, symbol_stack)
  print calRPN(RPN_stack)
if __name__ == '__main__':
  main()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python的Django框架可适配的各种数据库介绍

在 Django 中使用 PostgreSQL 使用 PostgreSQL 的话,你需要从 http://www.djangoproject.com/r/python-pgsql/ 下载...

基于python时间处理方法(详解)

在处理数据和进行机器学习的时候,遇到了大量需要处理的时间序列。比如说:数据库读取的str和time的转化,还有time的差值计算。总结一下python的时间处理方面的内容。 一、字符串和...

Python版微信红包分配算法

红包分配算法代码实现发给大家,祝红包大丰收! #coding=gbk import random import sys #print random.randint(0, 99)...

使用Python编写Prometheus监控的方法

要使用python编写Prometheus监控,需要你先开启Prometheus集群。可以参考/post/148895.htm 安装。在python中实现服务器端。在Prometheus...

python发送多人邮件没有展示收件人问题的解决方法

背景: 工作过程中需要对现有的机器、服务做监控,当服务出现问题后,邮件通知对应的人 问题: 使用python 2.7自带的email库来进行邮件的发送,但是发送后没有展示收件人列表内容...