Python 带条件的有效组合
给定代表玩家数量的用户输入Python 带条件的有效组合,python,conditional-statements,combinations,itertools,Python,Conditional Statements,Combinations,Itertools,给定代表玩家数量的用户输入n,我计算所有可能的玩家联盟(元组),然后计算所有可能的联盟集合,以便在每个集合中,每个玩家都属于一个且仅属于一个联盟。 示例:n=3 #coalitions [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] #combinations of coalitions that respect the condition [((1, 2, 3),), ((1,), (2, 3)), ((2,), (1, 3)),
n
,我计算所有可能的玩家联盟(元组),然后计算所有可能的联盟集合,以便在每个集合中,每个玩家都属于一个且仅属于一个联盟。
示例:n=3
#coalitions
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
#combinations of coalitions that respect the condition
[((1, 2, 3),), ((1,), (2, 3)), ((2,), (1, 3)), ((3,), (1, 2)), ((1,), (2,), (3,))]
为了做到这一点,我写道:
n = int(raw_input())
players = xrange(1,n+1)
players_comb = [coal for length in players for coal in list(combinations(players,length))]
coal_comb = [coalset for l in players for coalset in list(combinations(players_comb,l)) if sum(map(len,coalset)) == n and set(player for coal in coalset for player in coal) == set(players)]
问题是煤炭梳效率极低。对于istance,它将计算长度n
的所有组合,即使只有一个(即((1…n))
)符合该条件
我认为函数是O(2^(2^n))。
我的计算机甚至不能计算n=6
关于如何提高效率有什么想法吗
更新
我提出了这个解决方案:
combs = [comb for length in xrange(2,n) for comb in combinations_with_replacement(players,length) if sum(comb) == n]
H = [tuple(players_comb[:n]),(players_comb[-1],)]
for comb in combs:
layouts = set(frozenset(layout) for layout in product(*[[coal for coal in players_comb if len(coal) == length] for length in comb]) if set(player for coal in layout for player in coal) == set(players))
H.extend(tuple(tuple(layout) for layout in layouts))
但这只是一个微小的改进:现在我可以计算n=8
(运行时间超过50秒)。看看pythons@cybermoon ehm,怎么样?我已经在使用itertools.com了。。。