简体   繁体   中英

Python generating prime numbers using Set Comprehension

I am working on an assignment in beginning Python calling for a list of primes less then 100 using set comprehension. I can generate non primes using

nonPrime = { x for x in range(2, 100) for y in range(2, x) if x % y == 0 }

This effectively returns all non prime numbers but I can not find a way other than to Excursive Or this set with a set of all numbers from 2 to 100 to get a set of prime numbers. Is there a way that I can get the opposite of this set within the same set comprehension?

This is not the most efficient algorithm, but to implement it:

prime = {x for x in range(2, 100) if all(x % y != 0 for y in range(2, x))}

Or, equivalently:

prime = {x for x in range(2, 100) if not any(x % y == 0 for y in range(2, x))}

For one simple refinement, you can stop checking for possible factors once you've passed the square root of x :

prime = {x for x in range(2, 100) if all(x % y != 0 for y in range(2, int(math.floor(math.sqrt(x))) + 1))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM