0

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

假设我有一个包含两个相同元素的集合 - 例如AABCDE

3个项目的组合可能是:

"AAB"
"ABC"
"CDE"

但是,该程序会计算ABC两次——一次使用第一个 A,第二次使用第二个 A。

什么是生成这种不重复组合的好方法?

谢谢。

4

3 回答 3

2

将其转换为set,这是摆脱重复项的最简单方法。

于 2009-10-19T20:54:24.473 回答
2
>>> import itertools
>>> ["".join(x) for x in (itertools.combinations(set("AABCDE"),3))]
['ACB', 'ACE', 'ACD', 'ABE', 'ABD', 'AED', 'CBE', 'CBD', 'CED', 'BED']
>>> 

从您的其他评论中,我想我误解了您的要求。

>>> 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'])
于 2009-10-19T21:03:29.197 回答
0
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
于 2015-05-29T02:31:17.533 回答