Euler: Names scores

来源:互联网 发布:网络配音软件 编辑:程序博客网 时间:2024/06/06 11:03

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*countf1 = file(filename)line = f1.readline()f1.close()#print linewords = []tmp = line.split(",")for i in tmp:    words.append(i.strip('"'))#print len(words)#print words[2]words = sorted(words)#print words[2]num = 1result = 0for w in words:    result += score(w, num)    num += 1print result
0 0
原创粉丝点击