I’m trying to generate a list of primes using the this method. I need to loop through every number 2…n and check it for multiples of 2…n. For some reason, the wrong list seems to be getting modified.
import sys
import argparse
import math
parser = argparse.ArgumentParser(description='find the largest prime factor of a number')
parser.add_argument('n', type=int, help='number')
args = parser.parse_args()
sieve = []
for i in range(2,args.n+1): sieve.append(i) # tried int(i)
copy1 = sieve # tried making extra copies. . .
copy2 = sieve
copy3 = sieve
#print int(math.sqrt(args.n))
for index, i in enumerate(copy1):
#print index, i
for ii in copy2:
#print ii
if i % ii == 0:
sieve[index]= None
print sieve
I get the following error:
Traceback (most recent call last):
File "3.py", line 22, in <module>
if i % ii == 0: TypeError: unsupported operand type(s) for %:
'int' and 'str'
You’re not making copies. You’re using references, so
copy1,copy2, andcopy3all refer to the same list —sieve. If you want to copy, use:which will create a copy of
sieveand assign it tocopy1.