我想要一个O(1)方法来检查我是否处于一种状态。问题是,一个状态是由地图上几个缩放比的位置定义的。Zoombini = {(1,1):0,(2,2):1,(3,3):3} {Position: Zoombini ID}我正在使用广度优先搜索,并将这个位置字典推送到我的队列中。
dirs = [goNorth, goSouth, goWest, goEast] ## List of functions
zoom = {}
boulders = {}
visited = {} ## {(zoom{}): [{0,1,2},{int}]}
## {Map: [color, distance] 0 = white, 1 = gray, 2 = black
n = len(abyss)
for i in xrange(n):
for j in xrange(n):
if (abyss[i][j] == 'X'):
boulders[(i,j)] = True
elif (isInt(abyss[i][j])):
zoom[(i,j)] = int(abyss[i][j]) ## invariant only 1 zomb can have this position
elif (abyss[i][j] == '*'):
exit = (i, j)
sQueue = Queue.Queue()
zombnum = 0
done = False
distance = 0
sQueue.put(zoom)
while not(sQueue.empty()):
currZomMap = sQueue.get()
for zom in currZomMap.iterkeys(): ## zoom {(i,j): 0}
if not(zom == exit):
z = currZomMap[zom]
for fx in dirs: ## list of functions that returns resulting coordinate of going in some direction
newPos = fx(zom)
newZomMap = currZomMap.copy()
del(newZomMap[zom]) ## Delete the old position
newZomMap[newPos] = z ## Insert new Position
if not(visited.has_key(newZomMap)):
sQueue.put(newZomMap)我的实现还没有完成,但我需要一个更好的方法来检查我是否已经访问了一个状态。我可以编写一个函数,从字典中创建一个整数哈希,但我认为这样做效率不高。时间也是一个问题。我怎样才能以最佳的方式来做这件事呢?
发布于 2012-11-06 12:16:58
我可能只会使用frozenset,而不是构造一些脆弱的自定义散列函数
>>> Z = {(1,1): 0, (2,2):1, (3,3):3}
>>> hash(Z)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> frozenset(Z.items())
frozenset([((2, 2), 1), ((1, 1), 0), ((3, 3), 3)])
>>> hash(frozenset(Z.items()))
-4860320417062922210冻结集可以存储在集合和字典中,没有任何问题。您也可以使用从Z.items()构建的元组,但您必须确保它始终以规范的格式存储(例如,首先对其进行排序)。
发布于 2012-11-06 10:59:16
Python不允许可变的键,所以我最终创建了一个函数来散列我的字典。
编辑--
def hashthatshit(dictionary):
result = 0
i =0
for key in dictionary.iterkeys():
x = key[0]
y = key[1]
result+=x*10**i+y*10**(i+1)+\
10**(i+2)*dictionary[key]
i+=3
return result我使用了它,它特定于我的实现,这就是我最初没有包含它的原因。
https://stackoverflow.com/questions/13243577
复制相似问题