A. Rapoport
A. Rapoport

Reputation: 113

How to iterate through the digits of a number without having it under the form of a string in Python?

I've seen a couple posts explaning how to iterate through the digits of a number in Python, but they all turn the number into a string before iterating through it... For example:

n=578
print d for d in str(n)

How can I do this without the conversion into a string?

Upvotes: 1

Views: 2527

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61063

10**int(log(n, 10)) is basically 10*, such that it is the same length as n. The floor division of n by that will give us the leading digit, while the modulo % gives us the rest of the number.

from math import log

def digits(n):
    if n < 0:
        yield '-'
        n = -1 * n
    elif n == 0:
        yield 0
        return
    xp = int(log(n, 10).real)
    factor = 10**xp
    while n:
        yield int(n/factor)
        n = n % factor
        try:
            xp, old_xp = int(log(n, 10).real), xp
        except ValueError:
            for _ in range(xp):
                yield 0
            return
        factor = 10**xp
        for _ in range(1, old_xp-xp):
            yield 0

for x in digits(12345):
    print(x)

prints

1
2
3
4
5

Edit: I switched to this version, which is much less readable, but more robust. This version correctly handles negative and zero values, as well as trailing and internal 0 digits.

Upvotes: 4

Related Questions