回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我很难理解为什么expqueue会不断更改为状态的多次迭代,
从[:]到深度复制,我都试过了。有人能解释什么不对吗?
代码是一个8字谜游戏,如果我能得到一个运行列表去所有不同的
我相信我能自己完成,是的,这是家庭作业。你知道吗</p>
<pre><code>import copy
init = [[2,0,3], [1,5,6],[4,7,8]]
goal = [[1,2,3], [4,5,6],[7,8,0]]
expqueue = []
tempqueue = []
depth = 0
def myappend(lst1, lst2):
new = list(lst1)
new2 = list(lst2)
new.append(new2)
global expqueue
expqueue = new
def makeState(state):
for x in range(0,3):
for i in range(0,3):
print state[x][i],
print "\n"
def locate(state):
for x in range(0,3):
for y in range(0,3):
if state[x][y] == 0:
return [x, y]
def moveU(state):
location = locate(state)
x = location[0]
y = location[1]
s = x-1
if x>0:
swap = state[x][y]
state[x][y] = state[s][y]
state[s][y] = swap
myappend(expqueue, state)
def moveL(state):
location = locate(state)
x = location[0]
y = location[1]
s = y-1
if y>0:
swap = state[x][y]
state[x][y] = state[x][s]
state[x][s] = swap
myappend(expqueue, state)
def moveR(state):
location = locate(state)
x = location[0]
y = location[1]
s = y+1
if y<2:
swap = state[x][y]
state[x][y] = state[x][s]
state[x][s] = swap
myappend(expqueue, state)
def moveD(state):
location = locate(state)
x = location[0]
y = location[1]
s = x+1
if x<2:
swap = state[x][y]
state[x][y] = state[s][y]
state[s][y] = swap
myappend(expqueue, state)
def expand(lst):
tempqueue = lst[:]
while tempqueue != []:
state = tempqueue[0]
current = state[:]
moveU(current)
moveL(current)
moveR(current)
moveD(current)
del tempqueue[0]
return expqueue
def solve(queue, initial, solution, level):
length = len(queue)
for x in range(length):
if queue[x] == solution:
return "This works!"
return solve(expand(queue), initial, solution, level+1)
print solve([init], init, goal, 0)
</code></pre>
<p>从那以后,我在最初的切片上添加了deepcopy,并且我注意到ID在复制之后会恢复原样。有人知道为什么吗?你知道吗</p>
<p>显然我没有足够的街头信誉来发布截图,所以这里有一个链接:
<a href="http://imgur.com/sMBY8f9" rel="nofollow">Matching id's after copy</a></p>