【发布时间】:2016-09-27 11:57:24
【问题描述】:
上下文:我正在尝试在未知环境中编写 A* 搜索。为此,我在 2-D 或 3-D 列表(取决于环境)和另一个 n-D 列表中维护环境表示,该列表表示代理对环境的了解。
当代理移动时,我会根据实际环境检查他们周围的区域。如果有差异,他们的地图会更新,然后我再次运行 A*。
问题:检查这两个列表的范围之间是否存在差异的最快方法是什么?
简单的解决方案:
from itertools import product
from random import randint
width, height = 10, 10
known_environment = [[0 for x in range(width)] for y in range(height)]
actual_environment = [[0 for x in range(width)] for y in range(height)]
# Populate with obstacles
for i in xrange(10):
x = randint(0, len(actual_environment) - 1)
y = randint(0, len(actual_environment[x]) - 1)
actual_environment[x][y] += 1
# Run A* and get a path
path = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4),
(5, 5), (6, 6), (7, 7), (8, 8), (9, 9)] # dummy path
# Traverse path, checking for "new" obstacles
for step in path:
x, y = step[0], step[1]
# check area around agent
for (i, j) in product([-1, 0, 1], [-1, 0, 1]):
# don't bother checking out-of-bounds
if not 0 <= x + i < width:
continue
if not 0 <= y + j < height:
continue
# internal map doesn't match real world, update
if not known_environment[x + i][ y + j] == actual_environment[x + i][ y + j]:
known_environment[x + i][ y + j] = actual_environment[x + i][ y + j]
# Re-run A*
这可行,但感觉效率低下。我想我可以用set(known_environment).intersection(actual_environment) 之类的东西替换循环来检查是否存在差异,如果需要,then 更新;但这可能也可以改进。
想法?
编辑:我已切换到 numpy 切片,并使用 array_equal 而不是集合。
# check area around agent
left = x - sight if x - sight >= 0 else 0
right = x + sight if x + sight < width else width - 1
top = y - sight if y - sight >= 0 else 0
bottom = y + sight if y + sight < height else height - 1
known_section = known_environment[left:right + 1, top:bottom + 1]
actual_section = actual_environment[left:right + 1, top:bottom + 1]
if not np.array_equal(known_section, actual_section):
known_environment[left:right + 1, top:bottom + 1] = actual_section
【问题讨论】:
-
您有时间查看stackoverflow.com/questions/6105777/… 吗? ;-)
-
@Dilettant,谢谢,但我还需要不同元素矩阵中的 positions 以便我可以更新“地图”。
-
为什么要使用两个环境?只需在 A* 搜索中使用和修改全局环境。
-
我还建议使用
[[0] * width] * height而不是那个冗长的环境初始化语句。 -
@EvilTak,我已经切换到 numpy,它允许更好:known_environment = np.zeros(shape=(width, height), dtype=int)
标签: python algorithm performance search optimization