enumerate is very useful and now "progresserate"

Bengt Richter bokr at oz.net
Wed Nov 19 19:14:30 EST 2003


On Wed, 19 Nov 2003 18:41:26 -0500, "Francis Avila" <francisgavila at yahoo.com> wrote:

>Brian Kelley wrote in message
><3fbbbffd$0$577$b45e6eb0 at senator-bedfellow.mit.edu>...
>>It also inspired me to write "progresserate" which returns the percent
>>completed of the list and the current value.
>
>
>>This is useful for updating progress bars and the like.  I use it all
>>the time, it sure saves code duplication.
>>
>>Is this idea something that is useful enough for inclusion in the
>>standard library?  (Not this code as-is, I don't show error checking for
>>brevity's sake)
>
>
>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):

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)
>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