views:

47

answers:

2

1) Write a function that reads a file of sports team win/loss records, and computes the win percentage of each. For example, using the file leagueRecords.txt:

Lions, 20, 14
Tigers, 31, 0
Bears, 16, 17
Ohmy's, 11, 5
Ferocious Animals, 12, 8
Home Team Name, 15, 22
Screaming Eagles, 22, 13
Yelling Falcons, 16, 14
Loud-talkin' Bluebirds, 1, 20

computeAverages()

Enter name of win/loss file: leagueRecords.txt

Here's the summary report:

The Lions won 58.82% of their games.
The Tigers won 100.00% of their games.
The Bears won 48.48% of their games.
The Ohmy's won 68.75% of their games.
The Ferocious Animals won 60.00% of their games.
The Home Team Name won 40.54% of their games.
The Screaming Eagles won 62.86% of their games.
The Yelling Falcons won 53.33% of their games.
The Loud-talkin' Bluebirds won 4.76% of their games.

Note that the file you read in must be formatted in a particular way. Specifically, each line must contain three items, separated by commas: the team name, the number of wins, and the number of losses. You may assume that whatever file the user types in is formatted in this way. Of course, your program should work for any correctly formatted file, not just the example leagueRecords.txt above.

Notes: - Use string formatting to get the percentages to print as you see above. You are not allowed to use explicit rounding - the rounding should occur entirely through the string formatting functionality. - To get the % symbol to show up, you need to type %% in your string This is because a single % would be interpreted as the string formatting character.

A: 

You could read the file using a CSV reader (store the results in a dictionary in case you require persistence, keeping the wins & total games in each entry).

Then you can calculate the pctg (wins/played * 100) and print the results. You shoudl be able to do this in a single file iteration.

I hope this helps.

Thanks, Damian

Damian Schenkelman
+1  A: 

The standard Python library csv module looks like a good way to process the input file -- of course it gives you all fields as strings, so you'll need to call float or int to turn the second and third one into numbers (if you use int be sure to also use "true division" so the ratio won't be truncated! using float may make your life simpler here;-). As for output formatting, there are two ways, the old-fashioned one using percent signs and the new and shiny one -- from the text of your homework it looks like your instructor only knows the old-fashioned way (and perhaps he's right: what Python version are you constrained to use?), but it would be nice to get this clarified.

Alex Martelli