Python實(shí)現(xiàn)求一個(gè)集合所有子集的示例
方法一:回歸實(shí)現(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
方法二:二進(jìn)制法
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實(shí)現(xiàn)求一個(gè)集合所有子集的示例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python matlab庫(kù)簡(jiǎn)單用法講解
在本篇文章里小編給大家整理了一篇關(guān)于python matlab庫(kù)簡(jiǎn)單用法講解內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2020-12-12
Python模擬登錄之滑塊驗(yàn)證碼的破解(實(shí)例代碼)
這篇文章主要介紹了Python模擬登錄之滑塊驗(yàn)證碼的破解(實(shí)例代碼),代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-11-11
Python的collections模塊中的OrderedDict有序字典
字典是無(wú)序的,但是collections的OrderedDict類(lèi)為我們提供了一個(gè)有序的字典結(jié)構(gòu),名副其實(shí)的Ordered+Dict,下面通過(guò)兩個(gè)例子來(lái)簡(jiǎn)單了解下Python的collections模塊中的OrderedDict有序字典:2016-07-07
20個(gè)常用Python運(yùn)維庫(kù)和模塊
本篇文章給大家整理了20個(gè)最常用Python運(yùn)維中用到的庫(kù)和模塊,希望我們整理的內(nèi)容對(duì)大家有所幫助。2018-02-02
Python爬蟲(chóng)實(shí)戰(zhàn):分析《戰(zhàn)狼2》豆瓣影評(píng)
這篇文章主要介紹了Python爬蟲(chóng)實(shí)戰(zhàn):《戰(zhàn)狼2》豆瓣影評(píng)分析,小編在這里使用的是python版本3.5,需要的朋友可以參考下2018-03-03
pytorch簡(jiǎn)單實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)功能
這篇文章主要介紹了pytorch簡(jiǎn)單實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09

