views:

81

answers:

2

Hey.

I know how to generate combinations of a set and that's a builtin in Python (what I use), anyway. But how to generate combinations with replacements?

Suppose I have a set with, say, two identical elements - for example, "AABCDE".

Combinations of 3 items could be:

"AAB" "ABC" "CDE"

However, the program would count 'ABC' twice - once when using the first A, and the second one using the second A.

What is a good way to generate such combinations without duplicates?

Thanks

+2  A: 

convert it to set, that's the easiest way to get rid of duplicates.

SilentGhost
No, I consider "AAC" a valid combination
ooboo
so, how exactly is that contradicting my answer. build your list with duplicates, then apply set.
SilentGhost
I thought you meant convert the original list to a set like the other guy suggested. It's still tricky. If I want combinations with replacements of a a list with many copies of the same item it's highly inefficient, plus you can't use it as an iterator
ooboo
what do you mean by *can't use it as an iterator*?
SilentGhost
I meant a generator - you have to make the entire list and then iterate over it. And what if I want to break the loop in the middle? That creates a huge waste.
ooboo
+1  A: 
>>> import itertools
>>> ["".join(x) for x in (itertools.combinations(set("AABCDE"),3))]
['ACB', 'ACE', 'ACD', 'ABE', 'ABD', 'AED', 'CBE', 'CBD', 'CED', 'BED']
>>>

From your other comments, I think I misunderstood what you are asking.

>>> import itertools
>>> set("".join(x) for x in (itertools.combinations("AABCDE",3)))
set(['AAE', 'AAD', 'ABC', 'ABD', 'ABE', 'AAC', 'AAB', 'BCD', 'BCE', 'ACD', 'CDE', 'ACE', 'ADE', 'BDE'])
gnibbler