AAA_秃头码农 2023-12-05 16:38 采纳率: 61.5%
浏览 5
已结题

结果中有两个数对不上

img

import os
import sys


# 请在此输入您的代码
def fun(big_list, j, k):
    count = 0
    try:
        if big_list[j - 1][k] == 1:
            count += 1
    except:
        pass
    try:
        if big_list[j - 1][k - 1] == 1:
            count += 1
    except:
        pass
    try:
        if big_list[j - 1][k + 1] == 1:
            count += 1
    except:
        pass
    try:
        if big_list[j][k - 1] == 1:
            count += 1
    except:
        pass
    try:
        if big_list[j][k + 1] == 1:
            count += 1
    except:
        pass
    try:
        if big_list[j + 1][k - 1] == 1:
            count += 1
    except:
        pass
    try:
        if big_list[j + 1][k] == 1:
            count += 1
    except:
        pass
    try:
        if big_list[j + 1][k + 1] == 1:
            count += 1
    except:
        pass
    return count


n, m = map(int, input().split())
list_big = []
for i in range(n):
    list_big.append(list(map(int, input().split())))
j, k = 0, 0
list_input = []
for j in range(n):
    list0 = []
    for k in range(m):
        if list_big[j][k] == 1:
            list0.append(str(9))
            continue
        count = fun(list_big, j, k)
        list0.append(str(count))
    list_input.append(list0)
for item in list_input:
    str0 = " ".join(i for i in item)
    print(str0)

这个是我的输出结果

img

  • 写回答

2条回答 默认 最新

  • 无序繁星 2023-12-05 16:52
    关注

    你存在的问题是当索引为-1时,python会取最后一位索引,而不是报错,所以会取到错误数据,需要进行边界判断

    def fun(big_list, j, k):
        count = 0
        m = len(big_list)
        n = len(big_list[0])
        for x in range(-1, 2):
            for y in range(-1, 2):
                row = j + x
                col = k + y
                if (x | y) != 0 and 0 <= row < m and 0 <= col < n and big_list[row][col] == 1:
                    count += 1
        return count
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月13日
  • 已采纳回答 12月5日
  • 创建了问题 12月5日

悬赏问题

  • ¥15 asp写PC网站开通了微信支付,扫码付款不能跳转
  • ¥50 AI大模型精调(百度千帆、飞浆)
  • ¥15 关于#c语言#的问题:我在vscode和codeblocks中编写c语言时出现打不开源文件该怎么办
  • ¥15 非科班怎么跑代码?如何导数据和调参
  • ¥15 福州市的全人群死因监测点死亡原因报表
  • ¥15 Altair EDEM中生成一个颗粒,并且各个方向没有初始速度
  • ¥15 系统2008r2 装机配置推荐一下
  • ¥500 服务器搭建cisco AnyConnect vpn
  • ¥15 悬赏Python-playwright部署在centos7上
  • ¥15 psoc creator软件有没有人能远程安装啊