python中的前缀表示法解析 [英] prefix notation parsing in python

查看:121
本文介绍了python中的前缀表示法解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

马上开始-不,这不是功课.

Right off the bat - no, this is NOT homework.

例如,我想在python中编写一个前缀符号解析器(目前为总和)...

I would like to write a prefix notation parser in python (for sums presently)... for example

如果给出:+ 2 2,它将返回:4

if given: + 2 2 it would return: 4

想法?

推荐答案

def prefix(input):
  op, num1, num2 = input.split(" ")
  num1 = int(num1)
  num2 = int(num2)
  if op == "+":
    return num1 + num2
  elif op == "*":
    return num1 * num2
  else:
    # handle invalid op
    return 0

print prefix("+ 2 2")

打印4,还包括一个乘法运算符,只是为了展示如何扩展它.

prints 4, also included a multiplication operator just to show how to expand it.

这篇关于python中的前缀表示法解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆