0

I have this code, which runs an algorithm called Tomkins-Paige algorithm. The algorithm creates permutations of a sequence. The problem is that the code prints the different permutations p, but when i try to append it to a list, it only appends the initial p, i.e. p = [1,2,3,4].

import numpy as np 

n = 4
p = [i for i in range(1,n+1)]
c = [1 for i in range(1,n+1)]

i = 2
print(p)
listp = []

while i <= n:
    shift = np.roll(p[:i],-1)

    for k in range(len(shift)):
        p[k] = shift[k] 
    if c[i-1] < i:
        c[i-1] += 1
        i = 2
        print(p, c, i )
        listp.append(p)
    else:
        c[i-1] = 1
        i += 1

more information about the algorithm: https://en.wikipedia.org/wiki/Tompkins%E2%80%93Paige_algorithm

Thanks in advance :)

  • 1
    It's because the list `p` is mutable. If you append it, you're just appending a reference to the same object each time. Try `append(p.copy())` or `append(p[:])`. –  May 19 '20 at 12:42
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Tomerikoo May 19 '20 at 12:50

0 Answers0