Project Euler Problem 22: Names Scores¶
The source code for this problem can be found here.
Problem Statement¶
Using names.txt (right click and ‘Save Link/Target As…’), a \(46\) KB 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 \(938^{th}\) name in the list. So, COLIN
would obtain a score of
\(938 \times 53 = 49714\).
What is the total of all the name scores in the file?
Solution Discussion¶
Nothing clever is needed or used here. Simply load the name, sort them, and compute the required score.
Solution Implementation¶
from lib.util import load_dataset
def score(name: str) -> int:
""" Compute the numeric score of `name` by summing the individual letter scores
The letter scores are defined as:
.. math::
A & \\rightarrow 1 \\\\
B & \\rightarrow 2 \\\\
& \\dots \\\\
Z & \\rightarrow 26
:param name: the name to score
:return: the score of `name`
>>> score("COLIN")
53 # 3 + 15 + 12 + 9 + 14
"""
scores = {chr(i): i - ord('A') + 1 for i in range(ord('A'), ord('Z') + 1)}
return sum([scores[character] for character in name])
def solve():
""" Compute the answer to Project Euler's problem #22 """
names = load_dataset("problems", "p022_names", separator=",")
names = [name.strip("\"") for name in names] # strip quotes off each name
names.sort() # ascending lexicographical order
answer = 0
for pos, name in enumerate(names):
answer += (pos + 1) * score(name) # one-base the positions within the sorted list
return answer
expected_answer = 871198282
-
solutions.problem22.
score
(name)¶ Compute the numeric score of name by summing the individual letter scores
The letter scores are defined as:
\[\begin{split}A & \rightarrow 1 \\ B & \rightarrow 2 \\ & \dots \\ Z & \rightarrow 26\end{split}\]Parameters: name ( str
) – the name to scoreReturn type: int
Returns: the score of name >>> score("COLIN") 53 # 3 + 15 + 12 + 9 + 14
-
solutions.problem22.
solve
()¶ Compute the answer to Project Euler’s problem #22