Home > Programming > Project euler problem 22: Names scores

Project euler problem 22: Names scores

Problem 22

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?


Solution is for this problem is straight forward. I have used python for the ease of string operations.

def pyr():
    with open("names.txt", "r")as out:
        for i in out:
            apyr = i.split(',')
    apyr = sorted(apyr)
    gsum = 0
    for i in range(1, len(apyr) + 1):
        lsum = 0
        for j in range(0, len(apyr[i - 1])):
            lsum += (ord(apyr[i - 1][j]) - 64)
        gsum += lsum * i
    print gsum


Answer: 871198282

Time taken for the solution is:

real 0m0.160s
user 0m0.030s
sys 0m0.140s

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: