Python 算术运算符数组
我正在做一道数学题,我需要测试数字和数学运算的不同组合(+、-、*、/)。我可以用Perl或Python创建一个算术运算数组,以便循环使用这些组合吗 例如: (下划线表示某些操作,字母是整数的变量) A_B_C_D 可能是 A+B+C+D 或 A*B+C-D 或 A-B/C+D 等等 我需要测试是否能够在所有这些组合中测试整数值,而无需手动创建每个表达式(我相信上面的示例中有256种可能的组合) 感谢Python中的Python 算术运算符数组,python,arrays,perl,Python,Arrays,Perl,我正在做一道数学题,我需要测试数字和数学运算的不同组合(+、-、*、/)。我可以用Perl或Python创建一个算术运算数组,以便循环使用这些组合吗 例如: (下划线表示某些操作,字母是整数的变量) A_B_C_D 可能是 A+B+C+D 或 A*B+C-D 或 A-B/C+D 等等 我需要测试是否能够在所有这些组合中测试整数值,而无需手动创建每个表达式(我相信上面的示例中有256种可能的组合) 感谢Python中的 import operator ops = [operator.add, o
import operator
ops = [operator.add, operator.sub, operator.mul, operator.div]
你的问题似乎不考虑操作顺序,即你不会得到<代码>(A+B)/(C-D),或者<代码>(B/A+D)/C<代码>。这重要吗
编辑:from itertools import product
from operator import add, sub, mul, div
def make_function(x, y, z):
"""
Return a function that implements `(((A x B) y C) z D)`
where x,y,z are two-argument operators
"""
def fn(a, b, c, d):
return z(y(x(a, b), c), d)
return fn
# list: all unique operations
ops = [add, sub, mul, div]
# generator: all combinations of three operators
combos = product(ops, repeat=3)
# list: all functions implementing a three-operator combination
all_fns = [make_function(*trio) for trio in combos]
“A+A+A+A”合法吗?或者它总是只有一个数字?这是不合法的-每个数字只能使用一次。我有其他带括号的表达式,我会手动写入程序。我认为有11个括号的可能位置。谢谢回复。你能再解释一下你的答案吗?这样我就知道怎么用了?谢谢。我真的很感谢你的帮助,但是我是一个初学者,所以我不太明白你给我的大部分信息(即使在考虑过并用谷歌搜索了我不知道的信息之后)。如果你有时间,你能简单地解释一下我会怎么做吗?我计划做一个嵌套for循环,其中我将有ops[I]=x,ops[j]=y,ops[k]=z,然后有一个将要测试的组合列表。例如:AxByCzD,(AxB)yCzD,(AxB)y(CzD)
use Algorithm::Loops qw( NextPermute );
my %OPS = (
'+' => sub { $_[0] + $_[1] },
'-' => sub { $_[0] - $_[1] },
'*' => sub { $_[0] * $_[1] },
'/' => sub { $_[0] / $_[1] },
);
my @OPS = keys(@OPS);
sub evaluate {
my ($vals, $ops) = @_;
$vals = [ @$vals ];
my $acc = shift(@$vals);{
for my $op (@$ops) {
$acc = $OPS{$op}->($acc, shift(@$vals));
}
return $acc;
}
my @vals = ...;
my @indexes = 0..$#ops;
do {
my @ops = map $OPS[$_], @indexes;
my $rv = evaluate(\@vals, \@ops);
...
} while (NextPermute(@indexes));