一个简单的计算器,能计算括号加减乘除,由于还没有加入判断输入规范的功能,所以格式必须正确
例如:3/3*(25-6/3)+(1+4)/2.5
ps:不能用python自带的eval或者exec等方法
有两个方案,方案一是早期写的,能够实现,但代码较乱,方案二比较简洁易懂些,在页面看,可能代码看起来会是乱的,复制到编辑器就不会了
方案一
#Auther:He Jianhan
import re
def mul_div(front,after,symbol):
#计算带入的值进行计算*和/
if symbol == "*":
result = float(front) * float(after)
else:
result = float(front) / float(after)
return result
def add_sub(front,after,symbol):
# 计算带入的值进行计算+和-
if symbol == "+":
result = float(front) + float(after)
else:
result = float(front) - float(after)
return result
def process(value,one,two,functions,itmes):
#通过判断列表是否有四则运算,调取加减乘除的运算函数,不断进行计算
for symbol_list_number,symbol_list_forin in enumerate(value):
if one in symbol_list_forin:
result = functions(itmes[symbol_list_number],itmes[symbol_list_number+1], one)
itmes[symbol_list_number] = str(result)
itmes[symbol_list_number+1] = str(result)
elif two in symbol_list_forin:
result = functions(itmes[symbol_list_number], itmes[symbol_list_number+1], two)
itmes[symbol_list_number] = str(result)
itmes[symbol_list_number+1] = str(result)
def main(number):
digit_list = []
symbol_list = []
number_list = re.findall("^[0-9]+|..[0-9]+[.][0-9]+|..[0-9]+|.[0-9]+[.][0-9]+|"
".[0-9]+",number)#将要计算的数值进行分开
for n in number_list:
#将加减乘除和数值分开,以便于后面计算
if "*" in n or "/" in n or "+" in n or "-" in n:
digit_list.append(n[1:])
symbol_list.append(n[0])
else:
digit_list.append(n[:])
if "-" in number_list[0]:
#判断第一个输入的值是否为负数,是负数则将dict_list列表的第一个值进行替换
# 并删除symbol_list的第一个符号
digit_list[0] = number_list[0]
del symbol_list[0]
process(symbol_list,"*","/",mul_div,digit_list)
while "*" in symbol_list or "/" in symbol_list:
#将已经计算过才*和/进行删除
if "*" in symbol_list:
del digit_list[symbol_list.index("*")]
symbol_list.remove("*")
if "/" in symbol_list:
del digit_list[symbol_list.index("/")]
symbol_list.remove("/")
process(symbol_list,"+","-",add_sub,digit_list)
return digit_list[-1]
number = input("输入你要计算的\033[31;1m公式\033[0m")
while True:
#判断是否有括号,有括号则先进行括号内的运算
if "(" in number:
left = number.find(")")
right = number[:left].rfind("(")
number_small = number[right+1:left]
replace = main(number_small)
number = number[:right] + replace + number[left+1:]
else:
print("===>"+main(number))
break
方案二
import re
def count1(number):
# 利用正则匹配出乘除,计算,并不断循环直到没有乘除,并计算返回结果
while True:
search_var = re.search("[+\-/*]?-?\d+(\.\d+)?([/*])-?\d+(\.\d+)?",number)
if not search_var:
break
if search_var.group()[0] not in ["+","-","/","*"]:
var = search_var.group()
else:
var = search_var.group()[1:]
if "*" in var:
a,b = var.split("*")
var = str(float(a)*float(b))
else:
a, b = var.split("/")
var = str(float(a) / float(b))
if search_var.group()[0] not in ["+", "-", "/", "*"]:
number = number[:search_var.span()[0]] + var + number[search_var.span()[1]:]
else:
number = number[:search_var.span()[0]+1]+var+number[search_var.span()[1]:]
return str(number)
def count2(number):
# 利用正则匹配出加减,计算,并不断循环直到没有加减,并计算返回结果
while True:
search_var =re.search("-?\d+(\.\d+)?([+-])-?\d+(\.\d+)?",number)
if not search_var:
break
var = search_var.group()
if "+" in var:
a,b = var.split("+")
var = str(float(a) + float(b))
else:
if var[0] == "-":
new_var = var[1:]
find_var = new_var.find("-")
a = new_var[:find_var]
b = new_var[find_var+1:]
a = "-" + a
else:
find_var = var.find("-")
a = var[:find_var]
b = var[find_var + 1:]
var = str(float(a) - float(b))
number = number[:search_var.span()[0]]+var+number[search_var.span()[1]:]
return str(number)
def bracket(number):
# 匹配出里层括号
search_var = re.search("\([\d+\-/*.]*[^(][\d+\-/*.]*\)",number)
return search_var
if __name__ == "__main__":
while True:
number = input("请输入要计算的公式,小数负数随便输,算错算我输(q/Q退出)")
if number.upper() == "Q":
print(1)
break
else:
while True:
search_var = bracket(number)
if not search_var:
break
count_var = count1(search_var.group()[1:-1])
count_var = count2(count_var)
number = number[:search_var.span()[0]] + count_var + number[search_var.span()[1]:]
number = count1(number)
number = count2(number)
print(number)