Algorithm
[Euler Project] Problem 22 using Python
햇망고
2021. 2. 3. 03:45
Euler Project 22번 문제는 5000개 이상의 이름들이 나열된 파일이 제공된다. 요구되는 값은 이름을 정렬한 후, 정렬 순위와 이름 값을 곱한 값을 모두 더한 것이다. 이름 값이란, 아래의 get_alphabet_score로 구현되어 있으며, a, b, c ... 순으로 1, 2, 3 점을 누적 부여한다.
예를 들어 COLIN = 3 + 15 + 12 + 9 + 14 = 53이다.
이후는 순차적으로 진행될 뿐 큰 문제가 없다.
"""
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?
"""
import pandas as pd
# data check
# print(chr(97))
# print(ord('C')-ord('A')+1)
# print(list('hello'))
# read txt file >> make list >> sort
data = list(pd.read_csv('p022_names.txt').columns)
data.sort()
# total_score
sum = 0
# get alphabetic score for each name
def get_alphabet_score(name):
assert type(name) == type('colin')
name_list = list(name)
score = 0
for alphabet in name_list:
score += (ord(alphabet)-ord('A')+1)
return score
if __name__ == '__main__':
for i, name in enumerate(data):
sum += (i+1)*get_alphabet_score(name)
print(sum)