Which is faster? (if not b in m) or (if m.count(b) > 0)

Felipe Almeida Lessa felipe.lessa at gmail.com
Wed Feb 15 05:18:07 EST 2006


Em Ter, 2006-02-14 às 20:14 -0800, Farel escreveu:
> Which is Faster in Python and Why?
> 
> jc = {}; m = []
> x = [ [1,2,3,4,5,6,7,8,9],[..],.......] # upwards of 10000 entries
> def binm()
>     for item in x:
>         b = item[:]; b.sort(); bc = 0
>         for bitem in b: bc += int(bitem)
>         try: m = jc[bc]
>         except: m = []
>         if not b in m:
>             m.append(b); jc[bc]=m

Why do you copy the list and sort it if you're just summing its
elements? Instead of

        b = item[:]; b.sort(); bc = 0
        for bitem in b: bc += int(bitem)

you can do just

	bc = sum(int(i) for i in item)

or, if the order *really* matters, what is very strange, you can do

	bc = sum(int(i) for i in sorted(item))

Another thing, if you want to have in the values of the dictionary jc
only unique elements, you can use sets:

>>> a = set()
>>> print a
set([])
>>> a.add(10)
>>> print a
set([10])
>>> a.add(10)
>>> print a
set([10])
>>> a.add(10)
>>> print a
set([10])

So, the final example would be (assuming that you don't need to sum in
order):

def binm():
    for item in x:
        bc = sum(int(i) for i in item)
	try:
            jc[bc].add(b)
        except KeyError:
            jc[bc] = set([b])

Looks prettier, have less statements and is (or should be) faster. This
only works in Python 2.4, but you can adapt it to run on other versions,
too.

Cheers,
Felipe.

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"




More information about the Python-list mailing list