【问题标题】:Python, can't assign new string to matrix cellPython,无法将新字符串分配给矩阵单元
【发布时间】:2021-11-28 02:11:44
【问题描述】:

尝试解决leetcode 上的一项任务 提供代码、调试和代码本身的图片,但您不必真正深入研究所有代码,因为问题在第 3 行。这让我很难过。 为了避免两次击中同一个字母,我决定写“。”在它的位置上。正如您在调试时看到的那样,它在第一次运行时成功执行,然后当它找到下一个匹配项时,调用递归函数转到第 3 行并抛出错误TypeError: 'str' object does not support item assignment。但为什么?在第一次运行时一切都很好,为什么在第二次运行时它决定抛出错误?我不明白。为了防止进一步的错误,我将数组的副本而不是数组本身传递给递归。

def is_word(board, word: str, i: int, j: int) -> bool:
    print(i, j)
    board[i][j] = "."
    
    print(board)
    if len(word) == 0:
        return True;

    if i + 1 < len(board) and board[i + 1][j] == word[0]:
        return is_word(board.copy(), word[1:], i + 1, j)
    if j + 1 < len(board[0]) and board[i][j + 1] == word[0]:
        return is_word(board.copy()[i], word[1:], i, j + 1)
    if i - 1 >= 0 and board[i - 1][j] == word[0]:
        return is_word(board.copy(), word[1:], i - 1, j)
    if j - 1 >= 0 and board[i][j - 1] == word[0]:
        return is_word(board.copy(), word[1:], i, j - 1)
    return False;

def ft_main(board: [[str]], word: str) -> str:
    w_len = len(board[0])
    h_len = len(board)

    for i in range(0, h_len):
        for j in range(0, w_len):
            # once found accurance then check if word could be built
            if board[i][j] == word[0] and is_word(board.copy(), word[1:], i, j):
                return True;
    return False

board = [["A","B","C","E"], ["S","F","C","S"], ["A","D","E","E"]];
word = "ABCCED";

ft_main(board, word)

【问题讨论】:

  • 请注意,board.copy() 是浅拷贝。当您分配给board[i][j] 时,您仍在修改原始板。你应该使用copy.deepcopy(board)

标签: python arrays string list recursion


【解决方案1】:

错误出现在is_word(board.copy()[i], word[1:], i, j + 1):您将字符串列表board.copy()[i] 作为第一个参数传递,而不是字符串列表列表。删除[i]。

【讨论】:

  • 天啊....................... .........................
猜你喜欢
  • 1970-01-01
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 2019-08-16
  • 2015-01-22
相关资源
最近更新 更多