开发者

python reorganize codes

开发者 https://www.devze.com 2023-01-11 08:17 出处:网络
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

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


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!


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
0

精彩评论

暂无评论...
验证码 换一张
取 消