用Python代码写的计算器

import re, functools def cal(formula): while re.search(\'(?:\d+\.?\d+|\d+)[+\-*/]\', formula): while re.search(\'[*/]\', formula): formula = re.sub(\'(?:\d+\.?\d+|\d+)[*/](?:\d+\.?\d+|\d+)\', str(functools.reduce(lambda i, j: float(i) * float(j), re.search(\'(?:\d+\.?\d+|\d+)[*/](?:\d+\.?\d+|\d+)\', formula).group().split(\'*\')) if \'*\' in re.search(\'(?:\d+\.?\d+|\d+)[*/](?:\d+\.?\d+|\d+)\', formula).group() else functools.reduce(lambda i, j: float(i) / float(j), re.search(\'(?:\d+\.?\d+|\d+)[*/](?:\d+\.?\d+|\d+)\', formula).group().split(\'/\'))), formula, 1) if re.search(\'(?:\d+\.?\d+|\d+)[+\-]\', formula): formula = re.sub(\'-?(?:\d+\.?\d+|\d+)[+\-](?:\d+\.?\d+|\d+)\', str(functools.reduce(lambda i, j: float(i) + float(j), re.search(\'-?(?:\d+\.?\d+|\d+)[+\-](?:\d+\.?\d+|\d+)\', formula).group().rsplit(\'+\', 1)) if \'+\' in re.search(\'(?:\d+\.?\d+|\d+)[+\-](?:\d+\.?\d+|\d+)\', formula).group() else functools.reduce(lambda i, j: float(i) - float(j), re.search(\'-?(?:\d+\.?\d+|\d+)[+\-](?:\d+\.?\d+|\d+)\', formula).group().rsplit(\'-\', 1))), formula, 1) return formula formula = \'1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))\' while re.search(\'\([^\(\)]+\)\', formula): formula = re.sub(\'\([^\(\)]+\)\', cal(re.search(\'\([^\(\)]+\)\', re.sub(\'\s\', \'\', formula)).group()).strip(\'()\'), formula, 1) while re.search(\'[+\-*/]-\', formula): formula = re.sub(\'[+]-\', \'-\', formula) if \'+-\' in formula else re.sub(\'--\', \'\', formula) if formula.startswith(\'--\') else re.sub(\'(?:\d+\.?\d+|\d+)[*/]-\', \'-\' + re.findall(\'(?:\d+\.?\d+|\d+)[*/](?=-)\', formula)[0], formula) if re.search(\'[*/]-\', formula) else re.sub(\'--\', \'+\', formula) print(cal(formula).split(\'.0\')[0] if cal(formula).endswith(\'.0\') else cal(formula))

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgyysy.html