6
votes

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
Why without itertools? - jonrsharpe
The equivalent source code for combinations is on the itertools documentation page. Just copy-paste it into your file. - Kevin
Yea, I can't use alternative methods. Thanks, I'll take a look. - user3104548
@jonrsharpe the itertools.combinations function returns lexicographic sort order which may be undesirable for lists of integers - ie combinations([1,2,10,3], 3) yields [1,2,10] before [1,2,3]. - Oliver

5 Answers

10
votes

If you don't want to use itertools, then use the 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)
7
votes

This is trivial to do directly:

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

Then:

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

displays:

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

The only thing that makes combinations at all tricky is catering to a known-only-at-runtime number of elements to take at a time. So long as you know that number in advance, a fixed number of loops nested that deep does the job in an obvious way.

5
votes
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']]
2
votes

Here's a loose translation of the recursive C++ code in an answer to a similar question:

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

Output:

[['A', 'B'], ['A', 'C'], ['B', 'C']]
0
votes

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