Project Euler Problem 22
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, b
Solution
Answer: 871198282
We must:
- Read the list of names.
- Sort them alphabetically.
- For each name:
- Compute its alphabetical value (
A=1, B=2, ..., Z=26) - Multiply by its 1-based position in the sorted list.
- Sum all scores.
For example:
COLIN- Value =
3+15+12+9+14 = 53 - Position =
938 - Score =
938 × 53 = 49714
The computation is straightforward once the file is parsed correctly.
Python code:
from string import ascii_uppercase
# Build letter values
value = {c: i + 1 for i, c in enumerate(ascii_uppercase)}
# Read and parse names
with open("0022_names.txt") as f:
names = f.read().replace('"', '').split(',')
# Sort alphabetically
names.sort()
# Compute total score
total = 0
for i, name in enumerate(names, start=1):
name_value = sum(value[ch] for ch in name)
total += i * name_value
print(total)
Tracing the logic:
- The file contains 5163 names.
- Sorting matches the Project Euler specification.
- Each score is computed exactly once.
- Summing all scores yields the known correct Project Euler result.
Answer: 871198282