The nth term of the sequence of triangle numbers is given by, \$t_n = \frac{n(n+1)}{2}\$; 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 = t_{10}\$. If the word value is a triangle number then we shall call the word a triangle word.

Using words.txt, a 16K text file containing nearly two-thousand common English words, how many are triangle words?

Awaiting feedback.

import string

def check_triangles(filename):
    """returns triangle words."""
    letter_scores = {letter: score for score, letter in enumerate(string.ascii_lowercase, 1)}
    words = open(filename, 'r').read()
    words = words.lower().split("\",")
    temp = []
    for word in words:
        temp.append(word.replace("\"", ''))
    word_scores = {word: sum(letter_scores[letter] for letter in word) for word in temp}
    maximum = max(word_scores.values())
    start_triangle = 2
    triangles = [1]
    while max(triangles) < maximum:
        triangles.append(triangles[-1] + start_triangle)
        start_triangle += 1
    return ((word, score) for word, score in word_scores.items() if score in triangles)

if __name__ == '__main__':

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy