Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python modifying wrong list?

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'
like image 630
Nona Urbiz Avatar asked Feb 11 '26 22:02

Nona Urbiz


1 Answers

You're not making copies. You're using references, so copy1, copy2, and copy3 all refer to the same list -- sieve. If you want to copy, use:

copy1 = sieve[:]

which will create a copy of sieve and assign it to copy1.

like image 189
mipadi Avatar answered Feb 13 '26 15:02

mipadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!