spellchecker icon indicating copy to clipboard operation
spellchecker copied to clipboard

Return cmp in python 3

Open irvanseptiar opened this issue 6 years ago • 2 comments

hai, I am Irvan. I want to ask about cmp in your code:

freq_sorted = sorted(suggestions, cmp = comparefreq)[10:]     # take the top 10
hamming_sorted = sorted(suggestions, cmp = comparehamm)[10:] 

What is cmp? Would you mind to explaining it to me in python 3? thanks

irvanseptiar avatar Jan 04 '19 08:01 irvanseptiar

https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons

cmp in python 3 removed, equivalent operation. This means: take the difference, and then the sign of that difference.

infnetdanpro avatar Jan 04 '19 16:01 infnetdanpro

cmp stands for "compare", and it's a function used to compare the items in the list to come up with the sort order you need. Because you can pass any function you want to do the sorting, you can sort by other things besides alphabetical/lexical order, e.g sort by length of the words:

words = [
    'banana',
    'apple',
    'cherry',
    'pumpkin',
]

by_length = labmda a, b: len(a) - len(b)

list(sorted(words, cmp=by_length))
['apple', 'cherry', 'banana', 'pumpkin']

In Python 3, instead of a cmp "compare" function, they ask for a key function instead, which works like so:

by_length = lambda a: len(a)

list(sorted(words, key=by_length))

The difference is that instead of taking both items a and b and comparing them yourself, the key function just takes one item and returns the value you want to use to compare it against other items.

Did that help @irvanseptiar?

pirate avatar Jan 07 '19 21:01 pirate