Project Euler – Problem # 22 – Solved with Python

The hardest part about this problem was reading the file (names.txt) into the program for proper file manipulation.

Problem:

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?

One Possible Solution:

f = open('names.txt', 'rU')
names = []

names = sorted(f.read().replace('"', '').split(','), key=str)

letv = {'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10, \
        'K':11,'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,'R':18,'S':19, \
        'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26}

def letter_counter(letter):
    """Letter counter"""
    lc = letv[letter]
    return lc
   
def main():
    """Main program"""
    x = len(names)
    z = 0
    for i in range(0,(x)):
        x2 = 0
        y = 0
        for letter in names[i]:
            x1 = letter_counter(letter)
            x2 = x2 + x1
        y = x2 * (i + 1)
        z = z + y
    print "z = ", z
            
if __name__ == '__main__':
    main()
Advertisements

2 Comments

  1. sir,
    Firstly I liked the way you have written Line 4. This is really awesome.

    Next I think you should have used ord function instead of writing a dictionary. This will improve your speed.
    Also instead of calling the letter_counter function each and every time for a letter it would have been better if you have written a function for a word and have returned the value of the word directly.
    I have written a program for this problem and it is running in around 0.00949501991272 seconds.

    I will be delighted if you will review my code and point any mistakes if any or any improvements needed so that it will help the community.

    Code: Github Gist pep22.py

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s