optimization pointers?

Anton Vredegoor anton at vredegoor.doge.nl
Sun Dec 14 18:00:34 CET 2003

"Anthony McDonald" <tonym1972(at)club-internet(in)fr> wrote:

>return len (voc.keys())
>Which creates a list of keys to then apply len to, but thats an unneeded
>step as len applied directly to a dictionary returns the number of keys.

Below are two more small optimization possibilities. Originally I
wasn't going to post them because they are way into micro optimization
country and because the setdefault solution is beautiful but blond. At
least on some of my machines however they are both faster than the
solutions offered so far.


def lzx(s):
    word,D = '',{}
    Dget, Dset = D.get, D.__setitem__
    for c in s:
        word += c
        if not Dget(word):
            word = ''
    return len(D)

def lzy(s):
    j,D = 0,{}
    func = D.setdefault
    for i in xrange(1,len(s)+1):
        if func(s[j:i],j) is j:  j = i
    return len(D)

More information about the Python-list mailing list