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

时间:2015-04-03 04:40:35

标签: python algorithm list

我必须检查■是否是连续的:

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

在这种情况下返回True

例如,如果发生类似的事情:

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

在这种情况下返回False

我使用的列表如下:

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

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

3 个答案:

答案 0 :(得分:5)

走图表,如果你访问每个节点,那么你就连接了(连续),例如:

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

只要空白的瓷砖是假的,那么这应该按原样工作,例如[[1, 1, 0], [0, 0, 1], [0, 1, 0], [1, 1, 0]]也会返回True。如果您对空白磁贴的定义不同,则只需更改if f定义上的items

答案 1 :(得分:2)

我不会给你你可以插入的代码(因为它看起来像编程挑战),但我会告诉你如何解决你的问题。

您需要构建一个图表。因此,对于每个黑点,您都有相邻黑点的列表(您在此处定义相邻的黑点)。例如,如果所有对角线都按此计算,则对于点(2, 3),您的相邻列表将为:(1, 2), (3, 2)。您的图表看起来像

{
  (2, 3): {(1, 2), (3, 2)},
  ... every other node
}

您可以提出一个更简单的架构,其中(2, 3)将对应(2 - 1) * len(matrix row) + (3 - 1) = 5。我减去了一个,因为我用零作为起点。

现在,当您有图表时,可以使用算法connected components并检查是否只有一个这样的组件。如果是,则为True,否则为false。

您的单个​​连接组件只是BFS或DFS。

答案 2 :(得分:0)

这对我有用:

def findContiguous(myList):
    rowCount = 0
    previousRowFound = []
    rowsWithItems = []     
    for row in myList:
        currentRowFound = []
        rowCount += 1
        # Determine if target is in the row
        if "■" in row:
            currentRowFound = [i for i, x in enumerate(row) if x == "■"]
            rowsWithItems.append(rowCount)

        # Check if there is a cell adjacent or diagonal to previous
        if len(currentRowFound) != 0 and len(previousRowFound) != 0:
            for cell in currentRowFound:
                if not((cell + 1 in previousRowFound) or (cell - 1 in previousRowFound) or (cell in previousRowFound)):
                    return False

        # Check for blank rows in between rows with item
        if len(rowsWithItems) > 1 and len(previousRowFound) == 0:
            if rowsWithItems[-2] != rowCount - 1:
                print(rowsWithItems)
                print(rowCount)
                return False

        # Move on to next row
        previousRowFound = currentRowFound
        first = False
    return True