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.
What is the sum of scores of all the names in the file given below?
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.
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 = 0for letter in name:if letter in alphabet:sum += alphabet.index(letter)+1return sumwith open("__ed_input.txt","r") as File:Data = sorted(File.readlines()[0].split(','))result=0for position,name in enumerate(Data):name_score = sumPosition(name) * (position+1)result += name_scoreprint(result)
Enter the input below to be saved in file __ed_input.txt
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
.