From: Brian at digicool.com (Brian Lloyd)
Date: Thu, 22 Apr 1999 20:04:40 GMT
Subject: Reversing Long integers
Message-ID: <613145F79272D211914B0020AFF6401914DAD5@gandalf.digicool.com>
Content-Length: 1043
X-UID: 1381                                                  

> I am attempting to write an efficient Python program which 
> can add an integer to
> its reverse. This is quite easy to do in Lisp and Mathematica 
> but (mostly out of
> curiosity) I wanted to see how one might do this in Python. 
> Converting an
> integer to a string and reversing it and converting back is 
> quite easy (although
> not all of these ops are primitives) but the fact that Long 
> integers have the
> letter L appended means that the loop must include moving the 
> L to the end of
> the reversed string prior to summing. Can anyone think of a 
> particularly clever
> way to do this?


Ok, I'll bite :) I don't know if this is particularly clever,
but it works and should be pretty fast...


import string
def addrev(num, join=string.join, atol=string.atol):
    """Add a long to its reverse"""
    rev=list(str(num)[:-1])
    rev.reverse()
    return num + atol(join(rev, ''))
    


Brian Lloyd        brian at digicool.com
Software Engineer  540.371.6909              
Digital Creations  http://www.digicool.com 






