Combinations without using "itertools.combinations"

Viewed 31980

What I'd need is to create combinations for two elements a time.

If a list contains: seq = ['A', 'B', 'C'] the output would be com = [['A', 'B'], ['A', 'C'], ['B', 'C']]

all this without itertools.combinations method.

I used the following code for the permutations. But how could I modify it to make it work with the 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 Answers
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

Input:

combo2(list('ABC'),2)

Output:

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

Combination in pure 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

Output

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