Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

So I'm working with a couple of previous comparators that look at specific qualities in two tuples and return valid if the first is more prominent than the second, bogus assuming in any case. Here's the code for one of them: 

def cmpValue(subInfo1, subInfo2):

    """

    Returns True if value in (value, work) tuple subInfo1 is GREATER than

    value in (value, work) tuple in subInfo2

    """

    # TODO...

    if subInfo1[0] > subInfo2[0]:

        return True

    else:

        return False

Presently, I have a word reference that has various tuple sections of the sort being analyzed previously. I need to sort them all in the opposite request, yet I don't generally see how I would achieve that. I was thinking something like: 

sortedDict = sorted(subjects, key=comparator, reverse = True)

In any case, I don't have the foggiest idea of what to pass into the comparator on the grounds that each comparator takes two contentions (subInfo1, subInfo2). I can't change the comparator capacities. 

1 Answer

0 votes
by (26.4k points)

You're passing the comparator as the key capacity. You should be passing it as the cmp, enclosed by some sort of capacity that transforms it into a legitimate comparator.

def make_comparator(less_than):

    def compare(x, y):

        if less_than(x, y):

            return -1

        elif less_than(y, x):

            return 1

        else:

            return 0

    return compare

sortedDict = sorted(subjects, cmp=make_comparator(cmpValue), reverse=True)

Even though, You should be using key functions:

sorted(subjects, operator.itemgetter(0), reverse=True)

Make sure, sortedDict will not be dict.

Want to know more about python? Come and join: python certification course

For more details, do check out..

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 17, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
4 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...