へたっぴpythonista

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

ProjectEuler42 をpythonで解く

最近ご無沙汰だったProjectEuler。なんとなく解けそうだったので挑戦してみました。

 

Problem42

The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.

Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?

 

(適当な)訳

1からnまでの自然数の和を三角数といい、tn=n(n+1)/2で表す。今、ある英単語に含まれる各文字のアルファベット順での位置を数値とし、その和を単語の数値と呼ぶことにする。例えばSKYという単語はS=19、K=11、Y=25となるから単語の数値は55となる。

word.txtに含まれる単語のうち単語の数値が三角数であるもの(三角単語)の個数を求めよ。

 

解答

alphabet=[chr(i) for i in range(65,65+26)]
input=open("C:/python/words.txt")

read=str(input.read())

word=read.split('","')

 

def word_to_sum(word):
      sum=0
      for i in word:
           for j in range(26):
                if i ==alphabet[j]:
                sum += j+1
      return sum

def find_tri_num(num):
      boolean=False
      for i in range(1,100):
           if i*(i+1)/2==num:
                boolean=True
      return boolean

List=
for i in word:
      List.append(word_to_sum(i))
tri_num=

for i in List:
      if find_tri_num(i):
           tri_num.append(i)
print(len(tri_num))

 

 本当はreadline()で一気にリストが作れたらよかったんですが、words.txtが一行のテキストオブジェクトであるために上手くいかず断念。結局、一度文字列に変換してからsplit()を用いてリストに再変換することにしました。

word_to_num()では代入された文字列の各文字をアルファベットリスト内で探し、そのインデックス値を基に単語の数値を作成します。

find_tri_num()では代入された数値が三角数か否かを判定します。今回は1≦n≦100で判定しました。

len()でリストの長さを得れば完成で、答え162を得られます。