1. 程式人生 > >計算排列組合數-python

計算排列組合數-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)]