Problem 22: Names Scores
Using names.txt, 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?
def get_names():
"""Returns names from file as list."""
# Import names, delimited by comma
with open('names.txt') as f:
data = f.read().split(',')
# Remove " from around names, they are unnecessary here
for i in range(len(data)):
data[i] = data[i].replace('"', '')
return data
def alpha_score(s):
"""Returns alphabetical 'score' of string."""
score = 0
for i in s:
# If character is between A and Z inclusive,
if 'A' <= i <= 'Z':
# Add the distance from A to letter to the score.
# +1 since A itself should be 1
score += ord(i) - ord('A') + 1
return score
def main():
# Sort names ascending
names = sorted(get_names())
t = 0
for i in range(len(names)):
# Go through and multiply each name's score by its index + 1
t += alpha_score(names[i]) * (i+1)
print(t)
main()
Click to reveal output
871198282