长虫山小木屋

没有谁会为你踏雪而来 喜欢的风景要躬亲筚路

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理
import datetime
def PowerSetsBinary(items):#1,二进制方法
    N = len(items)
    # generate all combination of N items
    # enumerate the 2**N possible combinations
    res=[]
    for i in range(2 ** N):
        combo = []
        for j in range(N):  # jth bit of Integer i
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        res.append(combo)
    return res

def PowerSetsRecursive(items):#2,回归方法
    """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 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   # 递归退层中都要返回递归进层的那一个子集

def PowerSetsRecursive2(items): #3,这个应该算正序生成法了吧
	# 我和你赌,不是看你要什么,而是看我有什么(items combine with results which the former need to depend on)
    result = [[]]   # the power set of the empty set has one element: the empty set
    for x in items:
    	# 两个列表相加和extend同理
        result.extend([subset + [x] for subset in result])  # extend 会遍历args/kwargs,然后将其加入到列表中
    return result

from itertools import combinations
def PowerSetsRecursive3(items):#4,调用itertools 库
    result_list = sum([list(map(list, combinations(items, i))) for i in range(len(items) + 1)], [])
    return result_list

a=list(range(22))

start_t = datetime.datetime.now()
res=PowerSetsBinary(a)
end_t = datetime.datetime.now()
elapsed_sec = (end_t - start_t).total_seconds()
print(elapsed_sec)
print(len(res))

start_t = datetime.datetime.now()
res=PowerSetsRecursive(a)
end_t = datetime.datetime.now()
elapsed_sec = (end_t - start_t).total_seconds()
print(elapsed_sec)
print(len(res))

start_t = datetime.datetime.now()
res=PowerSetsRecursive2(a)
end_t = datetime.datetime.now()
elapsed_sec = (end_t - start_t).total_seconds()
print(elapsed_sec)
print(len(res))

start_t = datetime.datetime.now()
res=PowerSetsRecursive3(a)
end_t = datetime.datetime.now()
elapsed_sec = (end_t - start_t).total_seconds()
print(elapsed_sec)
print(len(res))

 

这个取了22个数字的集合,所有子集个数是4194304个,结果显示方法3最快,如果运算个数少一点,是使用自带库的方法4更快一点

14.354473
4194304
3.672871
4194304
2.823392
4194304
3.28878
4194304

 

 

posted on 2020-04-16 19:58  长虫山小木屋  阅读(445)  评论(0编辑  收藏  举报