简体   繁体   中英

What is the fastest way of computing powerset of an array in Python?

Given a list of numbers, eg x = [1,2,3,4,5] I need to compute its powerset (set of all subsets of that list). Right now, I am using the following code to compute the powerset, however when I have a large array of such lists (eg 40K of such arrays), it is extremely slow. So I am wondering if there can be any way to speed this up.

superset = [sorted(x[:i]+x[i+s:]) for i in range(len(x)) for s in range(len(x))]

I also tried the following code, however it is much slower than the code above.

from itertools import chain, combinations

def powerset(x):
    xx = list(x)
    return chain.from_iterable(combinations(xx, i) for i in range(len(xx)+1))

You can represent a powerset more efficiently by having all subsets reference the original set as a list and have each subset include a number whose bits indicate inclusion in the set. Thus you can enumerate the power set by computing the number of elements and then iterating through the integers with that many bits. However, as have been noted in the comments, the power set grows extremely fast, so if you can avoid having to compute or iterate through the power set, you should do so if at all possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM