Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write the digits of a number into an array

I want to calculate with seperated digits of a very long number. How can I do this in Python2.7? I thought about somehow write the digits in an array so that I can access the digits with array(x):

number = 123456789123456789
array = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]

The problem is, that the number has so many digits, that it would take very long to do that manually. So how can I do this automatically?

like image 303
Maxi Avatar asked Jan 03 '14 11:01

Maxi


1 Answers

You can use map, int and str functions like this

print map(int, str(number))

str function converts the number to a string.

map function applies the int function to each and every element of stringifed number, to convert the string to an integer.

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you are doing this again and again, like in a loop, then list comprehension will be faster than the map approach

number = 123456789123456789
from timeit import timeit
print timeit("map(int, str(number))", "from __main__ import number")
print timeit("[int(dig) for dig in str(number)]", "from __main__ import number")

Output on my machine

12.8388962786
10.7739010307
like image 148
thefourtheye Avatar answered Oct 23 '22 05:10

thefourtheye