spellchecker
spellchecker copied to clipboard
Return cmp in python 3
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
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.
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?