Combinations of lists

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Oct 3 11:42:47 EDT 2012


On Wed, 03 Oct 2012 16:26:43 +0200, Steen Lysgaard wrote:

> Hi,
> 
> I am looking for a clever way to compute all combinations of two lists.
> Look at this example:
> 
> h = ['A','A','B','B']
> m = ['a','b']
> 
> the resulting combinations should be of the same length as h and each
> element in m can be used twice. 

Why twice? What if you had these?

h = ['A', 'A', 'B', 'B', 'C', 'D', 'E', 'E']
m = ['a', 'b', 'c']

Would you still use each element in m twice? Or some other number?



> The sought after result using h and m from above is:
> 
> [['aA', 'aA', 'bB', 'bB'],
>   ['aA', 'aB', 'bA', 'bB'],
>   ['aB', 'aB', 'bA', 'bA']]
> 
> (the order of the results does not matter i.e. ['aA', 'aA', 'bB', 'bB']
> and ['aA', 'bB', 'aA', 'bB'] are considered the same)
> 
> This is achieved by the code below, this however needs to go through all
> possible combinations (faculty of len(h)) and rule out duplicates as
> they occur and this is too much if for example len(h) is 16.

I don't understand this requirement. In the example above, you don't rule 
out duplicates. Both 'aA' and 'bB' are duplicated. What duplicates are 
you ruling out?



-- 
Steven



More information about the Python-list mailing list