-
Notifications
You must be signed in to change notification settings - Fork 152
/
cmp.py
153 lines (135 loc) · 2.77 KB
/
cmp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
"""
Python 3 removed the 'cmp' function and raises a Type error when you try to
compare different types. This module recreates Python 2 style 'cmp' function
which produces a "total ordering" for mixed type lists.
"""
import functools
import itertools
def cmp(a, b):
"""
>>> cmp(1, 1)
0
>>> cmp('A', 'A')
0
>>> cmp(None, None)
0
>>> cmp(('A', 'B'), ('A', 'B'))
0
>>> cmp(['A', 'B'], ('A', 'B'))
0
>>> cmp((1, 2), (1, 2))
0
>>> cmp((1, 2), [1, 2])
0
>>> cmp(1, 2)
-1
>>> cmp('A', 'B')
-1
>>> cmp(('A', 'B'), ('A', 'C'))
-1
>>> cmp(['A', 'B'], ('A', 'C'))
-1
>>> cmp((1, 2), (1, 3))
-1
>>> cmp((1, 2), [1, 3])
-1
>>> cmp(2, 1)
1
>>> cmp('B', 'A')
1
>>> cmp(('A', 'C'), ('A', 'B'))
1
>>> cmp(['A', 'C'], ('A', 'B'))
1
>>> cmp((1, 3), (1, 2))
1
>>> cmp((1, 3), [1, 2])
1
>>> cmp(1, None)
1
>>> cmp('A', None)
1
>>> cmp(('A', 'B'), None)
1
>>> cmp(['A', 'B'], None)
1
>>> cmp((1, 2), None)
1
>>> cmp((1, 2), None)
1
>>> cmp(None, 2)
-1
>>> cmp(None, 'B')
-1
>>> cmp(None, ('A', 'B'))
-1
>>> cmp(None, ('A', 'C'))
-1
>>> cmp(None, (1, 2))
-1
>>> cmp(None, [1, 3])
-1
>>> cmp(1, 'A')
-1
>>> cmp('A', 1)
1
>>> cmp(('A', 'B'), 1)
1
>>> cmp(1, ['A', 'B'])
-1
>>> cmp((1, 2), 1)
1
>>> cmp(1, (1, 2))
-1
>>> cmp('A', 'AA')
-1
>>> cmp('AA', 'A')
1
>>> cmp(b'A', b'A')
0
>>> cmp(b'A', b'AA')
-1
>>> cmp(b'AA', b'A')
1
>>> def bit(*args):
... return args
>>> a = ('CLBLL', 'L', 'SLICEL', ('X', 0), 'AFFMUX', 'XOR')
>>> b = ('CLBLL', 'L', 'SLICEL', ('X', 0), 'AFFMUX', ('F', 7))
>>> cmp(a, b)
-1
>>> cmp(b, a)
1
"""
if not isinstance(a, (str, bytes)) and not isinstance(b, (str, bytes)):
try:
for i, j in itertools.zip_longest(iter(a), iter(b)):
r = cmp(i, j)
if r != 0:
return r
return 0
except TypeError:
pass
if type(a) == type(b):
if a == b:
return 0
elif a < b:
return -1
elif a > b:
return 1
else:
raise SystemError
return cmp(a.__class__.__name__, b.__class__.__name__)
cmp_key = functools.cmp_to_key(cmp)
if __name__ == "__main__":
import doctest
doctest.testmod()