我正在CS50实验室6上工作,simulate_tournament()函数有问题。我不想要解决办法,我只是想知道我做错了什么。simulate_tournament()函数应该接受一个团队列表,并反复执行simulate_round()函数,直到只剩下一个赢家。simulate_round函数返回优胜者列表,simulate_tournament()返回一个获胜者。我已经完成了所有其他功能,并且只对simulate_tournament有问题。
# Simulate a sports tournament
import csv
import sys
import random
from collections import defaultdict
# 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
file = sys.argv[1]
with open(file,"r") as fil:
reader = csv.DictReader(fil)
for row in reader:
name = row["team"]
rating = int(row["rating"])
teams += [name , rating]
#x = [name , rating]
#teams.append(x)
counts = {}
# TODO: Simulate N tournaments and keep track of win counts
for i in range(N):
teamname = simulate_tournament(teams)
#counts[teamname] = counts.get(teamname, 0) + 1
if teamname in counts:
counts[teamname] += 1
else:
counts[teamname] = 0
counts[teamname] += 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
tournateams = teams
while True:
winns = simulate_round(tournateams)
if len(winns) == 1:
return winns[0]
else:
tournateams = winns
if __name__ == "__main__":
main()发布于 2022-10-26 20:54:22
花一些时间检查teams变量。读取csv文件时,可以将teams创建为一个列表对象,其中包含一对名称和评等值。结果列表如下所示:['Uruguay', 976, 'Portugal', 1306, 'France', 1166, ... ]然后调用simulate_tournament(),后者调用simulate_round(),后者调用simulate_game(teams[i],teams[i+1])。(至少)最后一个电话有两个问题。
simulate_game()时,它将有teams[0]='Uruguay'和teams[1]=976 (基于上面的数据)。显然,这是行不通的。simulate_game()您正在使用字典符号来访问评等(参见rating1 = team1["rating"],rating2也是如此)。但是这些不是dictionaries.问题规范要求您将每个团队的数据导入为字典,例如{"team": "Uruguay", "rating": 976}。看上去你做了这件事,在第36-35行放弃了它。修复这个问题,这将使simulate_game()工作(以及_round()和_tournament())。一旦解决了这个问题,您还需要在第43-47行上计算赢家。同样,您正在尝试使用字典表示法,并有一些错误需要修复。祝好运。
https://stackoverflow.com/questions/74147907
复制相似问题