「前回の記事(全パターン網羅する方法)」では、
list から決められた個数を選んだ時の全パターン網羅について説明しました。
前回の記事では、
順番が異なるものを同じものとして数えていませんでしたが、
今回の記事では、
順番が異なるものを別のものとして数える方法について説明します。
まず、違いについて具体例をあげて簡単に説明します。
test_list = ["a", "b", "c"]という list があり、ここから2つを選ぶ場合、
順番が異なるものを同じものとするならば(前回の記事の内容)、
('a', 'b'), ('a', 'c')の2パターンだけです。
順番が異なるものを別のものとするならば(今回の記事の内容)、
('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')の6パターンです。
これを踏まえて、具体的なコードを使って説明します。
# 必要なモジュールをインポート
import itertools
# このlistの全並び順を網羅する
test_list = ["a", "b", "c", "d", "e", "f"]
# test_list から2個選んだ場合の全パターン検索(順番違いは同じとみなす)
all_pattern_no_sequence = list(itertools.combinations(test_list, 2))
print("test_list から2個選んだ場合の全パターン数(順番違いは同じとみなす) -> ", len(all_pattern_no_sequence))
print(all_pattern_no_sequence)
print()
# test_list から2個選んだ場合の全パターン検索(順番違いは別のものとみなす)
all_pattern_sequence = list(itertools.permutations(test_list, 2))
print("test_list から2個選んだ場合の全パターン数(順番違いは別のものとみなす) -> ", len(all_pattern_sequence))
print(all_pattern_sequence)
前回説明したように、「順番違いは同じものとみなす全パターン網羅」には
itertools.combinations()関数を使います。
そして「順番違いは別のものとみなす全パターン網羅」には
itertools.permutations()関数を使います。
この2つの関数を使って、対象 list から2つを選んだ場合の全パターン網羅を行った場合の
実行結果は以下の通りです。
test_list から2個選んだ場合の全パターン数(順番違いは同じとみなす) -> 15
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('c', 'd'), ('c', 'e'), ('c', 'f'), ('d', 'e'), ('d', 'f'), ('e', 'f')]
test_list から2個選んだ場合の全パターン数(順番違いは別のものとみなす) -> 30
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('b', 'f'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('c', 'e'), ('c', 'f'), ('d', 'a'), ('d', 'b'), ('d', 'c'), ('d', 'e'), ('d', 'f'), ('e', 'a'), ('e', 'b'), ('e', 'c'), ('e', 'd'), ('e', 'f'), ('f', 'a'), ('f', 'b'), ('f', 'c'), ('f', 'd'), ('f', 'e')]