views:

91

answers:

2

Sorry I dont know how to add a comment with the format, so I post another question with code here, as I am new to python, seems that there are many better ways to reorgnize the codes to make it better:

def min_qvalue(self):
    s = 0
    q = 1
    for i in range(len(self.results)):
        if self.results[i].score > s:
            s = self.results[i].score
            q = self.results[i].qvalue
    return q

For the above code, should not be the best piece, any improvements possible? thanks :)

+4  A: 

This is the same code:

max_score_qvalue = max( (result.score, result.qvalue) for result in self.results)[1]

It makes pairs of the score and qvalue, finds the pair with the highest score (with max) and then gets the qvalue from it.

Actually, I wrote the above just because I keep forgetting that max takes a key function too:

max_score_qvalue = max(self.results, key=(lambda result: result.score)).qvalue

Also your function says min_qvalue but it computes one with the maximum score!

THC4k
so the final functional style formula ismin_qvalue = lambda self: max(self.results,key = (lambda result:result.score)).qvalue
Odomontois
@THC4k, they go different directions, i.e. the lower the q-value, the higher the socre is
ladyfafa
You can even get rid of the lambda by using operator.attrgetter("score") (though of course you need to import it)
Liquid_Fire
+1  A: 

If you result list is mutable and you often have need to compute this, it's may be better to you heap queue algorithm. There's sample code:

import heapq
class ResultManager(object):
    def __init__( self , results ):
        self.results = [( -result.score, result) for result in results]
        heapq.heapify( self.results )
    def append( self , result ):
        heapq.heappush( self.results , ( -result.score, result) )
    def getMaxScoreQValue(self):
        return self.results[0][1].qvalue
Odomontois