0

I'm doing eight queens in python. I want to put all the outputs in a list by using the append method. However, it's very weird that all the outputs become the same. Can anyone help me plz ;)

I'm testing my program using four queens:

board = []
solution=[]

def isConflict(x, y):
   for (i, j) in board:
        if x == i:
            return True
        if y == j:
            return True
        if abs(x - i) == abs(y - j):
            return True
        else:
            return False


def solve(x,y):
    for y in range(1, 5):
        if isConflict(x, y)==False:
            board.append((x, y))
            solve(x + 1,y)
            board.remove((x,y))
    if x > 4:
        solution.append(board)
        print(solution)

solve(1,1)

The output is like:

[[(1, 2), (2, 4), (3, 1), (4, 3)]]
[[(1, 3), (2, 1), (3, 4), (4, 2)], [(1, 3), (2, 1), (3, 4), (4, 2)]]

However what I want is:

[[(1, 2), (2, 4), (3, 1), (4, 3)]]
[[(1, 2), (2, 4), (3, 1), (4, 3)], [(1, 3), (2, 1), (3, 4), (4, 2)]]

What shall I do?

manvi77
  • 536
  • 1
  • 5
  • 15
toyhtoza
  • 43
  • 1
  • 1
  • 7
  • I don't understand how your `solve(x,y)` functions uses its `y` parameter. It seems to overwrite it on the first line. – quamrana Mar 27 '17 at 13:29
  • You are adding the same `board` to your `solutions` multiple times. Either copy the `board` when you add it, or after you add `board` to `solution`, start a new `board` so you're not modifying the one you already added. – khelwood Mar 27 '17 at 13:29
  • 2
    That's not weird at all: you **do not make a copy of the list**. So that means every solution refers to the **same list**. If you `append(board)`, you should `append(list(board))`. – Willem Van Onsem Mar 27 '17 at 13:29
  • I don't know what is 8 queens problem,but somebody already did this in python try this link http://stackoverflow.com/questions/5133509/eight-queens-problem-in-python – Arun Mar 27 '17 at 13:37
  • run your code through [python tutor](http://pythontutor.com/visualize.html#mode=edit) and see it use the same list for `board` and the two entries in `solutions`, then use @WillemVanOnsem 's suggestion which should be posted as an answer. – Tadhg McDonald-Jensen Mar 27 '17 at 17:59

0 Answers0