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 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
In [1]:
# !wget http://projecteuler.net/project/names.txt
In [2]:
import csv
In [3]:
def foo(path):
score = 0
with open(path) as file:
for row in csv.reader(file):
for i, name in (enumerate(sorted(row), 1)):
score += i * sum((ord(c) - ord('A') + 1 for c in name))
return score
In [4]:
%timeit foo('names.txt')
foo('names.txt')
Out[4]:
In [5]:
[(x, y) for x in range(2) for y in range(3)]
Out[5]:
Try again with mondo list comprehension.
In [6]:
def foo(path):
with open(path) as file:
return sum([i * sum((ord(c) - ord('A') + 1 for c in name))
for row in csv.reader(file)
for i, name in (enumerate(sorted(row), 1))])
In [7]:
%timeit foo('names.txt')
foo('names.txt')
Out[7]:
Try again with mondo generator expression. This was slower.
In [8]:
def foo(path):
with open(path) as file:
return sum((i * sum((ord(c) - ord('A') + 1 for c in name))
for row in csv.reader(file)
for i, name in (enumerate(sorted(row), 1))))
In [9]:
%timeit foo('names.txt')
foo('names.txt')
Out[9]: