Python Implementation of Problem 42

View source code here on GitHub!

Includes

Problem Solution

Project Euler 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.

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?

python.src.p0042.main() int
 1"""
 2Project Euler Problem 42
 3
 4The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
 5
 61, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
 7
 8By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we
 9form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle
10number then we shall call the word a triangle word.
11
12Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common
13English words, how many are triangle words?
14"""
15from typing import Set
16
17from .lib.math import triangle
18from .lib.utils import get_data_file
19
20
21def main() -> int:
22    answer = 0
23    words = get_data_file('p0042_words.txt', 'rb').replace(b'"', b'').split(b',')
24    max_cached_idx: int = 0
25    max_cached: int = 0
26    cache: Set[int] = set()
27    for word in words:
28        n = sum(x - 0x40 for x in word)
29        while n > max_cached:
30            max_cached_idx += 1
31            max_cached = triangle(max_cached_idx)
32            cache.add(max_cached)
33        if n in cache:
34            answer += 1
35    return answer

Tags: triangle-number, figurate-number, word-problem, file-io