Skip to content

Instantly share code, notes, and snippets.

@mahmoud
Created October 28, 2011 05:12
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 mahmoud/1321673 to your computer and use it in GitHub Desktop.
Save mahmoud/1321673 to your computer and use it in GitHub Desktop.
Some subset fun.
#!/usr/bin/env python
from itertools import combinations, chain
fun_list = ['a','b','c']
print "\nThe FB way"
def subsets(ins, out=None):
if out is None:
out = ['']
if len(ins) == 0:
return ['']
out.extend([x+ins[0] for x in out])
subsets(ins[1:], out)
return out
results = subsets(fun_list)
print "\t",sorted(results)
print "\nPython itertools way (probably confusing for non-Pythonistas)"
results = [''.join(fun_list)] # only one combination of all list elements
sequences = [list(chain(combinations(fun_list, n)))
for (n,l) in enumerate(fun_list)]
results = sum(sequences, results) #sum combines lists, a little cleaner than chain here.
results = [''.join(s) for s in results] # formatting
print "\t",sorted(results)
print "\nA fun way (probably less confusing for non-Pythonistas, but still a bit silly)"
results = []
length = len(fun_list)
for i in range(2**length):
mask = [((i >> cur_dig) & 1) for cur_dig in range(length-1, -1, -1)]
results.append(''.join([c for i,c in enumerate(fun_list) if mask[i]]))
print "\t",sorted(results),"\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment