Python dials the first nonzero digit after the decimal point

A simple task is how to find the first nonzero digit after a decimal point. I really need the distance between the decimal point and the first non-zero digit.

I know that I can do this in a few lines, but I would like to have some pythonic, beautiful and clean way to solve this problem.

While I have it

>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)] >>> dist = lambda x: str(float(x)).find('.') - 1 >>> [(x[1], dist(x[0])) for x in t] [(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)] 
+4
source share
4 answers

The easiest way -

 x = 123.0 dist = int(math.log10(abs(x))) 

I interpreted the second entry in each pair of the list t as your desired result, so I selected int() to round the logarithm to zero:

 >>> [(int(math.log10(abs(x))), y) for x, y in t] [(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4, -4)] 
+6
source

One way to focus on the digits after the decimal point is to remove the integer part of the number, leaving something like x - int(x) on the fractional part x - int(x) .

By highlighting the fractional part, you can let python do the counting for you using the %e presentation (which also helps solve rounding problems).

 >>> '%e' % 0.000125 '1.250000e-04' >>> int(_.partition('-')[2]) - 1 3 
+3
source

Although this can technically be done with a single line (excluding the import statement), I added a few extra things to make it more complete.

 from re import search # Assuming number is already defined. # Floats always have a decimal in its string representation. if isinstance(float, number): # This gets the substring of zeros immediately following the decimal point # and returns the length of it. return len(search("\.(0*)", "5.00060030").group(1)) else: return -1 # or you can use raise TypeError() if you wanna be more restrictive. 

This is probably not a concern, but I thought I mentioned it for the sake of completeness, in some regions periods and commas change places when it comes to numbers. For example, 1,000,000.00 might be 1,000,000.00. I'm not sure Python confirms this, but since it does not represent any thousands delimited numbers, you can use the pattern ,(0*) for other regions. Again, this is probably not important to you, but it may be for other readers.

0
source
 ZerosCount = Ceil(-Log10(Abs(value) - Abs(Floor(value)))) - 1 
0
source

Source: https://habr.com/ru/post/1379655/


All Articles