wasm-demo/demo/ermis-f/python_m/cur/0607

46 lines
1.6 KiB
Plaintext

From: dfan at harmonixmusic.com (Dan Schmidt)
Date: 22 Apr 1999 15:31:45 -0400
Subject: Reversing Long integers
References: <371E0C46.E6FA76A9@princeton.edu>
Message-ID: <wk4sm8e9jy.fsf@turangalila.harmonixmusic.com>
Content-Length: 1295
X-UID: 607
"Ira H. Fuchs" <fuchs at princeton.edu> writes:
| 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?
This isn't particularly clever, but it does the job. The
time spent dealing with checking for longs should be negligible
compared to the rest of it.
s = `i`
m = map (None, s) # Turn into an array of characters
is_long = 0
if m[-1] == 'L':
m, is_long = m[0:-1], 1
m.reverse()
s2 = string.join (m, '')
if (is_long):
i2 = long(s2)
else:
i2 = int(s2)
--
Dan Schmidt -> dfan at harmonixmusic.com, dfan at alum.mit.edu
Honest Bob & the http://www2.thecia.net/users/dfan/
Factory-to-Dealer Incentives -> http://www2.thecia.net/users/dfan/hbob/
Gamelan Galak Tika -> http://web.mit.edu/galak-tika/www/