LoginSignup
2
4

More than 3 years have passed since last update.

pythonで組み合わせの総数を計算

Last updated at Posted at 2020-05-08

はじめに

組み合わせのリストはitertoolを用いるが,総数の計算を求める方法については,検索の上位に出てこず時間がかかったのでここでメモ書きする

Scipyの関数を使う(おすすめ)

scipy.special.combを用いる.詳細はこちら


from scipy.special import comb

【実行例】

print(comb(4, 2))           #4C2の計算
print(comb([4 ,3], [2, 1])) #リスト形式でも渡せる、この場合、4C2と3C1の計算ができる


【実行結果】

6.0
[6. 3.]

関数を自作する場合

_nC_r = \frac{n!}{r!(n-r)!}

を用いて,関数を自作する

import math
def combination(n,r):
    return math.factorial(n)/math.factorial(r)/math.factorial(n-r)


【実行例】

print(combination(4,2))  #4C2の計算

【実行結果】

6.0
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4