开发者

How do I get rid of this TypeError, and why is it occurring given that I am simply reassigning a value in a list?

Code:

http://pastie.org/1961455

Trackback:

Traceback (most recent call last):
  File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 149, in <module>
    main ()
  File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 144, in main
    move = computer_move(computer, board, human)
  File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 117, in computer_move
    board[i] = computer
TypeError: 'str' object does not support item assignment

As you can see for in my tic-tac-toe program, the board[i] = computer line in the computer_move function is the one (if I am reading this right) causing the error. But if I know this right, item assignment is allowed in lists, and I create a local copy of "board"开发者_StackOverflow社区 for my function so that I can reassign values and whatnot within the function...

Any input at all would be greatly appreciated. This is my first serious piece of code, so if the function in question looks too mangled


The problem is here:

def computer_move (computer, board, human):
    best = (4,0,8,2,6,1,3,5,7)
    board = board [:]
    for i in legal_moves(board):
        board[i] = computer
        if winner(board) == computer:
            return i
        board = EMPTY

At the end of the function, you assign EMPTY to board, but EMPTY is an empty string, as defined on line 4. I assume you must have meant board[i] = EMPTY.


In line 120, you reassign board to EMPTY (ie an empty string). So from that point on, board is no longer a list, so you can't assign board[i]. Not quite sure what you meant to do there.

Generally, your code would greatly benefit from using object-orientation - with Board as a class, keeping track of its member squares.


Looks like board is a string. I get the same error when I do this:

>>> s = ''
>>> s[1] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜