[英]finding kth smallest element
I followed the algorithm in the book for this problem. 我针对该问题遵循了书中的算法。 when I print result it is not correct.
当我打印结果不正确时。 the algorithm is exactly as in the book my code
算法与我的代码完全相同
import math
def quickSelect(A, k):
m = A[math.floor(len(A)/2)]
L = [i for i in A if i < m]
E = [i for i in A if i == m]
G = [i for i in A if i > m]
print(L)
print(E)
print(G)
if k <= len(L):
return quickSelect(L, k)
elif k <= (len(E) + len(G)):
return m
else:
return quickSelect(G, k- len(L) - len(E))
result = quickSelect([7, 14, 10, 12, 2, 11, 29, 3, 4], 4)
print(result)
These statements: 这些陈述:
L = [i for i in A if i < m] # less than m
E = [i for i in A if i == m] # equal to m
G = [i for i in A if i > m] # greater than m
partition the array into three ranges: 将数组划分为三个范围:
| L1 L2 L3 L4 | E1 | G1 G2 G3
| | |
0 | |
len(L) |
len(L) + len(E)
Your condition for the second range, 您对第二个范围的条件,
elif k <= (len(L) + len(G)):
return m
is wrong. 是错的。 It should be:
它应该是:
elif k <= (len(L) + len(E)):
return m
Node: Instead of using floating-point math, you can just calculate m
with Python's integer division: m = A[len(A) // 2]
节点:您可以使用Python的整数除法来计算
m
,而无需使用浮点数学: m = A[len(A) // 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.