Advertisement
rdrewd

problem22.py

Mar 31st, 2013
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. """
  2. Project Euler Project 22.
  3.    ParseInput: get the list of names provided into a Python list.
  4.    Sort input list into alpha order
  5.    Iterate through the list totaling up the weighted score for each name.
  6.        NameScore - given a name, compute its score (A=1, B=2, C=3...)
  7.            NameScore is the sum of the value of the letters in the name
  8. """
  9.  
  10. def ParseInput(filename):
  11.     # from pyparsing import (delimitedList, QuotedString, dblQuotedString,
  12.     #    Token, ParserElement)
  13.     from pyparsing import (delimitedList, QuotedString)
  14.     # qs=QuotedString('"')
  15.     # print "type(qs)", type(qs)
  16.     # if isinstance(qs, ParserElement):
  17.     #    print "qs is an instance of a ParserElement"
  18.     # else:
  19.     #    print "qs is not an instance of a ParserElement"
  20.     grammar=delimitedList(QuotedString('"'))
  21.     return(list(grammar.parseFile(filename, parseAll=True)))
  22.  
  23. def nameScore(name, valuedict):
  24.     total=0
  25.     for c in list(name):
  26.         total += valuedict[c]
  27.     return total
  28.  
  29. def main():
  30.     nameList=ParseInput("problem22.txt")
  31.     # print nameList   # test-it
  32.     # for name in nameList:
  33.     #     print name
  34.     # print "** Sorting **"
  35.     # print "type(nameList)", type(nameList)
  36.     nameList.sort()
  37.     # print "** Sorted name list **:"
  38.     # i=0
  39.     # for name in nameList:
  40.     #    print name
  41.     #    if i+1 >= len(nameList):
  42.     #        break
  43.     #    if nameList[i] > nameList[i+1]:
  44.     #        print "**Above name is not in the right place**"
  45.     #    i+=1
  46.     valuedict=dict()
  47.     i=1
  48.     for c in list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ."):
  49.         valuedict[c]=i
  50.         i+=1
  51.     #for c in list("ABCabcXYZxyz."): #test-it
  52.     #    print c, valuedict[c]
  53.     i=1
  54.     total=0
  55.     for name in nameList:
  56.         total+=i*nameScore(name, valuedict)
  57.         # print name, i, nameScore(name, valuedict) # test-it
  58.         i+=1
  59.     return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement