Issue
What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:
for i in range(1,600851475143):
Solution
range(1, 600851475143)
wants to generate a very large list in memory, and you'll get an out of memory error. To save memory, use xrange
instead of range
. Unfortunately, xrange
doesn't work with large numbers (it's an implementation restriction) Example (raises OverflowError):
for i in xrange(1, 600851475143):
print i
You can have large minimum or maximum values in your interval with range
, if their difference is small. Example:
x = 1 << 200
print list(xrange(x, x + 3))
Output:
[1606938044258990275541962092341162602522202993782792835301376L, 1606938044258990275541962092341162602522202993782792835301377L, 1606938044258990275541962092341162602522202993782792835301378L]
A fancy solution to your original for loop problem:
def bigrange(a, b = None):
if b is None:
b = a
a = 0
while a < b:
yield a
a += 1
for i in bigrange(1, 600851475143):
print i
A less fancy solution, which works even if you have continue
in the loop body:
i = 1 - 1
while i < 600851475143 - 1:
i += 1
print i
Answered By - pts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.