<gh_stars>0
"""
Author: AH-SALAH
tournament.py (c) 2021
Desc: simulating sports tournament
Created: 2021-05-17T10:49:26.627Z
Modified: 2021-05-17T10:50:50.295Z
"""
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 = []
    # Read teams into memory from file
    with open(sys.argv[1], "r") as teamsFile:
        reader = csv.DictReader(teamsFile)
        # next(reader)
        # teams = [{t[0]: int(t[1])} for t in reader]
        teams = [{"team": t["team"], "rating": int(t["rating"])} for t in reader]

        # for x in teams:
        #     print(f"team: {x}")

    counts = {}
    # Simulate N tournaments and keep track of win counts
    for x in range(N):
        wnr = simulate_tournament(teams)
        counts.update({wnr: counts[wnr] + 1}) if wnr in counts else counts.update({wnr: 1})
        
    # print(f"counts: {counts}")

    # 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
    team = ""
    rounds = len(winners)
    for r in range(rounds):
        if rounds == 1:
            break
        winners = simulate_round(winners)
        rounds = len(winners)
        team = winners[0]["team"]

    # print(f"winners: {winners}, team: {team}, rounds: {rounds}")
    
    return team


if __name__ == "__main__":
    main()

"""
Author: AH-SALAH
tournament.py (c) 2021
Desc: simulating sports tournament
Created: 2021-05-17T10:49:26.627Z
Modified: 2021-05-17T10:50:50.295Z
"""
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 = []
    # Read teams into memory from file
    with open(sys.argv[1], "r") as teamsFile:
        reader = csv.DictReader(teamsFile)
        # next(reader)
        # teams = [{t[0]: int(t[1])} for t in reader]
        teams = [{"team": t["team"], "rating": int(t["rating"])} for t in reader]

        # for x in teams:
        #     print(f"team: {x}")

    counts = {}
    # Simulate N tournaments and keep track of win counts
    for x in range(N):
        wnr = simulate_tournament(teams)
        counts.update({wnr: counts[wnr] + 1}) if wnr in counts else counts.update({wnr: 1})
        
    # print(f"counts: {counts}")

    # 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
    team = ""
    rounds = len(winners)
    for r in range(rounds):
        if rounds == 1:
            break
        winners = simulate_round(winners)
        rounds = len(winners)
        team = winners[0]["team"]

    # print(f"winners: {winners}, team: {team}, rounds: {rounds}")
    
    return team


if __name__ == "__main__":
    main()
Author: AH-SALAH tournament.py (c) 2021 Desc: simulating sports tournament Created: 2021-05-17T10:49:26.627Z Modified: 2021-05-17T10:50:50.295Z # Number of simluations to run # Ensure correct usage # Read teams into memory from file # next(reader) # teams = [{t[0]: int(t[1])} for t in reader] # for x in teams: #     print(f"team: {x}") # Simulate N tournaments and keep track of win counts # print(f"counts: {counts}") # Print each team's chances of winning, according to simulation Simulate a game. Return True if team1 wins, False otherwise. Simulate a round. Return a list of winning teams. # Simulate games for all pairs of teams Simulate a tournament. Return name of winning team. # print(f"winners: {winners}, team: {team}, rounds: {rounds}")