循环锦标赛的分组列表组合 [英] Grouping list combinations for round-robin tournament

查看:59
本文介绍了循环锦标赛的分组列表组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我的问题不是别人标记的重复。另一个问题是不正确的,甚至无法正常工作。

My question is not a duplicate as someone has marked. The other question is incorrect and does not even work.

我尝试了几种方法来对itertools.combinations的结果进行分组,但无法给出正确的输出。在游戏中创建比赛是必需的。每个团队每天都需要比赛,但只有一次。团队需要在接下来的几天中扮演不同的团队,直到每个人都扮演了所有人。

I have tried a few ways to group the results of itertools.combinations and been unable to come up with the correct output. It is needed to create matches in a game. Every team needs to play every day, but only once. Teams need to play different teams on the following days until everyone has played everyone.

teams = [team 1, team 2, team 3, team 4]
print list(itertools.combinations(teams, 2))

结果:

[(team 1, team 2), (team 1, team 3), (team 1, team 4), (team 2, team 3), (team 2, team 4), (team 3, team 4)]

但是我需要对它们进行分组,而没有任何重复的列表项。
示例:

But what I need is to group them without any duplicate list items. example:

[
    [(team 1,team 2), (team 3,team 4)], #day 1
    [(team 1,team 3), (team 2,team 4)], #day 2
    [(team 1,team 4), (team 2,team 3)]  #day 3
]

任何技巧都会受到赞赏,我觉得可能一个简单的单行代码即可完成此任务。

Any tips would be appreciated, I feel like there's probably a simple one-liner to get this done.

推荐答案

使用 collections.deque的实现基于链接问题中的 Scheduling_algorithm

An implementation using a collections.deque based on the Scheduling_algorithm in the linked question:

from collections import deque
from itertools import islice

def fixtures(teams):
    if len(teams) % 2:
        teams.append("Bye")

    ln = len(teams) // 2
    dq1, dq2 = deque(islice(teams, None, ln)), deque(islice(teams, ln, None))
    for _ in range(len(teams)-1):
        yield zip(dq1, dq2) # list(zip.. python3
        #  pop off first deque's left element to 
        # "fix one of the competitors in the first column"
        start = dq1.popleft() 
        # rotate the others clockwise one position
        # by swapping elements 
        dq1.appendleft(dq2.popleft())
        dq2.append(dq1.pop())
        # reattach first competitor
        dq1.appendleft(start)

输出:

In [37]: teams = ["team1", "team2", "team3", "team4"]

In [38]: list(fixtures(teams))
Out[38]: 
[[('team1', 'team3'), ('team2', 'team4')],
 [('team1', 'team4'), ('team3', 'team2')],
 [('team1', 'team2'), ('team4', 'team3')]]

In [39]: teams = ["team1", "team2", "team3", "team4","team5"]

In [40]: list(fixtures(teams))
Out[40]: 
[[('team1', 'team4'), ('team2', 'team5'), ('team3', 'Bye')],
 [('team1', 'team5'), ('team4', 'Bye'), ('team2', 'team3')],
 [('team1', 'Bye'), ('team5', 'team3'), ('team4', 'team2')],
 [('team1', 'team3'), ('Bye', 'team2'), ('team5', 'team4')],
 [('team1', 'team2'), ('team3', 'team4'), ('Bye', 'team5')]]

这篇关于循环锦标赛的分组列表组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆