Vadivel Vadivel
Vadivel Vadivel

Reputation: 41

python updating global dict inside recursive function

I am trying to find all permutations of elements in a list and add it to a global dictionary

Code:

outp={}
k=0
def func(i,arr):
    global outp
    global k
    arr=arr.copy()
    for j in range(i,len(list)):
        arr[i],arr[j] = arr[j],arr[i]
        if i!=j or i==0:
            k=k+1
            print("\n\n",arr,k)
            outp[k]=arr
            print("\n",outp)
        func(i+1,arr)

list = [1,2,3,8]
func(0,list)

Output below: Till 4th element it updated correctly. During 5th element, it updated both 5th and 3rd element in the dictionary. I don't know why it is happening. Kindly help

[1, 2, 3, 8] 1

 {1: [1, 2, 3, 8]}


 [1, 2, 8, 3] 2

 {1: [1, 2, 3, 8], 2: [1, 2, 8, 3]}


 [1, 3, 2, 8] 3

 {1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 3, 2, 8]}


 [1, 3, 8, 2] 4

 {1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 3, 2, 8], 4: [1, 3, 8, 2]}


 [1, 8, 2, 3] 5

 {1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 8, 2, 3], 4: [1, 3, 8, 2], 5: [1, 8, 2, 3]}

Upvotes: 1

Views: 319

Answers (2)

Sagar Ruchandani
Sagar Ruchandani

Reputation: 95

This would be a better way to copy list to a new list.
arr=arr[:] .
https://repl.it/repls/BronzeYellowConversion

Upvotes: 0

Dan D.
Dan D.

Reputation: 74655

You need to place a copy of the array in the dictionary:

outp[k] = arr.copy()

Upvotes: 1

Related Questions