Break up list into groups

Matt McCredie mccredie at gmail.com
Tue Jul 17 23:08:56 CEST 2007


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

<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>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070717/596db766/attachment.html>


More information about the Python-list mailing list