加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Python编程示例——识别字符串算式并计算

(2016-01-24 17:12:05)
标签:

it

python编程

python语言

python语言基础

分类: Python语言

编程示例——识别字符串算式并计算

 

问题 用字符串给出一个二目算术运算(加减乘除取余和幂运算),编程计算字符串表示的算式。

编程思路(方案一)

用一个列表给出所有的运算符号,plist = ["+", "-", "*", "/", "%", "**"],对其中的每个元素检查它是否含余该算式表达式exp中。如果是,记作op,然后用op来分割exp,得到两个操作数x, y。最后,根据不同的运算来计算x op y就可以了,

代码

'''计算一个二元的算术表达式''' 
def operate(op, x, y):
   answer =0
   if op == "^":
     answer = x**y
   elif op == "+":
     answer = x+y
   elif op == "-":
     answer = x-y
   elif op == "*":
     answer = x*y
   elif op == "/":
     answer = x/y
   elif op == "%":
     answer = x%y
   return answer
 
plist = ["+", "-", "*", "/", "%", "**"]

def getoperator (exp):
   if "+" in exp:
     op = "+"
   elif "-" in exp:
     op = "-"
   elif "*" in exp:
     op = "*"
   elif "/" in exp:
     op = "/"
   elif "%" in exp:
     op = "%"
   elif "^" in exp:
     op = "^"
   return op
 
 if __name__ == "__main__":
   myexp = "2^5"
   op = getoperator(myexp)
   x = int(x); y=int(y)
   print( operate(op, x, y))

 

方案二

上例中是用字符串分割函授split(分割符来获取两个操作数的。我们也可以扫描字符串exp,发现非数字符号就记作op,并记录op出现的位置,即它的索引号index。再根据index作字符串exp的切片[::index] [index+1:] 它们就是两操作数。最后,用函授result(exp)作算术,得到结果。这样可以从一个文件中读取算式,算出结果再写入文件中。
注意,初始算式中不能有空格,也不能有其他字符,否则程序将中断。

 

代码

'''两个数字的算术运算'''
# operate.py

number = "0123456789."
operater ="+-*/%"
# 得到运算符
def getoperator(exp):
  if '**' in exp:
    op = '**' # 双*号幂运算
  elif "+" in exp:
    op ='+'
  elif "-" in exp:
    op ='-'
  elif '*' in exp:
    op ='*'
  elif "/" in exp:
    op ='/'
  elif "%" in exp:
    op ='%'
  else:
    op = ''
  return op
# 得到两个操作数
def getoperand(exp):
  op = getoperator(exp)
  if op == "" :   #如果没有正确的运算符
    x = 0; y = 0 
  n = exp.index(op) #得到运算符是索引号
  x1 = exp[:n]    #索引号前切片为操作数1
  if op !='**' :
    x2 = exp[n+1:]  # *星号时往后调整一位作切片2
  else:
    x2 = exp[n+2:]  #索引号后切片为操作数2
  x = float(x1); y = float(x2)
  return (x, y)
# 进行计算
def result(exp):
  op = getoperator(exp)
  x,y = getoperand(exp)
  if op =='+' :
    ans = x + y
  elif op =='-' :
    ans = x - y
  elif op =='*' :
    ans = x * y
  elif op =='/' :
    ans = x / y
  elif op =='%' :
    ans = x % y
  elif op =='**' :
    ans = x ** y
  return ans

if __name__ == '__main__':
   explist = [ '8**3', '120-1' , '123+7.5' ,'12*12', '160/16', '111%4', '5^4', '4321']
   for exp in explist:
     if getoperator(exp) == "":
        print (exp,"不含正确的运算符")
     else:
        print (exp +' =' , result(exp))
  

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有