Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Reverse Iteration Through Integers

0 views
Skip to first unread message

Benjamin Middaugh

unread,
Oct 18, 2009, 2:34:09 PM10/18/09
to pytho...@python.org
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".

Any help would be much appreciated,

Benjamin "Self-Proclaimed Python Newbie"

Lie Ryan

unread,
Oct 18, 2009, 5:45:16 PM10/18/09
to

you need to turn the int to a str:
>>> n = 169
>>> rn = int(''.join(reversed(str(n))))
>>> rn
961
>>>

Christian Heimes

unread,
Oct 18, 2009, 5:51:20 PM10/18/09
to pytho...@python.org
Benjamin Middaugh schrieb:

> 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".
>
> Any help would be much appreciated,

Here is a simplistic version that doesn't use fancy math:

>>> str(24)
'24'
>>> str(24)[::-1]
'42'
>>> int(str(24)[::-1])
42

Rhodri James

unread,
Oct 18, 2009, 5:51:35 PM10/18/09
to pytho...@python.org
On Sun, 18 Oct 2009 19:34:09 +0100, Benjamin Middaugh
<benjamin.th...@gmail.com> wrote:

> 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".

Alternatively, turn your integer into a string, reverse the string, and
turn it back:

rhodri@gnudebst:~$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> n = 123
>>> int(str(n)[::-1])
321

--
Rhodri James *-* Wildebeest Herder to the Masses

Paul Rubin

unread,
Oct 18, 2009, 5:55:27 PM10/18/09
to
Benjamin Middaugh <benjamin.th...@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.

MRAB

unread,
Oct 18, 2009, 6:15:25 PM10/18/09
to pytho...@python.org
Benjamin Middaugh wrote:
> 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".
>
> Any help would be much appreciated,
>
You need to remember that you're not actually trying to reverse an
integer (does that actually make sense?), but the digits when it's
represented as a string (and in decimal).

Mick Krippendorf

unread,
Oct 18, 2009, 9:45:35 PM10/18/09
to
Paul Rubin wrote:
> Yet another way is to use recursion. I'll leave that as an exercise too.

This time with big numbers:


def trampoline(bouncing, *args, **kwargs):
while bouncing:
result, bouncing, args, kwargs = bouncing(*args, **kwargs)
if result:
return result()

def bouncy(function):
return lambda *args, **kwargs:(None, function, args, kwargs)

def land(result=None):
return lambda:result, None, None, None


def reverse(n):
@bouncy
def rev(i=n, j=0, k=0):
if i:
return rev(*divmod(i, 10), k=(j+k)*10)
return land(j + k)
return trampoline(rev)


print reverse(169883903200298309284038223098439430943092816286 ** 123)


Try it without the @bouncy decoration.

Granted, the code looks like a serious case of Haskell envy, but after
recursion and tail call optimization being cryptic was just the logical
consequence ;-)

Mick.

Jabba Laci

unread,
Oct 19, 2009, 1:53:04 AM10/19/09
to pytho...@python.org
Hi,

Would someone explain how str[::-1] work? I'm new to Python and I only
saw so far the str[begin:end] notation. What is the second colon?

Thanks,

Laszlo

Chris Rebert

unread,
Oct 19, 2009, 2:00:24 AM10/19/09
to Jabba Laci, pytho...@python.org
On Sun, Oct 18, 2009 at 10:53 PM, Jabba Laci <jabba...@gmail.com> wrote:
> Hi,
>
> Would someone explain how str[::-1] work? I'm new to Python and I only
> saw so far the str[begin:end] notation. What is the second colon?

Specifies the step value, as in: foo[start:stop:step]

When not specified it, defaults to 1.
So foo[::-1] gives the entire sequence backwards.
Analogously, foo[::2] gives every other item in the sequence, forwards.

Cheers,
Chris
--
http://blog.rebertia.com

alex23

unread,
Oct 19, 2009, 2:04:36 AM10/19/09
to
On Oct 19, 3:53 pm, Jabba Laci <jabba.l...@gmail.com> wrote:
> Would someone explain how str[::-1] work? I'm new to Python and I only
> saw so far the str[begin:end] notation. What is the second colon?

Slice notation is of the form [start:stop:step]. start defaults to the
start of the sequence, stop to the end, and step to 1.

So a slice of [::-1] returns the full sequence in reverse, stepping
back one character at a time from the end of the sequence to the
beginning.

The only mention I could find was http://docs.python.org/dev/3.0/library/functions.html#slice

alex23

unread,
Oct 19, 2009, 2:05:52 AM10/19/09
to
alex23 <wuwe...@gmail.com> wrote:
> The only mention I could find was http://docs.python.org/dev/3.0/library/functions.html#slice

No idea why that link was the one that came up, this is more
appropriate:

http://docs.python.org/3.1/library/functions.html#slice

Bearophile

unread,
Oct 19, 2009, 4:13:08 AM10/19/09
to
Paul Rubin:

> 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.

I think that with Psyco it's better to avoid divmod().

It's very positive to teach novices to always use tests every time
they write a function, because it makes their programs less buggy and
often allows them to solve the whole programming problem sooner:


def reverse(n):
"""
Reverse the digits of integer n, ignoring trailing zeros.

>>> reverse(12590)
9521
>>> reverse("abc")
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for divmod(): 'str' and
'int'
>>> [reverse(x) for x in (0, 1, -1, 2, -2L, 100L, -100)]
[0, 1, -1, 2, -2L, 1L, -1]
>>> [reverse(x) for x in (125, 1250, 123456789)]
[521, 521, 987654321]
>>> [reverse(x) for x in (0.0, 1.0, -5.3, 125.0, 1.23456e20)]
[0, 1.0, -5.2999999999999998, 521.0, 654321.0]
>>> str(reverse(169883903200298309284038223098439430943092816286
** 123))[:35]
'65852401624276201339740994895755844'
"""
# code removed ...

if __name__ == "__main__":
import doctest
doctest.testmod()
print "Doctests done"


Using tests (and a bit later to use a versioning system) is among the
things that have to be taught as soon as possible :-)

Bye,
bearophile

Martien Verbruggen

unread,
Oct 19, 2009, 4:42:45 PM10/19/09
to

There's also

http://docs.python.org/reference/datamodel.html#index-791

Martien
--
|
Martien Verbruggen | There are only 10 types of people in
first...@heliotrope.com.au | the world; those who understand binary
| and those who don't.

0 new messages