简体   繁体   中英

Function overwriting list passed in as argument - Python

I'm writing a program to play a game of Tic Tac Toe (I'm learning python). I have a function that gets a 10 item list called movelist passed in, which is then checks to see if any player, either Xs or Os has won the game. If one of them has, it returns 'X' or 'O', if no one has won it returns False. wins is a list of all possible winning combinations. However the function is overwriting the movelist and I can't figure out why. I assign movelist to test and then iterate through and change test, so I don't understand where/why movelist has been changed. A typical movelist being passed in would be ['#','X','X','X',4,'O',6,7,'O',9]. The function should not change the list 'movelist' at all, as it overwrites previous moves that have been made and makes the game unplayable. Please see code below:

def gamewon(movelist):

    #WINNING COMBINATIONS
    wins = [['N','Y','Y','Y','N','N','N','N','N','N'],['N','N','N','N','Y','Y','Y','N','N','N'],
            ['N','N','N','N','N','N','N','Y','Y','Y'],['N','Y','N','N','Y','N','N','Y','N','N'],
            ['N','N','Y','N','N','Y','N','N','Y','N'],['N','N','N','Y','N','N','Y','N','N','Y'],
            ['N','Y','N','N','N','Y','N','N','N','Y'],['N','N','N','Y','N','Y','N','Y','N','N']]

    test = movelist
    index = 0
    for item in test:
        if item == 'X':
            test[index] = 'Y'
            index += 1
        else:
            test[index] = 'N'
            index += 1

    if test in wins:
        return 'X'

    test = movelist
    index = 0

    for item in test:
        if item == 'O':
            test[index] = 'Y'
            index += 1
        else:
            test[index] = 'N'
            index += 1

    if test in wins:
        return 'O'

    return False

I think the problem your having is that you should be using test = movelist.copy() rather than test = movelist . This is a common problem in python and is part of how lists function in python 3. The same problem can occur with dictionaries, which also have .copy() methods. Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM