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?
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
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
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
You can do something like this.
number = 122322
num_str = str(number)
for num in num_str:
print num
>>> 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]
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.
If you strictly wants the modulo - you will have to go into two phases:
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
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]
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 )
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]
s := 0
and p := 1
(p
represents the power 10^s
)n < p
, go to 5 below.s := s + 1
and p := p * 10
.[Find digits]
m := n
and a[s]
be the array of digits to computei := 1
(indexes are 1-based)p := p / 10
(integer division)q
and r
be the quotient and remainder of the division of m
by p
a[i] := q
and m := r
i < s
put i := i + 1
and go to 7At 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
.
I think i need to create custom layout but i don't know how to do it
How to work Android Api response are use model class work response data properly
Constraint element to the TextInputLayout text (inside the TextInputLayout)
How to change a progress dialog layout when the progress completed?
(Off-topic) Can I use Xmpp server quickblox for chat application which works locally?
Forcing a DialogFragment to not recreate after orientation change
I am trying to update anaconda on my MacWhen I run the command conda update anaconda, I get the following output
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
I would like to retrieve a random set of X entries from my postgres database using sqlalchemyMy first approach was this
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