defPowerSetsBinary(items):
N =len(items)# generate all combination of N items# enumerate the 2**N possible combinationsfor i inrange(2** N):
combo =[]for j inrange(N):# jth bit of Integer iif(i >> j)%2==1:
combo.append(items[j])yield combo
"""
[]
['a']
['b']
['a', 'b']
['c']
['a', 'c']
['b', 'c']
['a', 'b', 'c']
"""
defPowerSetsRecursive(items):"""Use recursive call to return all subsets of items, include empty set"""iflen(items)==0:# if the lsit is empty, return the empty listreturn[[]]
subsets =[]
first_elt = items[0]# first element
rest_list = items[1:]# Strategy: Get all subsets of rest_list; # for each of those subsets,a full subset list will contain both the original subset # as well as a version of the subset that contains the first_elt(according to my a_2 思路,you will understand this)for partial_subset in PowerSetsRecursive(rest_list):
subsets.append(partial_subset)
next_subset = partial_subset[:]+[first_elt]
subsets.append(next_subset)return subsets # 遞歸退層中都要返回遞歸進層的那一個子集
a_2 思路
a_3
defPowerSetsRecursive2(items):# 我和你賭,不是看你要什麼,而是看我有什麼(items combine with results which the former need to depend on)
result =[[]]# the power set of the empty set has one element: the empty setfor x in items:# 兩個列表相加和extend同理
result.extend([subset +[x]for subset in result])# extend 會遍歷args/kwargs,然後將其加入到列表中return result