Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate float into digits

I have a float:

pi = 3.141

And want to separate the digits of the float and put them into a list as intergers like this:

#[3, 1, 4, 1]

I know to to separate them and put them into a list but as strings and that doesnt help me

like image 248
JoJo Avatar asked Mar 08 '26 14:03

JoJo


1 Answers

You need to loop through the string representation of the number and check if the number is a digit. If yes, then add it to the list. This can be done by using a list comprehension.

>>> pi = 3.141
>>> [int(i) for i in str(pi) if i.isdigit()]
[3, 1, 4, 1]

Another way using Regex (Not - preffered)

>>> map(int,re.findall('\d',str(pi)))
[3, 1, 4, 1]

A final way - Brute force

>>> pi = 3.141
>>> x = list(str(pi))
>>> x.remove('.')
>>> map(int,x)
[3, 1, 4, 1]

Few references from the docs

  • str.isdigit
  • re.findall
  • map

The timeit results

python -m timeit "pi = 3.141;[int(i) for i in str(pi) if i.isdigit()]"
100000 loops, best of 3: 2.56 usec per loop
python -m timeit "s = 3.141; list(map(int, str(s).replace('.','')))" # Avinash's Method
100000 loops, best of 3: 2.54 usec per loop
python -m timeit "import re;pi = 3.141; map(int,re.findall('\d',str(pi)))"
100000 loops, best of 3: 5.72 usec per loop
python -m timeit "pi = 3.141; x = list(str(pi));x.remove('.'); map(int,x);"
100000 loops, best of 3: 2.48 usec per loop

As you can see the brute force method is the fastest. The Regex answer as known is the slowest.

like image 83
Bhargav Rao Avatar answered Mar 10 '26 02:03

Bhargav Rao