Skip to content Skip to sidebar Skip to footer

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.combi

Solution 1:

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

Post a Comment for "Grouping List Combinations For Round-robin Tournament"