python計算排列組合數

2021-10-07 14:43:44 字數 1529 閱讀 2618

def combinatorial(n,i):

'''設計組合數'''

#n>=i

min=min(i,n-i)

result=1

for j in range(0,min):

#由於浮點數精度問題不能用//

result=result*(n-j)/(min-j)

return result

if __name__ == '__main__':

print(int(combinatorial(45,2)))

from scipy.special import comb, perm

#計算排列數

a=perm(3,2)

#計算組合數

c=comb(45,2)

print(a,c)

使用階乘的方式求組合數

import math

def factorial_me(n):

'''建立求階乘的函式'''

result = 1

for i in range(2, n + 1):

result = result * i

return result

def comb_1(n,m):

# 直接使用math裡的階乘函式計算組合數

return math.factorial(n)//(math.factorial(n-m)*math.factorial(m))

def comb_2(n,m):

# 使用自己的階乘函式計算組合數

return factorial_me(n)//(factorial_me(n-m)*factorial_me(m))

def perm_1(n,m):

# 直接使用math裡的階乘函式計算排列數

return math.factorial(n)

def perm_2(n,m):

# 使用自己的階乘函式計算排列數

return factorial_me(n)//factorial_me(n-m)

if __name__ == '__main__':

print(factorial_me(6))

print(comb_1(45,2))

print(comb_2(45,2))

print(perm_1(45,2))

print(perm_2(45,2))

from itertools import combinations, permutations

# 列舉排列結果[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

print(list(permutations([i for i in range(1,4)],2)))

#列舉組合結果[(1, 2), (1, 3), (2, 3)]

print(list(combinations([1,2,3],2)))

計算排列組合數 python

使用scipy計算排列組合的具體數值 from scipy.special import comb,perm perm 3,2 計算排列數 6 comb 3,2 計算組合數 3自己寫乙個計算排列組合具體數值的函式 import math def factorial n result 1 for i ...

排列組合(組合數)

儒雅隨和的小趙閒暇時很喜歡古典文學,比如金 金銀角大王和孫悟空。話說悟空一行在西天取經路上遇上了妖怪金角大王 銀角大王,把唐僧 八戒 沙僧 白馬,連行李一道擄去。兩個大王有幾個法寶,其中乙個是個魔葫蘆,妖怪叫誰的名字,誰應一聲,就被吸進葫蘆,兩個時辰化為膿水。孫悟空來鬥妖魔,魔王叫 孫悟空 他應了,...

排列 組合數學

定義 從n個不同的元素中,取出m個不同元素,按照順序排成一列,叫做從n個元素取出m個元素的乙個排列。我們將從n個不同的元素取出m個元素所得到得不同排列數,叫做從n個元素取出m個元素的排列數 記為a n,m 其中n m a n,m n n 1 n m 1 n n m 定義 n個不同元素中取m個不同元素...