Problem 42

Problem 42

https://projecteuler.net/problem=42

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.

讲单词中的字母转换为字母表中的位置(如:A=1),将它们相加。如果得到的数字是一个三教数,则这个单词为三角单词。

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?

找找这两千多个英语常用词中有多少个三角单词?

filename = 'p042_words.txt'
with open(filename) as f:
    data = f.read()

words = data.split(',')
for i in range(len(words)):
    words[i] = words[i][1:-1]

triangle_nums = [i * (i + 1) // 2 for i in range(1, 100)]
triangle_words = []
alphabet = [chr(i) for i in range(65, 65 + 26)]
word_value = 0
count = 0
for word in words:
    for letter in word:
        word_value += alphabet.index(letter) + 1
    if word_value in triangle_nums:
        triangle_words.append(word)
        count += 1
        word_value = 0
    else:
        word_value = 0

print(triangle_words)
print(count)
Resistance is Futile!
原文地址:https://www.cnblogs.com/noonjuan/p/11031205.html