python写计算器

python

    #!/usr/bin/env python

# -*- coding:utf-8 -*-

import re

def chu(arg1): #定义加减

arg = arg1[0] #beacuse price is a list ,so index 0

arg = arg.replace('--', '+').replace('++', '+').replace('-+', '-').replace('+-', '-') #重点重点重点:就是对负数的一个替换

# r = '-9-2-5-75884-1.6666666666666667-80.0-0.6+18'

li = re.findall("[\-\+]?\d+\.?\d*", arg) #意思是提取每个数,用findall变成列表形式,然后循环相加,张宇我佩服你

# 意思是用findall提取每个值包括值前面的运算符

num = 0 #定义空值,然后循环列表让每个值相加

for i in li:

num += float(i)

return num

def multiply(arg): #definition multip

while True:

nu = re.split("(\d+\.?\d*[*\/][\-]?\d+\.?\d*)",arg,1) #['-9-2-5-', '2*5', '/3+7/3*99/4*2998+10*568/14']

print(nu)

if len(nu) == 3:

bef, cen, aft = nu #split get there price

nu_cen = re.split("[*/]",cen) #['2', '5']

nu_bef, nu_af = nu_cen

# print(nu_bef,type(nu_af))

if "*" in cen: #如果*在中间那个

nu_cen = re.split("\*", cen)

# print(nu_cen)

nu_bef, nu_af = nu_cen

sum = float(nu_bef)*float(nu_af)

# print(sum)

nu = bef + str(sum) + aft #重新组合定义arg形参

arg = nu

return multiply(arg) #返回重新定义函数

elif "/" in cen:

nu_cen = re.split("[/]", cen)

nu_bef, nu_af = nu_cen

sum = float(nu_bef)/float(nu_af)

nu = bef + str(sum) + aft

arg = nu

return multiply(arg)# ['-9-2-5-3.3333333333333335+173134.50000000003+405.7142857142857']

else: #这个时候如果不等于3,那就是只剩下加减了执行加减

return chu(nu)

#return arg

#acc = "-9-2-5-244*311-5/3-40*4/2-3/5+6*3"

#acc = "-9-2-5-75884-5/3-160/2-3/5+18"

# acc = "-9-2-5-2*5/3+7/3*99/4*2998+10*568/14"

# ac = acc.strip(" ")

# a = multiply(ac)

# print(a)

# def multiply(arg):

# return 1

origin = "1 - 2 * ( (60-30 +(-9-2-5-24*11-5/3-40*4/2-3/5+6*3) * (-9-2-5-2*5/3 + 7 /3*9/4*98 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"

#寻找括号最里面的括号

while True: # 只要里面还有最里面的括号,就循环

origin = re.sub(r"\s*","",origin) #no1 strinp *****space**

print(origin)

res = re.split("\(([^()]+)\)",origin,1) #分割括号str得到第一个最里面括号内的值 no2

if len(res) == 3: #equal(等于)3,证明have bracket

before,centor,after = res #no3

print(centor)#centor是最里面的字符串,也是计算新函数乘法或除的实参

r = multiply(centor) #定义definition function multiply or ride (no4)

new_res = before + str(r) + after #重新组合

origin = new_res #重新定义origin

print(origin)

else:

final = multiply(origin)

print(final)

break

#this is comments

"""

acc = "-9-25-75884-5/3-160/2-3/5+18"

nu = re.split("(\d+\.?\d*[*][\-]?\d+\.?\d*)",acc,1)

print(type(nu[0]))

"""

注:凡注释的字段皆为测试所写,切记不可先全部乘法或除法结果不样!!!

以上是 python写计算器 的全部内容, 来源链接: utcz.com/z/388666.html

回到顶部