[Tutor] Workaround for limitation in xrange()?
Dick Moores
rdm at rcblue.com
Tue Oct 10 22:30:42 CEST 2006
At 12:31 PM 10/10/2006, Marc Poulin wrote:
>--- Dick Moores <rdm at rcblue.com> wrote:
> >
> > 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.
> >
>
>This is an example of a "coroutine".
>See http://en.wikipedia.org/wiki/Coroutine
>
>def hugerange(minval, maxval):
> val = minval
> while val < maxval:
> yield val
> ### return value of "val" to calling routine
> ### at this point and place
> ### hugerange() function temporarily
> ### on hold ...
> ###
> ### next call to hugerange()
> ### resumes at this point with
> ### all previous variable values
> ### still intact ...
> val += 1
Ah, it's beginning to make sense. However, it seems there's a need to
do this because the while loop is inside a function (made generator).
The while loop of mine in
<http://www.rcblue.com/Python/1histogram-5a-ForWeb.txt> is not in a
function, so it seems I don't need a generator. Am I correct? I have
a real interest in speed, however, and being forced to use the while
loop for k larger than 2**31-1 really slows things down. It seems a
while loop is about 20% slower than an equivalent for loop. Would
using a generator be a help speedwise? I suspect it wouldn't. How about it?
Thanks very much, Marc.
Dick
More information about the Tutor
mailing list