Python函数解决二项式函数

时间:2016-03-03 10:48:12

标签: python numpy combinatorics itertools discrete-mathematics

我需要一个可以解决以下问题的函数:对于二项式函数nCr = k,给定r和k找到n。在数学中nCr = n!/ r!(n-r)!我试过跟随,但它没有解决它。例如8C6 = 28,对于我的函数,输入是6和28,我想找到8.这可能没有完整的整数,所以我想找到一个x> = n。

"""
I am approaching it this way, i.e. find the solution of a polynomial function  iteratively, hope there is a better way"""
"""I am approaching it this way, i.e. find the solution of a polynomial function iteratively, hope there is a better way"""
def find_n(r,k):
    #solve_for_n_in(n*(n-1)...(n-r)=math.factorial(r)*k
    #in the above example solve_for_n(n*(n-1)(n-2)(n-3)(n-4)(n-5)=720*28)

    sum=math.factorial(r)*k
    n=r
    p=1
    while p<sum: 
        p=1
        for i in range(0,r+2):
            p*=(n-i+1)
        n+=1
    return n

感谢。

3 个答案:

答案 0 :(得分:0)

我在你的代码中发现了一个错误。

sum=n

你将总和设为n 那么,

while sum<factorial(r)*k:
    sum*=n

你再次将n乘以n。所以现在sum = n ** 2。 这会更好:

  while sum<factorial(r)*k:
    n+=1
    sum*=n

答案 1 :(得分:0)

这只是一个关于如何处理这个问题的想法,同时保持高度的可读性。

nCr = n! / {{r!}{n-r}!} = n(n-1)...(n-r+1) / {r!} 右侧是一些值k

n = 2*(r+1)开始。

nCr < RHS =&gt; n太小了=&gt;增加n

nCr > RHS =&gt; n太大了=&gt;减少n

nCr == RHS =&gt;找到了

... ... 继续这样做,直到找到n或出现问题为止。

import math

def find_n(r,k):

    if k==1:
        return r         # RHS is 1 when n and r are the same

    RHS = math.factorial(r) * k

    possible_n = 2 * r;
    possible_numerator = math.factorial(possible_n)
    possible_denom = math.factorial(possible_n - r)

    while True:
        # current n is too small 
        if ( possible_numerator // possible_denom ) < RHS:
            # try possible_n + 1
            possible_n = possible_n + 1
            possible_numerator = math.factorial(possible_n)
            possible_denom = math.factorial(possible_n - r)

        elif ( possible_numerator // possible_denom ) > RHS:
            # try possible_n - 1
            possible_n = possible_n - 1
            possible_numerator = math.factorial(possible_n)
            possible_denom = math.factorial(possible_n - r)

        elif ( possible_n == r):
            print ("***n smaller than r***");
            sys.exit(0);

        elif ( possible_numerator // possible_denom ) == RHS:
            return possible_n





print( find_n(6, 28) )      # should print 8

print( find_n(6, 462) )     # should print 11 

print( find_n(6, 3003) )        # should print 14

print( find_n(5, 3003) )        # should print 15

答案 2 :(得分:0)

我使用了一个计算二项式系数的函数来实现特征nCr

def binomial(n,k):
    return 1 if k==0 else (0 if n==0 else binomial(n-1, k) + binomial(n-1, k-1))

def nCr(r,c):
    n=0
    b=binomial(n,r)
    while b<c:
        n=n+1
        b=binomial(n,r)
        if b==c:
            return n

    return None

nCr的(6,28)

8