0
0

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.

python 文字列を並び替えて列挙し、リストにする(競プロ用)

Last updated at Posted at 2021-11-17

入力された文字列を並び替えてリストにする(昇順)

import itertools

s = input()
words = ["".join(i) for i in itertools.permutations(s)]
words.sort()
print(words)

出力 ('abcd'を入力した場合)

['abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba', 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba']

入力された文字列を並び替えてリストにする(降順)

import itertools

s = input()
words = ["".join(i) for i in itertools.permutations(s)]
words.sort(reverse=True)
print(words)

出力 ('abcd'を入力した場合)

['dcba', 'dcab', 'dbca', 'dbac', 'dacb', 'dabc', 'cdba', 'cdab', 'cbda', 'cbad', 'cadb', 'cabd', 'bdca', 'bdac', 'bcda', 'bcad', 'badc', 'bacd', 'adcb', 'adbc', 'acdb', 'acbd', 'abdc', 'abcd']

参考資料

python公式ドキュメント(itertools.permutations)

0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?