0

i am using Python 3.8 and i am having the following problem in one of the functions i was trying to use.

from random import randint

def cross_(l, q):  
    k=randint(1,5)
    for i in range(k,len(l)):
        l[i],q[i]=q[i], q[i]
    return l,q

off=[]
par_=[[1,0,0,1,0],[1,0,1,0,0]]
for i in range (0,4):
    s, p = cross_(par_[0], par_[1])
    off.append(s)
    off.append(p) 

The output is fine as long as i call the function once. but as soon as i call the function in a loop, it simply repeats the subsequent values as the same as that of the first call.

Why does it do that?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Why `l[i],q[i] = q[i], q[i]` and not `l[i],q[i] = l[i], q[i]` - you are not crossing you are just modifying `q` – Patrick Artner Dec 06 '20 at 08:31
  • And you do not store the lists - you store the references to a list in `off` - you need to store **copies** of the list if you do not want them to refernce the same data: `off.append(s[:]) off.append(p[:])` – Patrick Artner Dec 06 '20 at 08:34
  • 1
    @PatrickArtner , thank you for your kind reply. the crossover i typed was by mistake. i was trying to cross like you said. but i got my code working fine after using the copy of the list instead of the original list. Thanks a lot! – Kanwal Chaudhary Dec 06 '20 at 13:41

0 Answers0