1
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 3 years have passed since last update.

【itertools.permutations】Pythonで順列を出す方法

Posted at

モチベーション

AtCoderの問題をやってて、"辞書順で何番目か"を出したい時、順列を求める必要があった。
例えば、a,b,c,d,eを使って単語を作るとする。
この時、

  • 辞書順に並べると、abcdeは何番目か⇨勿論1番前
  • じゃあdeabcは??⇨わからん

ってなったのでやり方を学んだので備忘録。

環境

  • Python : 3.7.5

やり方

itertoolsのpermutationsを使うとすごい簡単
以下のコードではa,b,c,d,eを使って単語を作り、"abcde","deabc"が何番目なのか確認してみる

Code


import itertools

abcde_list = ["a", "b", "c", "d", "e"]
A = list(itertools.permutations(abcde_list))
# →[('a', 'b', 'c', 'd', 'e'), ('a', 'b', 'c', 'e', 'd'), ('a', 'b', 'd', 'c', 'e'), ('a', 'b', 'd', 'e', 'c'), ('a', 'b', 'e', 'c', 'd'), ('a', 'b', 'e', 'd', 'c'), ('a', 'c', 'b', 'd', 'e').....

# tupleになってることに注意
abcde_tuple = ("a", "b", "c", "d", "e")
deabc_tuple = ("d", "e", "a", "b", "c")

abcde_num = (A.index(abcde_tuple))
# →0
deabc_num = (A.index(deabc_tuple))
# →90

indexは0から始まってるのに注意。

1
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
1
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?