# Python 简单实现数学四则运算

## 一、题目描述

（1）能自动生成小学四则运算题目；

（2）能支持真分数的四则运算；

## 二、实现环境

PyCharm、Python3.0

## 三、代码实现

import re

def myCalculate(mystr):
if (mystr.__contains__("(")):
start = mystr.rindex("(")
lstr = mystr[0:start]
tmpstr = mystr[start + 1:]
end = tmpstr.index(")")
rstr = tmpstr[end + 1:]
nowstr = tmpstr[0:end]
newstr = lstr + str(myCalculate(nowstr)) + rstr
return myCalculate(newstr)
else:
return calcNoSym(mystr)

def calcNoSym(string):
if (string.__contains__("*")):
string = getNewStr(string, "*")
return calcNoSym(string)
if (string.__contains__("/")):
string = getNewStr(string, "/")
return calcNoSym(string)
if (string.__contains__("+")):
string = getNewStr(string, "+")
return calcNoSym(string)
if (string.__contains__("-")):
string = getNewStr(string, "-")
return calcNoSym(string)
return string

def getNewStr(string, op):
start = string.index(op)
lstr = string[0:start]
rstr = string[start + 1:]
lnum = re.search('\d+\$', lstr).group()
rnum = re.search('\d+', rstr).group()
newstr = lstr.rstrip(lnum) + str(calcs(lnum, rnum, op)) + rstr.lstrip(rnum)
return newstr

def calcs(num1, num2, op):
if (op == "+"):
return int(num1) + int(num2)
elif (op == "-"):
return int(num1) - int(num2)
elif (op == "*"):
return int(num1) * int(num2)
elif (op == "/"):
return int(num1) / int(num2)
else:
raise "error"

string = "11*22*3/4"

print(myCalculate(string))
sexp = "512+((112+212)*2-312)"
print(myCalculate(sexp))

1、加法测试

2、减法测试

3、乘法测试

4、除法测试

# 扫码关注微信公众号，了解更多

posted @ 2018-04-19 15:39  compassblog  阅读(8356)  评论(1编辑  收藏  举报