技術メモ

役に立てる技術的な何か、時々自分用の覚書。幅広く色々なことに興味があります。

2進数を使って(表裏/オンオフ)数え上げ

N枚のコインを同時に投げる場合やN人のYES/NOの数え上げなどがしたい時は、
2**N通りのパータンを2進数に変換してしてからパターンを作ると良い。
具体的には、
0~2**N-1までの数字を10進数⇒2進数表記に文字列として変換したのち、文字列をリストと考えて処理する。
ただし、桁数分ゼロ埋めする必要がある。

for i in range(2**n):
    pattern1 = list(map(int, bin(i)[2:].zfill(n)))
    pattern2 = list(map(int, format(i, '0'+str(n)+'b')))

itertoolsを使う方法

itertools.product([0,1], repeat=n)

リストの組み合わせをすべて列挙する

src = [1,2,3,4,5]
for i in itertools.product([0,1], repeat=len(src)):
    combination = [j for j in itertools.compress(src, i)]
    print(combination)

output:

[]
[5]
[4]
[4, 5]
[3]
[3, 5]
[3, 4]
[3, 4, 5]
[2]
[2, 5]
[2, 4]
[2, 4, 5]
[2, 3]
[2, 3, 5]
[2, 3, 4]
[2, 3, 4, 5]
[1]
[1, 5]
[1, 4]
[1, 4, 5]
[1, 3]
[1, 3, 5]
[1, 3, 4]
[1, 3, 4, 5]
[1, 2]
[1, 2, 5]
[1, 2, 4]
[1, 2, 4, 5]
[1, 2, 3]
[1, 2, 3, 5]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]