princeofsudan

Project Euler#22 Names scores

Mar 13th, 2013
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. #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.
  2.  
  3. #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.
  4.  
  5. #What is the total of all the name scores in the file?
  6.  
  7. namesHandle = open('names.txt','r')
  8. namesString = namesHandle.readline()
  9. namesHandle.close()
  10. namesListTemp = namesString.split(',')
  11. namesList = []
  12.  
  13. for i in namesListTemp:
  14.     namesList.append(i.strip('"'))
  15.  
  16. def selSort(L):
  17.     for i in range(len(L) - 1):
  18.         minIndx = i
  19.         minVal= L[i]
  20.         j = i + 1
  21.         while j < len(L):
  22.             if minVal > L[j]:
  23.                 minIndx = j
  24.                 minVal= L[j]
  25.             j += 1
  26.         temp = L[i]
  27.         L[i] = L[minIndx]
  28.         L[minIndx] = temp
  29.  
  30. selSort(namesList)
  31.  
  32. alpha = {'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11\
  33.          ,'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,'R':18,'S':19,'T':20,'U':21\
  34.          ,'V':22,'W':23,'X':24,'Y':25,'Z':26}
  35.  
  36. count = 0
  37. for i in range(len(namesList)):
  38.     subCount = 0
  39.     for j in namesList[i]:
  40.         subCount += alpha[j]
  41.     count += (subCount*(i+1))
  42.  
  43. print count
Advertisement
Add Comment
Please, Sign In to add comment