首页 > 解决方案 > 我在 CS50 Lab 6 中的代码发生了什么问题,我该如何解决?

问题描述

这是我的 CS50 Lab 6 代码:

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")

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

        
counts = {}
# TODO: Simulate N tournaments and keep track of win counts
for i in range(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):

    rating1 = team1["rating"]
    rating2 = team2["rating"]
    probability = 1 / (1 + 10 ** ((rating2 - rating1) / 600))
    return random.random() < probability


def simulate_round(teams):
   
    winners = []

    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):
    
    while len(teams) >= 2:
    teams = simulate_round(teams)
    return simulate_tournament(teams)
else:        
    return teams[0]["team"]


if __name__ == "__main__":
    main()

但是来自 IDE 的消息是:

Traceback (most recent call last):
      File "/usr/local/lib/python3.9/site-packages/ikp3db.py", line 2054, in main
        ikpdb._runscript(mainpyfile)
      File "/usr/local/lib/python3.9/site-packages/ikp3db.py", line 1525, in _runscript
        exec(statement, globals, locals)
      File "<string>", line 1, in <module>
      File "tournament.py", line 75, in <module>
        main()
      File "tournament.py", line 31, in main
        winner = simulate_tournament(teams)
      File "tournament.py", line 68, in simulate_tournament
        teams = simulate_round(teams)
      File "tournament.py", line 56, in simulate_round
        if simulate_game(teams[i], teams[i + 1]):
        IndexError: list index out of range

它显示错误分别存在于第31,56,68,75行,但大部分都是预先编写的,应该没有问题。我不知道如何解决它,这很奇怪,因为我看到了一些类似的源代码,但它们很好,只有我的结果出现了一堆索引错误。你介意给我一两个提示吗?

标签: pythoncs50index-errorlab

解决方案


推荐阅读