这是糟糕的编程习惯吗?

时间:2020-05-23 06:42:21

标签: python python-3.x exec

所以我已经读了一些关于现在在Python中使用exec的信息,以及它通常如何被皱眉。但是我在意识到负面因素之前就想到了解决这个特殊问题的方法。我终于使解决方案生效,我想知道这是否真的是一个糟糕的解决方案。我为能给出这个答案而感到自豪,现在我需要知道是否应该回到绘图板上。

我解决的问题是提出一种从True False数组创建扫雷网格的解决方案,其中True是炸弹,False是空白空间。事不宜迟,我给你代码:

import copy
def minesweeper(matrix):
    output_matrix = copy.deepcopy(matrix)
    flag=0
    for x in range(len(matrix)):
        for y in range(len(matrix[x])):
            # define search areas with a flag
            if x==0:
                flag += 1
            if y==0:
                flag += 2
            if x+1==len(matrix):
                flag += 4
            if y+1==len(matrix[x]):
                flag += 8
            sum_xy = check_around(x,y,flag, matrix)
            print(sum_xy)
            output_matrix[x][y] = sum_xy
            flag=0
    return output_matrix


def check_around(x,y,flag, matrix):
    summ = 0
    _locals = locals()
    operations = ["summ += matrix[x-1][y-1]",
                  "summ += matrix[x-1][y]",
                  "summ += matrix[x-1][y+1]",
                  "summ += matrix[x][y-1]",
                  "summ += matrix[x][y+1]",
                  "summ += matrix[x+1][y-1]",
                  "summ += matrix[x+1][y]",
                  "summ += matrix[x+1][y+1]"]
    # remove corresponding operations from array based on flag value
    if flag&1:
        indices = [i for i in range(len(operations)) if "x-1" in operations[i]]
        for i in reversed(indices):
            del operations[i]
    if flag&2:
        indices = [i for i in range(len(operations)) if "y-1" in operations[i]]
        for i in reversed(indices):
            del operations[i]
    if flag&4:
        indices = [i for i in range(len(operations)) if "x+1" in operations[i]]
        for i in reversed(indices):
            del operations[i]
    if flag&8:
        indices = [i for i in range(len(operations)) if "y+1" in operations[i]]
        for i in reversed(indices):
            del operations[i]
    # print(f"x={x}, y={y}, num operations={len(operations)}")

    for command in operations:
        # print("exec", command)
        exec(command, {}, _locals)
    return _locals["summ"]



matrix = [[True, False, False],
          [False, True, False],
          [False, False, False]]

print(minesweeper(matrix))

非常感谢您抽出宝贵的时间来帮助我改善!

0 个答案:

没有答案