首页 > 解决方案 > 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

标签: pythonlistfunctionrecursion

解决方案


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)

推荐阅读