Last active
December 30, 2015 10:08
-
-
Save cwidmer/7813528 to your computer and use it in GitHub Desktop.
Create power-set (the set of all possible subsets) from a python list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def power_set(orignal_list): | |
''' | |
PowerSet of a List | |
@param orignal_list: list from which to construct a powerset | |
''' | |
list_size = len(orignal_list) | |
num_sets = 2**list_size | |
powerset = [] | |
# Don't include empty set | |
for i in range(num_sets)[1:]: | |
subset = [] | |
binary_digits = list(int2bin(i,list_size)) | |
list_indices = range(list_size) | |
for (bit,index) in zip(binary_digits,list_indices): | |
if bit == '1': | |
subset.append(orignal_list[index]) | |
powerset.append(subset) | |
return powerset | |
def int2bin(n, count=24): | |
"""returns the binary of integer n, using count number of digits""" | |
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment