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?
fr = open('name.txt', 'r')
line = fr.read()
nametolist = line.split(',')
def namescores(nametolist):
sum=0
total=0
for i in range(len(nametolist)):
nametolist[i] = nametolist[i][1:-1]
print(nametolist)
for i in range(len(nametolist)):
for j in range(len(nametolist[i])):
if nametolist[i][j] == 'A':
sum+=1
elif nametolist[i][j] == 'B':
sum+=2
elif nametolist[i][j] == 'C':
sum+=3
elif nametolist[i][j] == 'D':
sum+=4
elif nametolist[i][j] == 'E':
sum+=5
elif nametolist[i][j] == 'F':
sum+=6
elif nametolist[i][j] == 'G':
sum+=7
elif nametolist[i][j] == 'H':
sum+=8
elif nametolist[i][j] == 'I':
sum+=9
elif nametolist[i][j] == 'J':
sum+=10
elif nametolist[i][j] == 'K':
sum+=11
elif nametolist[i][j] == 'L':
sum+=12
elif nametolist[i][j] == 'M':
sum+=13
elif nametolist[i][j] == 'N':
sum+=14
elif nametolist[i][j] == 'O':
sum+=15
elif nametolist[i][j] == 'P':
sum+=16
elif nametolist[i][j] == 'Q':
sum+=17
elif nametolist[i][j] == 'R':
sum+=18
elif nametolist[i][j] == 'S':
sum+=19
elif nametolist[i][j] == 'T':
sum+=20
elif nametolist[i][j] == 'U':
sum+=21
elif nametolist[i][j] == 'V':
sum+=22
elif nametolist[i][j] == 'W':
sum+=23
elif nametolist[i][j] == 'X':
sum+=24
elif nametolist[i][j] == 'Y':
sum+=25
else:
sum+=26
total += sum*(i+1)
sum=0
你还没有把名字分类。有问题
因此,在计算之前使用
nametolist.sort()
可以解决您的问题。你知道吗但请考虑使用字典来进行字母分数映射,而不是26 if case,并且不要隐藏内置方法
sum
。像这样:
相关问题 更多 >
编程相关推荐