Project Euler 22, off by 18,609
Change this line:
names = sorted(str(string).split(","))
to:
names = sorted(string[0].split(','))
File contains just one line, so you need to access that line using string[0]
. file.readlines
returns a list containing all lines from the file, it's better to do something like:
names = f.read().split(',')
names.sort()
A shorter version of your program:
from string import ascii_uppercase
def score(word):
return sum(ascii_uppercase.index(c) + 1 for c in word.strip('"'))
with open('names.txt') as f:
names = f.read().split(',')
names.sort()
print sum(i*score(x) for i, x in enumerate(names, 1))
Note: string
is a built-in module, don't use it as a variable name