0

I have written a code of permutation, when subarr.remove(set[i]) is executed, the store is getting automatically updated and value is getting removed from the list; and in end, output is returning as lists of empty lists. Can anyone please check and tell me why this is happening and how to correct it in the existing code? Thanks in advance.

def perm(n, set, subarr, map, store):
    if len(subarr) == n:
        store += [subarr]
    else:
        for i in range(n):
            if set[i] not in map:
                map.append(set[i])                     
                subarr.append(set[i])
                perm(n, set, subarr, map, store)
                map.remove(set[i])
                subarr.remove(set[i])  
    return store                              

set = [1, 2, 3]
n = len(set)
subarr = []
map = []
store = []
print(perm(n, set, subarr, map, store))
Chris
  • 26,361
  • 5
  • 21
  • 42
Sourya
  • 1
  • 1
  • 2
    `set` and `map` are reserved words for internal functions, you should not use it as variable names. – Cow Sep 07 '22 at 05:58
  • 4
    You have only one list object called `map` and one list object called `set`. You are passing that one list object from level to level, but it's just the one object. I suspect you were expecting each call to make a COPY of the lists, but that's not how Python works. If you want a copy, you have to make a copy explicitly using something like `set[:]`. – Tim Roberts Sep 07 '22 at 06:05
  • I have 4 list object, *map*, *set*, *store*,*subbarr*. *map* i am using to keep track of which number i am taking as first element in permutation formation. *set* is the list of numbers i am passing, *subarr* is the list in which i am creating the path of permutations formed and in *store* i am storing when one permutation is formed. changing the name of variables *set* and *map* to another name doesnt helps. – Sourya Sep 07 '22 at 06:17
  • 1
    `store` contains several references to `subarr` only, i.e. `store = [subarr, subarr, subarr]`. Yes, when you manipulate `subarr`, those references within `store` will be modified as well, because they're all the same object. – deceze Sep 07 '22 at 06:22

0 Answers0