Project Euler Problem #22:

Problem #22 is yet another simple question that involves analyzing a large amount of data. The question reads:

Project Euler Problem 22: Names scores
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 x 53 = 49714.

What is the total of all the name scores in the file?

We’ve seen just about every part of this problem in earlier problems (with the exception of calculating the position of a letter in the alphabet which can be done with ordinals). Here’s my solution:

Solution #1: Brute Force Approach

We begin by storing the names in a file that our script can read from. I stored the names in a file called “PE22Names.txt”. Then we store the names in an array, sort the array, and add up the value of every name in the list. Here is my solution:

 '''
 Author: Walker Kroubalkian
 Brute Force Approach to Project Euler Problem #22
 '''

 import time

 f = open("PE22Names.txt","r")

 if(f.mode == "r"):
     contents = f.readlines()
     realContents = []
     for x in contents:
         realContents.append(x.split(","))
 else:
     raise ValueError("Cannot read from file")

 finalList = realContents[0]

 def getValueString(myString):
     total = 0
     for x in myString:
         if("A"<=x<="Z"):
             total+=(ord(x)-ord("A")+1)
     return total

 def projectEulerProblemTwentyTwo(nameList):
     nameList = sorted(nameList)
     total = 0
     numberNames = len(nameList)
     for i in range(numberNames):
         total+=(i+1)*getValueString(nameList[i])
     return total

 start = time.time()
 print projectEulerProblemTwentyTwo(finalList)
 print ("--- %s seconds ---" % (time.time()-start))

 '''
 Prints

 871198282
 --- 0.00785303115845 seconds ---

 for input of given list of names
 '''

Unfortunately, this is yet another boring question near the start of Project Euler. Hopefully we get to some more interesting problems soon.

Thanks for reading!

Published by Walker Kroubalkian

My name is Walker Kroubalkian. I really enjoy math, computer science, and hiking.

Leave a comment

Design a site like this with WordPress.com
Get started