Break up list into groups

Ron Adam rrr at ronadam.com
Tue Jul 17 22:18:41 EDT 2007



Matt McCredie wrote:
> That certainly is fast, unfortunately it doesn't pass all of the tests. 
> I came up with those tests so I don't know how important they are to the 
> original poster. I modified it and came up with a generator and a 
> non-generator version based (roughly) on your algorithm, that are almost 
> as quick, and pass all of the tests. Some of the modifications were done 
> just to make it quicker, so it would be fair when comparing against the 
> other methods. I hard-coded the comparison instead of using a function 
> and created a function that directly generates and returns a list 
> instead of a generator. I would probably use the generator version in my 
> code, but wrapping `list' around a generator adds about 4us (on my 
> machine). Anyway, getgroups7 passes all of the tests I mentioned and it 
> was timed at 10.37usec/pass. The down side: the code doesn't seem nearly 
> as elegant.
> 
> Matt

In most cases you wouldn't wrap the generator version in a list(), but use 
it directly as a loop iterator.


A little renaming of variables helps it be a bit more elegant I think ...

def getgroups8(seq):
     groups = []
     iseq = iter(xrange(len(seq)))
     for start in iseq:
         if seq[start] & 0x80:
             for stop in iseq:
                 if seq[stop] & 0x80:
                     groups.append(seq[start:stop])
                     start = stop
             groups.append(seq[start:])
     return groups

This passes all the tests and runs about the same speed.


Cheers,
    Ron





> <code>
> def gengroups7(seq):
>     iseq = iter(xrange(len(seq)))
>     start = 0
>     for i in iseq:
>         if seq[i]&0x80:
>             start = i
>             break
>     else:
>         return
>     for i in iseq:
>         if seq[i]&0x80:
>             yield seq[start:i]
>             start = i
>     yield seq[start:]
> 
> 
> def getgroups7(seq):
>     groups = []
>     iseq = iter(xrange(len(seq)))
>     start = 0
>     for i in iseq:
>         if seq[i]&0x80:
>             start = i
>             break
>     else:
>         return groups
>     for i in iseq:
>         if seq[i]&0x80:
>             groups.append(seq[start:i])
>             start = i
>     groups.append(seq[start:])
>     return groups
> 
> </code>
> 
> 
> 
> 




More information about the Python-list mailing list