python - Project Euler: Sum varying by a significant margin -


i'm trying solve problem 22 on project euler...which follows:

**using names.txt (right click , 'save link/target as...'), 46k text file containing on five-thousand first names, begin sorting alphabetical order. working out alphabetical value each name, multiply value alphabetical position in list obtain name score.  example, when list sorted alphabetical order, colin, worth 3 + 15 + 12 + 9 + 14 = 53, 938th name in list. so, colin obtain score of 938 × 53 = 49714.  total of name scores in file?** 

here's code wrote solve problem:

f = open("f:\gnames.txt", "r") strr = f.read() w = strr.replace('"', "") li = w.split(',') dic = {} sum = 0 ee in li:     e in ee:         if (e == "a"):             sum+=1         elif (e == "b"):             sum+=2         elif (e == "c"):             sum+=3         elif (e == "d"):             sum+=4             elif (e == "e"):             sum+=5         elif (e == "f"):             sum+=6         elif (e == "g"):             sum+=7         elif (e == "h"):             sum+=8         elif (e == "i"):             sum+=9         elif (e == "j"):             sum+=10         elif (e == "k"):             sum+=11         elif (e == "l"):             sum+=12         elif (e == "m"):             sum+=13         elif (e == "n"):             sum+=14         elif (e == "o"):             sum+=15         elif (e == "p"):             sum+=16         elif (e == "q"):             sum+=17         elif (e == "r"):             sum+=18         elif (e == "s"):             sum+=19         elif (e == "t"):             sum+=20         elif (e == "u"):             sum+=21         elif (e == "v"):             sum+=22         elif (e == "w"):             sum+=23         elif (e == "x"):             sum+=24         elif (e == "y"):             sum+=25         else:             sum+=26     dic[ee] = sum     sum = 0 x = sorted(dic.items(), key=lambda t: t[1]) main_sum = 0 index = 0 c in x:     t = c[1]*index     main_sum = main_sum + t     index+=1 print main_sum     

the actual answer 871198282. however, code gives answer 995996966, off 124798684 compared actual answer. seems problem code?

i think issue in line x = sorted(dic.items(), key=lambda t: t[1]). sorts dictionary items scores, not alphabetically names. change t[1] t[0] in lambda , suspect you'll better result.

another possible issue (it's little ambiguous) indexing when go add scores. you're starting index @ zero, instructions suggest 938th name should multiplied 938, not zero-based index, 937. need start index = 1.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -