Home python Number of combinations (from N by k) Is there a quick algorithm?...

Number of combinations (from N by k) Is there a quick algorithm? Python




The number of combinations can be found using recursion and, accordingly, the recurrent ratio. The code is obtained here:

def c (n, k):
  IF k == n or k == 0:
    Return 1.
  IF k! = 1:
    Return C (N-1, K) + C (N-1, K-1)
    Return N.
Print (C (INT (INPUT ()), INT (INPUT ())))

But I know that the recursion is not fast and not always reliable. Are there any other algorithms and how fast they are?

Answer 1, Authority 100%

through the factorial is slow and not efficient.
In the n formula! / (K! (n - k)!) , if shortened, then it turns out (n - k + 1) (n-k + 2) .. n / k!

This code is obtained:

def c (n, k):
  IF 0 & lt; = k & lt; = n:
    Nn = 1.
    KK = 1.
    For t in xrange (1, min (k, n - k) + 1):
      nn * = n
      KK * = T
      N - = 1
    Return 0.

You can also see the library ITERTOOLS :

combinations ('abcd', 2) # ab AD BC BD CD

Answer 2, Authority 25%

We offer to use the ITERTOOLS module, the desired operation is immediately implemented there. It makes the necessary combinations. Calculate their number will not work.

import itertools
DEF C (N, K):

I want to note that it can be combined from anything (i.e., you can transmit any characteristic container).

Answer 3

for the vehicle is already irrelevant, probably, but may come in handy.

Pascal triangle (combinations are binomial coefficients).

To “draw it”, you do not need to multiply.

faster already in any way.

Answer 4

Use Math.comB

import math
n = int (input ())
k = int (input ())
Print (Math.comB (N, K))

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions