实用:python中求杨辉三角的n行r列的数(利用公式求解)

#杨辉三角定理:n行r列的数字可表示为C(n,r),有公式C(n,r) = n!/(r!(n-r)!)

n,r = 8,5    #求n行r列所在的数,编号从0开始,0代表第一行或第一列

targets = []    #依次放入r!  (n-r)!  n!
factorial = 1

for i in range(1,n+1):
    factorial *= i
    if i == r:
        #此时factorial = r!
        targets.append(factorial)
        #此时targets[0] = factorial = r!
    if i == n-r:
        #此时factorial = (n-r)!
        targets.append(factorial)
        #此时targets[1] = (n-r)!
    if i == n:
        #此时factorial = n!
        targets.append(factorial)
        #此时targets[2] = factorial = n!
print(targets[2]//(targets[0]*targets[1]))    #同等于:n!//(r!(n-r)!)

运行结果:

56

你可能感兴趣的:(python,Python学习记录,python,杨辉三角,算法优化)