Python itertools.combinations' results

Paolo picture Paolo · Dec 26, 2011 · Viewed 22.7k times · Source

I don't get the number of results I should obtain from that function in the Title, so I'm hoping in your help.

Looking at the Docs http://docs.python.org/library/itertools.html#itertools.combinations the number of results should be

The number of items returned is n! / r! / (n-r)! when 0 <= r <= n or zero when r > n.

And it works for the example in there

combinations('ABCD', 2) --> AB AC AD BC BD CD

because n! / r! / (n-r)! = 4! / 2! / 2! = 6

But if I try

combinations('ABCDEF', 3) --> AB AC AD AE AF BC BD BE BF CD CE CF DE DF EF

I get those 15 results. But n! / r! / (n-r)! = 6! / 3! / (6-3)! = 720 / 6 / 6 = 20

So: the Python Docs told me that I should have 20 results, but I get 15.

Can you please help me understand what I'm missing? Maybe is something in my math, as that formula should be right as it is in the Wikipedia Combination entry

Thanks, P.

Answer

unutbu picture unutbu · Dec 26, 2011

itertools.combinations should be returning an iterator with 20 items:

In [40]: len(list(itertools.combinations('ABCDEF',3)))
Out[40]: 20

Note that

In [41]: len(list(itertools.combinations('ABCDEF',2)))
Out[41]: 15

and the output posted

combinations('ABCDEF', 3) --> AB AC AD AE AF BC BD BE BF CD CE CF DE DF EF

shows only combinations of 2 letters. So it appears you've computed combinations('ABCDEF', 2), not combinations('ABCDEF', 3).