Pulling all n-sized combinations from a list

Paul Rubin http
Wed Feb 8 18:04:52 EST 2006


"Swroteb" <swrittenb at gmail.com> writes:
> I'm a little bit confused about your generator suggestion.  My list is
> a set of references to instantiated objects.  I'm just unsure about how
> to iterate through every unique combination of those references.  Are
> you suggesting that I set up methods to provide the indices I'm looking
> for in the list to iterate over?

I think the natural approach is to make a generator that yields a
5-tuple for each combination, and then have your application iterate
over that generator.  Here's my version:

    def comb(x,n):
        """Generate combinations of n items from list x"""
        if n==0:
            yield []
            return
        for i in xrange(len(x)-n+1):
            for r in comb(x[i+1:], n-1):
                yield [x[i]] + r

    for c in comb([1,2,3,4,5], 3):
        print c

The output is:
    >>>
    [1, 2, 3]
    [1, 2, 4]
    [1, 2, 5]
    [1, 3, 4]
    [1, 3, 5]
    [1, 4, 5]
    [2, 3, 4]
    [2, 3, 5]
    [2, 4, 5]
    [3, 4, 5]
    >>> 



More information about the Python-list mailing list