从移动8中生成后续操作

2024-10-03 02:46:14 发布

您现在位置:Python中文网/ 问答频道 /正文

import copy

goalState = [[1,2,3],[4,5,6],[7,8,0]]

def find_zero_tile(state):
    for i in range(0, 3):
        for j in range(0, 3):
            if state[i][j] == 0:
                x = j
                y = i
    return (x,y)

def _get_legal_moves(state):
        """Returns list of tuples with which the free space may
        be swapped"""
        row, col = find_free_tile(state)
        freeSpaces = []

        if row > 0:
            freeSpaces.append((row - 1, col))
        if col > 0:
            freeSpaces.append((row, col - 1))
        if row < 2:
            freeSpaces.append((row + 1, col))
        if col < 2:
            freeSpaces.append((row, col + 1))

        return freeSpaces

def succ(state): #my attempt of succesor funtion, does not work, need help with this function
    lista = []
    r = copy.deepcopy(state)
    moves = _get_legal_moves(state)
    idx = find_free_tile(state)
    x = idx[0]
    y = idx[1]
    for row,col in moves:
        r[x][y] = moves[row,col]
        r[row][col] = 0
    lista.append(r)
    return list

函数的作用是:返回一个包含空格(零)的元组列表。例如,在上述情况下:

_get_legal_moves(goalState)
returns [(1, 2), (2, 1)]

我想生成一个继承人的dict,交换初始状态下的合法移动,并生成新状态作为dict的值。我想dict的键是已交换的数字。 下面是我对succ()函数的预期输出:

Desired output: { 6: [[1, 2, 3], [4, 5, 0], [7, 8, 6]], 8: [[1, 2, 3], [4, 5, 6], [7, 0, 8]]}

Tags: inforgetreturnifdefcolfind
1条回答
网友
1楼 · 发布于 2024-10-03 02:46:14

几点

  1. 在for循环内移动深度副本作为第一行
  2. 您声明find\u zero\u tile,但使用find\u free\u tile
  3. 对于dict,您可以对声明和赋值进行以下更改。lista={},lista[moves[row,col]]=r

相关问题 更多 >