Long integers, xrange and number theory
Delaney, Timothy
tdelaney at avaya.com
Sun Dec 8 19:51:45 EST 2002
> From: Paul Rubin [mailto:phr-n2002b at NOSPAMnightsong.com.avaya.com]
>
> martin at v.loewis.de (Martin v. Löwis) writes:
> > > xrange would be the different story, since it involves a proxy
> > > object that supports a sequence protocol.
> >
> > Indeed. That proxy object would need to change, making it
> inefficient
> > even for small integers.
>
> No, with small integer arguments the xrange function could just
> construct the same proxy object it does now. It would only make a new
> kind of object if long ints were involved.
Just a quick implementation ... we can do better ;)
from __future__ import generators
def _xrange (start, stop, step):
while 1:
if step > 0 and start > stop:
return
if step < 0 and start < stop:
return
yield start
start += step
def xrange (start, stop=None, step=None, xrange=xrange):
if stop is None:
stop = start
start = 0
if step is None:
step = 1
try:
return xrange(start, stop, step)
except OverflowError:
return _xrange(start, stop, step)
if __name__ == '__main__':
for i in xrange(10):
print i
print
for i in xrange(1000000000000000L, 1000000000000010L):
print i
Tim Delaney
More information about the Python-list
mailing list