組み合わせとか順列とか

階乗

[2]:
import math
from scipy.special import perm

math.factorial(5)
[2]:
120

異なるn個のものからr個選んで1列に並べる場合の数

[4]:
# p = n! / (n - r)!
def permutaions_count(n, r):
    return math.factorial(n) // math.factorial(n - r)


#scipyで簡単に計算ができる。
perm(4, 2, exact=True)
[4]:
12

配列から順列を生成して列挙

[5]:
import itertools

l = ["a", "b", "c", "d"]
p = itertools.permutations(l, 2)

# 全て列挙する場合はfor文回す
for v in p:
    print(v)
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'a')
('b', 'c')
('b', 'd')
('c', 'a')
('c', 'b')
('c', 'd')
('d', 'a')
('d', 'b')
('d', 'c')

リストから取り出した3つの整数の合計が0になる組み合わせ

[6]:
import itertools

l = [1, 2, 41, -1, -2, -4]
for c in itertools.combinations(l, 3):
    if sum(c) == 0:
        print(c)
[ ]: