Velocity Reviews > Convert from numbers to letters

# Convert from numbers to letters

Steven Bethard
Guest
Posts: n/a

 05-19-2005
Jason Drew wrote:
> z = lambda cp: (int(cp[min([i for \
> i in xrange(0, len(cp)) if \
> cp[i].isdigit()]):])-1,
> sum(((ord(cp[0:min([i for i in \
> xrange(0, len(cp)) if \
> cp[i].isdigit()])][x])-ord('A')+1) \
> * (26 ** (len(cp[0:min([i for i in \
> xrange(0, len(cp)) if \
> cp[i].isdigit()])])-x-1)) for x in \
> xrange(0, len(cp[0:min([i for i in \
> xrange(0, len(cp)) if \
> cp[i].isdigit()])]))))-1)

While I think we can all agree that this is a sin against man and nature
I'll ignore that for the moment to note that you don't need any of
the '\' characters. You're already using parentheses and brackets. I
find there are *very* few cases where I really need a line-continuation
character.

STeVe

Steven Bethard
Guest
Posts: n/a

 05-19-2005
Gary Wilson Jr wrote:
> Gary Wilson Jr wrote:
>
>>alpha = 'abcdefghijklmnopqrstuvwxyz'.upper()
>>pairs = [x for x in alpha] + [''.join((x,y)) for x in alpha for y in alpha]

>
> I forget, is string concatenation with '+' just as fast as join()
> now (because that would look even nicer)?

Certain looping constructs like:

x = ''
for y in z:
x += y

are now (in CPython 2.4) somewhere near the speed of:

x = []
for y in z:
x.append(y)
x = ''.join(x)

but this isn't really relevant to your problem because you're only
joining two characters:

\$ python -m timeit -s "import string; a = string.ascii_uppercase"
"[''.join([x, y]) for x in a for y in a]"
1000 loops, best of 3: 1.02 msec per loop

\$ python -m timeit -s "import string; a = string.ascii_uppercase"
"[x + y for x in a for y in a]"
1000 loops, best of 3: 295 usec per loop

Unsurprisingly, it's actually faster to simply concatenate the two
characters.

STeVe

Jason Drew
Guest
Posts: n/a

 05-19-2005
Oh yeah, oops, thanks. (I mean the line continuations, not the alleged
sin against man and nature, an accusation which I can only assume is
motivated by jealousy Or fear? They threw sticks at Frankenstein's
monster too. And he turned out alright.

My elegant "line" of code started out without the enclosing
parentheses; forgot I didn't need the \s when I embraced it.

rh0dium
Guest
Posts: n/a

 05-19-2005
Wow - now that is ugly.. But it is effective. I would love a cleaner
version - but I did say brevity

Nice work.

rh0dium
Guest
Posts: n/a

 05-19-2005
Now can you reverse this process tuple2coord??

Thats what I'm really after

Mike Meyer
Guest
Posts: n/a

 05-19-2005
"rh0dium" <> writes:
> Now can you reverse this process tuple2coord??

You didn't provide enough context to know who you're asking, but
here's the inverse of my coord2tuple2 function:

from string import uppercase
def tuple2coord(number):
if 1 > number or number > 26:
raise ValueError("tuple2coord expected a number between 1 and 26, got '%s'" % number)
return (" " + uppercase)[number]

<mike
--
Mike Meyer <> http://www.mired.org/home/mwm/

Jason Drew
Guest
Posts: n/a

 05-20-2005
Er, yes! It's REALLY ugly! I was joking (though it works)! I retract it
from the code universe. (But patent pending nr. 4040404.)

Here's how I really would convert your (row_from_zero, col_from_zero)
tuple to spreadsheet "A1" coords, in very simple and easy to read code.

##def tuple2coord(tupl):
## def colnr2digraph(colnr):
## if colnr <= 26:
## return chr(ord('A') + colnr-1)
## m = colnr % 26
## if m == 0:
## m = 26
## h = (colnr - m) / 26
## return colnr2digraph(h) + colnr2digraph(m)
##
## rowfromzero, colfromzero = tupl
## row = rowfromzero+1
## col = colfromzero+1
## return colnr2digraph(col) + str(row)
##
##print tuple2coord((13,702))
### gives AAA14
### (because the tuple counts rows and columns from zero)

Note that this allows column nrs of any size, not just up to "ZZ". If
you really know the column limit is ZZ, then a lookup dictionary would
be a more efficient speed-wise solution. (Though I'd still use my nice
recursive no-brainer colnr2digraph function to populate the
dictionary.)

P.S. the line that says
h = (colnr - m) / 26
could really, in current Python, be just
h = colnr / 26
but the former is more language- and future-neutral.

Jason Drew
Guest
Posts: n/a

 05-20-2005
Sorry, scratch that "P.S."! The act of hitting Send seems to be a great
way of realising one's mistakes.

Of course you need colnr - m for those times when m is set to 26.
Remembered that when I wrote it, forgot it 2 paragraphs later!

Steven Bethard
Guest
Posts: n/a

 05-20-2005
Jason Drew wrote:
> ##def tuple2coord(tupl):

[snip]
> ## rowfromzero, colfromzero = tupl

Just a side note here that if you want a better function signature, you
might consider writing this as:

tuple2coord((rowfromzero, colfromzero)):
...

Note that the docstrings are nicer this way:

py> def tuple2coord(tupl):
.... x, y = tupl
....
py> help(tuple2coord)
Help on function tuple2coord in module __main__:

tuple2coord(tupl)

py> def tuple2coord((x, y)):
.... pass
....
py> help(tuple2coord)
Help on function tuple2coord in module __main__:

tuple2coord((x, y))

STeVe

Jason Drew
Guest
Posts: n/a

 05-20-2005
Hey, that's good. Thanks Steve. Hadn't seen it before. One to use.

Funny that Pythonwin's argument-prompter (or whatever that feature is
called) doesn't seem to like it.

E.g. if I have
def f(tupl):
print tupl

Then at the Pythonwin prompt when I type
f(
I correctly get "(tupl)" in the argument list pop-up box.

But if I have
def f((a, b)):
print a, b

then when I type
f(
I just get "(.0)" in the argument list pop-up box.

Or with
def f(p, q, (a, b)):
pass
Pythonwin prompts with
"(p, q, .4)"

However in each case the help() function correctly lists all the
arguments. Strange. I'll check if it's a known "feature".

This is with
"PythonWin 2.4 (#60, Feb 9 2005, 19:03:27) [MSC v.1310 32 bit (Intel)]
on win32."