## Posts Tagged ‘prob22’

### Problem 22

July 19, 2009

Just got back from dinner, depressed because a friend wanted to have a conversation about politics and things. Finally decided maybe some programming would pull me out of it. I’m not convinced it did, but whatever. It had the best shot of doing so.

In Problem 22 we’re supposed to read in a file, pull out the words between quotes, sort them, do some computation on each string to convert it to an int, and then take the sum of all of those words times their index in the list. I thought I’d see how little actual work I could do, which seems to translate to using lots of maps and lambda functions and such.

After a “from __future__ import with_statement”, it’s pretty easy to read in files:

```def readfile(filename):
ret = []
with open(filename) as file:
for line in file:
ret += line.split(",")
return ret
```

The given file has all of the names on one line, so the loop doesn’t last long. Next up, convert that list to a bunch of numbers, and sum them up, with an appropriate product:

```def process(names):
names.sort()
scores = map(lambda s:sum(map(lambda x:string.ascii_uppercase.index(x)+1,s[1:-1].upper())), names)
return sum([(i+1)*n for i,n in enumerate(scores)])
```

Perhaps some explanation is in order here. The first line, sort(), is pretty clear, I hope. In the next line, s[1:-1] strips the quote marks off of the name, and then the call to upper() converts all the characters to uppercase. This is probably superfluous, because the names all seem to be in uppercase to begin with, but better safe than sorry. Then I use the ascii_uppercase string provided by the string module, as documented here. This lets me easily convert letters to their position in the alphabet (remembering to add one because indices in strings start at 0). So my “scores” list above contains what the problem instructions call the “alphanumeric value” of each of the names. In the last line, I use the enumerate function (some documentation) to give me pairs: (index, value) in the list of scores (remembering, again, to add one to the index).

So that was fun.