A Combinations of Items in Given List
I'm currently in Python land. This is what I need to do. I have already looked into the itertools library but it seems to only do permutations.
I want to take an input list, like ['yahoo', 'wikipedia', 'freebase'] and generate every unique combination of one item with zero or more other items...
['yahoo', 'wikipedia', 'freebase']
['yahoo', 'w开发者_StackOverflowikipedia']
['yahoo', 'freebase']
['wikipedia', 'freebase']
['yahoo']
['freebase']
['wikipedia']
A few notes. Order does not matter and I am trying to design the method to take a list of any size. Also, is there a name for this kind of combination?
Thanks for your help!
>>> l = ['yahoo', 'wikipedia', 'freebase']
>>> import itertools
>>> for i in range(1, len(l) +1):
print(list(itertools.combinations(l, r=i)))
[('yahoo',), ('wikipedia',), ('freebase',)]
[('yahoo', 'wikipedia'), ('yahoo', 'freebase'), ('wikipedia', 'freebase')]
[('yahoo', 'wikipedia', 'freebase')]
P.S. why is this wiki?
It's called a powerset. This is an implementation from the itertools docs:
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
You're basically counting from 1 to 2n-1 in binary:
0 0 1 ['freebase']
0 1 0 ['wikipedia']
0 1 1 ['wikipedia', 'freebase']
1 0 0 ['yahoo']
1 0 1 ['yahoo', 'freebase']
1 1 0 ['yahoo', 'wikipedia']
1 1 1 ['yahoo', 'wikipedia', 'freebase']
That is called a power set. Just follow this algorithm. Here's a simple implementation:
def powerset(seq):
if len(seq):
head = powerset(seq[:-1])
return head + [item + [seq[-1]] for item in head]
else:
return [[]]
>>> powerset(['yahoo', 'wikipedia', 'freebase'])
[[], ['yahoo'], ['wikipedia'], ['yahoo', 'wikipedia'], ['freebase'], ['yahoo', 'freebase'], ['wikipedia', 'freebase'], ['yahoo', 'wikipedia', 'freebase']]
And another:
def powerset(s):
sets = []
indicator = lambda x: x & 1
for element in xrange(2**len(s)):
n = element
subset = []
for x in s:
if indicator(n):
subset.append(x)
n >>= 1
sets.append(subset)
return sets
精彩评论