Computing win/loss records in Python

Hans Mulder hansmu at xs4all.nl
Sun Aug 26 06:00:38 EDT 2012


On 26/08/12 04:42:59, Steven W. Orr wrote:
> On 8/25/2012 10:20 PM, Christopher McComas wrote:
>> Greetings,
>>
>> I have code that I run via Django that grabs the results from various
>> sports from formatted text files. The script iterates over every line
>> in the formatted text files, finds the team in the Postgres database
>> updates their w/l record depending on the outcome on that line, saves
>> the team's row in the db, and then moves on to the next line in the file.
>>
>> I'm trying to get away from Django for this project, I want to run the
>> files, get the W/L results and output a formatted text file with the
>> teams and their W/L records. What's confusing me I guess how to store
>> the data/results as the wins and losses tally up. We're talking
>> hundreds of teams, thousands of games, but a quick example would be:
>>
>> Marshall
>> Ohio State
>> Kentucky
>> Indiana
>>
>> Marshall,24,Ohio State,48,
>> Kentucky,14,Indiana,10,
>> Marshall,10,Indiana,7,
>> Ohio State,28,Kentucky,10
>>
>> That's just a quick example, I can handle seperating the data in the
>> lines, figuring it all out, I just am unsure of how to keep a running
>> total of a team's record. I would do "for line in file:" then on the
>> first line I see that Marshall lost so they would have 1, Ohio State
>> won so they'd have 1 win. It'd go to the next line Kentucky 1 win,
>> Indiana 1 loss, then on the 3rd line, Marshall got a win so they'd
>> have 1 win, but it would have to remember that loss from line 1...
>>
>> Does this make sense?
>>
>> Thanks,
> 
> win_count = defaultdict(int)
> loss_count = defaultdict(int)
> 
> items = line.split(',')
> if items[1] > items[3]:
>     windex = 0
>     lossdex = 2
> else:
>     windex = 2
>     lossdex = 0
> win_count[windex] += 1
> loss_count[lossdex] += 1

I think you meant:

win_count[items[windex]] += 1
loss_count[items[windex]] += 1


I think it would be more readable to do:

from collections import defaultdict

win_count = defaultdict(int)
loss_count = defaultdict(int)

items = line.split(',')
if int(items[1]) > int(items[3]):
    winner = items[0]
    loser = items[2]
else:
    winner = items[2]
    loser = items[0]
win_count[winner] += 1
loss_count[loser] += 1

It looks like you're afraid of wasting RAM by needlessly
copying strings.  However, this fear is unfounded: Python
doesn't copy strings, unless you tell it to do so explictly.
An assignment like "winner = items[0]" doesn't copy the string;
it merely creates a new reference to the existing string.


Hope this helps,

-- HansM



More information about the Python-list mailing list