計算排列組合數-python
阿新 • • 發佈:2018-12-11
- 使用scipy計算排列組合的具體數值
from scipy.special import comb, perm
perm(3,2) #計算排列數 6
comb(3,2) #計算組合數 3
- 自己寫一個計算排列組合具體數值的函式
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))
- 使用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)]