tags:

views:

1347

answers:

3

I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set S with n elements (|S|=n), to test a function on all possible subsets of a certain order m (i.e. with m number of elements). To use the answer to produce a partial solution, and then try again with the next order m=m+1, until m=n.

I am on my way to write a solution of the form:

def findsubsets(S,m):
    subsets=set([])
    ...
    return subsets

But knowing Python I expected a solution to be already there.

What is the best way to accomplish this?

+15  A: 

itertools.combinations is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.

import itertools
def findsubsets(S,m):
    return set(itertools.combinations(S, m))
recursive
i would not return a set, but simply return the iterator (or just use combinations() without defining a findsubsets()...)
hop
Thanks to both. I do in fact have Python 2.5 so I could not use the solution. But I found the implementation:http://docs.python.org/library/itertools.html#module-itertools
Pietro Speroni
Thank you, I just tested it and it works perfectly.
Pietro Speroni
@Pietro: you do realize that the link you found actually is actually the same as the one recursive gave you, right?
ΤΖΩΤΖΙΟΥ
+2  A: 

It seems like this recipe does the trick: http://code.activestate.com/recipes/500268/

PEZ
+1  A: 

and, if you want each element of the list to be used only once, use 'permutations' also found in itertools.

LOL, indeed, if I wanted a permutation, I would have used the permutations tool. :-D
Pietro Speroni