1

I am very new in Python, and I am doing an 8-puzzle problem (My first Program). I have a problem with appending list to another list. Below is part of my code.

def solvePuzzle(puzzle,path,visited):
   moveState = []

   if(init == goal):
       path.append(puzzle)
       return True;

   puzzleT = deepcopy(puzzle)
   visited.append(copy(puzzle))
   index = findBlankTile(puzzleT)
   moveState = moveTileChoice(puzzleT,visited,index)

   #move process

   for move in moveState:
       path.append(copy(puzzle))
       if(applyMove(move,puzzle,path,visited,index)):
           return True;
       else:
           path.remove()
           return False;

In the apply move function, when I swap the blank tile with other numbers tile in the puzzle (code below), all of the values in the Visited and Path lists are changed as well, and that's not what I wanted. What did I do wrong with my code?

def applyMove(move,puzzle,path,visited,index):   
    row = index[0]
    col = index[1]
    if move == "Left":
        puzzle[row][col] , puzzle[row][col-1] = puzzle[row][col-1] , puzzle[row][col]
        return solvePuzzle(puzzle,path,visited)

    elif move == "Right":
        puzzle[row][col] , puzzle[row][col+1] = puzzle[row][col+1] , puzzle[row][col]
        return solvePuzzle(puzzle,path,visited)

    elif move == "Up":
        puzzle[row][col] , puzzle[row-1][col] = puzzle[row-1][col] , puzzle[row][col]
        return solvePuzzle(puzzle,path,visited)

    elif move == "Down":
        puzzle[row][col] , puzzle[row+1][col] = puzzle[row+1][col] , puzzle[row][col]
        return solvePuzzle(puzzle,path,visited)

    else:
        return False;
2
  • Given a = [1,2] and b = [3,4] do you want [1,2,3,4] or [[1,2], [3,4]]? I ask because append for Python lists means adding an item to a list. Commented Mar 11, 2020 at 13:33
  • I want [[1,2], [3,4]] Commented Mar 11, 2020 at 16:41

1 Answer 1

1

Use list.extend(seq), and have a look here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.