python - 解决python 3中的基本数学运算
问题描述
我正在尝试开发一种简单的 python 方法,它可以让我计算基本的数学运算。这里的重点是我不能使用 eval()、exec() 或任何其他评估 python statemets 的函数,所以我必须手动完成。到目前为止,我遇到了这段代码:
solutionlist = list(basicoperationslist)
for i in range(0, len(solutionlist)):
if '+' in solutionlist[i]:
y = solutionlist[i].split('+')
solutionlist[i] = str(int(y[0]) + int(y[1]))
elif '*' in solutionlist[i]:
y = solutionlist[i].split('*')
solutionlist[i] = str(int(y[0]) * int(y[1]))
elif '/' in solutionlist[i]:
y = solutionlist[i].split('/')
solutionlist[i] = str(int(y[0]) // int(y[1]))
elif '-' in solutionlist[i]:
y = solutionlist[i].split('-')
solutionlist[i] = str(int(y[0]) - int(y[1]))
print("The solutions are: " + ', '.join(solutionlist))
所以我们有两个字符串列表,基本操作列表具有以下格式的操作:2940-81、101-16、46/3、10*9、145/24、-34-40。它们总是有两个数字,中间有一个操作数。我的解决方案的问题是,当我进行最后一个操作时, .split() 方法将我的列表拆分为一个空列表和一个包含完整操作的列表。总之,当我们将负数与减法运算混合时,此解决方案效果不佳。我不知道它是否会在其他任何情况下失败,因为我只注意到我之前描述的错误。这个想法是,在方法结束时,我将解决方案列表作为字符串列表,这些字符串将成为基本数学运算的有序答案。ValueError: int() 以 10 为底的无效文字:''
基本操作列表在这里定义:
basicoperationslist = re.findall('[-]*\d+[+/*-]+\d+', step2processedoperation)
如您所见,我使用正则表达式从较大的操作中提取基本操作。step2processed 操作是服务器发送到我的机器的字符串。但作为示例,它可能包含:
((87/(64*(98-94)))+((3-(97-27))-(89/69)))
它包含完整和平衡的数学运算。
也许有人可以帮助我解决这个问题,或者我应该完全改变这种方法。
先感谢您。
解决方案
我会放弃整个拆分方法,因为它太复杂了,并且在您注意到的某些情况下可能会失败。
相反,我会使用正则表达式和operator
模块来简化事情。
import re
import operator
operators = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv}
regex = re.compile(r'(-?\d+)' # 1 or more digits with an optional leading '-'
r'(\+|-|\*|/)' # one of +, - , *, /
r'(\d+)', # 1 or more digits
re.VERBOSE)
exprssions = ['2940-81', '101-16', '46/3', '10*9', '145/24', '-34-40']
for expr in exprssions:
a, op, b = regex.search(expr).groups()
print(operators[op](int(a), int(b)))
# 2859
# 85
# 15.333333333333334
# 90
# 6.041666666666667
# -74
这种方式更容易适应新案例(比如新运营商)
推荐阅读
- r - 部署到 Shinyapps.io 时无法连接到 Azure SQL
- node.js - 套接字 io 服务器在发射时使客户端感到困惑
- javascript - 如何使美国的 JQVMap 地图在小州之外放置标签
- r - 如何在闪亮的应用程序中调整边距中断
- python - 我的蜘蛛对我的需要来说太慢了,我不知道如何解决它
- git - 如何从未经验证的 Git 提交中删除未经验证的标签?
- reactjs - Redux reducer 改变另一个 reducer 的状态
- android - Viewpager 不清除片段
- java - 为什么 CJK UNIFIED IDEOGRAPHS EXTENSION B 块中的代码点未根据组模式命名
- ruby-on-rails - rbenv 使用 2.7.3 ruby gem 版本安装的 Rails 6 应用程序 - 捆绑程序/设置加载错误