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 30 19363
On 19 May 2005 06:56:45 0700,
"rh0dium" <sk****@pointcircle.com> 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/>
On 19 May 2005 06:56:45 0700, rh0dium <sk****@pointcircle.com> 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/pythonlist
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)x1)) 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
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
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.
Hi rh0dium,
Your request gives me the opportunity of showing a more realistic
example of the technique of "selfmodification 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 forloops 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.
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
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
On 19 May 2005 11:52:30 0700, rh0dium <sk****@pointcircle.com> 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
help you figure it out.
Peace
Bill Mill
bill.mill at gmail.com
On 19 May 2005 11:59:00 0700, rh0dium <sk****@pointcircle.com> 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 bi*******@gmail.com
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 ??
On 19 May 2005 12:20:03 0700, rh0dium <sk****@pointcircle.com> 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 purepython 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 bi*******@gmail.com
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 purepython partial replacement:
By the way, sorted() can be removed from your original post.
Code has no effect :)
Peter
On 5/19/05, Peter Otten <__*******@web.de> 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 purepython 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 wrote: On 5/19/05, Peter Otten <__*******@web.de> 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 purepython 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
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]
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
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
Peter Otten wrote:
[Something stupid]
You are right. I finally got it.
Peter
We weren't really backwards; just gave a full solution to a halfstated
problem.
Bill, you've forgotten the leastlinesofcode requirement :)
Mine's still a oneliner (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[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()])])x1)) for x in \
xrange(0, len(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp[i].isdigit()])]))))1)
print z("B14")
# gives (13, 1)
Maybe brevity isn't the soul of wit after all ...
Bill Mill <bi*******@gmail.com> writes: On 19 May 2005 11:59:00 0700, rh0dium <sk****@pointcircle.com> 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 <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
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)?
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()])])x1)) 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 linecontinuation
character.
STeVe
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
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.
Wow  now that is ugly.. But it is effective. I would love a cleaner
version  but I did say brevity :)
Nice work.
Now can you reverse this process tuple2coord??
Thats what I'm really after :)
"rh0dium" <sk****@pointcircle.com> 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 <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
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') + colnr1)
## 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 speedwise solution. (Though I'd still use my nice
recursive nobrainer 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 futureneutral.
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!
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
Hey, that's good. Thanks Steve. Hadn't seen it before. One to use.
Funny that Pythonwin's argumentprompter (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 popup 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 popup 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."
On 20 May 2005 10:07:55 0700, Jason Drew <ja*********@gmail.com> wrote: Hey, that's good. Thanks Steve. Hadn't seen it before. One to use. Funny that Pythonwin's argumentprompter (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 popup 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 popup 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."  http://mail.python.org/mailman/listinfo/pythonlist This discussion thread is closed Replies have been disabled for this discussion. Similar topics
7 posts
views
Thread by Gerard Flanagan 
last post: by

22 posts
views
Thread by federico_bertola 
last post: by

2 posts
views
Thread by karups 
last post: by

9 posts
views
Thread by Paul 
last post: by

8 posts
views
Thread by flyingisfun1217 
last post: by

2 posts
views
Thread by Tom 
last post: by

1 post
views
Thread by Jeff 
last post: by
            