我只是想向你指出解决方案,但我厌倦了试图在评论中解释:
这是一个解决方案:
import random
teams = ["Atletico", "Barcelona", "Real Madrid", "Sevilla", "Atletic Bilbao ", "Granada", "Mallorca", "Valencia"]
pairs = [(i, j) for i in teams for j in teams if i != j]
random.shuffle(pairs)
numWeeks = len(teams) - 1
numPairs = len(teams)//2
matchUps = {}
for week in range(numWeeks):
matchUps[f'Week {week}'] = []
for _ in range(numPairs):
while True:
pair = random.choice(pairs)
if pair[0] not in [team for match in matchUps[f'Week {week}'] for team in match]:
if pair[1] not in [team for match in matchUps[f'Week {week}'] for team in match]:
if pair not in [match for match in matchUps[f'Week {week}']] and (pair[1], pair[0]) not in [match for match in matchUps[f'Week {week}']]:
break
matchUps[f'Week {week}'].append(pair)
print(matchUps)
输出:
{'Week 0': [('Granada', 'Atletic Bilbao '),
('Barcelona', 'Real Madrid'),
('Sevilla', 'Valencia'),
('Atletico', 'Mallorca')],
'Week 1': [('Atletico', 'Atletic Bilbao '),
('Sevilla', 'Real Madrid'),
('Barcelona', 'Granada'),
('Mallorca', 'Valencia')],
'Week 2': [('Granada', 'Atletic Bilbao '),
('Barcelona', 'Real Madrid'),
('Mallorca', 'Valencia'),
('Atletico', 'Sevilla')],
'Week 3': [('Atletic Bilbao ', 'Mallorca'),
('Real Madrid', 'Valencia'),
('Granada', 'Sevilla'),
('Atletico', 'Barcelona')],
'Week 4': [('Atletic Bilbao ', 'Atletico'),
('Valencia', 'Real Madrid'),
('Sevilla', 'Barcelona'),
('Granada', 'Mallorca')],
'Week 5': [('Valencia', 'Atletic Bilbao '),
('Real Madrid', 'Sevilla'),
('Mallorca', 'Atletico'),
('Barcelona', 'Granada')],
'Week 6': [('Barcelona', 'Sevilla'),
('Valencia', 'Atletic Bilbao '),
('Granada', 'Real Madrid'),
('Atletico', 'Mallorca')]}
这会得到注释中显示的对:
teams = ["Atletico", "Barcelona", "Real Madrid", "Sevilla", "Atletic Bilbao ", "Granada", "Mallorca", "Valencia"]
pairs = [(i, j) for i in teams for j in teams if i != j]
然后它随机化:
random.shuffle(pairs)
然后获取所需的周数以及每周所需的对数:
numWeeks = len(teams) - 1
numPairs = len(teams)//2
然后它在几周内循环(每次创建一个新的一周):
for week in range(numWeeks):
matchUps[f'Week {week}'] = []
然后它遍历每个需要的对:
for _ in range(numPairs):
对于每个配对要求,它会遍历无重复列表以找到未使用的配对:
while True:
pair = random.choice(pairs)
if pair[0] not in [team for match in matchUps[f'Week {week}'] for team in match]:
if pair[1] not in [team for match in matchUps[f'Week {week}'] for team in match]:
if pair not in [match for match in matchUps[f'Week {week}']] and (pair[1], pair[0]) not in [match for match in matchUps[f'Week {week}']]:
break
一旦找到可以使用的一对,它就会将其放置在一周内:
matchUps[f'Week {week}'].append(pair)
注意:这给出了随机的主/离分配,但您可以更改:
numWeeks = len(teams) - 1
至:
numWeeks = (len(teams) - 1)*2
这将提供双循环赛,每支球队回家一次,每支球队离开一次。