On 01/23/2012 07:32 AM, Surya K wrote:
Date: Sun, 22 Jan 2012 21:28:14 -0500
From: d...@davea.name
To: sur...@live.com
CC: tutor@python.org
Subject: Re: [Tutor] how to handle very large numbers
On 01/22/2012 09:08 PM, Surya K wrote:
Well,
I have been doing a puzzle where I have to deal with number 10^18. A variable
can store that value but can't do operations.Ex: If I use range() on it, it
shows overflow error.
So, How do I handle this. I have to use range() for that number.. in this
instance.
Also mention how to handle in other cases too (A small tutorial/ book would be
appreciated )
Thanks
Check out the ongoing thread of someone who's probably doing the same
assignment. Subject is "OverflowError in lucky numbers script"
Short answers for range(): You need to specify your Python version.
In Python 2.7, range() has no problem handling longs as its arguments.
It does have a problem when the number of items gets too large for
memory. You could avoid the memory problem by using xrange(), which is
restricted to ints. You can, however, write a generator to operate over
a series of such longs.
I don't believe Python 3.x range has any constraints, and it's already a
generator, so you'll have to be more specific about what your
environment is.
--
DaveA
I am using Python 2.7. I don't think range() can take large values.
example:
I took a = 1000000000000000000 (10^18); This is the max limit in a puzzle.
python showed the following error :OverflowError: range() has too many items.
I even tried using xrange(), I didn't solve the issue..
Presumably you tried something like range(a), in which case you tried to
create a list of 10**18 items, which is clearly too large for memory.
But range(a, a+1000) would be perfectly fine. So it's not a case of
range not accepting large values, but merely a question of how much will
fit in memory.
As I said, just write your own generator to replace xrange, and you're
fine. You haven't said yet what you plan to do with it, but if you just
want a generator for consecutive integers, you can use (untested)
def myrange(a, b):
while a < b:
yield a
a += 1
It's not quite as flexible as xrange, nor as fast, but it's easy to type.
By the way, if you're evaluating some useful function for a few
quadrillion items, running out of memory will be the least of your
worries. Usually, when the assignment involves huge numbers, there's a
better approach than starting from zero.
--
DaveA
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor