Python combinators without repetition - Pyncomb?

I am trying to make combinatorial material with data in Python. I looked at the question How to generate all permutations of a list in Python , but I think that does not meet my needs. I have data of this type ...:

group1-Steve group1-Mark group1-Tom group2-Brett group2-Mick group2-Foo group3-Dan group3-Phil 

... and I need to make all possible combinations of the three elements with only one of each group without repetition, keeping each combination in the list.

I know that in this case there are 18 possible combinations (3 * 3 * 2 = 18), but I don’t know how I could write this code. I read about the Pyncomb package, but I don’t know what function to use in this case; perhaps there is a function that does this work.

Hope someone can help me ...

Thanks in advance;

Peixe

+6
source share
2 answers

The easiest way is to use itertools.product() :

 group1 = ["Steve", "Mark", "Tom"] group2 = ["Brett", "Mick", "Foo"] group3 = ["Dan", "Phil"] for x in itertools.product(group1, group2, group3): print x 

prints

 ('Steve', 'Brett', 'Dan') ('Steve', 'Brett', 'Phil') ('Steve', 'Mick', 'Dan') ('Steve', 'Mick', 'Phil') ('Steve', 'Foo', 'Dan') ('Steve', 'Foo', 'Phil') ('Mark', 'Brett', 'Dan') ('Mark', 'Brett', 'Phil') ('Mark', 'Mick', 'Dan') ('Mark', 'Mick', 'Phil') ('Mark', 'Foo', 'Dan') ('Mark', 'Foo', 'Phil') ('Tom', 'Brett', 'Dan') ('Tom', 'Brett', 'Phil') ('Tom', 'Mick', 'Dan') ('Tom', 'Mick', 'Phil') ('Tom', 'Foo', 'Dan') ('Tom', 'Foo', 'Phil') 
+9
source

Another alternative that avoids import is to use a list comprehension:

 [(a, b, c) for a in group1 for b in group2 for c in group3] 

This gives the same result as Sven, but it's good if you want to do some filtering.

+4
source

Source: https://habr.com/ru/post/889826/


All Articles