Python 集合理解

2022-01-17 00:00:00 python set set-comprehension

问题描述

所以我的家庭作业有这两个问题,我被困在第二个问题上.

So I have these two problems for a homework assignment and I'm stuck on the second one.

  1. 使用 Python Set Comprehension(Python 相当于 Set Builder 表示法)生成一个包含所有小于 100 的素数的集合.回想一下,素数是大于 1 且不大于 1 的整数可被除自身和 1 以外的任何整数整除.将素数集存储在变量中(附加部分将需要它).输出您的素数集(例如,使用打印功能).

  1. Use a Python Set Comprehension (Python's equivalent of Set Builder notation) to generate a set of all of the prime numbers that are less than 100. Recall that a prime number is an integer that is greater than 1 and not divisible by any integer other than itself and 1. Store your set of primes in a variable (you will need it for additional parts). Output your set of primes (e.g., with the print function).

使用 Python Set Comprehension 生成一组有序对(长度为 2 的元组),其中包含由小于 100 的素数组成的所有素数对.素数对是一对连续的奇数,它们是两者都是素数.将您的 Prime Pairs 集合存储在一个变量中.您的 1 号套装将非常有帮助.输出你的 Prime Pairs 集合.

Use a Python Set Comprehension to generate a set of ordered pairs (tuples of length 2) consisting of all of the prime pairs consisting of primes less than 100. A Prime Pair is a pair of consecutive odd numbers that are both prime. Store your set of Prime Pairs in a variable. Your set of number 1 will be very helpful. Output your Set of Prime Pairs.

对于第一个,这非常有效:

For the first one, this works perfectly:

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

但是,我对第二个感到很困惑.我想我可能不得不用一些东西来获取集合 r 的笛卡尔积,但我只是不确定.

However, I'm pretty stumped on the second one. I think I may have to take the Cartesian product of the set r with something but I'm just not sure.

这让我有点接近,但我只想要连续的对.

This gets me somewhat close but I just want the consecutive pairs.

cart = { (x, y) for x in r for y in r
     if x < y }


解决方案

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

我稍微简化了测试 - if all(x%y 而不是 if not any(not x%y

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

我也限制了 y 的范围;测试除数 > sqrt(x) 没有意义.所以 max(x) == 100 意味着 max(y) == 10.对于 x <= 10,y 也必须 <x.

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.

相关文章