Euler Problem 22

Back to overview.

Using names.txt (saved as EulerProblem022.txt in the same directory as this notebook), 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?

Okay, this should be straight forward.

In [ ]:
with open('EulerProblem022.txt', 'r') as f:
    names = f.read().split(',')

def get_score_for_name(name):
    return sum([ord(c) - ord('A') + 1 for c in name if not c == '"'])

assert(get_score_for_name('COLIN') == 53)
names.sort()
s = sum([(i + 1) * get_score_for_name(name) for i, name in enumerate(names)])
assert(s == 871198282)
print(s)

I think nothing to explain here. The only question is what was if we hadn't the Python sort function to sort into alphabetical order, then we would have to write our own compare function and use it with what ever sorting algorithm.

In [19]:
def compare(a, b):
    try:
        for i in range(len(a)):
            if a[i] < b[i]:
                return '{} before {}'.format(a, b)
            elif a[i] > b[i]:
                return '{} before {}'.format(b, a)
    except IndexError:
        pass
    if len(a) < len(b):
        return '{} before {}'.format(a, b)
    elif len(a) > len(b):
        return '{} before {}'.format(b, a)
    else:
        return '{} is {}'.format(b, a)

print(compare('Felix', 'Arnold'))
print(compare('Felix', 'Felixb'))
print(compare('Felixb', 'Felix'))
print(compare('Felix', 'Felix'))
Arnold before Felix
Felix before Felixb
Felix before Felixb
Felix is Felix

Obviously, the algorithm would return True/False or 0/1/-1 for real sorting.