10

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Maxi
  • 307
  • 1
  • 3
  • 13

4 Answers4

26

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
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
7

You can also use a list comprehension link this.

array = [int(x) for x in str(number)]
Buddhima Gamlath
  • 2,318
  • 1
  • 16
  • 26
7

As an alternative, the purely mathematical solution is below. By repeatedly dividing by 10 and taking the remainder you can extract each digit.

n = 123456789123456789
result = []
while n != 0:
    n, d = divmod(n, 10)
    result.append(int(d))
result.reverse()
print result # [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Tim
  • 11,710
  • 4
  • 42
  • 43
  • Good job. Two minor improvements: divmod returns ints when applied to an int, so `int(d)` is not needed and `insert(0,d)` instead of `append` to get rid of the reverse step. – georg Jan 03 '14 at 11:56
  • 2
    The questioner gave `123456789123456789` as the sample data, so (at least on 2.7) `divmod` returns a long. `insert(0,d)` would run in quadratic time - I'd much rather have a `reverse` and get linear time. Thanks for the suggestions though. – Tim Jan 03 '14 at 11:58
  • 2
    +1 You can also use [`collections.deque`](http://docs.python.org/2/library/collections.html#collections.deque) here for faster insertion on left side. – Ashwini Chaudhary Jan 03 '14 at 12:01
2

You can simply iterate over each digit in number and push into an array. Try this

result = []
for d in str(number):
    result.append (int(d))

print result
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • The answer from thefourtheye appears better, but this works too – Naveed Hasan Jan 03 '14 at 11:45
  • @NaveedHasan yeah, I really liked the answer from thefourtheye. It took me about 2 minutes to write this code and test it out. Meanwhile, thefourtheye posted an awesome answer :| – Sachin Jain Jan 03 '14 at 11:46