这篇文章给大家分享的是有关使用Python实现求一个集合所有子集的案例的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
方法一:回归实现
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实现求一个集合所有子集的案例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。