怎么在Python中遍历可执行的静态公式中的算术运算符?

本教程将介绍如何在Python中遍历可执行的静态公式中的算术运算符?的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

怎么在Python中遍历可执行的静态公式中的算术运算符? 教程 第1张

问题描述

我正在尝试使用迭代器来迭代数学运算符。
通常使用array[1, 2, 3],使用combinations可以得到结果:

1
1,2
1,3
2,3
1,2,3

我要在[1, 2, 3]array上使用它,其方式如下:

1+2+3
1+2-3
1+2/3
1+2*3
1-2+3
1-2-3
1-2/3
1-2*3
...

出现并给出方程的结果。

我该怎么着手做这件事?

推荐答案

泛化到任意数量的操作数并保持运算符的正常优先级的解决方案:

from itertools import product

operands = [1, 2, 3, 4]
operators = [ '+', '*', '-', '//' ] # change '//' to '/' for floating point division
for opers in product(operators, repeat=len(operands)-1):
 formula = [ str(operands[0]) ]
 for op, operand in zip(opers, operands[1:]):
  formula.extend([op, str(operand)])
 formula = ' '.join(formula)
 print('{} = {}'.format(formula, eval(formula)))

好了关于怎么在Python中遍历可执行的静态公式中的算术运算符?的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。