Skip to main content
 首页 » 编程设计

python之在python中用一个列表生成两组组合

2024年10月25日20yyy_WW

假设有 9 张不同的牌和 2 个不同的玩家。当从 9 张牌中给每个玩家 3 张牌(总共 6 张牌)时。

如何生成将 6 张牌分发给 2 位玩家的所有组合?

组合的数量很容易计算:

number_of_combinations = (9!/(6!*3!)) * (6!/(3!*3!)) = 1680 
  • 玩家 1 在 9 张牌中得到 3 张牌。可能的组合数是 9!/(6!*3!)。
  • 玩家 2 在剩余的 6 张牌中获得 3 张牌。可能的组合数是 6!/(3!*3!)。

因此,将 6 张牌分配给 2 个玩家的所有组合是 (9!/(6!*3!)) * (6!/(3!*3!)。

但是生成组合看起来非常困难;这是我试过的:

comb = itertools.combination([1,2,3,4,5,6,7,8,9], 6) 

但是有一个问题:

假设有两个列表,case1 和 case2。

case1 = [1,2,3 ,4,5,6] 
case2 = [1,2,4 ,3,5,6] 

就我而言,我必须以不同方式处理 case1 和 case2。

但如果我只生成 6 种尺寸组合,我就做不到。

请您参考如下方法:

要生成一个 交易,您需要使用 random.sample() function随机挑选6张牌;将前 3 个给玩家 1,其余的给玩家 2:

dealt_cards = random.sample(deck_of_cards, 6) 
player1_hand, player2_hand = dealt_cards[:3], dealt_cards[3:] 

然后要生成所有 可能的组合,您将使用 itertools.combinations()尺寸 6;但您仍然需要找到所有可能的排列,将这 6 张牌分成 2 手牌:

for dealt_cards in itertools.combinations(deck_of_cards, 6): 
    for hand1 in itertools.combinations(dealt_cards, 3): 
        hand2 = tuple(card for card in dealt_cards if card not in hand1) 

因此,从每 6 张牌的发牌组合中,所有 3 张牌的组合都给了一个玩家,剩下的 3 张牌给了另一个玩家。

这会产生预期数量的解决方案:

>>> from itertools import combinations 
>>> deck = range(9) 
>>> sum(1 for dealt in combinations(deck, 6) for _ in combinations(dealt, 3)) 
1680 

和演示:

>>> for dealt_cards in combinations(deck, 6): 
...     for hand1 in combinations(dealt_cards, 3): 
...         hand2 = tuple(card for card in dealt_cards if card not in hand1) 
...         print hand1, hand2 
...  
(0, 1, 2) (3, 4, 5) 
(0, 1, 3) (2, 4, 5) 
(0, 1, 4) (2, 3, 5) 
(0, 1, 5) (2, 3, 4) 
(0, 2, 3) (1, 4, 5) 
# ... 
(4, 6, 7) (3, 5, 8) 
(4, 6, 8) (3, 5, 7) 
(4, 7, 8) (3, 5, 6) 
(5, 6, 7) (3, 4, 8) 
(5, 6, 8) (3, 4, 7) 
(5, 7, 8) (3, 4, 6) 
(6, 7, 8) (3, 4, 5) 

您也可以只生成玩家 1 的手牌,然后继续使用牌组的其余部分生成玩家 2 的手牌:

for hand1 in itertools.combinations(deck_of_cards, 3): 
    for hand2 in itertools.combinations([c for c in deck_of_cards if c not in hand1], 3): 
        # ... 

具有相同的预期计数输出和结果:

>>> sum(1 for dealt in combinations(deck, 3) for _ in combinations([c for c in deck if c not in dealt], 3)) 
1680 
>>> for hand1 in combinations(deck, 3): 
...     for hand2 in combinations([c for c in deck if c not in hand1], 3): 
...         print hand1, hand2 
...  
(0, 1, 2) (3, 4, 5) 
(0, 1, 2) (3, 4, 6) 
(0, 1, 2) (3, 4, 7) 
(0, 1, 2) (3, 4, 8) 
(0, 1, 2) (3, 5, 6) 
# ... 
(6, 7, 8) (1, 3, 4) 
(6, 7, 8) (1, 3, 5) 
(6, 7, 8) (1, 4, 5) 
(6, 7, 8) (2, 3, 4) 
(6, 7, 8) (2, 3, 5) 
(6, 7, 8) (2, 4, 5) 
(6, 7, 8) (3, 4, 5) 

尽管现在顺序不同。