I programmed Problem #22 from Project Euler in Python. It works but I want to know if it really is pythonic enough.
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?
from itertools import count FILE = "e022.txt" CHAR_OFFSET = ord('A') - 1 def parse(file): """Return the read in list""" with open(file) as fid: return fid.read().replace('"',"").split(',') def score_name(name): """Returns the score of a single name""" return sum(ord(char) - CHAR_OFFSET for char in list(name)) def score_names(names): """Returns the score of the list""" return sum(ind*score_name(name) for (ind, name) in zip(count(1),sorted(names))) if __name__ == "__main__": print(score_names(parse(FILE)))
Please feel free to critic me on it. One thing I wasn't sure about: In the file parser, did I need to make the
with guard or is this not needed when encapsulated in a function?
Furthermore, the global variable
FILE is in a place where it is easy accessible, but let's say we would import it as a module and wouldn't need it. Should I move it down to the
main guard and loose a bit of overview?