LoginSignup
0
0

More than 1 year has passed since last update.

【Project Euler】Problem 24: 辞書式順列

Posted at
  • 本記事はProjectEulerの「100番以下の問題の説明は記載可能」という規定に基づいて回答のヒントが書かれていますので、自分である程度考えてみてから読まれることをお勧めします。

問題 24. 辞書式順列

原文 Problem 24: Lexicographic permutations

問題の要約:0123456789を並べ替えたものを辞書式順列にしたとき$10^6$番目を求めよ

安易ですが、itertoolsのpermutationは「 iterable に応じた辞書式順序で出力されます」とのことなのでそのまま使えます。一応"012"で確認します。

import itertools
for n, perm in enumerate(itertools.permutations("012"),1): 
  print(f"{n}: {''.join(perm)}")
#1: 012
#2: 021
#3: 102
#4: 120
#5: 201
#6: 210

確認できたので、$10^6$番目の値を出力します。

import itertools
for n, perm in enumerate(itertools.permutations("0123456789"),1): 
  if n >= 10**6:
    break

print(f"Answer : {''.join(perm)}")

(開発環境:Google Colab)

0
0
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
0