Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing all combinations in Python

I have two sets of options:

optionList1 = [a1,a2,a3,...,an]
optionList2 = [b1,b2,b3,...,bn]

The number of elements in the optionlists are not necessarily equal and I have to choose from the first optionlist twice. How do I ensure that I have tried every combination of 2 options from the first list and one from the second list. An example selection set below...

selectedOptions = [an1,an2,bn]
like image 724
thenickname Avatar asked Feb 05 '11 09:02

thenickname


1 Answers

Combine product and permutations from itertools assuming you don't want duplicates from the first list:

>>> from itertools import product,permutations
>>> o1 = 'a1 a2 a3'.split()
>>> o2 = 'b1 b2 b3'.split()
>>> for (a,b),c in product(permutations(o1,2),o2):
...     print a,b,c
... 
a1 a2 b1
a1 a2 b2
a1 a2 b3
a1 a3 b1
a1 a3 b2
a1 a3 b3
a2 a1 b1
a2 a1 b2
a2 a1 b3
a2 a3 b1
a2 a3 b2
a2 a3 b3
a3 a1 b1
a3 a1 b2
a3 a1 b3
a3 a2 b1
a3 a2 b2
a3 a2 b3
like image 68
Mark Tolonen Avatar answered Oct 05 '22 01:10

Mark Tolonen