Python Implementation of Problem 22
View source code here on GitHub!
Includes
Problem Solution
Project Euler Problem 22
I had to approach this by modifying the factors function from p0003, but it seemed to work fairly well.
Problem:
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
1"""
2Project Euler Problem 22
3
4I had to approach this by modifying the factors function from p0003, but it
5seemed to work fairly well.
6
7Problem:
8
9Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
10containing over five-thousand first names, begin by sorting it into
11alphabetical order. Then working out the alphabetical value for each name,
12multiply this value by its alphabetical position in the list to obtain a name
13score.
14
15For example, when the list is sorted into alphabetical order, COLIN, which is
16worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
17obtain a score of 938 × 53 = 49714.
18
19What is the total of all the name scores in the file?
20"""
21from .lib.utils import get_data_file
22
23
24def score(name: str, idx: int) -> int:
25 return sum(ord(x) & 0x3F for x in name) * idx
26
27
28def main() -> int:
29 names = sorted(get_data_file('p0022_names.txt').upper().replace('"', '').split(','))
30 return sum(score(name, idx) for idx, name in enumerate(names, 1))