CS50 lab6世界杯simulate_tournament功能问题
我的tournament.py 程序似乎工作正常,但通过 check50 运行它会出现一些错误,特别是使用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
f = open(sys.argv[1], "r")
handle = csv.DictReader(f)
for item in handle:
item['rating'] = int(item['rating'])
teams.append(item)
counts = {}
# TODO: Simulate N tournaments and keep track of win counts
for i in range(N):
winner = simulate_tournament(teams)
if winner['team'] in counts:
counts[winner['team']] += 1
else:
counts[winner['team']] = 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]
if __name__ == "__main__":
main()
和输出:
Brazil: 22.3% chance of winning
Belgium: 20.8% chance of winning
Portugal: 15.0% chance of winning
Switzerland: 10.8% chance of winning
Spain: 10.2% chance of winning
Argentina: 6.6% chance of winning
England: 3.4% chance of winning
France: 3.4% chance of winning
Denmark: 2.8% chance of winning
Croatia: 1.4% chance of winning
Colombia: 1.4% chance of winning
Mexico: 1.1% chance of winning
Sweden: 0.6% chance of winning
Uruguay: 0.2% chance of winning
可能是什么原因造成的?我仍然不太熟悉 python 中的列表和字典,或者一般的 python。
这是 check50 的结果:
:) tournament.py exists
:) tournament.py imports
:( simulate_tournament handles a bracket of size 2
simulate_tournament fails to return the name of 1 winning team
:( simulate_tournament handles a bracket of size 4
simulate_tournament fails to return the name of 1 winning team
:( simulate_tournament handles a bracket of size 8
simulate_tournament fails to return the name of 1 winning team
:( simulate_tournament handles a bracket of size 16
simulate_tournament fails to return the name of 1 winning team
:) correctly keeps track of wins
:) correctly reports team information for Men's World Cup
:) correctly reports team information for Women's World Cup
My tournament.py program seems to work fine but running it through check50 gives a few errors, specifically with the simulate_tournament function, saying it doesn't correctly return the name of the winner. Here's my code:
# 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
f = open(sys.argv[1], "r")
handle = csv.DictReader(f)
for item in handle:
item['rating'] = int(item['rating'])
teams.append(item)
counts = {}
# TODO: Simulate N tournaments and keep track of win counts
for i in range(N):
winner = simulate_tournament(teams)
if winner['team'] in counts:
counts[winner['team']] += 1
else:
counts[winner['team']] = 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]
if __name__ == "__main__":
main()
and the output:
Brazil: 22.3% chance of winning
Belgium: 20.8% chance of winning
Portugal: 15.0% chance of winning
Switzerland: 10.8% chance of winning
Spain: 10.2% chance of winning
Argentina: 6.6% chance of winning
England: 3.4% chance of winning
France: 3.4% chance of winning
Denmark: 2.8% chance of winning
Croatia: 1.4% chance of winning
Colombia: 1.4% chance of winning
Mexico: 1.1% chance of winning
Sweden: 0.6% chance of winning
Uruguay: 0.2% chance of winning
What could be causing this? I'm still not very familiar with lists and dicts in python, or python in general for that matter.
here is check50's results:
:) tournament.py exists
:) tournament.py imports
:( simulate_tournament handles a bracket of size 2
simulate_tournament fails to return the name of 1 winning team
:( simulate_tournament handles a bracket of size 4
simulate_tournament fails to return the name of 1 winning team
:( simulate_tournament handles a bracket of size 8
simulate_tournament fails to return the name of 1 winning team
:( simulate_tournament handles a bracket of size 16
simulate_tournament fails to return the name of 1 winning team
:) correctly keeps track of wins
:) correctly reports team information for Men's World Cup
:) correctly reports team information for Women's World Cup
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
感谢您的回答 Gennaro,这给了我一个想法来定义
simulate_tournament
函数,如下所示,它也起作用了:看到获胜者成为一个字典,它具有与关键“团队”相关的值,这个值就是获胜者的名字。
Thank you for your answer Gennaro, this gave me an idea to define
simulate_tournament
function as below, and it also worked:See that winner become a dict, which has a value associated with the key "team", and this value is the winner name.
simulate_tournament(teams)
必须返回一个字符串(而不是列表)。这是一个测试要求。simulate_tournament(teams)
must return a string (not a list). This is a test requirement.返回获胜团队的名称就足够了:
Return the name of the winner team should be enough:
我不知道为什么,但 check50 无法识别“名称”,我使用以下代码解决了问题:
我创建了一个列表,其中包含获胜国家/地区的名称及其排名,然后我返回列表 [0],因此名称,这有效。
idk why but check50 doesn't recognise "name", i resolved using this code:
i created a list that contains the name of the winning country and his ranking and then i returned list[0], so the name, and this worked.