首页 > 编程问答 >循环赛算法:每队比赛总数

循环赛算法:每队比赛总数

时间:2024-07-30 16:12:21浏览次数:10  
标签:python scheduled-tasks scheduling round-robin tournament

循环赛安排要求:每支球队的比赛总数

我是循环赛安排的新手,并且坚持这个要求,我们在团队数组中传递以及球队应该参加的最小比赛数。我已经实现了单循环算法和双循环算法,例如:

teams = ['T1', 'T2', 'T3', 'T4'];

单循环生成此:

T3 vs T2
T4 vs T1
T2 vs T4
T3 vs T1
T1 vs T2
T3 vs T4

双循环生成此:

例如

    count = len(teams)
    adjusted_count = count - 1 if count % 2 == 0 else count
    total_matches = adjusted_count * 2
T3 vs T4
T1 vs T2
T4 vs T1
T3 vs T2
T2 vs T4
T3 vs T1
T4 vs T3
T2 vs T1
T1 vs T4
T2 vs T3
T4 vs T2
T1 vs T3

现在,要求如下:我传递团队数组,我设置了每支球队应始终参加的最少比赛数量,例如 4 支球队,每支球队的最少比赛总数 =3

我如何实现这一点?

我的代码:

import random

def rotate(lst):
    return lst[1:] + lst[:1]

def make_schedule(teams, rounds=None, shuffle=True, seed=None):
    team_count = len(teams)
    
    if team_count < 2:
        return []
    
    # Account for odd number of teams by adding a bye
    if team_count % 2 == 1:
        teams.append(None)
        team_count += 1

    if shuffle:
        # Seed shuffle with seed or randomize if seed is None
        random.seed(seed)
        random.shuffle(teams)
    elif seed is not None:
        # Generate friendly notice that seed is set but shuffle is set to false
        raise ValueError("Seed parameter has no effect when shuffle parameter is set to False")
    
    half_team_count = team_count // 2
    
    if rounds is None:
        rounds = team_count - 1

    schedule = []
    for round in range(1, rounds + 1):
        round_matches = []
        for key in range(half_team_count):
            team1 = teams[key]
            team2 = teams[key + half_team_count]
            # Home-away swapping
            matchup = [team1, team2] if round % 2 == 1 else [team2, team1]
            round_matches.append(matchup)
        
        schedule.append(round_matches)
        teams = rotate(teams)
    
    return schedule

此代码基于以下内容创建了对战格式提供的轮次。但我想通过传递 minMatchesPer team 来修改它,例如 3 场比赛。一旦每支球队达到至少 3 场比赛,循环就会中断。我给出基本函数只是为了更好地理解。


import random

def rotate(lst):
    return lst[1:] + lst[:1]

def make_schedule(teams, min_matches_per_team, shuffle=True, seed=None):
    team_count = len(teams)

    if team_count < 2:
        return []

    if shuffle:
        random.seed(seed)
        random.shuffle(teams)
    elif seed is not None:
        raise ValueError("Seed parameter has no effect when shuffle parameter is set to False")

    half_team_count = team_count // 2

    schedule = []
    matches_played = {team: 0 for team in teams}  # Keep track of matches played by each team
    round = 1

    while any(count < min_matches_per_team for count in matches_played.values()):
        round_matches = []
        for key in range(half_team_count):
            team1 = teams[key]
            team2 = teams[key + half_team_count]

            # Check if both teams have played less than the minimum required matches
            if matches_played[team1] < min_matches_per_team and matches_played[team2] < min_matches_per_team:
                matchup = [team1, team2] if round % 2 == 1 else [team2, team1]
                round_matches.append(matchup)
                matches_played[team1] += 1
                matches_played[team2] += 1

        if round_matches:  # Only append if there are matches in the round
            schedule.append(round_matches)
            round += 1
        teams = rotate(teams)

    return schedule

# Example usage
teams = ['T1', 'T2', 'T3', 'T4']
min_matches_per_team = 3

schedule = make_schedule(teams, min_matches_per_team, shuffle=True, seed=42)

for i, round_matches in enumerate(schedule):
    print(f"Round {i+1}:")
    for match in round_matches:
        print(f"  {match[0]} vs {match[1]}")

Explanation:

  1. Track Matches Played:
  2. We introduce a dictionary matches_played to keep track of how many matches each team has played so far.

  3. Loop Until Condition Met:

  4. Instead of a fixed number of rounds, we use a while loop that continues until all teams have played at least min_matches_per_team .

  5. Conditional Match Scheduling:

  6. Inside the loop, we only schedule a match between team1 and team2 if both teams have played fewer than min_matches_per_team matches.

  7. Update Matches Played:

  8. After scheduling a match, we increment the match counts for both participating teams in the matches_played dictionary.

  9. Round Management:

  10. We only increment the round counter and append round_matches to the schedule if there were any matches scheduled in that round. This ensures we don't add empty rounds.

Now, the code will generate a schedule where each team plays at least the specified minimum number of matches, even if it means having fewer total rounds or some teams playing slightly more than the minimum.

标签:python,scheduled-tasks,scheduling,round-robin,tournament
From: 78810255

相关文章

  • 使用python从网站自动下载pdf时出错
    我想从一个名为epadossier.nl的网站自动批量下载pdf我用谷歌搜索了这个并找到了一段代码并修复了一个小错误。所以现在我得到了这个`importrequestsurl="https://www.epadossier.nl/adres/plaats/straat/num"response=requests.get(url)ifresponse.status_cod......
  • 避免字符串连接的嵌套循环的 Pythonic 方法
    我想找到所有5位数字的字符串,其中前三位数字在我的第一个列表中,第二个槽第四个数字在我的第二个列表中,第三到第五个数字在我的最后一个列表中:l0=["123","567","451"]l1=["234","239","881"]l2=["348","551","399"......
  • Python 环境配置(二)安装jupyter、matplotlib、numpy库
    Python环境配置(二)安装jupyter、matplotlib、numpy库一、numpypipinstallnumpy二、matplotlibpipinstallmatplotlib三、jupyter1、anaconda自带Jupyter2、pycharm插件只有Pycharm的Professional版才支持JupyterNotebook,请注意版本3、新建文件#%......
  • 如何使用 PIPE 并行运行 python 子进程?
    我正在使用inkscape将一堆SVG图像转换为PNG。单线程:importsubprocessimporttimeimportosinkscape_path=r'C:\ProgramFiles\Inkscape\bin\inkscape.com'steps=30filenames=[]processes=[]#t_start=time.process_time()t_start=time.time()f......
  • Python sqlite3 删除数据
    要从SQLite表中删除记录,你需要使用DELETEFROM语句。要删除特定的记录,你需要同时使用WHERE子句。要更新特定的记录,你需要同时使用WHERE子句。语法以下是SQLite中DELETE查询的语法- DELETEFROMtable_name[WHEREClause]PythonCopy例子假设我们使用以下查询创建了......
  • Python 环境配置(一)Python、Anaconda、Pycharm的安装
    Python环境配置(一)Python、Anaconda、Pycharm的安装本人之前已安装一次,此次为卸载之后的重新安装。。。一、Python1、下载下载官网:下载链接:DownloadPython|Python.org勾选添加到路径(环境变量)next如图所示之后点close关闭2、验证win+Rcmd:python退出ex......
  • Pycharm 设置 yaml 格式接口测试用例模板 (python+pytest+yaml)
    前言初次编写的伙伴们可能对yaml格式不太熟悉,自己写yaml用例的时候,总是格式对不齐啊记不住设定好的关键字啊等等等琐事是我们可以在pycharm上设置用例模块,通过快捷方式调用出对应的模块,达到高效写用例的目的。 pycharm操作集:1、File-Settings(快捷键Ctrl+Alt+S) 2、Live......
  • Python - Redirecting output of print to a file
    Theprintfunctioncanalsobeusedtowritetoafile.Theoutputofprint,thatisbydefault,senttothescreencanberedirectedtoanopenfile.Forthis,youhavetosupplythefileobjectasanargumentforthenamedparameterfile.Hereisanexa......
  • Python:添加到相对于当前运行脚本的 sys.path 的最佳方法
    我有一个充满脚本的目录(比如说project/bin)。我还有一个位于project/lib的库,并希望脚本自动加载它。这是我通常在每个脚本的顶部使用的:#!/usr/bin/pythonfromos.pathimportdirname,realpath,sep,pardirimportsyssys.path.append(dirname(realpath(_......
  • python身份证号码+姓名一致性核验、身份证号码真伪查询API集成
    身份证号码+姓名核验的方式,顾名思义是身份证二要素核验,一般情况下,身份证真伪查询需要上公安户籍系统查询,但此种方式仅适合个人查询,企业要想随时随地实现身份证实名认证的功能,便需要集成身份证实名认证接口功能。翔云人工智能开放平台提供身份证号实名认证接口,实时联网,上传身份证......