0

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.

7
  • You don't need to subclass the built-in dict class to sort them because regular dictionaries can be sorted. Are creating a subclass for some other reason and if so, what are they?
    – martineau
    Oct 17, 2019 at 1:15
  • @martineau To be able to implement the .rank() method?
    – Selcuk
    Oct 17, 2019 at 1:18
  • @martineau Selcuk is right. That is why I subclassed the built-in.
    – ricoflow
    Oct 17, 2019 at 1:20
  • @martineau It only appears that because you have (incorrectly) edited the question.
    – Selcuk
    Oct 17, 2019 at 1:34
  • 1
    @Selcuk: OK, sorry my mistake.
    – martineau
    Oct 17, 2019 at 1:39

1 Answer 1

1

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
2
  • just curious, but why do you say the naive way?
    – ricoflow
    Oct 17, 2019 at 13:45
  • 1
    Because this is probably not the most efficient way of doing it. That being said, it is probably reasonable for not-so-huge datasets. See Naive algoritms.
    – Selcuk
    Oct 20, 2019 at 23:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.