开发者

Combinations with replacements

开发者 https://www.devze.com 2022-12-09 01:54 出处:网络
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?

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 generat开发者_运维问答e such combinations without duplicates?

Thanks.


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号