My Python 3.6 script works great with
from scipy.special import binom
Running the code in AWS lambda, however, does not work. Attempting to load the zipped deployment package from S3 gives the error:
Unzipped size must be smaller than 262144000 bytes
Surely somewhere there is a Python package which can do what “binom” does without needing all of “scipy” which seems to require “numpy” ?
Solution:
The binomial coefficient is a known and fairly trivial calculation; binom(n, k) is just n! / (k! * (n - k)!). Python built-ins can do this in a perfectly straightforward (if theoretically sub-optimal, since it can produce excessively large intermediates that more tuned approaches could avoid, but it hardly matters most of the time) way:
from math import factorial
def binom(n, k):
return factorial(n) // (factorial(k) * factorial(n - k))
If you need it somewhat faster, gmpy2 offers a bincoef function, and gmpy2 is a bit more standalone than scipy/numpy (it needs GMP/MPFR/MPC, but it’s on the order of a few MB of binaries all told, not a few hundred MB). It returns a gmpy2.mpz type, which is largely interoperable with int, or you can just force conversion back to int by wrapping:
from gmpy2 import bincoef
def binom(n, k):
return int(bincoef(n, k))