Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping list combinations for round-robin tournament

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

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))

the result:

[(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.

like image 715
Johnny Craig Avatar asked Sep 02 '15 16:09

Johnny Craig


1 Answers

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)

Output:

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')]]
like image 188
Padraic Cunningham Avatar answered Oct 16 '22 08:10

Padraic Cunningham