My solutions to the problems found at Project Euler.

Jump to: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 20 | 21 | 22 | 25 | 3-2 |

Problem 22


#! /usr/bin/python
# Problem: Load a text file containing names, sort it alphabetically, and find the
#          product of it's names weight (total of it's letters according to their sequence in the
#          alphabet (a=1 etc) and it's position in the list. Find the total of all the name scores
#          in the file.
#
# Plan: The file is only 46K, and that's nothing in this day in computing. Just load it into memory,
#       sort() it, and iterate over it to find our answer.
import string
if __name__ == "__main__":
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    f = open('22.txt','r')
    names = f.readlines()[0]
    
    names = string.replace(names, '"','')
    names = string.split(names,',')
    names.sort()
    
    total = 0
    for i in xrange(len(names)):
        subtotal = 0
        for s in names[i]:
            subtotal += alphabet.index(s)+1
            
        total += ((i+1) * subtotal)   
        
    print total
22.txt: view

jb