为什么我的总数减少了324536?

2024-09-27 07:22:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python做问题22,但我的答案是关闭的。我浏览了一下名单,试过了一些名字,而且计算得很正确(我想)。在

有人能帮忙吗??在

问题:

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.

档案里所有的名字分数总和是多少?在

def letter_sum(word):
    total = 0
    for letter in word:
        total += ord(letter) - ord('A') + 1
    return total

def namescore(name, count):
    name_sum = letter_sum(name)
    return count * name_sum

def main():
    names = []
    f = open('p022_names.txt', 'r')
    string = f.read()
    f.close()

    total = 0
    names = sorted(string.replace('"', '').split(','))
    for i in range(len(names)):
        total += namescore(names[i], i)

    print total

Tags: thenameintxtforbynamesis
2条回答

只差一个错误。在准则中:

for i in range(len(names)):
    total += namescore(names[i], i)

i0开始,而名称应该从1开始计数,请改用namescore(names[i], i + 1)。在

你的索引被调低了一个。'COLIN'位于基于0的索引上的索引937,但赋值使用基于1的索引。您可以通过稍微更改代码来解决此问题:

total += namescore(names[i], i + 1)

相关问题 更多 >

    热门问题