Python實現(xiàn)求一個集合所有子集的示例
更新時間:2018年05月04日 15:11:57 作者:tszw1007
今天小編就為大家分享一篇Python 實現(xiàn)求一個集合所有子集的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
方法一:回歸實現(xiàn)
def PowerSetsRecursive(items):
"""Use recursive call to return all subsets of items, include empty set"""
if len(items) == 0:
#if the lsit is empty, return the empty list
return [[]]
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 sebset that contains the first_elt
for partial_sebset in PowerSetsRecursive(rest_list):
subsets.append(partial_sebset)
next_subset = partial_sebset[:] +[first_elt]
subsets.append(next_subset)
return subsets
def PowerSetsRecursive2(items):
# the power set of the empty set has one element, the empty set
result = [[]]
for x in items:
result.extend([subset + [x] for subset in result])
return result
方法二:二進制法
def PowerSetsBinary(items):
#generate all combination of N items
N = len(items)
#enumerate the 2**N possible combinations
for i in range(2**N):
combo = []
for j in range(N):
#test jth bit of integer i
if(i >> j ) % 2 == 1:
combo.append(items[j])
yield combo
以上這篇Python實現(xiàn)求一個集合所有子集的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python的collections模塊中的OrderedDict有序字典
字典是無序的,但是collections的OrderedDict類為我們提供了一個有序的字典結構,名副其實的Ordered+Dict,下面通過兩個例子來簡單了解下Python的collections模塊中的OrderedDict有序字典:2016-07-07
Python爬蟲實戰(zhàn):分析《戰(zhàn)狼2》豆瓣影評
這篇文章主要介紹了Python爬蟲實戰(zhàn):《戰(zhàn)狼2》豆瓣影評分析,小編在這里使用的是python版本3.5,需要的朋友可以參考下2018-03-03

