Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python combinatorials w/o repetition - Pyncomb?

I'm trying to do some combinatorial stuff with data in Python. I looked the question How to generate all permutations of a list in Python, but think that doesn't fit 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 three elements with only one from each group, without repetitions, saving to a list every combination.

I know in this case there are 18 possible different combinations(3*3*2=18), but don't know how could i write this code. I ve read about the Pyncomb package, but don't know the function to apply in this case; maybe there's a function which does the job.

Hope anyone could help me...

Thanks in advance;

Peixe

like image 475
peixe Avatar asked Jun 05 '11 18:06

peixe


1 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')
like image 139
Sven Marnach Avatar answered Nov 14 '22 10:11

Sven Marnach