Use the 46K text file filenames.txt with over 5000 names. Sort alphabetically first.
After that, the score of the name is calculated by assigning a value to the alphabet for each name and multiplying it by the number in the order of appearance in the list.
For example, if the list is sorted alphabetically, COLIN is at the 938th position in the list, and COLIN has the value 3 + 15 + 12 + 9 + 14 = 53, so COLIN is 938 × 53 = 49714. Have a score.
Find the sum of the scores for all the names in the file. http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2022
Practice using the reduce function.
dict = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26}
def get_point(name,i):
#if name == 'COLIN':
# print reduce(lambda x,y:x+y, map(lambda x:dict[x], name)) * (i+1)
return reduce(lambda x,y:x+y, map(lambda x:dict[x], name)) * (i+1)
def main():
filename = "names.txt"
F = open(filename)
names = F.read()
namelist = map(lambda x: x.strip('"'), names.split(","))
namelist.sort()
ans = 0
lng = len(namelist)
for i in range(lng):
ans += get_point(namelist[i],i)
print ans
main()
Recommended Posts