Skip to content

Commit 9d83843

Browse files
author
Jiang
committed
增加寻找最小的k个数问题解法一、二的实现,修订解法三的实现
1 parent 4149dc8 commit 9d83843

File tree

1 file changed

+60
-14
lines changed

1 file changed

+60
-14
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,70 @@
1-
import heapq
1+
# -*- coding: utf-8 -*-
22

3+
# bonus for Python
4+
# from heapq import nsmallest
5+
# nsmallest(n, iterable, key=None)
36

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
69

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
715
8-
def unwrap(x):
9-
return -x
16+
author: jiang
17+
1018
19+
created on 2014-5-25
20+
"""
21+
return sorted(lst)[:k]
1122

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)
1962

2063

2164
if __name__ == "__main__":
22-
l = [1, 9, 2, 4, 7, 6, 3]
65+
lst = [1, 9, 2, 4, 7, 6, 3]
2366
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

Comments
 (0)