Recently, the top league of Bundesliga and the Major League of La Liga have been fighting again. I think of a piece of code that I have previously written to generate a competition schedule. It is so comfortable to use python to write this kind of thing.
This algorithm is called the snake ring algorithm.
That is to say, all teams are arranged in a ring (two columns), and the first team does not move on the right side of the left side. Other teams cycle clockwise, so that they will definitely not repeat.
For convenience, assume there are eight Teams A to H. Sort in a ring as below.
A H
|
B g
|
C f
|
D-e
In this way, in the 1st round, the game is (a, H) (B, G) (C, F) (D, E ).
In the next round, the first team A does not move, and other teams follow the same grid clockwise as the gear.
A B
|
C H
|
D G
|
E-F
In this way, in the 2nd round, the game is (a, B) (C, H) (d, g) (E, F ).
The gear continues to slide until it returns to the origin so that every team matches all the other 7 teams.
A thousand words is worse than a single code. Take the Premier League as an example.
From collections import dequeimport randomdef build_schedule (_ teamarr): scheduleobj = dict. fromkeys (range () fixpos = _ teamarr [0] ring = _ teamarr [1:] ring = deque (ring) # First Half of the competition, 1-19 round (round) for round in range (1st): # teams do not move, plus the rotate cycle teams = [fixpos] + List (ring) # Cut into 2 columns, left main team, home, away = teams [: Len (teams)/2], teams [Len (teams)/2:] away = away [:: -1] # randomly disrupt the main queue scheduleobj [round] = [(x, y) If random. random ()> = 0.5 else (Y, x) for X, Y in zip (home, away)] ring. rotate (1) # the last half of the season is the same as the last half of the season, but the main line is opposite to round in range (20, 39): scheduleobj [round] = [(Y, x) for X, Y in scheduleobj [round-19] Return scheduleobjif _ name _ = '_ main _': teamarr = [U 'manchester United ', u 'aston Villa ', U 'Chelsea ', u 'westham', u 'call', u 'hotspur', u 'Liverpool ', u 'southup', u 'efl', u 'inval ', U 'newcastle ', u 'manchester City', u 'stoke city', u 'santand', u 'crystal gong', u 'West buroww', u 'gun ', U 'hull city', u 'cardiff city', u 'swangsi'] scheduleobj = build_schedule (teamarr) print U' --- League 1st round --- 'for H, a In scheduleobj [1]: Print U '{}-{}'. format (H, A) print U' --- League Round 2nd --- 'for H, A in scheduleobj [2]: Print U '{}-{}'. format (H,)