New submission from George Sakkis <[email protected]>:
According to the docs, heapq.nlargest should be equivalent to
sorted(iterable, key=key, reverse=True)[:n], and since sorted() is
stable, so should heapq.nlargest be. This is not the case:
>>> s =[
('Mike', -1),
('John', 3),
('George', 2),
('Adam', 3),
('Paul', -3),
('Peter', -2),
('Mary', -1)
]
>>> heapq.nlargest(2, s, key=lambda x:abs(x[1]))
[('Paul', -3), ('Adam', 3)]
>>> sorted(s, key=lambda x:abs(x[1]), reverse=True)[:2]
[('John', 3), ('Adam', 3)]
The fix should be easy:
--- heapq.py 2009-04-04 23:27:53.125000000 -0400
+++ heapq2.py 2009-04-05 10:51:32.187500000 -0400
@@ -133 +133 @@
-from operator import itemgetter
+from operator import itemgetter, neg
@@ -334 +334 @@
- it = izip(imap(key, in1), count(), in2) # decorate
+ it = izip(imap(key, in1), imap(neg, count()), in2) # decorate
----------
components: Library (Lib)
messages: 85508
nosy: gsakkis
severity: normal
status: open
title: heapq.nlargest does not perform stable sort
type: behavior
versions: Python 2.5
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue5697>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com