A little advice please? (Convert my boss to Python)

Christophe Delord christophe.delord at free.fr
Mon Apr 15 18:43:08 EDT 2002


On Mon, 15 Apr 2002 22:27:56 GMT
Alex Martelli <aleax at aleax.it> wrote:

> Duncan Smith wrote:
>         ...
> >     U = P = 0
> >     for value in dict.values():
> >         if value == 1:
> >             U += 1
> >         elif value == 2:
> >             P += 1
> 
> Again I think it might be faster to avoid the if/else with yet
> another dictionary:
> 
> counts = {}
> for count in adict.values():
>     counts[count] = 1 + counts.get(count, 0)
> 
> U = counts.get(1, 0)
> P = counts.get(2, 0)
> 
> >     return U*S/(U*S+P*(1-S))
> 

As indices are integers (1 and 2), a simple array may be faster :

counts = [None, 0, 0]		# counts[0] not used
for count in adict.values():
	counts[count] += 1

U = counts[1]
P = counts[2]

-- 
Christophe Delord
http://christophe.delord.free.fr/



More information about the Python-list mailing list