# 在 Python 中查找 Powerset

Hemank Mehtani 2023年1月30日

## 在 Python 中使用迭代方法获取 Powerset

``````def powerset(fullset):
listsub = list(fullset)
subsets = []
for i in range(2 ** len(listsub)):
subset = []
for k in range(len(listsub)):
if i & 1 << k:
subset.append(listsub[k])
subsets.append(subset)
return subsets

subsets = powerset(set([1, 2, 3, 4]))
print(subsets)
print(len(subsets))
``````

``````[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], [4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]
16
``````

## 在 Python 中使用 `itertools.combinations` 函数查找幂集

`itertools` 是 Python 中的一个模块，用于迭代数据结构。这些数据结构也称为可迭代对象。可以使用 for 循环跳过它们。

``````from itertools import combinations

def powerset(string):
n = len(string)
for i in range(0, n + 1):
for element in combinations(string, i):
print("".join(element))

string = ["x", "y", "z"]
powerset(string)
``````

``````x
y
z
xy
xz
yz
xyz
``````

## 在 Python 中使用列表推导式查找幂集

``````def get_subsets(fullset):
listrep = list(fullset)
n = len(listrep)
return [[listrep[k] for k in range(n) if i & 1 << k] for i in range(2 ** n)]

string = ["x", "y", "z"]
print(get_subsets(string))
``````

``````[[], ['x'], ['y'], ['x', 'y'], ['z'], ['x', 'z'], ['y', 'z'], ['x', 'y', 'z']]
``````

## 在 Python 中使用递归方法查找幂集

``````def powerSet(string, index, c):
if index == len(string):
print(c)
return
powerSet(string, index + 1, c + string[index])
powerSet(string, index + 1, c)

s1 = ["a", "b", "c"]
index = 0
c = ""
powerSet(s1, index, c)
``````

``````abc
ab
ac
a
bc
b
c
``````