再会
请帮我找出代码中的错误。屏幕截图中的任务\
代码:
x, y, k = map(int, input().split())
mines = []
for i in range(k):
a, b = map(int, input().split())
mines.append((a - 1, b - 1))
field = [list(0 for j in range(x)) for i in range(y)]
for mine in mines:
field[mine[1]][mine[0]] = "*"
if mine[1] - 1 >= 0 and mine[0] - 1 >= 0 and field[mine[1]-1][mine[0]-1] !="*":
field[mine[1]-1][mine[0]-1] += 1
if mine[1] - 1 >= 0 and field[mine[1]-1][mine[0]] !="*":
field[mine[1]-1][mine[0]] += 1
if mine[1] - 1 >= 0 and mine[0] + 1 <= (x-1) and field[mine[1]-1][mine[0]+1] !="*":
field[mine[1]-1][mine[0]+1] += 1
if mine[0] - 1 >= 0 and field[mine[1]][mine[0]-1] !="*":
field[mine[1]][mine[0]-1] += 1
if mine[0] + 1 <= (x-1) and field[mine[1]][mine[0]+1] !="*":
field[mine[1]][mine[0]+1] += 1
if mine[1] + 1 <= (y-1) and mine[0] - 1 >= 0 and field[mine[1]+1][mine[0]-1] !="*":
field[mine[1]+1][mine[0]-1] += 1
if mine[1] + 1 <= (y-1) and field[mine[1]+1][mine[0]] !="*":
field[mine[1]+1][mine[0]] += 1
if mine[1] + 1 <= (y-1) and mine[0] + 1 <= (x-1) and field[mine[1]+1][mine[0]-1] !="*":
field[mine[1]+1][mine[0]+1] += 1
for i in range(x):
for j in range(y):
print(field[j][i], end = " ")
print()
当检查关闭时,它显示错误的答案。我不知道它是从什么输入数据获得的。当我自己输入值时似乎没有错误
还有另一种解决方案:
x, y, k = map(int, input().split())
mines = []
for i in range(k):
a, b = map(int, input().split())
mines.append((a - 1, b - 1))
field = [[0 for j in range(y)] for i in range(x)]
directions = [
(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)
]
for mine in mines:
field[mine[0]][mine[1]] = "*"
for d in directions:
new_x = mine[0] + d[0]
new_y = mine[1] + d[1]
if 0 <= new_x < x and 0 <= new_y < y and field[new_x][new_y] != "*":
field[new_x][new_y] += 1
for i in range(x):
for j in range(y):
print(field[i][j], end=" ")
print()
逻辑是相同的,但检查通过并被计数。为什么我不明白,以及在哪些输入数据上答案也会不正确
在问题的定义中,我们读到行数是第一位的,所以这
x
是一个不幸的指定这就是结果 - 字段宽度已设置
x
,但需要相反Логика такая же
- 并且注意力更高(尽管名称也具有误导性)。也许只是更相关的变量命名会有所帮助 - 例如,height
或者rowcount
行数复制面食是邪恶的。他们到处都变成
-
了+
,但在一个地方(至少)他们没有改变:不要复制和粘贴代码。这是无法用肉眼检查的,而且这样的代码很容易出错。突出显示常见内容并将其放入使用不同参数调用的函数中。可以从集合中选择哪个,如第二个代码示例所示,它是按照
DRY
.在那里,无需将代码移动到函数中,而只需在循环中使用一段代码,替换集合中的不同值即可完成此操作。这段代码更容易理解并且不易出错。