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?
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 = 0 for letter in name: if letter in alphabet: sum += alphabet.index(letter)+1 return sum with open("__ed_input.txt","r") as File: Data = sorted(File.readlines().split(',')) 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
Line 11: We take the
names_file as input and store it in a
list or a
Line 12: We sort this
Lines 15–18: We run a
for loop over names in this list, and for each name, we calculate
Line 18: We add this
name_score to the main
result, which is the sum of name scores of all words in the
View all Courses