【问题标题】:manhattan distances曼哈顿距离
【发布时间】:2017-01-25 11:54:56
【问题描述】:

计算manhattan distances的最佳方法是什么

我目前的解决方案是:

def distance(state):
    target_state = (1,2,3,4,5,6,7,8,0)
    target_matrix = np.reshape(np.asarray(list(target_state)),(-1,3))
    reshaped_matrix = np.reshape(np.asarray(list(state)),(-1,3))
    dist = 0
    for i in range(1,9):
        dist = dist + (abs(np.where(target_matrix == i)[0][0]
                           - np.where(reshaped_matrix == i)[0][0]) +
                       abs(np.where(target_matrix == i)[1][0]
                           - np.where(reshaped_matrix == i)[1][0]))

    return dist

【问题讨论】:

  • 一定有你没有向我们解释的事情。曼哈顿距离是dx + dy,这也是一种非常有效的计算方法。
  • 目标状态保持不变。有没有比我的方法更好的方法?
  • 我绝对不会为此使用 numpy...
  • 有什么更好的方法呢?
  • 使用普通 Python 列表。

标签: python python-3.x numpy


【解决方案1】:

怎么样

import numpy as np

def summed_manhattan(state):
    shuffle = np.reshape((np.array(state)-1) % 9, (3, 3))
    all_dists = np.abs(np.unravel_index(shuffle, (3, 3)) - np.indices((3, 3)))
    all_dists.shape = 2, 9
    gap = np.where(shuffle.ravel() == 8)[0][0]
    return all_dists[:, :gap].sum() + all_dists[:, gap + 1 :].sum()

这通过避免重复调用 where(总计为 O(n^2))来改进您的解决方案。相反,利用 target_state 的简单结构,它为每个 index into state 计算具有相同值的 target_state 索引;排列存储在随机播放中。这个小技巧使算法 O(n) 变得容易,并且更容易矢量化。

这个解决方案是最优的,因为显然不能比 O(n) 做得更好。

【讨论】:

  • 这不会对输入状态给出相同的答案。示例状态为 (2, 8, 3, 1, 0, 5, 4, 7, 6)
  • 糟糕,抱歉,我会调查的。
  • @Harjatin 我想我找到了罪魁祸首(引用了错误排序中的差距),你能再看看吗?
猜你喜欢
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多