へたっぴpythonista

ド素人pythonistaとして、日々の学習成果や気づいたことについて書きます。

ProjectEuler22をpythonで解く

最近Rosalindばかり解いていて放置気味のEuler。パッと見て解けそうだったので久々に挑戦しました。

Problem22

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714.

What is the total of all the name scores in the file?

 

訳(PukiWiki様より)

5000個以上の名前が書かれている46Kのテキストファイル names.txt を用いる. まずアルファベット順にソートせよ.
のち, 各名前についてアルファベットに値を割り振り, リスト中の出現順の数と掛け合わせることで, 名前のスコアを計算する.
たとえば, リストがアルファベット順にソートされているとすると, COLINはリストの938番目にある. またCOLINは 3 + 15 + 12 + 9 + 14 = 53 という値を持つ. よってCOLINは 938 × 53 = 49714 というスコアを持つ.
ファイル中の全名前のスコアの合計を求めよ.

解答

names=sorted(open("C:/python33/names.txt").read().replace('"','').split(","))
s=0
for i in range(len(names)):

     a=0

     for j in range(len(names[i])):
           a +=int(ord(names[i][j]))-64
     s +=a*(i+1)
print(s)

ポイントは2つ

①テキストファイルをアルファベット順にソートされたリストに変換する。

  まずread()でテキストファイルを一つの文字列にまとめ、replace()で文字列から不要なダブルクォーテーションを取り除き、split()でカンマごとに区切ったリストに変換します。後はsorted()でリストをアルファベット順にソートします。(list.sort()はもう使われていないのでエラーになります)

②各文字を数値に変換する。

  ord()を使います。愚直にアルファベットと数値の対応表を作らない点で進歩したを感じました(笑)

  ord()は因数に指定した文字に対応するASCⅡコードを返す関数です。ord("A")=65なのでord(w)-64 (wはA~Z)は1~26に対応することになります。

  他にもord()を使ってアルファベット・数値対応表を先に作っちゃうという手もありますね。ord()便利です。

 

さて、以上を実行すれば答え871198282が得られます。