Python 集合理解

作业有两个问题,第二个问题卡住了。

  1. 使用 Python 集合理解(Python 相当于 Set Builder 符号)生成一组所有小于100的素数。回想一下,素数是一个大于1的整数,除了它自己和1之外,不能被其他任何整数整除。将一组素数存储在一个变量中(其他部分需要它)。输出一组素数(例如,使用 print 函数)。

  2. 使用 Python 集合理解生成一组有序对(长度为2的元组) ,其中包含所有由小于100的素数组成的素数对。素数对是一对连续的奇数,它们都是素数。将素数对集存储在一个变量中。你的第一组数字会很有帮助。输出一组素数对。

对于第一种情况,这种方法非常有效:

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

然而,我对第二个问题很困惑。我想我可能需要一些笛卡儿积,但是我不确定。

这让我有点接近,但我只是希望连续的对。

cart = { (x, y) for x in r for y in r
if x < y }
124669 次浏览

You can generate pairs like this:

{(x, x + 2) for x in r if x + 2 in r}

Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.

A different way of doing it: (Although slower for large sets of primes)

{(x, y) for x in r for y in r if x + 2 == y}
primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

I simplified the test a bit - if all(x%y instead of if not any(not x%y

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

pairs = {(x, x+2) for x in primes if x+2 in primes}

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.