Convert from numbers to letters

Jason Drew jasondrew72 at gmail.com
Thu May 19 12:13:13 EDT 2005


It seems strange to want to set the values in actual variables: a, b,
c, ..., aa, ab, ..., aaa, ..., ...

Where do you draw the line?

A function seems more reasonable. "In terms of lines of code" here is
my terse way of doing it:

nrFromDg = lambda dg: sum(((ord(dg[x])-ord('a')+1) * (26 **
(len(dg)-x-1)) for x in xrange(0, len(dg))))

Then, for example
    nrFromDg("bc")
gives
    55
and
    nrFromDg("aaa")
gives
    703
and so on for whatever you want to evaluate.

This is efficient in terms of lines of code, but of course the function
is evaluating ord("a") and len(dg) multiple times, so it's not the most
efficient in terms of avoiding redundant calculations. And
nrFromDg("A") gives you -31, so you should really force dg into
lowercase before evaluating it. Oh, and it's pretty hard to read that
lambda expression.

"Least amount of code" == "best solution"
False




More information about the Python-list mailing list