Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python random sports schedule generator

Tags:

python

I found the following

Generating natural schedule for a sports league

That generates the same schedule each time you run it.. If I add a random.shuffle() in there it's still too predictable.

Below is my simple edit from that post with a random in place and I get odd results

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

sometimes it seems teams won't even play each other.. see the results

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

My question is.. how can I do a random schedule generator in python or fix what I have already.

Pretty much I need to take 4 teams and come out with 3 weeks of play where they play each other once. Or like 5 teams where there are 5 weeks of play and they all play each other once but one team is left out per week

like image 895
Mike Avatar asked Mar 28 '12 03:03

Mike


1 Answers

I am assuming that each team needs to play with other team. Is it not? Then does not this question boil down to simple permutation and then shuffling the result?

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
like image 71
Senthil Kumaran Avatar answered Oct 12 '22 01:10

Senthil Kumaran