Python: can I extend the upper bound of the range () method?

What is the upper bound of the range () function and how can it be expanded, or, alternatively, the best way to do this:

for i in range(1,600851475143):
+3
source share
5 answers

range(1, 600851475143)wants to create a very large list in memory, and you get an error in memory. To save memory, use xrangeinstead range. Unfortunately, it xrangedoes not work with large numbers (this is an implementation restriction) Example (throws an OverflowError):

for i in xrange(1, 600851475143):
  print i

You can have large minimum or maximum values ​​in your interval with rangeif their difference is small. Example:

x = 1 << 200
print list(xrange(x, x + 3))

Output:

[1606938044258990275541962092341162602522202993782792835301376L, 1606938044258990275541962092341162602522202993782792835301377L, 1606938044258990275541962092341162602522202993782792835301378L]

Unusual solution to the problem with your original for the loop:

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

, , continue:

i = 1 - 1
while i < 600851475143 - 1:
  i += 1
  print i
+9

pts python xrange:

xrange() . . Python C longs ( "" Python), , C . , itertools: islice(count(start, step), (stop-start+step-1)//step)

c python .

+2

, ? - , range()?

x = 1
while x < 600851475143:
    // some code
    x += 1
+1

, Python . 2.5.2, xrange OverflowError . .

def g(start, stop):
    i = start
    while i < stop:
        yield i
        i += 1

x = 1<<200
for i in g(x, x+3):
    print i
0

Here is the answer using itertools. This is a little far-fetched, but it works:

from itertools import repeat, count, izip
for i,_ in izip(count(1), repeat(1, 600851475143)):
    ...

Another answer is to write your own generator:

def my_xrange(a, b):
    while a < b:
        yield a
        a += 1

for i in my_xrange(1, 600851475143):
    ...
0
source

Source: https://habr.com/ru/post/1707971/


All Articles