# Homework 7 Solutions

**Solutions:** You can find the file with solutions for all
questions here.

## Baseball Season!

### Question 1: MLB All Star

It's October, which means its baseball playoffs season! In this exercise, let's utilize dictionaries to see if we can model and learn more about some of our favorite players. In this problem, you will be implementing multiple functions.

As you can see within your hw06.py file, the dictionaries mapping players to their team and statistics respectively have been created already. However, instead of accessing these values directly, we'll be implementing two functions to retrieve the appropriate values as a layer of abstraction.

Implement the `get_team`

and `get_stats`

functions to retrieve the team or statistics given a player's name.

```
full_roster = {
"Manny Machado" : "Dodgers",
"Yasiel Puig" : "Dodgers",
"Aaron Judge" : "Yankees",
"Clayton Kershaw" : "Dodgers",
"Giancarlo Stanton" : "Yankees"
}
full_stats = {
"Manny Machado": ["SO", "1B", "3B", "SO", "HR"],
"Yasiel Puig": ["3B", "3B", "1B", "1B", "SO"],
"Aaron Judge": ["SO", "HR", "HR", "1B", "SO"],
"Clayton Kershaw": ["1B", "SO", "SO", "1B", "SO"],
"Giancarlo Stanton": ["HR", "SO", "3B", "SO", "2B"],
}
def get_team(player):
"""Returns team that the provided player is a member of.
>>> get_team("Manny Machado")
'Dodgers'
>>> get_team("Aaron Judge")
'Yankees'
"""
return full_roster[player]
def get_stats(player):
"""Returns the statistics associated with the provided player.
>>> get_stats("Manny Machado")
['SO', '1B', '3B', 'SO', 'HR']
>>> get_stats('Aaron Judge')
['SO', 'HR', 'HR', '1B', 'SO']
"""
return full_stats[player]
```

Use OK to test your code:

```
python3 ok -q get_team --local
python3 ok -q get_stats --local
```

## Retrieval Methods

### Question 2: Team Roster

Implement the function `get_players`

which takes a team name and returns a list containing all the players that are members of the given team.

```
def get_players(team):
"""Returns a list of all players who are members of the given team.
>>> get_players("Dodgers")
['Manny Machado', 'Yasiel Puig', 'Clayton Kershaw']
>>> get_players("Yankees")
['Aaron Judge', 'Giancarlo Stanton']
"""
roster = []
for player in full_roster:
if get_team(player) == team:
roster = roster + [player]
return roster
```

Use OK to test your code:

`python3 ok -q get_players --local`

### Question 3: Build the Full Rosters

Implement the function `common_players`

. The `common_players`

function identifies which keys from the `full_roster`

share the same values. The function returns a new dictionary where each key is the value from the original dictionary, and the corresponding values of the new dictionary are list that contain keys that share the same value.

```
def common_players(roster):
"""Returns a dictionary containing values along with a corresponding
list of keys that had that value from the original dictionary.
>>> common_players(full_roster)
{'Dodgers': ['Manny Machado', 'Yasiel Puig', 'Clayton Kershaw'], 'Yankees': ['Aaron Judge', 'Giancarlo Stanton']}
>>> full_roster = {"bob": "excellent", "barnum": "passing", "beatrice": "satisfactory", "bernice": "passing", "ben": "no pass", "belle": "excellent", "bill": "passing", "bernie": "passing", "baxter": "excellent"}
>>> common_players(full_roster)
{'excellent': ['bob', 'belle', 'baxter'], 'passing': ['barnum', 'bernice', 'bill', 'bernie'], 'satisfactory': ['beatrice'], 'no pass': ['ben']}
"""
result_dict = {}
for player in roster:
team = roster[player]
if team in result_dict:
result_dict[team] += [player]
else:
result_dict[team] = [player]
return result_dict
```

Use OK to test your code:

`python3 ok -q common_players --local`

## Sabremetrics

### Question 4: Baseball Statistics

If you're a Moneyball movie fan, you know that statistics helps teams find value in players that nobody else sees. In this problem, you'll be implementing two functions to calculate the team batting average for one team, and the mean slugging percentage for all teams.

We highly encourage you to use the functions that you've defined before to solve these problems, specifically the `common_players`

and `get_players`

functions from the previous two problems.

Two functions have already been defined for you to calculate batting average and slugging percentage given a player's statistics. Use these functions when you calculate the averages for each team.

```
# Following Functions have been given to you, do NOT modify
def calculate_batting_average(stats):
hits = 0
total_bats = 0
for at_bat in stats:
if at_bat != "SO":
hits += 1
total_bats += 1
return float(round(hits/total_bats, 1))
def calculate_slugging_percent(stats):
bases = 0
total_bats = 0
for at_bat in stats:
if at_bat == "1B":
bases += 1
elif at_bat == "2B":
bases += 2
elif at_bat == "3B":
bases += 3
elif at_bat == "HR":
bases += 4
total_bats += 1
return float(round(bases/total_bats, 1))
# Modify Functions below
def calculate_team_BA(team):
"""Given a single team name, returns the mean batting average of all players on that team. You are encouraged to use previous functions that you've defined already
>>> calculate_team_BA('Dodgers')
0.6
>>> calculate_team_BA('Yankees')
0.6
"""
roster = get_players(team)
total_BA = 0
total_players = 0
for player in roster:
player_stats = get_stats(player)
total_BA += calculate_batting_average(player_stats)
total_players += 1
return total_BA / total_players
def calculate_all_team_SP():
"""Returns a dictionary mapping every team to the average slugging percentage of all players on that team. You are encouraged to use previous functions that you've defined already.
>>> calculate_all_team_SP()
{'Dodgers': 1.2, 'Yankees': 1.8}
"""
team_SP = {}
rosters = common_players(full_roster)
for team in rosters:
total_SP = 0
total_players = 0
for player in rosters[team]:
player_stats = get_stats(player)
total_SP += calculate_slugging_percent(player_stats)
total_players += 1
team_SP[team] = total_SP / total_players
return team_SP
```

Use OK to test your code:

```
python3 ok -q calculate_team_BA --local
python3 ok -q calculate_all_team_SP --local
```