Reverse Iteration Through Integers

Bearophile bearophileHUGS at lycos.com
Mon Oct 19 04:13:08 EDT 2009


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



More information about the Python-list mailing list