python语言实现 十道经典的算法编程题目( 二 )

如何获取最好的矩阵链相乘方法def MatrixChainOrder(array,i,j):if i==j:return 0mins=2**32k=iwhile k<j:min=MatrixChainOrder(array,i,k)+MatrixChainOrder(array,k+1,j)+array[i-1]*array[k]*array[j]if min<mins:mins=mink+=1return minsif __name__=="__main__":array=[1,5,2,4,6]print(MatrixChainOrder(array,1,len(array)-1))#将除了第一个和最后一个的包裹起来如何对大量重复的数字进行排序defsort(array):data_count=dict()i=0while i<len(array):if str(array[i]) in data_count:data_count[str(array[i])]=data_count.get(str(array[i]))+1else:data_count[str(array[i])]=1i+=1index=0#print(data_count)for key in sorted(data_count.keys(),key=lambda d:int(d)):i=data_count[key]while i>0:array[index]=keyindex+=1i-=1if __name__=="__main__":array=[15,12,15,2,2,12,2,3,12,100,3,3]sort(array)i=0while i<len(array):print(array[i])i+=1如何在有规律的二维数组中进行高效的数据查找def findWithBinary(array,data):if array==None or len(array)<1:print("参数不合理")return Falsei=0rows=len(array)columns=len(array[0])j=columns-1while i<rows and j>=0:if array[i][j]==data:return Trueelif array[i][j]>data:j-=1else:i+=1return Falseif __name__=="__main__":array=[[1,2,3,4],[11,12,13,14],[21,22,23,24],[31,32,33,34],[41,42,43,44]]print(findWithBinary(array,17))print(findWithBinary(array,24))从三个有序的数组中找出他们的公共元素def findCommon(array1,array2,array3):i=0j=0k=0while i<len(array1) and j<len(array2)and k<len(array3):if array1[i]==array2[j]==array3[k]:i+=1j+=1k+=1print(array1[i-1])elif array1[i]<array2[j]:i+=1elif array2[j]<array3[k]:j+=1else:k+=1if __name__=="__main__":array1=[2,5,12,20,45,85]array2=[16,19,20,85,200]array3=[3,4,15,20,39,72,85,190]findCommon(array1,array2,array3)如何求一个字符串所有的排列def swap(str,index1,index2):tmp=str[index1]str[index1]=str[index2]str[index2]=tmp#看成是两个子问题,一个子问题的从一个字符缩减角度,另外一个是从替换的角度def Permutation(str,start):if str is None and start <0:returnif start==len(str)-1:print("".join(str))else:i = startwhile i<len(str):swap(str,start,i)Permutation(str,start+1)swap(str,start,i)i+=1def Permutation_transe(s):str=list(s)Permutation(str,0)if __name__=="__main__":a="abc"Permutation_transe(a)print()递归问题的核心是将问题转变为子问题,然后还要设置好结束条件

【python语言实现 十道经典的算法编程题目】


推荐阅读