python实现50行代码_50行代码实现python计算器主要功能
實現功能:計算帶有括號和四則運算的式子 3*( 4+ 50 )-(( 100 + 40 )*5/2- 3*2* 2/4+9)*((( 3 + 4)-4)-4)
基本思路:使用正則表達式提取出每一層小括號式子,計算出結果后替換該括號,直至最后一層。
0、計算前的準備,進行式子的整理,如果非法則退出。這里我只對空格和符號進行了處理,真實場景中應該做更多的判斷:
def check(s):
s = s.replace(" ", '')
s = re.sub(r'(\+-)|(-\+)', '-', s)
s = re.sub(r'(\+\+)|(--)', '+', s)
return s
1、只有加減運算的式子:findall匹配后直接使用sum函數對list求和,此時的減號看作負號,加號看作了正號,所以代碼極其簡潔:
import re
def plus_all(s): #實現加減運算
patter_plus = r'[+-]?\d+\.?\d*'
ret = re.findall(patter_plus, s)
return sum([float(x) for x in ret])
2、只有乘除運算的式子:和以上思路一致,主要想把除法(/)轉換為乘法后用reduce計算。其先匹配出帶有乘除運算符的list,然后通過change_mul_div()函數將除法轉換成倒數計算
from functools import reduce
def mul_all(s):
patter_mul = r'[*/]?[-]?\d+\.?\d*'
ret = re.findall(patter_mul, s)
return reduce(lambda m, n: m*n, [change_mul_div(x) for x in ret])
def change_mul_div(s):
if "/" in s:
return 1 / float(s.replace('/', ""))
else:
return float(s.replace("*", ''))
3、含有加減乘除但不含有括號的式子:先用mul_all(s)函數將式子中的所有乘除法計算完畢,然后回到第1步。cal_all_mul_div函數實現計算式子中所有乘除法:
def cal_all_mul_div(s):
patter_all_mul_div = r'([+-]?\d+\.?\d*[*/])+[+-]?\d+\.?\d*'
ret = re.search(patter_all_mul_div, s)
while ret:
mul_div = mul_all(ret.group())
s = s.replace(ret.group(), ''.join(['+', str(mul_div)]))
ret = re.search(patter_all_mul_div, s)
return s
4、不斷提取括號進行計算:
def bracket(s):
patter_kuohao = r'\([^()]+\)'
ret = re.search(patter_kuohao, s)
while ret:
cal_result = plus_all(cal_all_mul_div(ret.group()))
s=s.replace(ret.group(), ''.join(['+', str(cal_result)]))
ret = re.search(patter_kuohao, s)
return s
所有代碼合并如下:
import re
from functools import reduce
s3 = "3*( 4+ 50 )-(( 100 + 40 )*5/2- 3*2* 2/4+9)*((( 3 + 4)-4)-4)"
def check(s):
s = s.replace(" ", '') #對空格進行處理
s = re.sub(r'(\+-)|(-\+)', '-', s) #對符號進行處理
s = re.sub(r'(\+\+)|(--)', '+', s)
return s
def plus_all(s):
patter_plus = r'[+-]?\d+\.?\d*'
ret = re.findall(patter_plus, s) #找出所有的加數
return sum([float(x) for x in ret]) #生成器生成列表并求和
def mul_all(s):
patter_mul = r'[*/]?[-+]?\d+\.?\d*'
ret = re.findall(patter_mul, s)
return reduce(lambda m, n: m * n, [change_mul_div(x) for x in ret]) #reduce連乘
def change_mul_div(s): #把除法改成乘以其倒數
if "/" in s:
return 1 / float(s.replace('/', ""))
else:
return float(s.replace("*", ''))
def cal_all_mul_div(s):
patter_all_mul_div = r'([+-]?\d+\.?\d*[*/])+[+-]?\d+\.?\d*'
ret = re.search(patter_all_mul_div, s)
while ret:
mul_div = mul_all(ret.group())
s = s.replace(ret.group(), ''.join(['+', str(mul_div)]))
ret = re.search(patter_all_mul_div, s)
return s
def bracket(s):
patter_kuohao = r'\([^()]+\)'
s = check(s)
ret = re.search(patter_kuohao, s)
while ret:
cal_result = plus_all(cal_all_mul_div(ret.group()))
s = check(s.replace(ret.group(), ''.join(['+', str(cal_result)]))) #替換時需要在前面加入正號,并對s進行check操作
ret = re.search(patter_kuohao, s)
return s
s3 = ''.join(["(", s3, ")"])
print(float(bracket(s3)))
以上即用不超過50行代碼實現了計算器的主要功能。
總結
以上是生活随笔為你收集整理的python实现50行代码_50行代码实现python计算器主要功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python创建excel_python
- 下一篇: python求n的阶乘_python求n