带替换的组合

2024-09-29 23:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何生成集合的组合,这是Python中的内置(我使用的)。但是如何用替换生成组合呢?在

假设我有一个集合,有两个相同的元素——例如,AABCDE。在

3个项目的组合可以是:

"AAB"
"ABC"
"CDE"

然而,程序将计数两次,一次是使用第一个A,第二个使用第二个A

什么是一个好的方法来产生这样的组合没有重复?在

谢谢。在


Tags: 项目方法程序元素内置计数abcaab
3条回答

将其转换为set,这是消除重复的最简单方法。在

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
>>> import itertools
>>> ["".join(x) for x in (itertools.combinations(set("AABCDE"),3))]
['ACB', 'ACE', 'ACD', 'ABE', 'ABD', 'AED', 'CBE', 'CBD', 'CED', 'BED']
>>> 

从你的其他评论来看,我想我误解了你的要求。在

^{pr2}$

相关问题 更多 >

    热门问题