$ uv run magic.py "Houston Astros"
Reading inline script metadata from: magic.py
The magic number for the Houston Astros is 12.
Last active
September 13, 2024 18:13
-
-
Save amcclosky/902ff5df5adc787b7bb73303d461eaac to your computer and use it in GitHub Desktop.
Script to find the current Magic Number of an MLB Team
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /// script | |
# dependencies = [ | |
# "MLB-StatsAPI", | |
# ] | |
# /// | |
""" | |
o1-preview prompt: | |
Write a python method which uses the mlb api to calculate the current magic number of a given team. | |
""" | |
import sys | |
import statsapi | |
def calculate_magic_number(team_name): | |
""" | |
Calculates the current magic number of a given MLB team. | |
""" | |
standings = statsapi.standings_data() | |
team_found = False | |
team_data = None | |
division_teams = None | |
# Search for the team in the division standings | |
for division_data in standings.values(): | |
teams = division_data["teams"] | |
for team in teams: | |
if team["name"].lower() == team_name.lower(): | |
team_found = True | |
team_data = team | |
division_teams = teams | |
break | |
if team_found: | |
break | |
if not team_found: | |
print(f"Team '{team_name}' not found.") | |
return | |
# Sort teams in the division by wins | |
sorted_teams = sorted(division_teams, key=lambda x: int(x["w"]), reverse=True) | |
leading_team = sorted_teams[0] | |
total_games = 162 # Total games in an MLB regular season | |
if team_data["name"] == leading_team["name"]: | |
# Team is leading the division | |
if len(sorted_teams) > 1: | |
second_place_team = sorted_teams[1] | |
magic_number = ( | |
total_games - int(team_data["w"]) - int(second_place_team["l"]) + 1 | |
) | |
print(f"The magic number for the {team_data['name']} is {magic_number}.") | |
else: | |
print(f"The {team_data['name']} are the only team in their division.") | |
else: | |
# Team is trailing in the division | |
magic_number = total_games - int(leading_team["w"]) - int(team_data["l"]) + 1 | |
print(f"The elimination number for the {team_data['name']} is {magic_number}.") | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print("Usage: uv run magic.py 'Team Name'") | |
else: | |
team_name = sys.argv[1] | |
calculate_magic_number(team_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment