Skip to content

Instantly share code, notes, and snippets.

@ojacobson
Created October 15, 2011 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ojacobson/1289180 to your computer and use it in GitHub Desktop.
Save ojacobson/1289180 to your computer and use it in GitHub Desktop.
def all_subsets(*elements):
# ensure elements is indexable and contains only unique values
elements = list(set(elements))
# Each bit pattern in an n-bit bitfield corresponds to a unique subset
# of an n-element set. Iterate over all such bitfields where
# n = len(elements).
for permutation_bits in xrange(2**len(elements)):
indexes = [
i
for i in xrange(len(elements))
if (1 << i) & permutation_bits != 0
]
yield set(elements[i] for i in indexes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment