powerset

How to get all subsets of a set? (powerset)

吃可爱长大的小学妹 提交于 2019-11-26 00:14:41
问题 Given a set {0, 1, 2, 3} How can I produce the subsets: [set(), {0}, {1}, {2}, {3}, {0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}, {0, 1, 2}, {0, 1, 3}, {0, 2, 3}, {1, 2, 3}, {0, 1, 2, 3}] 回答1: The Python itertools page has exactly a powerset recipe for this: from itertools import chain, combinations def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) Output: >>>