Lostsoul
Lostsoul

Reputation: 26037

Is there a effective way to get only K combinations of a list?

Say I have a simple list from 1 to 8 and only want the combinations that include 7 characters. How could I do that efficiently? Is it possible to do it without iterating the entire list?

For example, This does the entire list:

import itertools
stuff = [1, 2, 3,4,5,6,7,8]
count = 0
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print(subset)
        count = count + 1
print count #returns 256 results with 8 matching the 7 length

if you change the L in itertools.combinations(stuff, L): to 7 then it works but it'll give you alot of duplicates(72 results and most are duplicates). I know I can just extract the 7 items I want from the code above but for larger lists it seems inefficient for me to do that. Any suggestions?

In this case the end result I'm looking for is:

(1, 2, 3, 4, 5, 6, 7)
(1, 2, 3, 4, 5, 6, 8)
(1, 2, 3, 4, 5, 7, 8)
(1, 2, 3, 4, 6, 7, 8)
(1, 2, 3, 5, 6, 7, 8)
(1, 2, 4, 5, 6, 7, 8)
(1, 3, 4, 5, 6, 7, 8)
(2, 3, 4, 5, 6, 7, 8)

Upvotes: 1

Views: 112

Answers (1)

Fred Foo
Fred Foo

Reputation: 363757

itertools.combinations works just fine:

>>> for c in itertools.combinations(stuff, 7):
...     print(c)
...     
(1, 2, 3, 4, 5, 6, 7)
(1, 2, 3, 4, 5, 6, 8)
(1, 2, 3, 4, 5, 7, 8)
(1, 2, 3, 4, 6, 7, 8)
(1, 2, 3, 5, 6, 7, 8)
(1, 2, 4, 5, 6, 7, 8)
(1, 3, 4, 5, 6, 7, 8)
(2, 3, 4, 5, 6, 7, 8)

The duplicates are caused by the fact that you're running combinations in a loop.

Upvotes: 11

Related Questions