Using names.txt (right click and 'Save Link/Target As...'), 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 \(938\)th name in the list. So, COLIN would obtain a score of \(938 \times 53 = 49714\).
What is the total of all the name scores in the file?
There's a wealth of literature on sorting algorithms, and instead of reiterating it here, I'm just going to link to this GeeksforGeeks page that describes a bunch of them and includes a nice table comparing them. My solution just relies on Python's built-in sort function.
The more interesting part here, in my view, is the file loading and string manipulation. The file begins with the text "MARY","PATRICIA","LINDA","BARBARA"
and continues on like that for one very long line. First, I remove the opening quote of the first name and the closing quote of the last name; second, I split the string according to the separator ","
(including the quotes); third, I sort the new list of names; fourth, I find the score for each name, which can be done by comparing the ASCII value of each character to that of the character A
.
import urllib.request
def p22():
url = "https://projecteuler.net/resources/documents/0022_names.txt"
f = urllib.request.urlopen(url)
line = f.read().decode('utf-8')
f.close()
L = sorted(list(line[1:-1].split('","')))
res = 0
for i in range(len(L)):
score = sum(map(lambda c: ord(c) - ord('A') + 1, L[i]))
res += (i + 1) * score
return res