Published: March 5, 2024

Project Euler

Problem 22 - Names Scores

Problem

This problem comes from Project Euler 22

Problem

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 = 49 714.

What is the total of all the name scores in the file?

Code

# Project Euler: Problem 22
# Names scores

# Read file
with open('names.txt') as file:
    names = file.read()

# Turn names into a alphabetical list
names = sorted(names.replace('"', "").split(","))

# Calculate Scores
total_score = 0
chart = "_ABCDEFGHIJKLMNOPQRSTUVWXYZ"

for index, name in enumerate(names):
    score = 0
    for letter in name:
        score += chart.index(letter)

    total_score += score*(index+1)

print(total_score)

Solution

A fairly straightforward solution

  1. The file names.txt is opened and read
  2. The data is cleaned up, turned into a list that can be used, and sorted
  3. chart is a string which is iterable. We use the index of the string as the points amount (the underscore uses index 0 so that “A” has an index/score of 1)
  4. We loop over the names using enumerate, which allows us to access the index of the for loop
  5. Calculate the scores. The process should be fairly clear in the code