0

美好的一天编码大师,我正在研究项目,我正在尝试了解禁忌搜索。下面是我基于对这个主题的一点了解编写的简单实现。这个实现正确吗?

#!/usr/bin/pyhton

from math import exp,fabs
from random import randint

numRange = 100

class candidate:
    def __init__(self,x=0,y=0):
        self.x = x
        self.y= y
        self.error = self.cost()

    def cost(self):
        return fabs(((self.x**3)-(self.x**2)+(2*self.x)+30) - ((self.y**2)+self.y+10))



def neighborHood(tabuList, candidateSize):
    Clist = []
    for i in range(candidateSize):
        x = randint(0,numRange)
        y = randint(0,numRange)
        flag = False
        for j in tabuList:
            if x == j[0].x:
                flag = True
            elif y == j[0].y:
                flag = True
        if flag == False:
            Clist.append(candidate(x,y))
    return Clist

def locateBest(candidateList):
    newList = sorted(candidateList, key=lambda candidate: candidate.error)
    return newList[0]


def tabuSearch(tabuListSize,candidateSize):
    bestCandidate = candidate(randint(0,numRange),randint(0,numRange))
    tabuList = []
    candidateList = []
    itr = 0
    while itr <1000:
        print "Error: ",bestCandidate.error, " x = ",bestCandidate.x," y = ",bestCandidate.y
        candidateList = neighborHood(tabuList,candidateSize)
        tempCandidate = locateBest(candidateList)
        if tempCandidate.error < bestCandidate.error:
            bestCandidate = tempCandidate
            tabuList.append([tempCandidate])
            while len(tabuList) > tabuListSize:
                tabuList.pop()
        itr+=1


tabuSearch(10,50)
4

0 回答 0