条件

时间:2016-02-25 10:28:18

标签: 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)), ((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)]

问题是coal_comb非常低效。对于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秒)。

0 个答案:

没有答案