Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python itertools.combinations' results

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.

like image 632
Paolo Avatar asked Dec 26 '11 10:12

Paolo


People also ask

What does Itertools combinations return?

combinations(iterable, r) : It return r-length tuples in sorted order with no repeated elements. For Example, combinations('ABCD', 2) ==> [AB, AC, AD, BC, BD, CD].

How does Itertools combinations work?

The itertools. combinations() function takes two arguments—an iterable inputs and a positive integer n —and produces an iterator over tuples of all combinations of n elements in inputs .

What does Itertools Zip_longest return?

zip_longest() This iterator falls under the category of Terminating Iterators. It prints the values of iterables alternatively in sequence.


1 Answers

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).

like image 115
unutbu Avatar answered Oct 20 '22 07:10

unutbu