python - 如何检查列表的元素是否连续

标签 python algorithm list

我必须检查 ■ 是否连续:

_|_ _|_1_|_2_|_3_|_
_|_1_|_■_|_■_|_ _|_
_|_2_|_ _|_ _|_■_|_
_|_3_|_ _|_■_|_ _|_
_|_4_|_■_|_■_|_ _|_

在这种情况下返回 True

例如,如果发生这样的事情:

_|_ _|_1_|_2_|_3_|_
_|_1_|_■_|_■_|_ _|_
_|_2_|_ _|_ _|_■_|_
_|_3_|_ _|_ _|_ _|_
_|_4_|_■_|_■_|_ _|_

在这种情况下返回 False

我正在使用如下列表:

my_list=[[" "," "," "],[" "," "," "],[" "," "," "],
[" "," "," "]]

数字仅在打印电路板时出现,因此我可以使用 my_list 进行任何其他操作。

最佳答案

遍历图表,如果您访问每个节点,那么您就已连接(连续),例如:

def is_contiguous(grid):
    items = {(x, y) for x, row in enumerate(grid) for y, f in enumerate(row) if f}
    directions = [(0, 1), (1, 0), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]
    neighbours = {(x, y): [(x+dx, y+dy) for dx, dy in directions if (x+dx, y+dy) in items]
                  for x, y in items}

    closed = set()
    fringe = [next(iter(items))]
    while fringe:
        i = fringe.pop()
        if i in closed:
            continue
        closed.add(i)
        for n in neighbours[i]:
            fringe.append(n)

    return items == closed

>>> is_contiguous([["X", "X", ""], ["", "", "X"], ["", "X", ""], ["X", "X", ""]])
True
>>> is_contiguous([["X", "X", ""], ["", "", "X"], ["", "", ""], ["X", "X", ""]])
False

只要空白图 block 是假的,那么它就应该按原样工作,例如[[1, 1, 0], [0, 0, 1], [0, 1, 0], [1, 1, 0]] 也会返回 True。如果您对空白图 block 有不同的定义,则只需更改 items 定义中的 if f

关于python - 如何检查列表的元素是否连续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29426303/

相关文章:

python - Flask 应用程序可以在本地运行,但不能在 Heroku 上运行(方法不允许)

python - 如何在 Ray 中使用 python 日志记录?

algorithm - 计算不同于背景和前景的颜色

java - 找到数组中的 k 最小整数

algorithm - 通过动态规划构建最小尺寸的特里树( war 故事 : What’s Past is Prolog from The Algorithm Design Manual by Steven S Skiena)

python - 如何将字符串转换为列表?

python - 如何将字符串列表转换为整数列表 - 很多事情似乎不起作用

c - free() struct** 指针的值

大型 CSV 文件 (numpy) 上的 Python 内存不足

python - scikit-learn 在管道中使用多个类预处理 SVM