Reputation: 125
Given the following classes:
class Comparison():
def __init__(self, value):
self.value = value
self.rank = 0
class Comparisons(dict):
def __init__(self):
super(Comparisons, self).__init__()
def rank(self):
# Method to examine each Comparison instance and
# assign Comparison.rank based on Comparison.value
What is an efficient way for the rank()
method to examine the objects and assign a rank? For example:
comparisons = Comparisons()
# store some Comparison instances
comparisons['one'] = Comparison(10)
comparisons['two'] = Comparison(5)
comparisons['three'] = Comparison(1)
# function to rank the comparisons
comparisons.rank()
print(comparisons['one'].rank)
print(comparisons['two'].rank)
print(comparisons['three'].rank)
Returns:
3
2
1
If the rank()
method could handle ties, that would be even more beneficial.
Upvotes: 0
Views: 109
Reputation: 59238
This looks like the most intuitive (naive?) way:
def rank(self):
sorted_comparisons = sorted(self.values(), key=lambda c: c.value)
for rank, comparison in enumerate(sorted_comparisons, 1):
comparison.rank = rank
Upvotes: 1