[英]Basic Greedy Search in Python
def basic_greedy():
start = 1
mindist = d_dict[(1,2)]
m = 0
while len(tour)!=size:
tour.append(start)
for k in range(len(cities)):
if cities[k] not in tour:
if d_dict[(start,cities[k])]<mindist:
mindist = d_dict[(start,cities[k])]
m = k
start = cities[m]
return tour
这是我在Python中进行基本贪婪搜索的代码。 开始时启动城市, 旅游是他们参观,应包含为了城市名单, 城市是含有1至大小所有城市的列表(1,2,3,4 ..... 12..size),其中大小是城市数。 d_dict是一个字典,其中包含每对可能的城市之间的距离。 mindist和m只是临时变量,用于跟踪最近的邻居等。
我希望代码从城市1开始,移至最近的邻居,然后移至最近,直到每个城市覆盖一次。 我希望此代码的输出类似于城市1至8的[1,5,3,8,4,6,2,7]的线条(访问所有城市仅一次的某种组合),但是我得到了[1,7,7,7,7,7,7,7] 。 怎么了?
问题:一般而言,问题不明确。 代码不完整。 但是,让我提供一些基本的指示。 希望能帮助到你。 开始...
def basic_greedy():
# greedy search algorithm
d_dict = {1: [(1, 2), (2, 15), (3, 30)], 2: [(1, 30), (7, 10)]} # dict of lists of tuples such that nodei : [ (neighbourj, distancej), .... ]
currentCity = 1
tour = [] # list of covered nodes
tour.append(currentCity)
distanceTravelled = 0 # distance travelled in tour
while len(set([neighbourCity for (neighbourCity, distance) in d_dict.get(currentCity, [])]).difference(set(tour))) > 0: # set(currentCityNeighbours) - set(visitedNodes)
# way 1 starts
minDistanceNeighbour = None
minDistance = None
for eachNeighbour, eachNeighbourdDistance in d_dict[currentCity]:
if eachNeighbour != currentCity and eachNeighbour not in tour:
if minDistance is not None:
if minDistance > eachNeighbourdDistance:
minDistance = eachNeighbourdDistance
minDistanceNeighbour = eachNeighbour
else:
minDistance = eachNeighbourdDistance
minDistanceNeighbour = eachNeighbour
nearestNeigbhourCity = (minDistanceNeighbour, minDistance)
# way 1 ends
# way 2 starts
# nearestNeigbhourCity = min(d_dict[currentCity], key=lambda someList: someList[1] if someList[0] not in tour else 1000000000) # else part returns some very large number
# way 2 ends
tour.append(nearestNeigbhourCity[0])
currentCity = nearestNeigbhourCity[0]
distanceTravelled += nearestNeigbhourCity[1]
print(tour)
print(distanceTravelled)
这是您要的吗? 我可能也更改了距离字典和其他一些变量的结构,但这不会影响贪婪的进场逻辑,希望这对您nearestNeighbourCity
。编辑我的答案,因为这是我第一次在所有人中找到nearestNeighbourCity
currentCity
邻居,但现在我正在当前城市的所有未访问邻居中找到nearestNeighbourCity
,因为我使用方法way 1
和way 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.