不使用“itertools.combinations”的组合

时间:2013-12-24 17:53:47

标签: python string graph combinations permutation

我需要的是一次为两个元素创建组合。

如果列表包含:seq = ['A','B','C'] 输出将是com = [['A','B'],['A','C'],['B','C']]

所有这些没有“itertools.combinations”方法。

我习惯使用此代码进行排列。但是,如何修改代码以使其与组合一起使用?

def permute(seq):

    if len(seq) <= 1:
        perms = [seq]
    else:
        perms = []
        for i in range(len(seq)):
            sub = permute(seq[:i]+seq[i+1:]) 
            for p in sub:    
                perms.append(seq[i:i+1]+p)

return perms

5 个答案:

答案 0 :(得分:8)

如果您不想使用itertools,请使用documented pure-Python equivalent

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

答案 1 :(得分:5)

直接做这件事是微不足道的:

def comb2(s):
    for i, v1 in enumerate(s):
        for j in range(i+1, len(s)):
            yield [v1, s[j]]

然后:

print list(comb2(['A', 'B', 'C']))

显示:

[['A', 'B'], ['A', 'C'], ['B', 'C']]

唯一能让组合变得棘手的事情就是满足一次只能运行时已知的元素数量。只要您事先知道这个数字,就会以明显的方式嵌套固定数量的循环。

答案 2 :(得分:3)

def combo2(lst,n):
    if n==0:
        return [[]]
    l=[]
    for i in range(0,len(lst)):
        m=lst[i]
        remLst=lst[i+1:]
        for p in combo2(remLst,n-1):
            l.append([m]+p)
    return l

输入:

combo2(list('ABC'),2)

输出:

[['A', 'B'], ['A', 'C'], ['B', 'C']]

答案 3 :(得分:1)

以下是answer中递归C ++代码对类似问题的松散翻译:

def combinations(sequence, length, NULL=object()):
    """ Find all combinations of the specified length from a sequence. """
    if length <= 0:
        combos = [NULL]
    else:
        combos = []
        for i, item in enumerate(sequence, 1):
            rem_items = sequence[i:]
            rem_combos = combinations(rem_items, length-1)
            combos.extend(item if combo is NULL else [item, combo]
                            for combo in rem_combos)
    return combos

print(combinations(['A', 'B', 'C'], 2))

输出:

[['A', 'B'], ['A', 'C'], ['B', 'C']]

答案 4 :(得分:0)

纯python组合

# generate combination of two list
import copy
def extend_list(list1,list2):
    temp=[];temp=copy.deepcopy(list1);temp.append(list2)
    return temp
def combination(list1, list2):
    return [extend_list(item1,item2) if type(item1) is list else [item1,item2] for item1 in list1 for item2 in list2]

# generate all combination of list of variables
def list_combination(list_of_variables):
    '''list_of_variables is a list of list e.g [[1,2],['True','False']]'''
    node_combinations=[]
    no_of_variables=len(list_of_variables)
    node_combinations=list_of_variables[0]
    for i in range(no_of_variables-1):
        node_combination = combination(node_combinations,list_of_variables[i+1])
        node_combinations=node_combination
    return node_combinations

输出

input_list = [['TRUE', 'FALSE'], [1, 2], ['TRUE', 'FALSE']]
list_combination(input_list)

[['TRUE', 1, 'TRUE'],
 ['TRUE', 1, 'FALSE'],
 ['TRUE', 2, 'TRUE'],
 ['TRUE', 2, 'FALSE'],
 ['FALSE', 1, 'TRUE'],
 ['FALSE', 1, 'FALSE'],
 ['FALSE', 2, 'TRUE'],
 ['FALSE', 2, 'FALSE']]