Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get most significant digit in python

Say I have list [34523, 55, 65, 2]

What is the most efficient way to get [3,5,6,2] which are the most significant digits. If possible without changing changing each to str()?

like image 813
Nicky Feller Avatar asked Nov 26 '15 22:11

Nicky Feller


People also ask

How do you find the most significant digit in Python?

Assuming you're only dealing with positive numbers, you can divide each number by the largest power of 10 smaller than the number, and then take the floor of the result.

How do you find most significant digits?

The number of significant figures is determined by starting with the leftmost non-zero digit. The leftmost non-zero digit is sometimes called the most significant digit or the most significant figure. For example, in the number 0.004205, the '4' is the most significant figure.

What is the most significant digit?

The leftmost, non-zero digit in a number. It is the digit with the greatest value in the number.

How do you find the least significant digit?

Sometimes abbreviated as LSD, the least significant digit of a number is the digit with the lowest exponent value, located in the rightmost position. For example, in the number 2516, the "6" is the least significant digit.


1 Answers

Assuming you're only dealing with positive numbers, you can divide each number by the largest power of 10 smaller than the number, and then take the floor of the result.

>>> from math import log10, floor
>>> lst = [34523, 55, 65, 2]
>>> [floor(x / (10**floor(log10(x)))) for x in lst]
[3, 5, 6, 2]

If you're using Python 3, instead of flooring the result, you can use the integer division operator //:

>>> [x // (10**floor(log10(x))) for x in lst]
[3, 5, 6, 2]

However, I have no idea whether this is more efficient than just converting to a string and slicing the first character. (Note that you'll need to be a bit more sophisticated if you have to deal with numbers between 0 and 1.)

>>> [int(str(x)[0]) for x in lst]
[3, 5, 6, 2]

If this is in a performance-critical piece of code, you should measure the two options and see which is faster. If it's not in a performance-critical piece of code, use whichever one is most readable to you.

like image 94
senshin Avatar answered Sep 29 '22 22:09

senshin