Convert from numbers to letters

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

  1. rh0dium

    rh0dium Guest

    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
    #1
    1. Advertising

  2. rh0dium

    Dan Sommers Guest

    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
    #2
    1. Advertising

  3. rh0dium

    Bill Mill Guest

    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
    #3
  4. rh0dium

    Jason Drew Guest

    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
    #4
  5. 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.
     
    Steven Bethard, May 19, 2005
    #5
  6. rh0dium

    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
    #6
  7. rh0dium

    rh0dium Guest

    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
    #7
  8. rh0dium

    rh0dium Guest

    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
    #8
  9. rh0dium

    Bill Mill Guest

    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
    help you figure it out.

    Peace
    Bill Mill
    bill.mill at gmail.com
     
    Bill Mill, May 19, 2005
    #9
  10. rh0dium

    Bill Mill Guest

    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
    #10
  11. rh0dium

    rh0dium Guest

    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
    #11
  12. rh0dium

    Bill Mill Guest

    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

    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
     
    Bill Mill, May 19, 2005
    #12
  13. rh0dium

    Peter Otten Guest

    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
    #13
  14. rh0dium

    Bill Mill Guest

    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
    #14
  15. 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
    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]
     
    Gary Wilson Jr, May 19, 2005
    #15
  16. rh0dium

    Peter Otten Guest

    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, May 19, 2005
    #16
  17. rh0dium

    Peter Otten Guest

    Peter Otten wrote:

    [Something stupid]

    You are right. I finally got it.

    Peter
     
    Peter Otten, May 19, 2005
    #17
  18. rh0dium

    Jason Drew Guest

    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
    #18
  19. 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
    #19
  20. rh0dium

    Mike Meyer Guest

    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/
    Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
     
    Mike Meyer, May 19, 2005
    #20
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Pablo

    Numbers or letters in a TextBox

    Pablo, Aug 26, 2003, in forum: ASP .Net
    Replies:
    2
    Views:
    410
    Jerry III
    Aug 26, 2003
  2. Merrigan
    Replies:
    4
    Views:
    583
    Chris
    Dec 14, 2007
  3. PABLIN

    Numbers or letters in a TextBox

    PABLIN, Aug 26, 2003, in forum: ASP .Net Building Controls
    Replies:
    1
    Views:
    161
  4. Venugopal
    Replies:
    11
    Views:
    1,562
    Tassilo v. Parseval
    Nov 5, 2003
  5. Rene Ivon Shamberger

    convert Phone Letters to Phone numbers

    Rene Ivon Shamberger, Dec 4, 2012, in forum: C++
    Replies:
    5
    Views:
    405
Loading...

Share This Page