我正在尝试编写一个脚本来随机化锦标赛的循环赛时间表。
约束是:
- 8支球队
- 两队交手两次,一次主场,一次客场
- 14周,每周每队一场比赛
我的代码理论上可以正常工作,但是当它生成时,它有时会在某些周冻结,因为那一周只剩下两支球队,而且两场可能的比赛都已经进行过。我使用一个 numpy 数组来检查已经进行了哪些比赛。
目前我的代码如下所示:
import random
import numpy
regular_season_games = 14
regular_season_week = 0
checker = numpy.full((8,8), 0)
for x in range (0,8):
checker[x][x] = 1
teams_left = list(range(8))
print ("Week " + str(regular_season_week+1))
while (regular_season_week < regular_season_games):
game_set = False
get_away_team = False
while get_away_team == False:
Team_A = random.choice(teams_left)
if 0 in checker[:,Team_A]:
for x in range (0,8):
if checker[x][Team_A] == 0 and x in teams_left:
teams_left.remove(Team_A)
get_away_team = True
break
while game_set == False:
Team_B = random.choice(teams_left)
if checker[Team_B][Team_A] == 0:
teams_left.remove(Team_B)
print(str(Team_A) + " vs " + str(Team_B))
checker[Team_B][Team_A] = 1
game_set = True
if not teams_left:
print ("Week " + str(regular_season_week+2))
teams_left = list(range(8))
regular_season_week = regular_season_week + 1