A for loop iterate through a long list. I tried to accelerate the iteration modifying the list (without success). the code:
from math import sqrt
def holeofStrainer():
isPrime = [False, False] + [True]*999999
for num in range(3, len(isPrime)):
if isPrime[num] == False:
continue
else:
for x in range(2, int(sqrt(num)) + 1):
if num % x == 0:
isPrime[num] = False
break
else:
isPrime[num] = True
for item in range (2, int(1000001/num) + 2):
ple = item * num
if ple < len(isPrime):
isPrime[ple] = False
return(isPrime)
print(holeofStrainer())
The goal of line 5 is to spare unnecessary calculation.
in lines 14-17 I make the modifications (following the sieve of Eratosthenes, I change the value of the multiples of prime numbers to False) avoiding by this way more calculation through the line 5.
SUMMARY:
- Is it possible to modify the loop-iterated list from the loop itself?
- If the answer is Yes, why is it not good in my code?