Twitter Updates

    follow me on Twitter

    Sunday, March 1, 2009

    Immature fac and nCr functions in Python

    Okay, here goes nothing!


    def fac(n,k=1):
    #k for multifactorials
    if n<k:
    return 1
    else:
    return n*fac(n-k)

    def nCr(n,*k): #(n,k1,k2,k3,k4), no k defaults to n/2
    #negative generalization not supt for multifact
    for r in k:
    r=r//1 #get floor of r
    if r<0: #negative exception
    return 0
    if not k:
    k=(abs(n)//2,)
    if len(k)<=1: #if binomial, n*...*(n-k+1)/k!
    prod=1 #k=n-k is not used for negative considerations
    for i in range(k[0]):
    prod*=n/(i+1)
    n-=1
    else: #if multinomial, n!/k1!k2!k3, does not generalize to neg
    if n<0: #negative exception
    return 0
    prod=fac(n)
    for r in k: #for every dimension
    prod/=fac(r)
    return prod


    Hehe : D

    No comments: