Is there a more elegant way to do this?

Greg Landrum glandrum at my-deja.com
Wed Sep 13 19:56:54 EDT 2000


In article <8poglt$10fq$1 at news.rchland.ibm.com>,
  "Larry Whitley" <ldw at us.ibm.com> wrote:
> Here's the problem:
>
> I have a list of counters that will have a wide variety of different
values
> in them.  At intervals while the program runs, I will print out the
indexes
> of the counters with the five largest counts.  The counters are in a
list
> identified below as self.counters.  Here's my inelegant way of doing
it.
>

If you are willing to use Numeric you'll get a lot of what you want
for "free":


    def runningReport(self,num=5):
        order = argsort(self.counters)[-num:].tolist()
        order.reverse()

        return order

That's not the prettiest code, but it should be pretty fast.  argsort()
is truly a wonderful thing. (Don't forget the 'from Numeric import *'
though.)

If you switch completely to Numeric, you can skip the conversions to
a list, which should produce another speedup.

Further use of Numeric features leads to:

    def runningReport(self,num=5):
        return argsort(self.counters)[-1:-(num+1):-1].tolist()

but that's maybe a bit *too* perliffic.

-greg


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list