分治算法
判断某个元素是否在列表中
''' 判断某个元素是否在列表中 ''' def is_in_list(init_list,el): return [False,True][init_list[0]==el] #分治法 def solve(init_list,el): n=len(init_list) if n==1: return is_in_list(init_list,el) #分解 left_list,right_list=init_list[:n//2],init_list[n//2:] #合并 res=solve(left_list,el) or solve(right_list,el) return res if __name__ == '__main__': #测试数据 test_list=[12,2,23,45,67,3,2,4,45,63,24,23] #查找 print(solve(test_list,45)) print(solve(test_list,5))
求顺序表中最大值
''' 求顺序表中最大值 ''' #基本子算法 def get_max(max_list): return max(max_list) #分治法 def solve2(init_list): n=len(init_list) if n<=2: return get_max(init_list) left_list,right_list=init_list[:n//2],init_list[n//2:] left_max,right_max=solve2(left_list),solve2(right_list) return get_max([left_max,right_max]) if __name__ == '__main__': test_list=[2,1,4,5,523,433,] print(solve2(test_list))
找出序列中第k小的元素
#划分 ''' 找出一组序列中第k小的元素 ''' def partition(seq): pi=seq[0] lo=[x for x in seq[1:] if x<=pi] hi=[x for x in seq[1:] if x>pi] return lo,pi,hi 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) if __name__ == '__main__': seq=[2,3,5,1,56,5,7,6,45,3,444,333] print(select(seq,3)) print(select(seq,1))