简体   繁体   English

Python使用Set Comprehension生成素数

[英]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. 我正在开始Python的一项工作中,使用set comprehension调用少于100的质数列表。 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. 这有效地返回了所有非素数,但是我无法找到除Excursive之外的其他方法。或者,这是一组从2到100的所有数的集合,以获得一组素数。 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 : 作为一种简单的改进,您可以在通过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))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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