Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinations without using "itertools.combinations"

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
like image 514
user3104548 Avatar asked Dec 24 '13 17:12

user3104548


People also ask

How do you find the number of combinations without repetitions in Python?

In the formula of combinations without repetition, input the values: C ( n , r ) = n ! That's it! That's how you calculate the number of combinations without repetition.

How does Itertools combinations work?

The itertools. combinations() function takes two arguments—an iterable inputs and a positive integer n —and produces an iterator over tuples of all combinations of n elements in inputs .


1 Answers

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)
like image 143
Martijn Pieters Avatar answered Nov 24 '22 20:11

Martijn Pieters