本题来自 Project Euler 第22题:https://projecteuler.net/problem=22
''' Project Euler: Problem 22: Names scores 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? Answer: 871198282 ''' lst = [] #姓名列表 for i in open("Files/p022_names.txt").readline().split(','): lst.append(i.strip('"')) lst.sort() nameScore = 0 for i in range(len(lst)): wordSum = 0 for j in range(len(lst[i])): wordSum += (ord(lst[i][j])-64) nameScore += (lst.index(lst[i])+1) * wordSum print(nameScore)
本题中,有个txt文件,内有5000个英文姓名,要求首先对这些姓名进行排序,然后分别计算各个姓名每个字母的序号之和a、以及该姓名在txt文件中的序号b,将a和b相乘,作为该姓名的分值。最后,将这5000个分值相加,得出结果。
本题涉及的知识点:
- data = open("xxxxx.txt"):可打开txt文件
- data.readline():可读取txt文件其中一行。本题只有一行,所以不需要逐行读取
- str.split(','):以逗号为分隔符,将字符串分割成若干单元
- str.strip('"'):将字符串前后的特定字符(此处为双引号)去掉
- ord('A'):返回单个字符A对应的ASCII码
- lst.index('COLIN'):返回COLIN在lst列表中的位置
思路则很简单:读取txt文件,将每个英文姓名剥离出来,放入lst列表。之后逐一将姓名中的每个单词转化为序号,相加得出wordSum,因为字母A对应的序号是1,ASCII码是65,所以用ord()转换为ASCII码之后应该减去64。接着获取姓名在lst列表中的位置,因为lst.index()获得的位置从0开始,而本题单词的序号从1开始,所以需要获取位置值之后再加1。把wordSum和该单词的序号相乘,可得该单词的nameScore。5000个单词遍历一下就可以了。