Reverse Iteration Through Integers
Paul Rubin
http
Sun Oct 18 17:55:27 EDT 2009
Benjamin Middaugh <benjamin.the.violinist at gmail.com> writes:
> I'm trying to make an integer that is the reverse of an existing
> integer such that 169 becomes 961. I guess I don't know enough yet to
> figure out how to do this without a ton of awkward-looking code. I've
> tried for loops without much success. I guess I need a good way of
> figuring out the length of the input integer so my loop can iterate
> that many times to reverse the number, but I keep getting errors that
> say "TypeError: 'Int' object is not iterable".
Sounds like you're working on Euler problems ;-).
The simplest way is to turn the integer to a string:
n_int = 961
n_string = str(n_int)
then reverse the string:
n_string_reversed = reversed(n_string)
and turn it back into an int:
n_int_reversed = int(n_string_reversed)
If you want to peel off digits from an int one by one without string
conversions, it's easiest to do that in reverse order:
n = 961
digits = []
while n > 0:
n,d = divmod(n, 10)
digits.append(d)
Look up the docs for "divmod" for an explanation of that handy function.
Now the above gives you a reversed list of digits--what to do with it
is an exercise for you ;-). Note that if n=0 then you get the empty list.
Yet another way is to use recursion. I'll leave that as an exercise too.
More information about the Python-list
mailing list