python - List passed as an input to a recursive function acts like a global in that function rather than a local
问题描述
def miniMax(liste, depth,isMaximizing, jogadas):
scores = {'X': 1, 'O': -1, 'empate': 0}
result = checkWinner(liste.copy(), jogadas)
if result is not (None):
return (scores[result])
if isMaximizing:
bestScore = -80000000
for i in range(0, 3):
for j in range(0, 3):
if liste[i][j] == "Nada":
liste[i][j] = "X"
score = miniMax(liste.copy(), depth + 1, False, jogadas)
liste[i][j] = "O"
if score > bestScore:
bestScore = score
return bestScore
else:
bestScore = 80000000
for i in range(0, 3):
for j in range(0, 3):
if liste[i][j] == "Nada":
liste[i][j] = "O"
score = miniMax(liste.copy(), depth + 1, True, jogadas)
liste[i][j] = "X"
if score < bestScore:
bestScore = score
return bestScore
score = miniMax(lista.copy(), depth, True, jogadas)
print(lista)
The lista is changed after running the function minimax. I have tried to use the .copy() method but the list is still changed in the function
解决方案
As I understand, you are using a 2d list, so using a copy won't be sufficent because it will copy outer lists only. A better solution is using copy.deepcopy
:
from copy import deepcopy
score = miniMax(deepcopy(lista), depth, True, jogadas)
推荐阅读
- google-sheets-formula - Google表格公式用于对具有多个排序条件的数据范围进行排序,以便分配给一列
- sql-server - 如果在存储过程中更新后我的触发器失败怎么办?
- javascript - 使用 axios 突然无法通过 HTTP/S 请求 - 在浏览器上运行良好
- django - 在将 UUID 字段附加到列表中时,它还存储了字段的类型
- python - 如何在 spaCy 中获取唯一令牌列表?
- python - 如何从 Altair 中的选定数据中检索属性?
- c - 每当输入数组中的元素时,如何做出一个正确的 if 语句?(C)
- python - 如何使用 `mysql.connector` 使用 `pd.read_sql`
- pyspark - 如何将 JSON 键值对转换为 pyspark 中的记录?
- r - 在 r 中动态删除行