Number Sequencing, Grouping and Filtering

Raymond Hettinger python at rcn.com
Wed Mar 11 00:05:08 EDT 2009


[flebber]
> the only issue i can see is that i am using python 2.54 currently as
> ifelt it more supported by other programs than 2.6 or 3.0. After
> searching it seems that itertools has had a upgrade in 2.61

All of the itertools include pure python equivalents in their docs,
so it should be possible to backport them to 2.5 by cutting and
pasting the code equivalent.


Raymond

-------------
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)
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while 1:
        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)





More information about the Python-list mailing list