views:

4573

answers:

2

Hi,

I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.

I've found some code (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution.

The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers.

Does anyone know of a better way? Using map(), maybe?

Thanks,

Ben

+13  A: 

Have a look at itertools.combinations:

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Since 2.6, batteries are included!

Alabaster Codify
That looks good to me! Thanks.
Ben
I don't have python 2.6, but since that link contained the code for combinations, I was able to get it working. Thanks again!
Ben
Ah, yes - I didn't see that it was 2.6 only... updated my answer
Alabaster Codify
+4  A: 

If you don't have access to Python 2.6 you might find it in a recipe from the Python Cookbook. I'm sure there are some more recipes for this topic.

unbeknown