programming puzzles?

Michael Tobis mtobis at gmail.com
Sat Apr 8 20:43:33 EDT 2006


The first piece of code that I ever voluntarily wrote was intended to
solve this puzzle:

Assign the number 2 to 'a', 3 to 'b' ... 27 to 'z'. To each word assign
the value of the product of its characters. Find the English (or
language of your choice) word whose product is closest to a million (or
number of your choice).

I didn't have a lexicon handy. So I just printed out the letter
combinations closest to a million and manually played Jumble with them.
This was on a PDP-11 using Fortran, so you should have no problem doing
this in Python.

The prize was a VCR, which was a big deal in those days, but I didn't
have a Green Card yet, so I didn't submit my answer, for (probably
unfounded) fear the immigration authorities would give me a hard time
for unauthorized income. My answer returned
<hack hack type> 999856 for its product. Can you do better?

You can go further. If you have a unix-like system you already have a
lexicon, probably at /usr/share/dict/words .

Compare various ways to solve this problem for performance, for
arbitrary ciphers, which you can pass in as a dictionary like
{'a':2,'b':4,'c':5 .... etc.

To get you started here's the calculation, which may be interesting in
itself. I don't have the Fortran, but I'm sure it was MUCH longer than
this!

#####
cipher0= {}

for i in range(ord('a'),ord('z')+1):
   cipher0[chr(i)] = i - ord('a') + 2

from operator import mul

def numify(word,cipher=cipher0):
   return reduce(mul,[cipher[c] for c in word])

if __name__ == "__main__":
   print numify("hello")

# prints 146016

####

mt




More information about the Python-list mailing list