最近邻居算法?

问题描述 投票:0回答:1

尝试执行我的功能时,我总是收到错误消息。我认为这是由于计算了两个坐标之间的距离。例如[5,2]和[6,7],它无法计算这些坐标之间的距离。

这是我的代码:

import math
import copy

def calculate_distance(starting_x, starting_y, destination_x, destination_y):
    distance = math.hypot(destination_x - starting_x, destination_y - starting_y)  # calculates Euclidean distance (straight-line) distance between two points
    return distance

def nearest_neighbour_algorithm(selected_map):

  temp_map = copy.deepcopy(selected_map)
  optermised_map = [] 

  optermised_map.append(temp_map.pop()) 

  for x in range(len(temp_map)):
    nearest_value = 1000 
    neares_index = 0       
    for i in range(len(temp_map[x])):
      current_value = calculate_distance(*optermised_map[x], *temp_map[x])

      if nearest_value > current_value: 
        nearest_value = current_value 
        nearest_index = i 

    optermised_map.append(temp_map[nearest_index])
    del temp_map[nearest_index] 

  return optermised_map

copy_map = generate_map_1(200,200,5)
print("Map Points: ", copy_map)
print("Nearest Neighbour: ", nearest_neighbour_algorithm(copy_map))

问题在这里:

 current_value = calculate_distance(optermised_map[x] - temp_map[i])

我正在尝试将2个坐标传递给我的计算距离函数,但由于出现错误,它不允许我这样做

python artificial-intelligence distance nearest-neighbor
1个回答
0
投票

因为您不能从另一个列表中减去列表

您到底要从经优化的映射中减去temp_map的每个元素是什么?

© www.soinside.com 2019 - 2024. All rights reserved.