您的位置:首页 > 编程语言 > Python开发

python学习Day7

2018-02-05 19:46 232 查看
学习简述:计算器编程 和正则知识回顾

import re
#检查表达式合法性
def check_expression(string):
flag =True
#括号是否匹配
if not string.count('(')==string.count(')'):
print('表达式错误,括号未闭合!')
flag = False
if re.findall('[a-zA-Z]]',string):
print('表达式错误,含非法字符!')
flag = False
return flag

#格式化字符串
def format_string(string):
string = string.replace(' ','')
string = string.replace('++','+')
string = string.replace('--','+')
string = string.replace('-+','-')
string = string.replace('+-','-')
string = string.replace('*+','*')
string = string.replace('*-','*')
string = string.replace('/+','/')
return string

#计算乘、除法 (30+2*6+9/3)
def cal_mul_div(string):
# 从字符串里获取一个乘法或除法的表达式
regular = '[\-]?\d+\.?\d*([*/]|\*\*)[\-]?\d+\.?\d*'
#如果还能找到乘法或除法表达式
while re.findall(regular,string):
#获取表达式
expression = re.search(regular,string).group()
#如果是乘法
if expression.count('*')==1:
#获取要计算的两个数
x,y = expression.split('*')
#计算结果
mul_result = str(float(x)*float(y))
#将计算的表达式替换为计算结果值
string = string.replace(expression,mul_result)
#格式化一下
string = format_string(string)

#如果是除法
if expression.count('/'):
x,y = expression.split('/')
div_result = str(float(x)/float(y))
string = string.replace(expression, div_result)
string = format_string(string)

return string
#计算加减法
def cal_add_sub(string):
add_regular = '[\-]?\d\.?\d*\+[\-]?\d+\.?\d*'
sub_regular = '[\-]?\d\.?\d*\-[\-]?\d+\.?\d*'
#开始加法
while re.findall(add_regular,string):
#把所有的加法都加完,获取所有加法表达式
add_list = re.findall(add_regular,string)
for add_str in add_list:
x,y = add_str.split('+')
add_result = '+'+str(float(x)+float(y))
string = string.replace(add_str,add_result)
string = format_string(string)

#开始减法
while re.findall(sub_regular,string):
#把所有的减法都减完,获取所有减法表达式
sub_list = re.findall(sub_regular,string)
for sub_str in sub_list:
numbers = sub_str.split('-')
# -3-5的情况split会返回3个值
if len(numbers)==3:
result = 0
for v in numbers:
if v:
result -=float(v)
else:
x,y = numbers
result = float(x) -float(y)
sub_result = '+' + str(result)
string = string.replace(sub_str, sub_result)
string = format_string(string)
return string

source = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
if check_expression(source):
print('source:',source)
#print('eval result:',eval(source))
source = format_string(source)
print(source)

while source.count('(')>0:
#格式化
#去括号,得到括号的字符串(30+6/3)
strs = re.search('\([^()]*\)',source).group()
replace_str = cal_mul_div(strs)
replace_str = cal_add_sub(replace_str)
#将括号的字符串替换为计算结果,结果包含(),替换时去掉():[1:-1]
source = format_string(source.replace(strs,replace_str[1:-1]))

else:
#没有括号到最后单一表达式了
replace_str = cal_mul_div(source)
replace_str = cal_add_sub(replace_str)
source = source.replace(source,replace_str)
print('my result:',source.replace('+',''))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: