120 likes | 312 Vues
In this lab, we will explore Python's data types to display and access information from a list, specifically focusing on computing batting averages in baseball. The batting average measures a player's hitting efficiency, calculated by dividing total hits by total at-bats. We will work with a data file to create a dictionary that holds player names and their averages. Steps include opening the file, processing its contents, and providing functionality to retrieve batting averages for players, along with calculating the team's overall batting average as extra credit.
E N D
Lab 10 - Python Data Types JT Turner
Lab Objectives -This lab we will be using pythons data types to display and access information from a list -Gain Practice using File I/O -Learn how Batting Averages are computed
Batting Average In baseball, a player's batting average is how efficiently they hit the ball, computed by how many times they have hit the ball divided by how many total at bats they have had .avg = Total Hits Total At Bats For this lab, assume Total At bats = 1000 1.000 = Perfect Batting 0.000 = No hits 0.232 = Washington Nationals Average
Step 0: Main We need the data file from JT's pub directory... cp /afs/umbc.edu/users/j/t/jturner1/pub/retrievers.txt . Your main should: -Open the file -Create a new Dictionary -Pass lines of file and dictionary to "makeDict" function -Pass Dictionary to "getAvg" function
Step 1: makeDict -Make Dictionary should take in as parameters: -The dictionary to add to -Line of the data file -We can use the line.split() to change: 'dan 236' into ['dan' , '236'] -Cast the 236 into a float, and divide by 1000.0 dict_name[player_name] = average
Step 2: getAvg - Get Average should only take in the dictionary, and prompt the user for name -If the player is not in the dictionary, dict_name.has_key(player) #will be false -And you should say that the player is not on the team -If the player is on the team, print "%s has avg %.3f" %(name, dict_name.get(name))
Extra Credit: Team Average Write a function that takes in the dictionary, and computes what the teams batting average is. -Don't reread the file and add all the hits again, it's easier to just sum the batting averages and divide by number of players.