0
def permute(x, p, last, ind, t):
    s = len(x)
    for i in range(s):
        p[ind] = x[i]
        if(ind == last):
            print(p)
            t.append(p)
        else:
            permute(x, p, last, ind+1, t)

x is the original list of elements say [1,2,3] p is the list for generating permutations. its [0,0,0] initially. t is an empty list for getting ( appending ) all the permutations.

print(p) statement prints the correct permutations but when I try to append p list to t list I am not getting the desired output.

The t list that I am getting is -

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

Where I am making mistake ? Thanks in advance !

Desperado
  • 29
  • 6
  • Check out: [Python recursion permutations](https://stackoverflow.com/questions/13109274/python-recursion-permutations) – DarrylG Aug 04 '22 at 19:49
  • If `p` is initially `[0,0,0]`, how is `print(p)` printing lists that are less than 3 elements? – Barmar Aug 04 '22 at 19:54
  • 2
    `t.append(p)` doesn't make a copy of `p`. So all the elements of `t` are references to the same list, which holds the most recent permutation. You should make a copy when appending. `t.append(p.copy())` – Barmar Aug 04 '22 at 19:55
  • In main driver code I have generated power set and passing the lists in a loop in x and p is initialized accordingly for a 2 elements list its **[0,0]** for 3 elements list its **[0,0,0]** – Desperado Aug 04 '22 at 19:57

0 Answers0