Grouping list combinations for round-robin tournament

前端 未结 1 690
花落未央
花落未央 2021-02-15 10:55

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 iter

1条回答
  •  后悔当初
    2021-02-15 11:08

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

    0 讨论(0)
提交回复
热议问题