目前,我正在Python上编写一段代码,以便为CS50x创建lab 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()发布于 2021-02-24 19:13:03
我想这是因为你没有在你的while循环中增加?
i = 0
while i < N:
winner = simulate_tournament(teams)
if winner in counts:
counts["winner"] += 1
else:
counts["winner"] = 1发布于 2021-01-22 03:30:37
我认为您的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我不知道这是不是最有效的函数,但它对我来说工作得很好!
发布于 2021-01-22 04:27:40
我今天也在同一个实验室工作。我认为您的错误在这里:使用open(sys.argv1,"r")作为文件:它应该是唯一的,使用open(sys.argv1)作为文件。
https://stackoverflow.com/questions/65788032
复制相似问题