Python itertools.combinations' results

23,164

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

Share:
23,164
Paolo
Author by

Paolo

Updated on December 27, 2020

Comments

  • Paolo
    Paolo over 3 years

    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.

  • Paolo
    Paolo over 12 years
    You are right. My fault. Double fault: one because I wrote "combination('ABCDEF', 3)" but I really tried with 2 instead of 3. The second fault is for sure with the iterable object I'm using with combinations(). Thanks :-)