-1
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

The _get_legal_moves() function returns a list of tuples containing free spaces(zeros). For eg. in the above case:

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

I want to generate a dict of successors, swapping the legal moves in the initial state and generate new state as the value of the dict. I want the key of the dict to be the number that has been swapped. Here is what my expected output is of the succ() function:

Desired output: { 6: [[1, 2, 3], [4, 5, 0], [7, 8, 6]], 8: [[1, 2, 3], [4, 5, 6], [7, 0, 8]]}
Prune
  • 76,765
  • 14
  • 60
  • 81
John Smith
  • 21
  • 6
  • 1
    Welcome to StackOverflow. See [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). We cannot effectively help you until you post your MRE code and accurately specify the problem. We should be able to paste your posted code into a text file and reproduce the problem you specified. `find_free_tile` is missing, and you haven't shown your attempt to solve the problem. This is a matter of bookkeeping -- I expect that you've already come close, since you can identify which tiles can move to the zero. – Prune Feb 07 '20 at 00:27
  • What is the issue, exactly? Which part are you struggling with? – AMC Feb 07 '20 at 01:29

1 Answers1

0

Couple of points

  1. Move deep copy inside the for loop as first line.
  2. You declare find_zero_tile but use find_free_tile.
  3. For a dict you can make the following changes to declaration and assignment. lista = {}, lista[ moves[row,col] ] = r
ychnh
  • 197
  • 1
  • 12