Euler: Names scores

Problem 22: Using names.txt, 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?

Thinking:
1. Read from the txt file to memory.
2. sort.
3. Traverse again and count each score.

Code:

filename = "p022_names.txt"

def score(word, num):
    count = 0
    for i in word:
        count += ord(i) - ord('A') + 1
    return num*count

f1 = file(filename)
line = f1.readline()
f1.close()
#print line
words = []
tmp = line.split(",")
for i in tmp:
    words.append(i.strip('"'))
#print len(words)
#print words[2]
words = sorted(words)
#print words[2]

num = 1
result = 0
for w in words:
    result += score(w, num)
    num += 1
print result
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章