"Natural" use of cmp= in sort
Peter Otten
__peter__ at web.de
Mon Nov 10 14:19:46 EST 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)]
> on win32 Type "copyright", "credits" or "license()" for more information.
>>>> 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:]:
> ............greater_thans.add((t1, t2))
> ............all_f.add(t1)
> ........all_f.add(t2)
>
>
>>>> 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:
$ cat paddy.py
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:]:
greater_thans.add((t1, t2))
all_f.add(t1)
all_f.add(t2)
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))
$ PYTHONHASHSEED=0 python paddy.py
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']
$ PYTHONHASHSEED=1 python paddy.py
set(['f5', 'f4', 'f3', 'f2', 'f1'])
set([('f1', 'f3'), ('f2', 'f3'), ('f2', 'f1'), ('f4', 'f1'), ('f3', 'f5'),
('f4', 'f3'), ('f4', 'f2')])
['f5', 'f4', 'f2', 'f1', 'f3']
More information about the Python-list
mailing list