Python集合理解 [英] Python Set Comprehension
问题描述
所以我在家庭作业中遇到了这两个问题,而我被第二个问题困住了.
So I have these two problems for a homework assignment and I'm stuck on the second one.
使用 Python Set Comprehension(Python 等效于 Set Builder 表示法)生成所有小于 100 的质数的集合.回想一下,质数是大于 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 的素数组成的素数对.素数对是一对连续的奇数,它们是两个素数.将您的一组质数对存储在一个变量中.您的第 1 组将非常有帮助.输出您的一组质数对.
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.
这篇关于Python集合理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!