gpt4 book ai didi

python - 欧拉计划 #22 名称分数 - Python

转载 作者:行者123 更新时间:2023-12-02 18:24:45 25 4
gpt4 key购买 nike

我正在努力寻找代码中的逻辑错误。所以恳请您帮我找出问题所在。

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?

感谢大家指出我忽略的部分。已经编辑了。它给我的答案是871179673,而正确答案是871198282

import string

alphabet = string.ascii_uppercase
alpha_d = {}
letter_score, total_score = 0, 0


for ind, let in enumerate(alphabet, start=1): # Assigning all letters and their indexes to the dictionary
alpha_d[let] = ind


with open("name.txt", 'r') as f:
lines = f.readlines()
lines = str(lines).split(",") # Opening the file and assigning the string to "lines"
lines = sorted(lines)


for index, line in enumerate(lines, start=1): # This 'for' goes through all the names
line = line.upper()
letter_score = 0

for letter in list(line): # This 'for' goes through the letter in the name
if letter in alpha_d:
letter_score += alpha_d[letter] # If the letter is in the dictionary, it's score will be added

total_score += (letter_score * index) # The final score will be added to 'total score'

最佳答案

尝试:

# read your file and sort it
lines = sorted(eval(open('names.txt').read()))

total_score = 0
for index, line in enumerate(lines, start=1):
total_score += index * sum(ord(c) - 64 for c in line)

# Alternative with alphabet
total_score = 0
for index, line in enumerate(lines, start=1):
total_score += index * sum(alphabet.index(c)+1 for c in line)

输出:

>>> total_score
871198282

没有排序文件,total_score 为 850081394。

来源:https://projecteuler.net/project/resources/p022_names.txt

关于python - 欧拉计划 #22 名称分数 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70386390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com