Chester. Y
Chester. Y

Reputation: 91

A combination algorithm in python

import copy

def combine(l, n):
    answers = []
    one = [0] * n
    def next_c(li = 0, ni = 0):
        if ni == n:
            answers.append(copy.copy(one))
            return
        for k in range(li, len(l)):
            one[ni] = l[k]
            next_c(k+1, ni+1)
    next_c()
    return answers

print(combine([1,2,3,4],2)) 

Recently I found this code on internet. It works very well. However, I do not know the details that how does it work? So can anybody tell me how does it work? And how to understand a recursive code quickly? Thanks very much

Upvotes: 0

Views: 1442

Answers (1)

RoadRunner
RoadRunner

Reputation: 26315

As @AChampion said, You could also get the combinations with the itertools library, which is much easier to understand:

import itertools

def combine2(lst, n):
    return [list(x) for x in itertools.combinations(lst, n)]

Output:

>>> combine2([1,2,3,4],2)
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

Upvotes: 1

Related Questions