0
1

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.

全パターン網羅する方法2(順番が異なるものを別のものとして数える場合)

Posted at

「前回の記事(全パターン網羅する方法)」では、
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')]
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?