Another list comprehension hack nobody should use. Just for fun. With a bonus hack about int
s.
import gc
print([
num
for two in [(9**99 + 2) % 9**99]
for nums in [[two], range(3, 100, 2)]
for num in nums
if num is two
or all(num % prime
for obj in gc.get_objects() if type(obj) is list and obj and obj[0] is two
for prime in obj)
])
Output (Try it online!):
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Lists get registered for cyclic garbage collection, so I use that to find the list object being built by the comprehension. How do I identify the list among all other lists? By starting it with a special 2
. Not the usual 2
, but a different int
object with the value 2. That goes into the list directly. After that, I go through the odd numbers in the range. I find the list in the garbage collector by looking for my special 2
. Once I have it, I go through it to check the current num
for primality.
Optimized version, only searches the list once (Try it online!):
import gc
print([
num
for two in [(9**99 + 2) % 9**99]
for nums in [[two], range(3, 100, 2)]
for num in nums
for primes in [() if num is two else primes or next(obj for obj in gc.get_objects() if type(obj) is list and obj and obj[0] is two)]
if all(num % prime for prime in primes)
])
When num
is my 2
, I assign an empty dummy tuple to primes
. When num
is 3
, I find and assign the list to primes
. For all later numbers, I just re-assign primes
to itself.