Related Tags

sorting
communitycreator
namescores

# Project Euler 22

Armaan Nougai

### Name scores

There are more than 5000 names in the file given below.

The score of a name is calculated as the sum of the position of each letter in the name in the English alphabet multiplied by the position of the name in the sorted list of names.

### Problem statement

What is the sum of scores of all the names in the file given below?

names_file.txt

### Analysis

The names_file is a text file with comma-separated names in double quotes. All the names are in upper case. For example, “MARY”.

The sorting should be done lexicographically.

To understand this better, let’s look at the figure given below.

Lexicographical order example

### Code

We will implement the solution to the problem above using Python. Click the “Run” button to see how the code works.

def sumPosition(name):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sum = 0
for letter in name:
if letter in alphabet:
sum += alphabet.index(letter)+1

return sum

with open("__ed_input.txt","r") as File:

result=0
for position,name in enumerate(Data):

name_score = sumPosition(name) * (position+1)
result += name_score

print(result)



Enter the input below to be saved in file __ed_input.txt

### Explanation

• Line 11: We take the names_file as input and store it in a list or a vector.

• Line 12: We sort this list lexicographically.

• Lines 15–18: We run a for loop over names in this list, and for each name, we calculate name_score.

• Line 18: We add this name_score to the main result, which is the sum of name scores of all words in the list.

RELATED TAGS

sorting
communitycreator
namescores

CONTRIBUTOR

Armaan Nougai
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 