[root@www ~]# python twentytwo.py
871198282
Started at: Wed Sep 17 10:00:57 2008 Ended at: Wed Sep 17 10:00:57 2008
[root@www ~]# cat twentytwo.py
# -*- coding: utf-8 -*-
"""
<+ MODULE_NAME +>
Project Euler Problem Set
<+ DESCRIPTION +>
Solutions in Python to the problems at http://projecteuler.net
Licensed under the Creative Commons license; see http://creativecommons.org for more details. In short, this means you can freely reuse, modify and distribute this program, also commercially, for as long you provide a proper attribution.
Copyright by Jonathan Mark, jonathanmark.com/aristede.com, jmark@aristede.com
>>> print 881 + 1
882
"""
import time
starttime = time.asctime()
class Namescore:
"""A class for solving problem 22 in Project Euler"""
def __init__(self, filename):
"""Reads names from file
"""
f=open(filename, 'r')
self.sL = eval("[" + f.read() + "]")
def length(self):
"""returns number of names
>>> name = Namescore('names.txt')
>>> name.length()
5163
"""
return len(self.sL)
def first(self):
"""return first name in file
>>> name = Namescore('names.txt')
>>> name.first()
'MARY'
"""
return self.sL[0]
def last(self):
"""return last name in file
>>> name = Namescore('names.txt')
>>> name.last()
'ALONSO'
"""
return self.sL[len(self.sL) - 1]
def alphabetical_score(self,name):
"""assigns a score of 1 to 26 for each letter a-z
and uses these scores to sum the letters in a name.
>>> name = Namescore('names.txt')
>>> name.alphabetical_score('COLIN')
53
>>> name = Namescore('names.txt')
>>> name.alphabetical_score('abcdefgHiJklmnopqrstuvwxyz')
351
"""
name = name.lower()
lookup = {'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 }
total = 0
for i in range(len(name)):
total += lookup[name[i]]
return total
totalVal = 0
name = Namescore('names.txt')
name.sL.sort()
nameVal = map(name.alphabetical_score, name.sL)
for n in range(len(nameVal)):
totalVal += (n+1) * nameVal[n]
print totalVal
print "Started at: ", starttime, " Ended at: ",time.asctime()
if __name__ == "__main__":
import doctest
doctest.testmod()
Wednesday, September 17, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment