I'm struggling to find the logical error in my code. So I'm kindly asking you to help me find the problem.
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?
Thank all of you for pointing out to the part overlooked by me. Already edited. The answer it gives me is 871179673, whereas the correct answer is 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'