Convert from numbers to letters

R

rh0dium

Hi All,

While I know there is a zillion ways to do this.. What is the most
efficient ( in terms of lines of code ) do simply do this.

a=1, b=2, c=3 ... z=26

Now if we really want some bonus points..

a=1, b=2, c=3 ... z=26 aa=27 ab=28 etc..

Thanks
 
D

Dan Sommers

Hi All,
While I know there is a zillion ways to do this.. What is the most
efficient ( in terms of lines of code ) do simply do this.
a=1, b=2, c=3 ... z=26

(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) = range( 1, 27 )
Now if we really want some bonus points..
a=1, b=2, c=3 ... z=26 aa=27 ab=28 etc..

It's still one line, following the pattern from above, just longer.

Now why do you want to do this?

Regards,
Dan
 
B

Bill Mill

Hi All,

While I know there is a zillion ways to do this.. What is the most
efficient ( in terms of lines of code ) do simply do this.

a=1, b=2, c=3 ... z=26

Now if we really want some bonus points..

a=1, b=2, c=3 ... z=26 aa=27 ab=28 etc..

just for fun, here is one way to do it with a listcomp. Obfuscated
python fans, rejoice!
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha \
for y in [''] + [z for z in alpha]], key=len)):
.... locals()[digraph] = i + i
....
 
J

Jason Drew

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
 
S

Steven Bethard

Bill said:
py> alpha = 'abcdefghijklmnopqrstuvwxyz'
py> for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha
... for y in [''] + [z for z in alpha]], key=len)):
... locals()[digraph] = i + i
...

It would probably be better to get in the habit of writing
globals()[x] = y
instead of
locals()[x] = y
You almost never want to do the latter[1]. The only reason it works in
this case is because, at the module level, locals() is globals().

You probably already knew this, but I note it here to help any newbies
avoid future confusion.

Steve

[1] For 99% of use cases. Modifying locals() might be useful if you're
just going to pass it to another function as a dict. But I think I've
seen *maybe* 1 use case for this.
 
Q

qwweeeit

Hi rh0dium,
Your request gives me the opportunity of showing a more realistic
example of the technique of "self-modification coding".
Although the coding is not as short as that suggested by the guys who
replayed to you, I think that it can be interesting....

# newVars.py
lCod=[]
for n in range(1,27):
.. lCod.append(chr(n+96)+'='+str(n)+'\n')
# other for-loops if you want define additional variables in sequence
(ex. aa,bb,cc etc...)
# write the variable definitions in the file "varDef.py"
fNewV=open('varDef.py','w')
fNewV.writelines(lCod)
fNewV.close()
from varDef import *
# ...
If you open the generated file (varDef.py) you can see all the variable
definitions, which are runned by "from varDef import *"
Bye.
 
R

rh0dium

Call me crazy.. But it doesn't work..

for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha for
y in [''] + [z for z in alpha]], key=len)):
globals()[digraph]=i+1

How do you implement this sucker??

Thanks
 
R

rh0dium

This is great but backwards...

Ok because you all want to know why.. I need to convert Excel columns
A2 into , [1,0] and I need a simple way to do that..

( The way this works is A->0 and 2->1 -- Yes they interchange -- So
B14 == [13,1] )

So my logic was simple convert the A to a number and then do the swap.
I didn't really care about the function so to speak it was a minor step
in the bigger picture..

By the way if you haven't played with pyXLWriter is it really good :)

So can anyone simply provide a nice function to do this? My logic was
along the same lines as Dans was earlier - but that just seems too
messy (and ugly)

Thanks
 
B

Bill Mill

Call me crazy.. But it doesn't work..

What doesn't work? What did python output when you tried to do it? It
is python 2.4 specific, it requires some changes for 2.3, and more for
earlier versions of python.
for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha for
y in [''] + [z for z in alpha]], key=len)):
globals()[digraph]=i+1

How do you implement this sucker??

Works just fine for me. Let me know what error you're getting and I'll
help you figure it out.

Peace
Bill Mill
bill.mill at gmail.com
 
B

Bill Mill

This is great but backwards...

Ok because you all want to know why.. I need to convert Excel columns
A2 into , [1,0] and I need a simple way to do that..

( The way this works is A->0 and 2->1 -- Yes they interchange -- So
B14 == [13,1] )

why didn't you say this in the first place?

def coord2tuple(coord):
row, col = '', ''
alpha = 'abcdefghijklmnopqrstuvwxyz'.upper()
pairs = [''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]]
pairs = sorted(pairs, key=len)
coord = coord.upper()
for c in coord:
if c in alpha:
row += c
else:
col += c
return (int(col)-1, pairs.index(row))
(1, 0)

Are there cols greater than ZZ? I seem to remember that there are not,
but I could be wrong.

Hope this helps.

Peace
Bill Mill
(e-mail address removed)
 
R

rh0dium

Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'sorted' is not defined

I think you're probably using 2.4 ??
 
B

Bill Mill

Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'sorted' is not defined

I think you're probably using 2.4 ??

Yes, sorted() is new in python 2.4 .You could use a very lightly
tested pure-python partial replacement:

def sorted(lst, **kwargs):
l2 = lst[:]
if kwargs.has_key('key'):
f = kwargs['key']
l2.sort(lambda a,b: cmp(f(a), f(b)))
return l2
l2.sort()
return l2

And from your other email:
I need to go the other way! tuple2coord

Sorry, I only go one way. It should be transparent how to do it backwards.

Peace
Bill Mill
(e-mail address removed)
 
P

Peter Otten

Bill said:
Yes, sorted() is new in python 2.4 .You could use a very lightly
tested pure-python partial replacement:

By the way, sorted() can be removed from your original post.

Code has no effect :)

Peter
 
B

Bill Mill

By the way, sorted() can be removed from your original post.

Code has no effect :)

I'm gonna go ahead and disagree with you:
sorted([''.join((x, y)) for x in alpha \
.... for y in [''] + [z for z in alpha]], key=len) == \
.... [''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]]
False

If you want to see why, here's a small example:
alpha = 'abc'
[''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]]
['a', 'aa', 'ab', 'ac', 'b', 'ba', 'bb', 'bc', 'c', 'ca', 'cb', 'cc']
sorted([''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]],
key=len)
['a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']

Peace
Bill Mill
bill.mill at gmail.com
 
G

Gary Wilson Jr

Bill said:
I'm gonna go ahead and disagree with you:

Me too, although I would forgo the sort altogether (while making things
a little more readable IMO):
alpha = 'abcdefghijklmnopqrstuvwxyz'.upper()
pairs = [''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]]
pairs = sorted(pairs, key=len)

alpha = 'abcdefghijklmnopqrstuvwxyz'.upper()
pairs = [x for x in alpha] + [''.join((x,y)) for x in alpha for y in alpha]
 
P

Peter Otten

Bill said:
By the way, sorted() can be removed from your original post.

Code has no effect :)

I'm gonna go ahead and disagree with you:
sorted([''.join((x, y)) for x in alpha \
...    for y in [''] + [z for z in alpha]], key=len) == \
... [''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]]
False

That's not your original code. You used the contents to modify the locals()
(effectively globals()) dictionary:
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha \
for y in [''] + [z for z in alpha]], key=len)):
...     locals()[digraph] = i + i
...

Of course you lose the order in that process.
When you do care about order, I suggest that you swap the for clauses
instead of sorting, e. g:
alpha = list("abc")
items = [x + y for x in [""] + alpha for y in alpha]
items == sorted(items, key=len)
True

Peter
 
J

Jason Drew

We weren't really backwards; just gave a full solution to a half-stated
problem.

Bill, you've forgotten the least-lines-of-code requirement :)

Mine's still a one-liner (chopped up so line breaks don't break it):

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)

print z("B14")
# gives (13, 1)

Maybe brevity isn't the soul of wit after all ...
 
G

Gary Wilson Jr

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)?
 
M

Mike Meyer

Bill Mill said:
This is great but backwards...

Ok because you all want to know why.. I need to convert Excel columns
A2 into , [1,0] and I need a simple way to do that..

( The way this works is A->0 and 2->1 -- Yes they interchange -- So
B14 == [13,1] )

why didn't you say this in the first place?

def coord2tuple(coord):
row, col = '', ''
alpha = 'abcdefghijklmnopqrstuvwxyz'.upper()
pairs = [''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]]
pairs = sorted(pairs, key=len)
coord = coord.upper()
for c in coord:
if c in alpha:
row += c
else:
col += c
return (int(col)-1, pairs.index(row))

That seems like the long way around. Python can search strings for
substrings, so why not use that? That gets the search loop into C
code, where it should be faster.

from string import uppercase

def coord2tuple2(coord):
if len(coord) > 1 or uppercase.find(coord) < 0:
raise ValueError('coord2tuple2 expected a single uppercase character, got "%s"' % coord)
return uppercase.index(coord) + 1

Without the initial test, it has a buglet of return values for "AB"
and similar strings. If searching uppercase twice really bothers you,
you can drop the uppercase.find; then you'll get less informative
error messages if coord2tuple2 is passed single characters that aren't
in uppercase.

<mike
 

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,020
Latest member
GenesisGai

Latest Threads

Top