[Tutor] Workaround for limitation in xrange()?
Dick Moores
rdm at rcblue.com
Tue Oct 10 20:10:21 CEST 2006
>
>> >>> for x in xrange(2**31):
>> pass
>>
>>Traceback (most recent call last):
>> File "<pyshell#16>", line 1, in <module>
>> for x in xrange(2**31):
>>OverflowError: long int too large to convert to int
>
Here are the suggestions I've received:
Danny's
>#################
>def myxrange(m, n=None, skip=1):
> """An xrange-like function that can deal with long ints.
> Note: doesn't deal with negative ranges particularly well."""
> if n is None:
> m, n = 0, m
> i = m
> while i < n:
> yield i
> i = i + skip
>#################
Kent's
Encapsulate the while loop in a generator:
def count(limit):
n=0
while n<limit:
yield n
n += 1
Andrei's
Write your own iterator:
>>> def hugerange(minval, maxval):
... val = minval
... while val < maxval:
... yield val
... val += 1
All 3 are essentially the same, aren't they. Which makes me feel even
dumber, because I don't understand any of them. I've consulted 3
books, and still don't understand the use of yield.
Let me show you what I was doing when I ran into the 2**31-1
limitation: <http://www.rcblue.com/Python/1histogram-5a-ForWeb.txt>
This is one of my attempts to test the degree of uniformity of
random(). The others are seeing how close the average random() return
comes to 0.5, and using random() in an approximation of pi.
I've realized now that all 3 scripts require an immense number of
calls to random(), so many that I wouldn't be able to use my computer
for anything else for weeks, maybe months. But be that as it may, I'd
still like to know how to use yield in my 1histogram-5a.
For your convenience, here's the list h, and the while loop I used:
h = 100*[0]
c = 0
while c < k:
r = random()
i = int(math.floor(100*r))
h[i] += 1
c += 1
So, for a random() return of 0.27862506717494118, i would be 27, and
h[27] would be incremented by 1.
Thanks,
Dick
More information about the Tutor
mailing list