Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created June 30, 2015 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cslarsen/7aa2ab400346c6801cb2 to your computer and use it in GitHub Desktop.
Save cslarsen/7aa2ab400346c6801cb2 to your computer and use it in GitHub Desktop.
# Fast way to compute the Stirling numbers of the second kind.
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
from math import factorial
def binom(a,b):
return factorial(a) / (factorial(b)*factorial(a-b))
def stirling_fast(n,k):
"Returns the Stirling number of the second kind."
if n<=0 or n!=0 and n==k:
return 1
elif k<=0 or n<k:
return 0
elif n==0 and k==0:
return -1
else:
s = sum((-1)**(k-j)*binom(k,j)*j**n for j in range(k+1))
return s / factorial(k)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment