0

compute combination is as follows:

def C(n,r):
    if n==r:
        return 1
    elif r==1:
        return n
    else:
        return C(n-1,r)+C(n-1,r-1)

While refer the above equation to compute C( 990, 33 ), python will take too much time.

how to boost its performance??

1 Answers1

0

Inspired by the comment by @user1558604; this is a lot quicker:

cache = dict()

def C(n,r):
    if (n,r) in cache:
        return cache[(n,r)]
    elif n==r:
        cache[(n,r)] = 1
        return 1
    elif r==1:
        cache[(n,r)] = n
        return n
    else:
        cache[(n,r)] = C(n-1,r)+C(n-1,r-1)
        return C(n-1,r)+C(n-1,r-1)

Output:

>>> import timeit
>>> %timeit C(990, 33)
321 ns ± 24.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
CDJB
  • 14,043
  • 5
  • 29
  • 55