When I was doing AtCoder problem and wanted to get the "number in dictionary order", I had to find the permutation. For example, suppose you make a word using a, b, c, d, e. This time,
I learned how to do it, so I made a memorandum.
Very easy with itertools permutations In the code below, create a word using a, b, c, d, e and check what number "abcde", "deabc" is.
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').....
#Note that it is a 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
Note that *** index starts from 0. *** ***
Recommended Posts