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.
Use python's builtin set to prevent duplicates:
perms = set()
while len(perms) != totalperm:
random.shuffle(lst)
perms.add(tuple(lst))
When you're shuffling the list, you're modifying it in place. Later, you add a reference to it to your list of perms. Next time through your loop, you shuffle the list in place again. If you look at perms, it will contain n references to your original list.
You probably want to do something like this instead:
shuffled = list[:]
random.shuffle(shuffled)
if shuffled not in perms:
perms.append(shuffled)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With