0

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

0

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

3 Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.