Whoops, left the list off this reply

On 6/14/06, Martin Pool <[EMAIL PROTECTED]> wrote:

On 14/06/2006, at 3:20 PM, Jamie Wilkinson wrote:

> This one time, at band camp, Tim Leslie wrote:
>> On 6/14/06, Jamie Wilkinson <[EMAIL PROTECTED]> wrote:
>>> List comprehensions!
>>>
>>>> def is_prime(n, primes):
>>>>   """ primes is a list of primes where sqrt(n) <= max(primes) <
>>>> n"""
>>>>   for p in primes while p*p <= n:
>>>>       if n % p == 0:
>>>>           return False
>>>>   return True
>>>>
>>>> Does this look like a sane piece of syntax to other people? If it
>>>> existed would you use it? Does something like this exist
>>>> somewhere and
>>>> I'm just really slow?
>>>
>>> [p for p in [p in primes if p*p < n] if n % p == 0]
>>>
>>> and then fold that all together ;-)
>>
>> Yeah, you can do that, but your inner loop still iterates over all p
>> in primes, when you know that once p*p >= n you can stop looking.
>
> Hrm, so you really want to lazily evaulate the list, like Haskell
> or Ocaml
> would do; perhaps use a generator and keep yielding until you want
> to stop?
>
> Can you make a generator that looks like a list comprehension? :-)

Yes,

   (p for p in primes if p*p < n)

is a generator comprehension.

However, this is only a partial solution because it will keep on
evaluating the squaring expression for the whole list so it's a bit
pointless.  There's no straightforward way to avoid this in a
generator expression.  However one can write

   itertools.takewhile(lambda p: p*p < n,
                       primes)


itertools.takewhile! That's the one I was after. I thought I'd seen a
takewhile lying around somewhere but I couldn't remember where it
lived. And yeah, as you say, there's probably nothing to really be
gained from using it, especially in this case, but I'm happy knowing
it's there :-)

Tim

so overall

   for p in takewhile(lambda p: p*p < n, primes):
     if n % p == 0:
       return False
   return True

but I'm not convinced this is much simpler and it's probably slower
than just

   for p in primes:
     if p*p >= n:
       break
     if n % p == 0:
       return False
   return True

--
Martin



_______________________________________________
coders mailing list
[email protected]
http://lists.slug.org.au/listinfo/coders

_______________________________________________
coders mailing list
[email protected]
http://lists.slug.org.au/listinfo/coders

Reply via email to