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

时间:2016-10-27 21:17:55

标签: python

我非常感谢有关以下问题的任何反馈。到目前为止,我在Python上编写了一个代码,它生成了2维元组的组合,其中每个元素都是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)]

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

sum_tuple_combinations = [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]

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

 [6,6,4,4]

我如何在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]

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

2 个答案:

答案 0 :(得分: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]

n-dim case:

>>> 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]

答案 1 :(得分:0)

wim的代码是一次完成所有操作的好方法。您可以通过将最后一行更改为

来修改代码以使其正常工作
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_daily_selfie, menu);
    return true;
}