gpt4 book ai didi

python - 收到 KeyError : '0_0' for my python program

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:17:17 25 4
gpt4 key购买 nike

我正在研究这个问题(来自 Leetcode):

"Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Return 4.

我不断遇到 KeyError:

Traceback (most recent call last):
File "/Users/Desktop/longest_increasing_path_in_a_matrix.py", line 41, in <module>
print(test.longestIncreasingPath(matrix))
File "/Users/Desktop/longest_increasing_path_in_a_matrix.py", line 31, in longestIncreasingPath
traverse(x, y, [])
File "/Users/Desktop/longest_increasing_path_in_a_matrix.py", line 5, in traverse
if traverse.traveled[str(x_coor) + "_" + str(y_coor)]:
KeyError: '0_0'

而且我不确定我做错了什么。我知道这与我的字典有关。如果我还需要发布任何其他内容,请告诉我:

class Solution(object):
def longestIncreasingPath(self, matrix):

def traverse(x_coor, y_coor, build):
key = str(x_coor) + "_" + str(y_coor)
if key in traverse.traveled and traverse.traveled[key]:
if traveled[str(x_coor) + "_" + str(y_coor)]:
return
elif x_coor < 0 or y_coor < 0 or x_coor >= len(matrix[0]) or y_coor >= len(matrix)-1:
return
elif len(build) > 0 and matrix[x_coor][y_coor] <= build[-1]:
if len(build) > traverse.count:
traverse.count = len(build)
return

traveled[str(x_coor) + "_" + str(y_coor)] = true
build.append(matrix[y_coor][x_coor])
traverse(x_coor, y_coor-1, build)
traverse(x_coor, y_coor+1, build)
traverse(x_coor+1, y_coor, build)
traverse(x_coor-1, y_coor, build)
build.pop()
del traveled[str(x_coor) + "_" + str(y_coor)]

traverse.count = 0
traverse.traveled = {}


for y in range(0, len(matrix)-1, 1):
for x in range(0, len(matrix[0]), 1):
traverse(x, y, [])

return(traverse.count)
matrix = [
[9,9,4],
[6,6,8],
[2,1,1]
]
test = Solution()
print(test.longestIncreasingPath(matrix))

最佳答案

您正在尝试访问字典中尚不存在的键 (0_0)。

你必须事先检查它是否存在,我建议使用 in 关键字:

key = str(x_coor) + "_" + str(y_coor)
if key in traverse.traveled and traverse.traveled[key]:
# ...

关于python - 收到 KeyError : '0_0' for my python program,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39523479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com