|
1 |
| -import heapq |
| 1 | +# -*- coding: utf-8 -*- |
2 | 2 |
|
| 3 | +# bonus for Python |
| 4 | +# from heapq import nsmallest |
| 5 | +# nsmallest(n, iterable, key=None) |
3 | 6 |
|
4 |
| -def wrap(x): |
5 |
| - return -x |
| 7 | +# all example are compatible with both Python 2.7.X and Python 3.X |
| 8 | +from heapq import heappush, heappushpop |
6 | 9 |
|
| 10 | +# 等价于ksmallest1 = lambda lst, k : sorted(lst)[:k] |
| 11 | +def ksmallest1(lst, k): |
| 12 | + """ |
| 13 | + code example for section 2.1 solution 1 |
| 14 | + see https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/02.01.md |
7 | 15 |
|
8 |
| -def unwrap(x): |
9 |
| - return -x |
| 16 | + author: jiang |
| 17 | + |
10 | 18 |
|
| 19 | + created on 2014-5-25 |
| 20 | + """ |
| 21 | + return sorted(lst)[:k] |
11 | 22 |
|
12 |
| -def topk(lst, k): |
13 |
| - h = [] |
14 |
| - for i in lst[0:k]: |
15 |
| - heapq.heappush(h, wrap(i)) |
16 |
| - for i in lst[k:]: |
17 |
| - heapq.heappushpop(h, wrap(i)) |
18 |
| - return map(unwrap, h) |
| 23 | + |
| 24 | +def ksmallest2(lst, k): |
| 25 | + """ |
| 26 | + code example for section 2.1 solution 2 |
| 27 | + see https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/02.01.md |
| 28 | +
|
| 29 | + author: jiang |
| 30 | + |
| 31 | +
|
| 32 | + created on 2014-5-25 |
| 33 | + """ |
| 34 | + result = lst[:k] |
| 35 | + kmax = max(result) |
| 36 | + for elem in lst[k+1:]: |
| 37 | + if elem < kmax: |
| 38 | + result.remove(kmax) |
| 39 | + result.append(elem) |
| 40 | + kmax = max(result) |
| 41 | + return result |
| 42 | + |
| 43 | + |
| 44 | +def ksmallest3(lst, k): |
| 45 | + """ |
| 46 | + code example for section 2.1 solution 3 |
| 47 | + see https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/02.01.md |
| 48 | +
|
| 49 | + modified by jiang |
| 50 | + |
| 51 | +
|
| 52 | + modified on 2014-5-24 |
| 53 | + """ |
| 54 | + heap = [] |
| 55 | + # 需要map是因为标准库中实现的是最小堆 |
| 56 | + tmp = map(lambda x: -x, lst) |
| 57 | + for elem in tmp[:k]: |
| 58 | + heappush(heap, elem) |
| 59 | + for elem in tmp[k:]: |
| 60 | + heappushpop(heap, elem) |
| 61 | + return map(lambda x: -x, heap) |
19 | 62 |
|
20 | 63 |
|
21 | 64 | if __name__ == "__main__":
|
22 |
| - l = [1, 9, 2, 4, 7, 6, 3] |
| 65 | + lst = [1, 9, 2, 4, 7, 6, 3] |
23 | 66 | k = 3
|
24 |
| - print topk(l, k) |
| 67 | + print(ksmallest1(lst,k)) |
| 68 | + print(ksmallest2(lst,k)) |
| 69 | + print(ksmallest3(lst, k)) |
| 70 | + |
0 commit comments