matlab cody部分题目的 Python 解法

Problem 173. Minefield Sonar

原题 matlabcody

class Mine:
    def __init__(self, row, col):
        self.row, self.col = row, col   # 地图的行列
        # 搜索的范围
        self.neighbors = [[-1, -1], [-1, 0], [-1, 1], 
                          [0, -1],           [0, 1], 
                          [1, -1], [1, 0], [1, 1]]
        self.grids = [[0 for j in range(col + 1)] for i in range(row + 1)]  # 地图

    # 在地图中标出地雷
    def set_mines(self, coordinates):
        for coordinate in coordinates:
            self.grids[coordinate[0]][coordinate[1]] = -1

    # 检测地雷
    def hunt(self):
        for i in range(1, self.row + 1):
            for j in range(1, self.col + 1):
                if self.grids[i][j] == -1:
                    for neighbor in self.neighbors:
                        r, c = i + neighbor[0], j + neighbor[1]
                        if not (1 <= r <= self.row and 1 <= c <= self.col):
                            continue
                        if self.grids[r][c] == -1:
                            continue
                        self.grids[r][c] += 1

    # 输出
    def __str__(self):
        res = ""
        for i in range(1, self.row + 1):
            for j in range(1, self.col + 1):
                if self.grids[i][j] >= 0:
                    res += " "
                res += str(self.grids[i][j])
                res += " "
            res += "\n"
        return res
    

if __name__ == "__main__":
    I = [int(i) for i in input().split()]
    J = [int(i) for i in input().split()]
    (M, N) = [int(i) for i in input("the number of rows and columns on the grid = ").split()]
    mine = Mine(row=M, col=N)
    mine.set_mines(coordinates=zip(I, J))
    mine.hunt()
    print(mine)

Problem 65. Word Counting and Indexing

def solve(str_list):
    word_table = sorted(list(set((' '.join(str_list)).split())))
    str2index = {}
    index_list = []
    for i in range(len(word_table)):
        str2index[word_table[i]] = i + 1
    for nums in str_list:
        index_list.append([])
        for num in nums.split():
            index_list[-1].append(str2index[num])
    return word_table, index_list, 


if __name__ == "__main__":
    str_list = "one two three", "two one four zero"
    word_table, index_list = solve(str_list)
    print(word_table)
    print(index_list)

#word_table = {'four','one','three','two','zero'}
#str_index_list = {[2 4 3],[4 2 1 5]}.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sink Arsenic

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值