How to extract digits from a number from left to right?

224
December 25, 2016, at 11:07 PM

I know that I can extract digits from a number from right to left by implementing something like:

while (number => 10)
  digit = number modulo 10
  number = number / 10

But is there a way to do it from left to right that works similar to this one, simply by using stuff like the modulo value?

Answer 1

If you don't have problem with recursion approach then here is a solution with little change in your code:-

def get_digit(num):
    if num <10:
        print num
    else:
        get_digit(num/10)
        print num%10 
get_digit(543267)
5
4
3
2
6
7
Answer 2

You can do like this,

number = 2164524
for i in str(number)[::-1]:
     digit = int(i)
     print digit

Convert number to string,reverse and iterate through it.

Mathematical way:

number = 2164524
while(number >= 10):
    digit = number % 10
    number = number / 10
    print digit
print number # Last element will be in number

Alternative method with divmod

while n:
    n, remainder = divmod(n, 10)
    print remainder

Results:

4
2
5
4
6
1
Answer 3

You can do it "mathematical way". If you take log10 from absolute value of number and round result up, then you get number of digits in a number (except for cases of 0 and 1). You can round up or round down, it will just alter origin of exponent. Note that it uses log10 and other math functions, so it might be slower than using strings. And actual timeit shows just that:

>>> print(timeit.timeit('list(digits_reverse_str(12345))', setup='from __main__ import digits_reverse_str', number=10000))
>>> print(timeit.timeit('list(digits_reverse(12345))', setup='from __main__ import digits_reverse', number=10000))
0.02799521596170962
0.05542760493699461
def digits_reverse(number):
    abs_value = abs(number)
    if abs_value <= 1:
        e = 1
    else:
        l10 = math.log10(abs_value)
        e = math.ceil(l10)
    while e > 0:
        e -= 1
        digit, abs_value = divmod(abs_value, 10 ** e)
        yield digit

def digits_reverse_str(number):
    for i in str(number)[::-1]:
        digit = int(i)
        yield digit
Answer 4

You can do something like this.

number = 122322
num_str = str(number)
for num in num_str:
  print num
Answer 5
>>> import math
>>> def digitsLTR(num):
    assert num > 0
    start = int(math.log(num, 10))
    for i in range(start, -1, -1):
        power = 10 ** i
        dig = num / power
        yield dig
        num -= dig * power          
>>> list(digitsLTR(3567))
[3, 5, 6, 7]
Answer 6

Recursion is your friend:

def digits(n):
    if n < 10:
        print n
    else:
        q = n // 10
        r = n - 10 * q
        digits(q)
        print r

The digits are extracted right-to-left as the recursion winds down, then printed left-to-right as the recursion unwinds. Recursion stops when n is only a single digit.

Answer 7

If you strictly wants the modulo - you will have to go into two phases:

  1. Find the closest power of 10.
  2. Use division and remainder.

Coming into code would be:

# 1
n, p = number, 1
while n >= 10:
    n, p = n // 10, p * 10
# 2
while number >= 0:
    number, digit, p = number % p, number // p, p // 10
Answer 8

Here is a generator which returns the digits of a positive integer in a left to right manner:

from math import floor, log10
def digits(n):
    """generator which returns digits in left to right order"""
    k = floor(log10(n))
    for e in range(k,-1,-1):
        d,n = divmod(n,10**e)
        yield d

For example,

>>> list(digits(2016))
[2, 0, 1, 6]
Answer 9

Here is mathematical way of doing this:

from math import log
number = 2164524
lenght = int(log(number, 10))
for i in range(lenght, -1, -1):
    print( (number//(10**i)) % 10 )
Answer 10

Let's n be the number whose digits we want to compute from left to right.

Imagine first that we are given s such that n < 10^s (this isn't usually the case, but for now let's assume we know such an s)

This means that

n = q 10^(s-1) + r

where q is the quotient and r < 10^(s-1) is the remainder of the division of n by 10^(s-1).

Since n < 10^s, we deduce that q <= 9. If q > 0, then q must be the leftmost digit of n. In other words

n = (q....)

where the dots represent the digits to the right.

Now, let's use this understanding to write an algorithm that computes the digits of n from left to right. We will assume that n > 0.

[Find Max Power]

  1. Put s := 0 and p := 1 (p represents the power 10^s)
  2. If n < p, go to 5 below.
  3. Put s := s + 1 and p := p * 10.
  4. Go to 2

[Find digits]

  1. Let m := n and a[s] be the array of digits to compute
  2. Put i := 1 (indexes are 1-based)
  3. Put p := p / 10 (integer division)
  4. Let q and r be the quotient and remainder of the division of m by p
  5. Put a[i] := q and m := r
  6. If i < s put i := i + 1 and go to 7

At this point the array a[] contains the digits from left to right of n.

Note: By replacing everywhere 10 by any positive integer b, you get the digits of n in base b.

READ ALSO
Issue with conda update anaconda

Issue with conda update anaconda

I am trying to update anaconda on my MacWhen I run the command conda update anaconda, I get the following output

464
Median replace the empty values in Pandas

Median replace the empty values in Pandas

I have a column called Reservation some of its rows is empty and some rows have several valuesI want to extract the letter before the numbers

470
getting a random set of database entries

getting a random set of database entries

I would like to retrieve a random set of X entries from my postgres database using sqlalchemyMy first approach was this

330
How does Python&#39;s super() work with multiple inheritance?

How does Python's super() work with multiple inheritance?

I'm pretty much new in Python object oriented programming and I have trouble understanding the super() function (new style classes) especially when it comes to multiple inheritance

188