3

I want to run a range from a start to an end value. It works fine on low numbers but when it gets too large it causes an overflow error as int too large to convert to C Long. I am using Python 2.7.3.

I read here OverflowError Python int too large to convert to C long on using the itertools.count() method except that method works differently to the xrange method by stepping as opposed to declaring an end range value.

Can the itertools.count() be set up to work like xrange()?

print "Range start value"
start_value = raw_input('> ')
start_value = int(start_value)

print "Range end value"
end_value = raw_input('> ')
end_value = int(end_value)

for i in xrange(start_value, end_value):
    print hex(i)
Community
  • 1
  • 1
Python_newbie
  • 133
  • 1
  • 2
  • 7
  • Related, giving different alternatives to `xrange()` not using `itertools.count()`: [range and xrange for 13-digit numbers in Python?](http://stackoverflow.com/q/2187135) – Martijn Pieters Dec 28 '14 at 11:34

1 Answers1

4

You can use itertools.islice() to give count an end:

from itertools import count, islice

for i in islice(count(start_value), end_value - start_value):

islice() raises StopIteration after end_value - start_value values have been iterated over.

Supporting a step size other than 1 and putting it all together in a function would be:

from itertools import count, islice

def irange(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start
    length = 0
    if step > 0 and start < stop:
        length = 1 + (stop - 1 - start) // step
    elif step < 0 and start > stop:
        length = 1 + (start - 1 - stop) // -step
    return islice(count(start, step), length)

then use irange() like you'd use range() or xrange(), except you can now use Python long integers:

>>> import sys
>>> for i in irange(sys.maxint, sys.maxint + 10, 3):
...     print i
... 
9223372036854775807
9223372036854775810
9223372036854775813
9223372036854775816
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • This worked perfectly so it seems @Martijn, I only needed to use part of the code (around islice) and it is handling much much larger numbers. The only thing I see on the values is the "L" suffix displayed at the end of each value but from what I can tell its working as expected. – Python_newbie Dec 28 '14 at 20:35
  • @Python_newbie: Python `long` integers have a `L` added when represented (`repr(value)`) to show that they are long integers, distinguishing them from 'small' integers. – Martijn Pieters Dec 28 '14 at 21:58