Speed up this code?

Paul Rubin http
Thu May 25 21:58:52 EDT 2006


aomighty at gmail.com writes:
> Does anybody know a faster way to do this? (finding the difference all
> items in list a that are not in list b)?

    >>> a = [3, 7, 16, 1, 2, 19, 13, 4, 0, 8]    # random.sample(range(20),10)
    >>> b = [15, 11, 7, 2, 0, 3, 9, 1, 12, 16]   # similar
    >>> sorted(set(a)-set(b))
    >>> [4, 8, 13, 19]

but you probably don't want to use that kind of implementation.

Here's a version using generators:

    def sieve_all(n = 100):
        # yield all primes up to n
        stream = iter(xrange(2, n))
        while True:
            p = stream.next()
            yield p
            def s1(p, stream):
                # yield all non-multiple of p
                return (q for q in stream if q%p != 0)
            stream = s1(p, stream)

    # print all primes up to 100
    print list(sieve_all(100))

It's cute, but horrendous once you realize what it's doing ;-)



More information about the Python-list mailing list