Computing win/loss records in Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Aug 25 23:19:23 EDT 2012


On Sat, 25 Aug 2012 22:42:59 -0400, Steven W. Orr wrote:

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

When I try that, I get "NameError: name 'defaultdict' is not defined."

I think it is rather unfair on beginners to show them code that almost, 
but not quite, works, and expect them to somehow work out what this 
mysterious "defaultdict" is.

The answer is probably to do this first:

from collections import defaultdict


> items = line.split(',')
> if items[1] > items[3]:
>      windex = 0
>      lossdex = 2

That's not going to work, because you are doing string comparisons 
instead of numeric comparisons. Consider:

Kentucky,6,Indiana,59

'6' > '59' and you will wrongly count that as a win to Kentucky.


> else:
>      windex = 2
>      lossdex = 0
> win_count[windex] += 1
> loss_count[lossdex] += 1

And that certainly won't work, because all you are doing is counting how 
many times the first team beats the second, instead of counting how many 
times each team wins.


-- 
Steven



More information about the Python-list mailing list