Skip to content

Instantly share code, notes, and snippets.

@miku
Created June 29, 2010 11:15
Show Gist options
  • Save miku/457086 to your computer and use it in GitHub Desktop.
Save miku/457086 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# http://stackoverflow.com/questions/3139869/heapq-nlargest-index-of-returned-result-in-original-sequence/3139918#3139918
import heapq
from timeit import Timer
seq = [100, 2, 400, 500, 400] + range(9995)
# seq = ("hello", 2, "world", 500, 400)
def a(seq, n=2):
"""
returns [(3, 500), (2, 400)]
"""
return heapq.nlargest(n, enumerate(seq), key=lambda x: x[1])
def b(seq, n=2):
"""
returns [3, 2]
"""
return map(seq.index, heapq.nlargest(n, seq))
def c(seq, n=2):
"""
returns [(500, 3), (400, 2)]
"""
map(lambda n: (n, seq.index(n)), heapq.nlargest(n, seq))
if __name__ == '__main__':
loops, n = 1000, 100
_a = Timer("a(seq, n=%s)" % n, "from __main__ import a, seq")
_b = Timer("b(seq, n=%s)" % n, "from __main__ import b, seq")
_c = Timer("c(seq, n=%s)" % n, "from __main__ import c, seq")
print _a.timeit(number=loops)
print _b.timeit(number=loops)
print _c.timeit(number=loops)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment