027.【其他算法】

1. 分治算法

分治算法也称分而治之算法,通过分治算法可以将复杂的问题简单化。它的核心思想是将一个复杂的大问题分割为多个子问题,通过解决子问题来获得总问题的解。这些子问题虽然是独立的,但是问题的本质是一样的。一个大问题可以通过分割的方式来解决,使分割后的子问题的规模不断缩小,直到这些子问题都足够简单,最后再通过子问题的解来获得总问题的解。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
定义一个数值列表[2,-2,5,3,-3,0,9,6],应用递归排序法将该数值列表中的元素按照由小到大的顺序进行排序。代码如下:

def dgSort(theList):                               		# 定义函数并传入参数theList
    if len(theList) < 2:                             	# 如果theList只有一个元素
        return                                  		# 终止程序执行

    sep = len(theList) // 2                           	# 将列表一分为二
    listA = theList[:sep]                           	# 获取左子列表
    listB = theList[sep:]                            	# 获取右子列表
    dgSort(listA)                               		# 对左子列表进行递归排序
    dgSort(listB)                               		# 对右子列表进行递归排序
    index = 0                                    		# 定义列表索引
    pointerA = 0                                		# 定义指针A
    pointerB = 0                               			# 定义指针B

    # 如果两个指针都没走到最后
    while(pointerA<len(listA) and pointerB < len(listB)):  
        if(listA[pointerA] < listB[pointerB]):          # 比较指针指向的两个元素大小
            theList[index] = listA[pointerA]            # 把较小的元素作为当前索引的元素
            pointerA += 1                       		# 向后移动指针A
        else:
            theList[index] = listB[pointerB]            # 把较大的元素作为当前索引的元素
            pointerB += 1                        		# 向后移动指针B
        index += 1                            			# 当前索引加1

    while(pointerA < len(listA)):                     	# 如果指针B走到最后而指针A没有
        theList[index] = listA[pointerA]                # 把指针A指向的元素作为当前索引的元素
        pointerA += 1                            		# 向后移动指针A
        index += 1                               		# 当前索引加1

    while (pointerB < len(listB)):                      # 如果指针A走到最后而指针B没有
        theList[index] = listB[pointerB]                # 把指针B指向的元素作为当前索引的元素
        pointerB += 1                             		# 向后移动指针B
        index += 1                               		# 当前索引加1

sList = [2,-2,5,3,-3,0,9,6]                             # 定义数值列表
print("原数值列表:",sList)                        		# 打印原数值列表
dgSort(sList)                            				# 调用函数
print("排序后的数值列表:",sList)                  		# 打印排序后的数值列表

在这里插入图片描述
在这里插入图片描述

定义一个数值列表[12,9,6,3,1,7,15,10],应用迭代排序法将该数值列表中的元素按照由小到大的顺序进行排序。代码如下:

def ddSort(theList):                                      	# 定义函数并传入参数theList
    n = 1                                          			# 子列表长度,初始值为1
    while n < len(theList):
        for i in range(0,len(theList),n*2):
            listA = theList[i:i+n]                    		# 获取长度为n的左子列表
            listB = theList[i+n:i+n*2]                    	# 获取长度为n的右子列表
            index = i                               		# 定义列表索引
            pointerA = 0                             		# 定义指针A
            pointerB = 0                           			# 定义指针B
            # 如果两个指针都没走到最后
            while(pointerA<len(listA) and pointerB < len(listB)):
                if(listA[pointerA] < listB[pointerB]):     	# 比较指针指向的两个元素的大小
                    theList[index] = listA[pointerA]      	# 把较小的元素作为当前索引的元素
                    pointerA += 1                   		# 向后移动指针A
                else:
                    theList[index] = listB[pointerB]      	# 把较大的元素作为当前索引的元素
                    pointerB += 1                   		# 向后移动指针B
                index += 1                          		# 当前索引加1

            while(pointerA < len(listA)):                	# 如果指针B走到最后而指针A没有
                theList[index] = listA[pointerA]            # 把指针A指向的元素作为当前索引的元素
                pointerA += 1                       		# 向后移动指针A
                index += 1                          		# 当前索引加1
            while (pointerB < len(listB)):                  # 如果指针A走到最后而指针B没有
                theList[index] = listB[pointerB]            # 把指针B指向的元素作为当前索引的元素
                pointerB += 1                        		# 向后移动指针B
                index += 1                         			# 当前索引加1
        n = n * 2

sList = [12,9,6,3,1,7,15,10]                                # 定义数值列表
print("原数值列表:",sList)                               	# 打印原数值列表
ddSort(sList)                               				# 调用函数
print("排序后的数值列表:",sList)                         		# 打印排序后的数值列表

2. K最近邻算法

K最近邻(KNN)算法是比较简单的机器学习算法。它通过采用测量不同特征值之间距离的方法进行分类。该算法的思想是:如果一个样本在特征空间中的K个最近邻(最相似)的样本中属于大多数的某一个类别,则该样本也属于这个类别。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
假设今天是周末,天气指数是4,并且店内推出了打折活动。根据这些历史数据预测该汉堡店今天能售出多少汉堡。下面使用K最近邻算法实现预测,其中K为3。代码如下:

import math
def getMaxIndex(list):                   		# 获取列表中的最大值
    maxValue = float("-inf")
    for i in range(len(list)):                 	# 遍历列表
        if maxValue < list[i]:              	# 如果列表元素值比较大
            maxValue = list[i]          		# 获取最大值
            index = i                 			# 获取最大值的索引
    return index

def KDistance(K, dest, source):
    destLen = len(dest)                  		# 获取特征个数
    sourceLen = len(source)              		# 获取历史数据个数
    distance = []
    final = source
    for i in range(sourceLen):
        sum = 0
        for j in range(destLen):
            sum += (dest[j] - source[i][j]) * (dest[j] - source[i][j])
        # 计算欧几里得距离
        distance.append(math.sqrt(sum))    
    for n in range(sourceLen-K):
        index = getMaxIndex(distance)       	# 获取距离列表最大值的索引
        distance.remove(distance[index])    	# 移除最大距离
        final.remove(final[index])          	# 移除历史数据中对应位置的元素
    return final                           		# 返回最终K个最接近的元素

hamburger = {
    
    }                            		# 历史数据
hamburger[4, 1, 0] = 100
hamburger[3, 0, 1] = 75
hamburger[1, 1, 0] = 40
hamburger[4, 0, 1] = 95
hamburger[5, 1, 0] = 150
hamburger[2, 0, 1] = 60
dest = [4, 1, 1]                               	# 今天的三个特征列表
source = []
for i in hamburger:
    source.append(i)

K = 3
# 获取最终K个最接近的元素
result = KDistance(K, dest, source)      
avg = 0
for i in range(len(result)):
    avg += hamburger[result[i]]

# 计算平均值
avg /= K                            
print("预测结果:今天能售出%d个汉堡"%round(avg))

猜你喜欢

转载自blog.csdn.net/qq_42226855/article/details/131269502