Well for the last few weeks I've been hacking away with C++ whenever I get some free time which although interesting has been tedious, after all having to remember when you're passing pointers, references or values gets to be a pain real quick.
One of the really nice things with something like C++ though is memory management and speed when you get it right, you're working with natively compiled code and not having to wait for a garbage collector to clear up your allocations for you which makes for nice neat code. Of course like I said this is when you get it right, the downside is getting it wrong means memory leaks, stack overflows, variables pointing to garbage and so on which is troublesome to fix.
Today I got a little bored of all this so I figured it was time to put my Python hat back on and do some coding which was a little more interesting. So I took up one of the puzzles over at Project Euler (22 to be exact) which involves reading in a file of over 5000 names, sorting them alphabetically and then adding the numerical value of each name multiplies by it's position to an overall count and deducing what the total value of the names is. So where "COLIN" is at position 938 and it's numerical value is 53 (C=3, O=15 etc...) it's overall value is 49741.
I dread to think how to do this in C++ but in python it's a breeze thanks to it's list comprehension and easy file methods. So reading in the file is simply:
names_file = open("names.txt", "r")
names = names_file.read().replace('"', '').split(',')
And there we have the file being opened, the contents being read, having any quotes removed and then split by commas to get a list and finally the file being closed. Then to do something like figure out the numerical value of COLIN we do something like this:
alphas = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
name_value = sum([alphas.index[c] for c in "COLIN"])
so alphas is defining a string (with an intentional first space so that A is now at index 1), the alphas.index[c] part basically returns the index in the alphas string of a character and the "for c in "COLIN"" part is looping through each letter in the name. Surrounded by the square brackets means we are producing a list, so each iteration adds a new value to the list and then the sum() adds them all together. It's just to easy.
If anyone is interested, the finished code (not published here as I shall leave it as an exercise for the reader to complete) takes about 92 milliseconds to run against all 5163 names.