Python scips 函数的执行(CS50x 实验 6:世界杯)

Python scips executing of a function (CS50x Lab 6: World Cup)

目前,我正在 Python 上编写代码,为 CS50x 制作实验 6。当我尝试调试我的代码时,似乎只是跳过函数 simulate_tournament() 并生成任何内容作为输出。我将不胜感激有关如何调试此代码并使程序 运行:)

的建议

我的代码有上述问题:

# Simulate a sports tournament

import csv
import sys
import random

# Number of simluations to run
N = 1000


def main():

    # Ensure correct usage
    if len(sys.argv) != 2:
        sys.exit("Usage: python tournament.py FILENAME")

    teams = []
    # TODO: Read teams into memory from file
    with open(sys.argv[1], "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            row["team"]
            row["rating"] = int(row["rating"])
            teams.append(row)

    counts = {}
    # TODO: Simulate N tournaments and keep track of win counts
    i = 0
    while i < N:
        winner = simulate_tournament(teams)
        
        if winner in counts:
            counts["winner"] += 1
        else:
            counts["winner"] = 1

    # Print each team's chances of winning, according to simulation
    for team in sorted(counts, key=lambda team: counts[team], reverse=True):
        print(f"{team}: {counts[team] * 100 / N:.1f}% chance of winning")


def simulate_game(team1, team2):
    """Simulate a game. Return True if team1 wins, False otherwise."""
    rating1 = team1["rating"]
    rating2 = team2["rating"]
    probability = 1 / (1 + 10 ** ((rating2 - rating1) / 600))
    return random.random() < probability


def simulate_round(teams):
    """Simulate a round. Return a list of winning teams."""
    winners = []

    # Simulate games for all pairs of teams
    for i in range(0, len(teams), 2):
        if simulate_game(teams[i], teams[i + 1]):
            winners.append(teams[i])
        else:
            winners.append(teams[i + 1])

    return winners


def simulate_tournament(teams):
    """Simulate a tournament. Return name of winning team."""
    # TODO
    while len(teams) > 1:
        teams = simulate_round(teams)
    return teams[0]["team"]




if __name__ == "__main__":
    main()



我认为您的 simulate_tournament 函数没有返回值。 尝试:

if len(teams) > 2:
    winners = simulate_round(teams)
    ganador = simulate_tournament(winners)
else:
    ganador = simulate_round(teams)
    return ganador[0]['team']

return ganador

我不知道它是否是最有效的功能,但它对我来说效果很好!

我今天在同一个实验室工作。我认为你的错误在这里: 打开(sys.argv[1],“r”)作为文件: 应该只有,with open(sys.argv[1]) as file.

我认为这是因为你没有在你的 while 循环中递增?

i = 0
while i < N:
    winner = simulate_tournament(teams)
    
    if winner in counts:
        counts["winner"] += 1
    else:
        counts["winner"] = 1

您的计数变量中需要包含 keys/values。它不打印任何东西的原因是因为没有任何东西可以计数。此外,您不应该将 winner 用作字符串,函数 returns 是一个字符串,因此 python 会自动使 winner 成为一个字符串变量。您应该将为获胜者返回的字符串散列到 counts 变量,从而将 count 更新为正确的名称。