Created With

linkProblem 42 - Coded Triangle Numbers

linkQuestion

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

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?

linkSolution

euler_042.py
1linkimport string

2link

3linkdef is_triangular(x):

4link if (((8*x) + 1)**0.5) % 1 == 0:

5link return True

6link else:

7link return False

8link

9linkdef word_to_number(word):

10link alphabet = list(string.ascii_lowercase)

11link

12link sum_of_positions = 0

13link for w in word:

14link position = alphabet.index(w.lower()) + 1

15link sum_of_positions += position

16link

17link return sum_of_positions

18link

19linkwith open("p042_words.txt", 'r') as f:

20link words = f.read().replace('"', '')

21link

22linktriangle_count = 0

23linkfor w in words.split(","):

24link value = word_to_number(w)

25link if is_triangular(value):

26link triangle_count += 1

linkDiscussion

linkAnswer

Show Answerchevron_right

162

Problem 42 - Coded Triangle NumbersQuestionSolutionDiscussionAnswer

Home

Project Eulerchevron_right
Essayschevron_right

Awesome Stuff