-
CS50 Week6: Lab6, World cupProgramming/CS50 2023. 7. 18. 23:11
하버드 CS50 강의 6주차 Lab 과제 World Cup 의 풀이를 다룹니다.
Python으로 작성한 FIFA 월드컵 시뮬레이션 프로그램입니다.Task
문제 링크에서 자세한 내용을 확인할 수 있습니다.
프로그램 실행 예시
$ python tournament.py 2018m.csv Belgium: 20.9% chance of winning Brazil: 20.3% chance of winning Portugal: 14.5% chance of winning Spain: 13.6% chance of winning Switzerland: 10.5% chance of winning Argentina: 6.5% chance of winning England: 3.7% chance of winning France: 3.3% chance of winning Denmark: 2.2% chance of winning Croatia: 2.0% chance of winning Colombia: 1.8% chance of winning Sweden: 0.5% chance of winning Uruguay: 0.1% chance of winning Mexico: 0.1% chance of winning
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 = [] with open(sys.argv[1]) as file: reader = csv.DictReader(file) for row in reader: row["rating"] = int(row["rating"]) teams.append(row) counts = {team["team"]: 0 for team in teams} for i in range(N): counts[simulate_tournament(teams)] += 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.""" winners = teams while len(winners) != 1: winners = simulate_round(winners) return winners[0]["team"] if __name__ == "__main__": main()
파이썬이 확실히 시원시원해서 좋다.