试图找到所有可能的组合和分组

时间:2014-09-10 13:51:27

标签: python python-2.7

我一直在尝试使用excel解决以下问题,并意识到这可能更适合Python,但不知道从哪里开始,我只对Python有基本的了解。你们怎么解决这个问题?

有6种咖啡,有10种风味,你可以在每种咖啡中放一次,两次或三次。基于此,我想知道(并列出)独特的风味组合,以及如果没有同一杯咖啡,你可以走多长时间。

3 个答案:

答案 0 :(得分:2)

使用itertools.combinations,您可以轻松获得所有不同的风味组合组合:

from itertools import combinations

shots = range(1,11)
N = 3

coms = [c for n in range(1, N+1) for c in combinations(shots, n)]

coms的长度将为您提供组合的数量,在6种口味的情况下,一次,两次或三次射击为175.

添加到咖啡中的风味组合数量只是6 * 175 = 1050

修改

另外(作为旁白)你甚至不需要通过编程来做到这一点。假设您有n个元素,并且您想知道有多少种不同的方法可以选择k,那么数字由Binomial coefficient给出,可以使用C(n, k) = n!/(k!*(n-k)!)轻松计算,

在你的情况下,你有n = 10和k = 1,k = 2,和k = 3。因此,您的解决方案是:

C(10, {1, 2, 3}) = C(10, 3) + C(10, 2) + C(10, 1)
                 = 10!/(3!*(10-3)!) + 10!/(2!*(10-2)!) + 10!/(1!*(10-1)!)
                 = 175
           Total = 175 * 6 = 1050

答案 1 :(得分:2)

>>> flavor = ["F1","F2","F3","F4","F5","F6","F7","F8","F9","F10"]
>>> coffee = ["C1","C2","C3","C4","C5","C6"]
>>> from itertools import product, combinations, chain
>>> len(list(product(coffee, chain(combinations(flavor, 1), combinations(flavor, 2), combinations(flavor, 3)))))
1050
>>> list(product(coffee, chain(combinations(flavor, 1), combinations(flavor, 2), combinations(flavor, 3))))
[('C1', ('F1',)), ('C1', ('F2',)), ('C1', ('F3',)), ('C1', ('F4',)), ('C1', ('F5',)), ('C1', ('F6',)), ('C1', ('F7',)), ('C1', ('F8',)), ('C1', ('F9',)), ('C1', ('F10',)), ('C1', ('F1', 'F2')), ('C1', ('F1', 'F3')), ('C1', ('F1', 'F4')), ('C1', ('F1', 'F5')), ('C1', ('F1', 'F6')), ('C1', ('F1', 'F7')), ('C1', ('F1', 'F8')), ('C1', ('F1', 'F9')), ('C1', ('F1', 'F10')), ('C1', ('F2', 'F3')), ...

我认为这是正确的。我们构建了咖啡口味的所有1,2和3元组组合,并将它们链接在一起成为一个可迭代的。然后我们将每种口味的组合与每种咖啡结合起来。

答案 2 :(得分:1)

这听起来像是itertools.product的工作:

将咖啡定义为:

 coffee = ["C1","C2","C3","C4","C5","C6"]

味道如下:

 flavor = ["F1","F2","F3","F4","F5","F6","F7","F8","F9","F10"]

一种味道:

 itertools.product(coffee,flavor)

两种味道:

 [i for i in itertools.product(coffee,flavor,flavor) if i[1] != i[2]]

三种味道:

 [i for i in itertools.product(coffee,flavor,flavor, flavor) if i[1] != i[2] and i[2] != i[3] and i[1] != i[3]]