Combinations Algorithm.

sismex01 at hebmex.com sismex01 at hebmex.com
Tue Nov 19 18:12:26 EST 2002


OK, Thanks y'all for your replies.

I've made a simple generator function which returns all
combinations of a given size, of the elements of a list.

Here's the code, for all who wish to play with it,
criticize it, ignore it, use it, abuse it, read it,
etc. ;-)

--------------------------------------------------------
def Combinations(set, length):
    """Combinations([...], length) -> iterator
    """
    # Catch anything we don't like.
    if not set or not length or len(set) < length:
        yield (())
    elif len(set) == length:
        yield tuple(set)
    elif len(set) > length:
        Z = (set[0],)
        for c in Combinations(set[1:], length-1):
            yield Z + c
        for c in Combinations(set[1:], length):
            yield c


for c in Combinations(range(5), 3):
    print c
--------------------------------------------------------

Enjoy!?

;-)

-gustavo




More information about the Python-list mailing list