Generating all combinations

Raymond Hettinger python at rcn.com
Wed Jun 3 23:27:56 EDT 2009


> > What, no partitions?
>
> >http://en.wikipedia.org/wiki/Partition_of_a_set

Simpler version:

def partition(s):
    n = len(s)
    parts = range(1, n)
    for i in range(n):
        for div in combinations(parts, i):
            print map(s.__getslice__, chain([0], div), chain(div,
[n]))

>>> partition('abcd')
['abcd']
['a', 'bcd']
['ab', 'cd']
['abc', 'd']
['a', 'b', 'cd']
['a', 'bc', 'd']
['ab', 'c', 'd']
['a', 'b', 'c', 'd']



More information about the Python-list mailing list