"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to divide a collection into all possible subsets in Python?

How to divide a collection into all possible subsets in Python?

Posted on 2025-03-13
Browse:541

How Can You Partition a Set Into All Its Possible Subsets in Python?

Partitioning Sets in Python

The task at hand is to partition a given set of elements into all possible subsets. For instance, partitioning the set [1, 2, 3] yields the following subsets:

[[1], [2], [3]]
[[1,2], [3]]
[[1], [2,3]]
[[1,3], [2]]
[[1,2,3]]

Recursive Solution

One approach to this problem is recursion. Given a partition of n-1 elements, we can extend it to create a partition of n elements by either including the nth element in one of the existing subsets or creating a new singleton subset containing only the nth element.

This recursive algorithm effectively partitions the input set while avoiding duplicate outputs and unnecessary dependencies on external libraries:

def partition(collection):
    if len(collection) == 1:
        yield [ collection ]
        return

    first = collection[0]
    for smaller in partition(collection[1:]):
        # insert `first` in each of the subpartition's subsets
        for n, subset in enumerate(smaller):
            yield smaller[:n]   [[ first ]   subset]    smaller[n 1:]
        # put `first` in its own subset 
        yield [ [ first ] ]   smaller

something = list(range(1,5))

for n, p in enumerate(partition(something), 1):
    print(n, sorted(p))
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3