# "Natural" use of cmp= in sort

Peter Otten __peter__ at web.de
Mon Nov 10 20:19:46 CET 2014

```Paddy wrote:

> Hi, I do agree with
>                   Raymond H. about the relative merits of cmp= and key= in
> sort/sorted, but I decided to also not let natural uses of cmp= pass
> silently.
>
> In answering this question, http://stackoverflow.com/a/26850434/10562
> about ordering subject to inequalities it seemed natural to use the cmp=
> argument of sort rather than key=.
>
> The question is about merging given inequalities to make 1 inequality such
> that the inequalities also stays true.
>
>
> Here is a copy of my code:
>
> Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
>>>> ineq = """f4 > f2 > f3
> f4 > f1 > f3
> f4 > f2 > f1
> f2 > f1 > f3"""
>>>> print(ineq)
> f4 > f2 > f3
> f4 > f1 > f3
> f4 > f2 > f1
> f2 > f1 > f3
>>>> greater_thans, all_f = set(), set()
>>>> for line in ineq.split('\n'):
> ....tokens = line.strip().split()[::2]
> ....for n, t1 in enumerate(tokens[:-1]):
> ........for t2 in tokens[n+1:]:
>
>
>>>> sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else
> ...........(1 if (t1, t2) not in greater_thans else -1))
> ['f4', 'f2', 'f1', 'f3']
>>>>

I'm not sure this works. I tried:

ineq = """f4 > f2 > f3
f4 > f1 > f3
f4 > f2 > f1
f2 > f1 > f3
f3 > f5
"""

greater_thans = set()
all_f = set()

for line in ineq.split('\n'):
tokens = line.strip().split()[::2]
for n, t1 in enumerate(tokens[:-1]):
for t2 in tokens[n+1:]:

print all_f
print greater_thans

print sorted(all_f, cmp=lambda t1, t2: 0 if t1==t2 else
(1 if (t1, t2) not in greater_thans else -1))
set(['f1', 'f2', 'f3', 'f4', 'f5'])
set([('f1', 'f3'), ('f2', 'f1'), ('f2', 'f3'), ('f4', 'f3'), ('f4', 'f2'),
('f4', 'f1'), ('f3', 'f5')])
['f4', 'f2', 'f1', 'f3', 'f5']