0

I am working on a Latin square solver, so I have a 2d array with each element as the set of possible values in this location. The problem is when I try to iterate through this array to remove choices according to my given Latin square, it keeps removing the element from every set on the first removal:

choices = [[set(range(n))] * n] * n
for i in range(n):
  for j in range(n):
    if ls[i][j] > 0:
      val = ls[i][j] - 1
      for k in range(n):
        if k != j: # remove this choice from every column
          print(choices)
          choices[i][k].remove(val)
        if k != i: # remove this choice from every row
          print(choices)
          choices[k][j].remove(val)

Printing the following:

[[{0, 1, 2}, {0, 1, 2}, {0, 1, 2}], [{0, 1, 2}, {0, 1, 2}, {0, 1, 2}], [{0, 1, 2}, {0, 1, 2}, {0, 1, 2}]]
[[{0, 2}, {0, 2}, {0, 2}], [{0, 2}, {0, 2}, {0, 2}], [{0, 2}, {0, 2}, {0, 2}]]

I tried fixing this by changing choices initialization to the following:

n = 3
choices = [[set()]* n] * n
for i in range(n):
    for j in range(n):
        y = set(range(n))
        choices[i][j] = y

The printing changed to the following:

[[{0, 1, 2}, {0, 1, 2}, {0, 1, 2}], [{0, 1, 2}, {0, 1, 2}, {0, 1, 2}], [{0, 1, 2}, {0, 1, 2}, {0, 1, 2}]]
[[{0, 1, 2}, {0, 2}, {0, 1, 2}], [{0, 1, 2}, {0, 2}, {0, 1, 2}], [{0, 1, 2}, {0, 2}, {0, 1, 2}]]
[[{0, 2}, {0, 2}, {0, 1, 2}], [{0, 2}, {0, 2}, {0, 1, 2}], [{0, 2}, {0, 2}, {0, 1, 2}]]
[[{0, 2}, {0, 2}, {0, 2}], [{0, 2}, {0, 2}, {0, 2}], [{0, 2}, {0, 2}, {0, 2}]]

I would love some suggestion and explanation of what and why this is happening?

  • Try replace `choices = [[set(range(n))] * n] * n` with `[[set(range(n)) for _ in range(n)] for __ in range(n)]` – tkburis Nov 20 '22 at 22:19
  • `choices = [[set(range(n))] * n] * n` defines the **same** list referenced multiple times. Use `choices = [[set(range(n)) for _ in range(n)] for _ in range(n)]` – mozway Nov 20 '22 at 22:20

0 Answers0