0

This code permutes a list. I am appending the whole permuted list to another list, but the output is always the last appended permuted list.

import random
def permute(a):
    for i in range(len(a)-1, 0, -1):
        k = random.randint(100,200) % i
        temp = a[i]
        a[i] = a[k]
        a[k] = temp
    return a


def generate_parents():
    p = [1,2,3,4]
    Parent = list()
    print p
    Parent.append(p)
    print Parent
    new_p = permute(p)
    print new_p
    Parent.append(new_p)
    print Parent
    new_p1 = permute(new_p)
    print new_p1
    Parent.append(new_p1)
    print Parent

generate_parents()

The output looks like this:

[1, 2, 3, 4] 
[[1, 2, 3, 4]] 
[3, 1, 4, 2]           
[[3, 1, 4, 2], [3, 1, 4, 2]]  
[2, 3, 1, 4] 
[[2, 3, 1, 4], [2, 3, 1, 4], [2, 3, 1, 4]]

But the output should look like this:

[1, 2, 3, 4] 
[[1, 2, 3, 4]] 
[3, 1, 4, 2]           
[[1, 2, 3, 4], [3, 1, 4, 2]]  
[2, 3, 1, 4] 
[[1, 2, 3, 4], [3, 1, 4, 2], [2, 3, 1, 4]]

I have no idea where I am going wrong. Please help. Thanks in advance.

Ankan Kumar Giri
  • 243
  • 1
  • 3
  • 12
  • 1
    This is a classic case of accidental re-use of the original list. I don't want to try to close your question as a duplicate myself since I'm not a very regular python commenter and am not sure this is a good duplicate, but see http://stackoverflow.com/q/2612802/1256452 – torek Dec 26 '15 at 08:00
  • Thanks I had the same problem – Ankan Kumar Giri Dec 26 '15 at 08:11

0 Answers0