Created
October 28, 2011 05:12
-
-
Save mahmoud/1321673 to your computer and use it in GitHub Desktop.
Some subset fun.
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
#!/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