Home > Article > Backend Development > Analysis of the comparison principle of Python's built-in comparison function cmp
Comparison principle of Python's cmp comparison function
cmp(x, y): Compare two objects. If the former is less than the latter, it returns -1, if they are equal, it returns 0, and if it is greater than the latter, it returns 1.
Python's cmp comparison function comparison principle
Python’s cmp function can compare between the same type or between different data types. Then determine the comparison size based on the return value of Python's cmp comparison function.
>>> list1, list2 = [123, 'xyz'], [456, 'abc']
>>> cmp(list1, list2)
-1
>>> cmp (list2, list1)
1
>>> list3 = list2 + [789]
>>> list3
[456, 'abc', 789]
>>> cmp(list2, list3)
-1
Observing several comparisons of the cmp function above, we can summarize:
Python’s cmp comparison function, if we are comparing two similar objects, the comparison operation is very intuitive.
Comparison of numbers and strings, directly compare their values.
For comparison of sequence types, the methods are similar. Python tries to produce fair results when two objects are basically incomparable. For example, when two objects have no relationship, or when the two types have no functions for comparison at all, Python can only make conclusions based on "logic". Algorithm logic of comparison:
1. Compare the elements of two lists.
2. If the compared elements are of the same type, compare their values and return the result.
3. If the two elements are not of the same type type, check whether they are numbers.
a. If they are numbers, perform the necessary numeric cast, and then compare.
b. If the elements of one side are numbers, the elements of the other side are "big" (numbers) is the "smallest")
c. Otherwise, compare by alphabetical order of type names.
4. If one list reaches the end first, then the other longer list is "bigger".
5. If we If the elements of both lists are exhausted and all elements are equal, then the result is a tie, which means returning a 0.
This is the comparison principle of Python's cmp function