Convert from numbers to letters

S

Steven Bethard

Jason said:
z = lambda cp: (int(cp[min([i for \
i in xrange(0, len(cp)) if \
cp.isdigit()]):])-1,
sum(((ord(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp.isdigit()])][x])-ord('A')+1) \
* (26 ** (len(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp.isdigit()])])-x-1)) for x in \
xrange(0, len(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp.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
 
S

Steven Bethard

Gary said:
Gary said:
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
 
J

Jason Drew

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.
 
R

rh0dium

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

Nice work.
 
M

Mike Meyer

rh0dium said:
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
 
J

Jason Drew

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.
 
J

Jason Drew

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!
 
S

Steven Bethard

Jason said:
##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
 
J

Jason Drew

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."
 
B

Bill Mill

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".

That sounds like a bug in pythonwin autocomplete. Tuple unpacking in
function arguments is definitely a known feature, there were some
recent (fairly extensive) clp threads about it.[1]

I wish people would use it more, I think it's an awesome feature when
properly used. I like it especially for signatures like "def
change_coord((x, y))". It was one of those features, for me, where I
just tried it without knowing of its existence, assuming it would
work, and I was pleasantly surprised that it did.

Peace
Bill Mill
bill.mill at gmail.com

[1] http://tinyurl.com/89zar

I think there was another about ways to improve tuple unpacking, but I
didn't find it in a brief search.
This is with
"PythonWin 2.4 (#60, Feb 9 2005, 19:03:27) [MSC v.1310 32 bit (Intel)]
on win32."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top