In [30]: def partition(seq):
...: pi = seq[0]
...: lo = [x for x in seq[1:] if x<=pi] #seq[0]是主元
...: hi = [x for x in seq[1:] if x>pi]
...: return lo,pi,hi
...:
...:
In [31]: def select(seq,k):
...: # 分解
...: lo,pi,hi = partition(seq)
...: m = len(lo)
...: if m ==k:
...: return pi
...: elif m < k:
...: return select(hi,k-m-1)
...: else :
...: return select(lo,k)
...:
In [32]: if __name__== '__main__':
...: seq = [73,298,2,3,4,2,4,2,90]
...: print(select(seq,4))
...: print(select(seq,5))