1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[AtCoder] 個人的に使用頻度が高いitertoolsまとめ

Posted at

AtCoderで組み合わせ問題など抽出方法をどうしようか迷いますよね。
自作するのも一つの手ですが、itertools関数を使った方がバグらないです。
※一度自作して処理を考えることをお勧めします

表示用関数用意

import itertools

def printitertools(itertool_return, describe):
    print(describe)
    for i in itertool_return:
        print(i)
    print("")


デカルト積(product)

全bit探索にも使えます。

printitertools(itertools.product(range(2), repeat=3), "product")

#product
#(0, 0, 0)
#(0, 0, 1)
#(0, 1, 0)
#(0, 1, 1)
#(1, 0, 0)
#(1, 0, 1)
#(1, 1, 0)
#(1, 1, 1)

順列(Permutation)

高校時代勉強した3P2です。

printitertools(itertools.permutations([1, 2, 3], 2), "permutations")

#permutations
#(1, 2)
#(1, 3)
#(2, 1)
#(2, 3)
#(3, 1)
#(3, 2)

組み合わせ(combinations)

高校時代勉強した3C2です。

printitertools(itertools.combinations([1, 2, 3], 2), "combinations")

#combinations
#(1, 2)
#(1, 3)
#(2, 3)

組み合わせ(combinations_with_replacement)

同じ項目を2つ選ぶの可能なバージョンです。

printitertools(itertools.combinations_with_replacement([1, 2, 3], 2), "combinations_with_replacement")

#combinations_with_replacement
#(1, 1)
#(1, 2)
#(1, 3)
#(2, 2)
#(2, 3)
#(3, 3)

対応した項目だけ抽出(compress)

printitertools(itertools.compress([1, 2, 3], [True, False, True]), "compress")

#combinations
#1
#3
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?