How to deal with very large numbers in python (19 digits) [closed]
-
04-07-2021 - |
Pergunta
In python I need to be able to cycle through a 19 digit number; what is the typical way of doing this? I'm using python 2.7.x; but will use python 3.x if there is a viable solution.
I have a large number; 1000**5
(and even larger 1000**10
) for example; I need to cycle through this number list in a for loop. I am aware of the time it will take; but because I cannot find a way to cycle through such a big number I'm at a loss.
I've tried with xrange
, range
, and itertools.islice
in python 2.7 and receive Overflow
errors.
Thanks
Solução
The following is true for python 3.x:
The int
type in python does not have a limit. If you want to iterate through 0,1,2...n where n is a 19-digit number, you can just do:
for i in range(n):
pass #whatever you like
Although that would take a very long time.
Outras dicas
Not as pretty as for, but just use while() and you will overcome the problem (plus it will work with whatever version of Python):
i=0
while (i<1000**10):
i += 1
# do some stuff
In case you were trying to iterate the single digits:
long_int_string = '34234345456575657'
for digit in [int(x) for x in long_int_string]:
# do something useful with digit
print digit
It sounds like you want to iterate through the individual digits of an integer.
For situations like these, it is useful to know that x % 10
is equal to the rightmost digit of a positive integer x
in base ten.
With that in mind, you can get every digit by iteratively using modulus and reducing the number.
def splitIntoDigits(x):
digits = []
while x != 0:
digits.insert(0, int(x%10))
x /= 10
return digits
print splitIntoDigits(15016023042)
[1, 5, 0, 1, 6, 0, 2, 3, 0, 4, 2]
Also, comedy one-line answer:
>>> [int(num/(10**x)%10) for x in range(int(math.log(num,10)),-1,-1)]
[1, 5, 0, 1, 6, 0, 2, 3, 0, 4, 2]