Project Euler Solution 22: Names scores

Problem 21: Names scores is one where one doesn't need mathematical insight and implement some parsing and string manipulation.

Using names.txt, 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?

The names are contained in double quotes and comma separated, so they are like JSON but without the square brackets. We use the JSON module to parse the file easily. Then we build the scores for each letter by just subtracting the keycode of "A" from each letter (and adding 1). We then sum up the scores of each letter. And finally we take the row numbers and scores, multiply those, and add everything together.

def solution() -> int:
    with open("data/p022_names.txt") as f:
        names = json.loads(f"[{f.read()}]")
    names.sort()
    scores = [sum(map(lambda c: ord(c) - ord("A") + 1, name)) for name in names]
    return sum(row * score for row, score in enumerate(scores, 1))

This was pretty easy in Python because we could parse it with two lines, sort with another one. The computation of the scores was just another line, albeit a complicated one. In C this would have been much harder with the string manipulations, for instance.