Basically, I need to get few permutations of a list. So, the method that I have used is to shuffle the list string randomly to get the permutation and add it to a list, while adding I check if there exists the same permutation in the list. I am not able to implement the check. Here is the code that I have written.
list = [x for x in range(0,max)]
totalperm = 10
perms = []
while(len(perms) <> totalperm):
random.shuffle(list)
if list not in perms:
perms.append(list)
Please let me know what am I missing here.
This doesn’t work because you’re working with a reference to the single list the whole time, so it is always in the list after the first time you append it.
Consider:
The answer is,
permshas two references to a single list, so it is [1, 3, 2], [1, 3, 2]].In your code,
itemsandperms[0]are the same object and have the same value. So when you ask ifitemsis inpermsthe answer is always yes. Because you just put it in there!The solution is simple: add a copy of the list.
By the way, you should probably use a
setrather than alistfor storing your permutations. It’s much faster to check membership of asetand attempts to add duplicates are simply ignored. The only downside is that you can’t put lists in asetbecause lists are mutable and therefore unhashable — fortunately, you can just convert them to tuples, which are immutable and hashable. Then you have: