I was mucking around, trying to code a prime sieve in one line. I don't know 
about filters and bit shifting and stuff like that but I thought I could do it 
with builtins, albeit a very long one line. This is the part of my stupid trick 
in question that got me wondering about a key parameter for all() and the "why" 
is below that.

[n for n in xrange(3, int(pow(upper, 0.5) + 1), 2)
 if all(map(lambda d: n%d!=0, xrange(2, int(pow(n, 0.5) + 1))))]

Where upper is the upper bound for the sieve. That list comprehension will 
provide a list of prime numbers up to the square root of upper using trial 
division. Then that list was going to be used for the rest of the sieve using 
the set.difference method to remove multiples of all those primes.

That's when I realized that all() doesn't necessarily go through every item in 
the alterable. It's stops the moment it finds a false value. You can test that 
that's true with.

>>> all(xrange(10**9))

It's instant because 0 is the false value and so it stops and returns false 
after only checking the first value. Also because we're using xrange the 
generator function cousin of range.

The following on the other hand should take a while.

>>> all(xrange(1, 10**9))

And the following, although the same thing really as all(xrange(10**9)), is not 
as instant and will take even longer than the above.

>>> all(map(lambda x: bool(x), xrange(10**9)))

However if all by some chance (I don't know how this stuff works underneath) 
has a key parameter then we could do something like.

>>> all(xrange(10**9), key=lambda x: bool(x))

Which would return False instantly (ideally).
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to