Problem

The $n^\text{th}$ term of the sequence of triangle numbers is given by, $t_n=\frac{1}{2}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 = $t_{10}$. 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?

Solution in Python

#!/usr/bin/python
 
import time
 
# start the clock
start = time.time()
 
# turn the string of words into a list of python strings
with open('words.txt','r') as f:
    words = f.read().split(',')
    words = [list(word.strip('\"')) for word in words]
    f.close()
 
# we should have an idea of how long the longest word is,
# giving us an idea of the magnitude of the triangle words
m = max([len(word) for word in words])
# form triangle numbers up to the given range
triangles = [n*(n + 1)/2 for n in range(1,2*m)]
 
# make a dictionary map for character values
vals = {}
s = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
for c in s:
    vals[c] = s.index(c) + 1
 
# count triangle words
triangle_words = 0
for word in words:
    if sum([vals[c] for c in word]) in triangles:
        triangle_words += 1
 
# terminate the clock
elapsed = time.time() - start
 
print "found %s triangle words in %s seconds" % (triangle_words, elapsed)

When executed, this returns as follows.

found 162 triangle words in 0.00315809249878 seconds

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">