python - 在递归调用中附加到列表后结果发生变化

标签 python list recursion

下面是一个Python程序,用于将八个皇后放置在8*8的网格上,其中没有两个皇后位于相同的行、列和对角线上。

程序看起来正确,但当我将位置列表附加到列表结果时,它会更改列表中早期成员的值。

GRID_SIZE = 8
def placeQueen(row, columns):
  if(row == GRID_SIZE):
    print(columns) # it is where I print the positions
    return [columns] # it is where I append the positions 

  results = []
  for col in range(GRID_SIZE):
    if(checkVlaid(row, col, columns)):
      columns[row] = col
      results += placeQueen(row+1, columns)
  return results


def checkVlaid(row0, col0, columns):
  for row in range(row0):
    if(columns[row] == col0):
      return False
    if(abs(row - row0) == abs(columns[row] - col0)):
      return False
  return True  



def Test():
  columns = [-1]*GRID_SIZE
  print placeQueen(0, columns) #the results are different from what I originally appended


Test()

最佳答案

问题在于您重复地将相同的列实例附加到结果列表中。这是正在发生的事情的简化示例

>>> results = []
>>> columns = ["original column value"]
>>> results.append(columns)
>>> results.append(columns)
>>> results
[['original column value'], ['original column value']]
>>> columns[0] = "A new value"
>>> results
[['A new value'], ['A new value']]
>>> 

要解决此问题,您需要复制列列表,这样就不会修改已附加到结果中的列

复制列表的一个简单方法是通过 columns = columns[:] 对其进行切片

复制 placeQueen 函数中的 columns 列表应该可以解决问题

def placeQueen(row, columns):
    # creates a copy of the columns list
    columns = columns[:]
    if (row == GRID_SIZE):
        print(columns)  # it is where I print the positions
        return [columns]  # it is where I append the positions


    results = []
    for col in range(GRID_SIZE):
        if (checkVlaid(row, col, columns)):
            columns[row] = col

            results += placeQueen(row + 1, columns)

    return results

关于python - 在递归调用中附加到列表后结果发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58042019/

相关文章:

python - 使用 basemap 在世界地图上绘制网络/图形(python)

List.sum 自定义类

c# - 仁慈SSH.NET : Is it possible to create a folder containing a subfolder that does not exist

python - 将 'a' 替换为数字 7 或 8 递归(python)

java - Actor 列表到 Collection

递归地将字符串转换为整数?

python - 如何在带有输出的 Visual Studio Code 和 Python 中仅运行一个测试

python - python 中的直接列表分配 - 不插入

python - 提取 pandas df 列中两个子字符串之间的字符串

java - 在 Scala 中将 java.util.Set 转换为 java.util.List