0

I am trying to write recursive code to get all permutations of an array. While appending answer to a list it gives an unexpected answer. Can someone help..

def permute(A):
    p = []
    def permute_util(a,l,r):
        if l==r:
            p.append(a)
            print (a)
        else:
            for i in range(l,r+1):
                a[l],a[i] = a[i],a[l]
                permute_util(a,l+1,r)
                a[l],a[i] = a[i],a[l]
    permute_util(A,0,len(A)-1)
    print (p)

OUTPUT -

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

Last line of output is not what i expected.. what am i missing?

  • Is your problem just that you were expecting `p.append(a)` to append a copy of `a`, rather than `a` itself? If so, there are duplicate questions with good explanations, but I don't want to close this as a dup without being sure that's what you're confused about. – abarnert Jul 06 '18 at 18:04
  • Yes, I was confused about `p.append(a)` to append a copy of `a`, rather than `a` itself. Got my answer thanks @abarnert – hello_world Jul 07 '18 at 04:07

0 Answers0