0

几个小时以来,我一直在困惑如何为这个问题制作一个程序。我搜索了类似的解决方案,但没有成功。

有6组2个值a [a1,a2] ; b [b1, b2] ; ... f [f1, f2].

每个组合都需要每个集合中至少有一个值,但它也可以同时具有。因此,有 64 种组合。

我需要计算所有这些组合,并打印如下内容:

Combination 1: a1, b1, c1, d1, e1, f1 Sum:  (sum of those listed)

Combination 2: ...

Total sum:
4

1 回答 1

2
>>> from itertools import product   
>>> for item in product(['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']):
...     print item
...     
('a1', 'b1', 'c1')
('a1', 'b1', 'c2')
('a1', 'b2', 'c1')
('a1', 'b2', 'c2')
('a2', 'b1', 'c1')
('a2', 'b1', 'c2')
('a2', 'b2', 'c1')
('a2', 'b2', 'c2')

看起来您的 a1、a2 等是数字。那也很好

>>> from itertools import product
>>> for item in product([1, 2], [3, 4], [5, 6]):
...     print item, sum(item)
... 
(1, 3, 5) 9
(1, 3, 6) 10
(1, 4, 5) 10
(1, 4, 6) 11
(2, 3, 5) 10
(2, 3, 6) 11
(2, 4, 5) 11
(2, 4, 6) 12
于 2013-03-15T09:53:16.613 回答