有关python的问题

我想知道怎么解决以下问题,如何在python里面表示递减的整数相乘(即数学里的n!)

img

img

python没有自带阶乘的功能,只能调用库或者使用循环

def num(n):

    if n == 0:

        return 1

    else:

        return n * num(n - 1)
import math

value = math.factorial(6)

print(value)

from math import factorial
res=factorial(40)/(factorial(10)*factorial(10)*factorial(10)*factorial(10)*factorial(0))
print("分法有:",res)

###这题也好理解,40个先排列,然后分到4个箱子里,箱子里不排列,把每个箱子里的 10的阶乘除掉。
###一般组合的思路就是 C(40,10)*C(30,10)*C(20,10)*C(10,10)= 40!/(10!*30!) * 30!/(10!*20!) * 20!/(10!*10!) * 10!/(10!*0!)=40!/(10!*10!*10!*10!*0!) ,也就是你例8 中的公式了

permutations 有序排列

combinations 无序排列

factorial 阶乘

img

from itertools import combinations, permutations

from math import factorial

# permutations 有序排列
# combinations 无序排列
# factorial 阶乘
print(len(list(permutations([1, 2, 3, 4], 3))), list(permutations([1, 2, 3, 4], 3)))  # 有序排列
print(len(list(combinations([1, 2, 3, 4], 3))), list(combinations([1, 2, 3, 4], 3)))  # 无序排列

# 40个球,四个盒子,一个盒子十个球搞排列组合,每个球和盒子都是不可分辨的(没有贴标签或者怎么样),去得到有多少种解法
ball_list = [i for i in range(1, 41)]  # 1~40
box_list = [i for i in range(1, 5)]  # 1~4

# 不区分球,不区分盒子;
# 相当于是C40,10 * C30,10 * C20,10 *  C10,10 * C4,4
print('共%d种组合' % (factorial(40) / (pow(factorial(10), 4)) * len(list(combinations(box_list, 4)))))

# 每一种放置球的组合方法,下边程序运行电脑会卡,谨慎运行
count = 0
for ball_1 in combinations(ball_list, 10):
    # 第一组球 ball_1
    # 剩下的球
    ball_list_last2 = list(set(ball_list).difference(set(ball_1)))
    for ball_2 in combinations(ball_list_last2, 10):
        # 第2组球 ball_2
        # 剩下的球
        ball_list_last3 = list(set(ball_list_last2).difference(set(ball_2)))
        for ball_3 in combinations(ball_list_last3, 10):
            # 第3组球 ball_3
            # 剩下的球
            ball_4 = list(set(ball_list_last3).difference(set(ball_3)))
            # 第4组球剩10个取10个,只有1种方法不用去排了
            count = count + 1
            print('第%d种组合 %s,%s,%s,%s' % (count, str(ball_1), str(ball_2), str(ball_3), str(ball_4)))
print('共%d种方法' % count)

各种球盒问题的python实现
https://blog.csdn.net/qq_40013071/article/details/89293652

math库有factorial函数可以使用啊

用递归应该可以