Python中的联赛夹具生成器 [英] League fixture generator in python

查看:71
本文介绍了Python中的联赛夹具生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用python写一个League Fixture生成器,但是我不能.这是详细信息:

I would like to write a League Fixture generator in python, but I can't. Here is the details:

这里有动态的团队列表,例如teams = ["Team1", "Team2", "Team3", "Team4"]. 如何从团队列表中生成一个fix_weekx列表?例如:

There is a dynamic list of teams like teams = ["Team1", "Team2", "Team3", "Team4"]. How can I generate a fixture_weekx list from the teams list? For example:

fixture_week1 = ["Team1", "Team2", "Team3", "Team4"]
fixture_week2 = ["Team1", "Team3", "Team2", "Team4"]
fixture_week2 = ["Team1", "Team4", "Team2", "Team3"]

#Return matches:
fixture_week1 = ["Team2", "Team1", "Team4", "Team3"]
fixture_week2 = ["Team3", "Team1", "Team4", "Team2"]
fixture_week2 = ["Team4", "Team1", "Team3", "Team2"]

有什么主意吗?

推荐答案

固定调度是一个众所周知的问题.这是在以下位置给出的算法的python实现: http://en.wikipedia.org/wiki/Round- robin_tournament

Fixture scheduling is a well known problem. This is python implementation of algorithm given at: http://en.wikipedia.org/wiki/Round-robin_tournament

# generation code - for cut and paste

import operator
def fixtures(teams):
    if len(teams) % 2:
        teams.append('Day off')  # if team number is odd - use 'day off' as fake team     

    rotation = list(teams)       # copy the list

    fixtures = []
    for i in range(0, len(teams)-1):
        fixtures.append(rotation)
        rotation = [rotation[0]] + [rotation[-1]] + rotation[1:-1]

    return fixtures

# demo code
teams = ["Team1", "Team2", "Team3", "Team4", "Team5"]

# for one match each - use this block only
matches = fixtures(teams)
for f in matches:    
    print zip(*[iter(f)]*2)

# if you want return matches 
reverse_teams =  [list(x) for x in zip(teams[1::2], teams[::2])]
reverse_teams = reduce(operator.add,  reverse_teams)    # swap team1 with team2, and so on ....

#then run the fixtures again
matches = fixtures(reverse_teams)

print "return matches"
for f in matches:    
    print f

这将生成输出:

[('Team1', 'Day off'), ('Team2', 'Team5'), ('Team3', 'Team4')]
[('Team1', 'Team5'), ('Day off', 'Team4'), ('Team2', 'Team3')]
[('Team1', 'Team4'), ('Team5', 'Team3'), ('Day off', 'Team2')]
[('Team1', 'Team3'), ('Team4', 'Team2'), ('Team5', 'Day off')]
[('Team1', 'Team2'), ('Team3', 'Day off'), ('Team4', 'Team5')]

这篇关于Python中的联赛夹具生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆