ooboo
ooboo

Reputation: 17069

Combinations with replacements

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.

Upvotes: 0

Views: 2844

Answers (3)

mikeLundquist
mikeLundquist

Reputation: 1009

def stepper_w_w(l,stop):#stepper_with_while
"""l is a list of any size usually you would input [1,1,1,1...],
stop is the highest number you want to stop at so if you put in stop=5
the sequence would stop at [5,5,5,5...]
This stepper shows the first number that equals the last.
This generates combinations with replacement. """
    numb1=1
    while numb1<stop:
        #print(numb1)
        l[0]=numb1
        NeL=0 
        while l[len(l)-1]<=numb1: 
            if l[NeL]==l[len(l)-1]:
                l[NeL]+=1
                l[(NeL+1):]=[1]*((len(l))-(NeL+1))
                print(l)
                """iter_2s=NeL+1
                while iter_2s<=(len(l)-1): #this is different from above
                    l[iter_2s]=2
                    iter_2s+=1
                    print(l)"""
                NeL=-1
            NeL+=1
        numb1+=1

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304355

>>> 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'])

Upvotes: 2

SilentGhost
SilentGhost

Reputation: 319831

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

Upvotes: 2

Related Questions