enumerate is very useful and now "progresserate"

Brian Kelley bkelley at wi.mit.edu
Thu Nov 20 15:39:20 CET 2003

Bengt Richter wrote:
>>It's very neat (I always seem to want to turn every problem into a generator
>>problem :).  But actually, in this case (unless that error checking code you
>>mention forbids it), you don't need a class.  The only methods you define
>>are for the generator protocol, and none of them have arguments.  So a
>>generator function is enough (and undoubtably faster):

The generator solution is better.

> If it's being used to e.g. update a display, you can help overall speed by
> returning a change flag that is only on when a new percentage is returned,
> so it's easy to skip the i/o. (Of course, this makes a difference when you have
> size much greater than 100) e.g., (untested changes)

I let the GUI control this.  I.e. don't update if the last percentage 
the same as the current.  I'm not sure if this functionality should be 
in the generator or outside.

>>def progresserate(seq):
>>   size = float(len(seq))
>>   iterator = iter(seq)
>>   i = 0
>      percent = -1
>>   #what did self.last do?
>>   while True: #StopIteration from iterator will propagate.
>>       value = iterator.next()
>>       i += 1
>>       percent = int(i/size * 100)
>          lastpc, percent = percent, int(i/size * 100 +.5)
>>       yield percent, value
>          yield percent!=lastpc, percent, value
> Regards,
> Bengt Richter

More information about the Python-list mailing list