Python随机运动计划生成器

时间:2012-03-28 03:41:52

标签: python

我找到了以下

Generating natural schedule for a sports league

每次运行时都生成相同的计划。如果我在那里添加random.shuffle(),它仍然是可预测的。

以下是我在该帖子中的简单编辑,随机到位,我得到奇怪的结果

import random

def round_robin(units, sets = None):
    """ Generates a schedule of "fair" pairings from a list of units """
    count = len(units)
    sets = sets or (count - 1)
    half = count / 2

    for turn in range(sets):
        left = units[:half]
        right = units[count - half - 1 + 1:][::-1]
        pairings = zip(left, right)
        if turn % 2 == 1:
            pairings = [(y, x) for (x, y) in pairings]
        units.insert(1, units.pop())

        yield pairings


teams = range(5)
random.shuffle(teams)
schedule = list(round_robin(teams, sets = len(teams) * 2 - 2))

for week in schedule:
    for game in week:
        if 0 in game:
            print game

有时似乎球队甚至不会互相比赛..看结果

(0, 4)
(4, 0)
(0, 2)
(0, 4)
(4, 0)
(0, 2)

我的问题是..如何在python中执行随机计划生成器或修复我已经拥有的计划生成器。

我几乎需要带4支队伍参加3周的比赛,他们互相比赛一次。或者像5支球队一样,有5周的比赛,他们都互相比赛,但每周只剩下一支球队

1 个答案:

答案 0 :(得分:4)

我假设每支球队都需要和其他球队一起比赛。不是吗?那么这个问题不归结为简单的排列,然后改组结果吗?

import itertools
import random
set_size = 2
schedule = set()
teams = range(5)
for comb in itertools.product(teams, repeat=set_size):
    comb = sorted(list(comb))
    if len(set(comb)) == set_size:
        schedule.add(tuple(comb))

schedule = list(schedule)
random.shuffle(schedule)
print schedule