根据它们的总和来获取元组元素的乘积

M31*_*105 1 python

我非常感谢有关以下问题的任何反馈.到目前为止,我在Python上编写了一个代码,它生成了二维元组的组合,其中每个元素都是1到4的值.因此对于(a1,a2),a1和a2可以是1到4之间的任何值

因此,这产生了以下元组

tuple_combinations =  [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
Run Code Online (Sandbox Code Playgroud)

然后我获取了生成的每个元组的元素总和:

sum_tuple_combinations = [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]
Run Code Online (Sandbox Code Playgroud)

现在我需要帮助计算元素总和为5的元素的乘积.所以对于这个例子,它将是元组(2,3),(3,2),(1,4)和(4, 1)哪会给我

 [6,6,4,4]
Run Code Online (Sandbox Code Playgroud)

我将如何在Python上编写代码?

这是我到目前为止所做的:

  import itertools
  x = [1,2,3,4]
  combinations= [p for p in itertools.product(x, repeat=2)]
  print(combinations)
  sum_of_combinations = map(sum, combinations)
  print(sum_of_combinations)
  #product_of_combinations = [x*y for sum_of_combinations = 5]
Run Code Online (Sandbox Code Playgroud)

此外,虽然这解决了二维情况,其中n = 2,我想考虑元组中元素的乘积,用于其他维度,例如n = 200等等.因此,特别是对于诸如N = 200的尺寸,我想知道是否有一种计算上廉价的方法来实现这一目标?

wim*_*wim 5

不要忘记(1,4)和(4,1)也总和为5.

二维案例:

>>> from itertools import product
>>> L = [1, 2, 3, 4]
>>> [a*b for a,b in product(L, L) if a+b == 5]
[4, 6, 6, 4]
Run Code Online (Sandbox Code Playgroud)

n-dim案例:

>>> from operator import mul
>>> n = 2
>>> [reduce(mul, t, 1) for t in product(L, repeat=n) if sum(t) == 5]
[4, 6, 6, 4]
Run Code Online (Sandbox Code Playgroud)