计算排列组合数-python

  1. 使用scipy计算排列组合的具体数值
from scipy.special import comb, perm

perm(3,2)     #计算排列数    6

comb(3,2)   #计算组合数     3
  1. 自己写一个计算排列组合具体数值的函数
import math

def factorial_(n):
    result=1
    for i in range(2,n+1):
        result=result*i
    return result

def comb_1(n,m):
    return math.factorial(n)//(math.factorial(n-m)*math.factorial(m))  #直接使用math里的阶乘函数计算组合数

def comb_2(n,m):
    return factorial_(n)//(factorial_(n-m)*factorial_(m))              #使用自己的阶乘函数计算组合数

def perm_1(n,m):
    return math.factorial(n)//math.factorial(n-m)                        #直接使用math里的阶乘函数计算排列数

def perm_2(n,m):
    return math.factorial(n)//math.factorial(n-m)                        #使用自己的阶乘函数计算排列数

if __name__=='__main__':
    print(comb_1(3,2))
    print(comb_2(3,2))
    print(perm_1(3,2))
    print(perm_2(3,2))
  1. 使用itertools列出排列组合的全部情况
from itertools import combinations, permutations

list(permutations([1,2,3],2))         #列举排列结果[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

list(combinations([1,2,3],2))        #列举组合结果[(1, 2), (1, 3), (2, 3)]
  • 6
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值