我被困在Codefights上的一个问题上。这里是描述:Python:为什么这个算法不能按预期工作?
在流行的扫雷游戏中,你有一个有一些地雷的电路板,那些不包含地雷的单元有一个数字,表示相邻单元中的地雷总数。从一些排雷开始,我们要创建一个扫雷游戏设置。
例
对于
matrix = [[True, False, False],
[False, True, False],
[False, False, False]]
输出应该是:
minesweeper(matrix) = [[1, 2, 1],
[2, 1, 1],
[1, 1, 1]]
所以从我个人理解,我们来看看低谷整个矩阵,因为我们需要知道哪些单元格是真的,即包含炸弹,那么当我们找到一个时,所有邻居单元格的值应该增加我首先尝试使用if/elif语句为边界单元编写代码(不要抛出错误),但代码变得非常丑陋而且很长。所以,我能想出的唯一的事情是这样的:
def minesweeper(matrix):
# First creating the same matrix but instead full of zeros.
result = [[0]* len(matrix[0]) for row in matrix]
# Start iterating through the original matrix to find True elements
for y in range(len(matrix)):
for x in range(len(matrix[0])):
if matrix[y][x] == True:
# The remaining code tries to increment all possible neighbours by 1.
for j in range(-1,2):
for i in range(-1,2):
# If statement so that we do not increment the bomb cell itself.
if not (j == 0 and i == 0):
try:
result[y+j][x+i] += 1
except:
continue
return result
我的函数为
input = [[True, False, False],
[False, True, False],
[False, False, False]]
输出是
[[1, 2, 2], [2, 1, 2], [2, 2, 2]]
任何人有一个想法,为什么它不工作?而且我也知道你应该尝试用try/except语句来捕获错误,并且这可能是不好的做法,我只是想不出超长的if/elif语句的另一种方式。
请进一步解决您的例子:小写的'真'和'FALSE'应弦(即“真”和“假”)或大写。另外,内部循环中的'yi'和'xi'实际上没有定义。所以,你的代码看起来很糟糕。 – alisianoi
[列表中的列表更改意外地反映到子列表中]的可能重复(https:// stackoverflow。com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) –
@ŁukaszRogalski它不是重复的。结果变量被正确初始化。 – Enfenion