Python正则表达计算器

Python学习笔记(十二):

  1. 计算器

  • 利用Python的正则表达式写的简易计算器
# author : Ryoma
# time : 17:39 import re def add(string):
equ = string
flag = True
while flag:
is_right = re.search('[\-]?\d+\.?\d*\+[\-]?\d+\.?\d*', equ)
if is_right:
old = is_right.group()
# 计算加法
nums = old.split('+')
sum = float(nums[0]) + float(nums[1])
new = str(sum)
equ = equ.replace(old,new)
else:
flag = False
return equ def reduce(string):
equ = string
flag = True
while flag:
is_right = re.search('[\-]?\d+\.?\d*-[\-]?\d+\.?\d*', equ)
if is_right:
old = is_right.group()
# 计算减法
count = len(re.findall('-',old))
if count==1:
nums = old.split('-')
sum = float(nums[0]) - float(nums[1])
new = str(sum)
equ = equ.replace(old, new)
elif count==2:
nums = old.split('-')
sum = - float(nums[1]) - float(nums[2])
new = str(sum)
equ = equ.replace(old, new)
else:
flag = False
return equ def ride(string):
equ = string
flag = True
while flag:
is_right = re.search('[\-]?\d+\.?\d*\*[\-]?\d+\.?\d*', equ)
if is_right:
old = is_right.group()
# 计算乘法
nums = old.split('*')
sum = float(nums[0]) * float(nums[1])
new = str(sum)
equ = equ.replace(old,new)
else:
flag = False
return equ def divide(string):
equ = string
flag = True
while flag:
is_right = re.search('[\-]?\d+\.?\d*/[\-]?\d+\.?\d*', equ)
if is_right:
old = is_right.group()
# 计算除法
nums = old.split('/')
if nums[1] == '0':
exit('0不能做被除数!')
sum = float(nums[0]) / float(nums[1])
new = str(sum)
equ = equ.replace(old,new)
else:
flag = False
return equ # 判断优先级 按照优先级进行计算:括号>乘除法>加减法
def pri(equ):
flag = True
while flag:
# 查找最里层括号
ret = re.search('\([^()]+\)', equ)
if ret:
# 记录查找的式子
old = ret.group()
# 去除括号
new = old.replace('(', '')
new = new.replace(')', '')
# 计算-先乘除后加减
new = ride(new)
new = divide(new)
new = add(new)
new = reduce(new)
# 替换方程式
equ = equ.replace(old, new)
else:
flag = False
else:
equ = ride(equ)
equ = divide(equ)
equ = add(equ)
equ = reduce(equ) return equ # 格式处理
def check(equ):
equ = equ.replace(' ','')
if len(re.findall('[^0-9\-+/*\(\).]', equ)):
print("请输入正确的表达式!")
elif not equ.count('(') == equ.count(')'):
print("存在未闭合的括号!")
else:
equ = pri(equ)
return equ if __name__ == '__main__':
print("欢迎使用计算器".center(50,'-'))
while 1:
equ = input("输入你要计算的式子:")
equ = check(equ)
print(equ)
上一篇:CentOS升级Svn到最新版


下一篇:poj 3641 Pseudoprime numbers(快速幂)