Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test to check if a list is present inside a python list of lists

Tags:

python

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.

like image 758
AKG Avatar asked Feb 04 '26 04:02

AKG


2 Answers

Use python's builtin set to prevent duplicates:

perms = set()
while len(perms) != totalperm:
    random.shuffle(lst)        
    perms.add(tuple(lst))
like image 68
Rob Wouters Avatar answered Feb 05 '26 22:02

Rob Wouters


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)
like image 20
Chris AtLee Avatar answered Feb 05 '26 22:02

Chris AtLee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!