我正在努力在我的代碼中找到邏輯錯誤。所以我懇請您幫我找出問題所在。
使用 names.txt(右鍵單擊并“將鏈接/目標另存為...”),這是一個包含超過五千個名字的 46K 文本檔案,首先按字母順序對其進行排序。然后計算出每個名字的字母順序值,將該值乘以其在串列中的字母順序位置得到名稱分數。
例如,當串列按字母順序排序時,值 3 15 12 9 14 = 53 的 COLIN 是串列中的第 938 個名稱。因此,COLIN 將獲得 938 × 53 = 49714 的分數。
檔案中所有名稱分數的總和是多少?
謝謝大家指出我忽略的部分。已經編輯。它給我的答案是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'
uj5u.com熱心網友回復:
嘗試:
# 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
uj5u.com熱心網友回復:
“從按字母順序排序開始”您似乎沒有!
uj5u.com熱心網友回復:
我懷疑差異來自名稱的順序。在遍歷名稱之前,我看不到您將串列排序的位置。
uj5u.com熱心網友回復:
那么它只適用于排序陣列,因為單詞的索引在未排序的陣列中會有所不同,這會total_score出錯。
此外,在lines = str(lines).split(",")您的代碼行中, the 也str(lines)考慮 list 的括號 ie [],您通過添加if來檢查字串中的字母是否在字母字典中進行管理。現在沒有它if它會作業得更快。所以,你通過剝離它關閉的修改字串自身需要",[,,,]。
我想建議的另一個建議是,您可以使用f.read()將整個檔案作為字串讀取,這將更有幫助,因為您可以洗掉不需要的東西并單獨獲取名稱......像這樣
from string import ascii_uppercase as upper
total_score = 0
with open("names.txt") as f:
data = f.read().split(",") # Removes the comma, so as to get names along with quotes
L1 = sorted([_.strip('"') for _ in data]) # Removes the individual quotes and sorts the list as well
for i in L1:
letter_score = sum([upper.index(j) 1 for j in i]) # Sums up the index of individual letters in the words so as to get letter score
total_score = letter_score*(L1.index(i) 1)
print(total_score)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384564.html
