What is the most efficient way to calculate the number of 0s in a decimal before the first non 0 number?
Desired outcome:
0.0000456 ---> 4
0.00406 ---> 2
0.000456 ---> 3
So far I have tried mathematically this (which is slow):
from math import floor, log
def num_zeros(decimal):
return 10 - floor(log(decimal *10e10,10))
and this (which is not right as 0 after a first number will be counted):
def count_0(number):
n = format(number, 'f').count('0')
return n - 1
Why not simply:
from math import floor, log10, inf
def num_zeros(decimal):
return inf if decimal == 0 else -floor(log10(abs(decimal))) - 1
This handles 0.001 correctly (2 zeros), whereas some answers would print 3. It also now works for negative numbers and zero.
I'd be shocked if string methods were faster.
To handle non-finite numbers correctly as well, simply swap out the definition of floor as follows:
def floor(decimal):
return math.floor(decimal) if math.isfinite(decimal) else decimal
Or equivalently:
from math import floor, log10, inf, isinf, nan, isnan
def num_zeros(decimal):
if isnan(decimal):
return nan
if isinf(decimal):
return -inf
return inf if decimal == 0 else -floor(log10(abs(decimal))) - 1
Here's a way to approach this using a regular expression:
# Update, simplified sol thanks to @Aran-Fey's comments
import re
s = '0.0000456'
len(re.search('\d+\.(0*)', s).group(1))
#4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With