# Convert from numbers to letters

Discussion in 'Python' started by rh0dium, May 19, 2005.

1. ### rh0diumGuest

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

rh0dium, May 19, 2005

2. ### Dan SommersGuest

On 19 May 2005 06:56:45 -0700,
"rh0dium" <> wrote:

> 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

--
Dan Sommers
<http://www.tombstonezero.net/dan/>

Dan Sommers, May 19, 2005

3. ### Bill MillGuest

On 19 May 2005 06:56:45 -0700, rh0dium <> wrote:
> 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
....
>>> a

1
>>> b

2
>>> ac

29
>>> dg

111
>>> zz

702
>>> 26**2 + 26

702

> Thanks
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Bill Mill, May 19, 2005
4. ### Jason DrewGuest

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

Jason Drew, May 19, 2005
5. ### Steven BethardGuest

Bill Mill wrote:
>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
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.

Steven Bethard, May 19, 2005
6. ### Guest

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.

, May 19, 2005
7. ### rh0diumGuest

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

rh0dium, May 19, 2005
8. ### rh0diumGuest

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

rh0dium, May 19, 2005
9. ### Bill MillGuest

On 19 May 2005 11:52:30 -0700, rh0dium <> wrote:
> 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

Peace
Bill Mill
bill.mill at gmail.com

Bill Mill, May 19, 2005
10. ### Bill MillGuest

On 19 May 2005 11:59:00 -0700, rh0dium <> wrote:
> 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))

>>> coord2tuple('B14')

(13, 1)
>>> coord2tuple('ZZ14')

(13, 701)
>>> coord2tuple('ZZ175')

(174, 701)
>>> coord2tuple('A2')

(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

Bill Mill, May 19, 2005
11. ### rh0diumGuest

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

rh0dium, May 19, 2005
12. ### Bill MillGuest

On 19 May 2005 12:20:03 -0700, rh0dium <> wrote:
> 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

> 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

Bill Mill, May 19, 2005
13. ### Peter OttenGuest

Bill Mill wrote:

>> 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:

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

Code has no effect

Peter

Peter Otten, May 19, 2005
14. ### Bill MillGuest

On 5/19/05, Peter Otten <> wrote:
> Bill Mill wrote:
>
> >> Traceback (most recent call last):
> >>File"<stdin>",line1,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:

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

Bill Mill, May 19, 2005
15. ### Gary Wilson JrGuest

Bill Mill wrote:
> On 5/19/05, Peter Otten <> wrote:
>
>>Bill Mill wrote:
>>
>>
>>>>Traceback (most recent call last):
>>>>File"<stdin>",line1,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:

>>
>>By the way, sorted() can be removed from your original post.
>>
>>Code has no effect

>
>
> I'm gonna go ahead and disagree with you:

Me too, although I would forgo the sort altogether (while making things

> 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]

Gary Wilson Jr, May 19, 2005
16. ### Peter OttenGuest

Bill Mill wrote:

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

>>> alpha = list("abc")
>>> items = [x + y for x in [""] + alpha for y in alpha]
>>> items == sorted(items, key=len)

True

Peter

Peter Otten, May 19, 2005
17. ### Peter OttenGuest

Peter Otten wrote:

[Something stupid]

You are right. I finally got it.

Peter

Peter Otten, May 19, 2005
18. ### Jason DrewGuest

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

Jason Drew, May 19, 2005
19. ### Gary Wilson JrGuest

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

Gary Wilson Jr, May 19, 2005
20. ### Mike MeyerGuest

Bill Mill <> writes:

> On 19 May 2005 11:59:00 -0700, rh0dium <> wrote:
>> 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
--
Mike Meyer <> http://www.mired.org/home/mwm/