Python Set Comprehension

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

  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).

  2. 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))}

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)))}

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.


Back to homepage or read more recommendations: