检查行是否有相同的元素

时间:2015-12-06 15:58:20

标签: python matrix

我需要检查矩阵行中是否有匹配项。如果任何行包含彼此相邻的两个相同元素或仅由None分隔,则匹配。例如

[[2, None, 2],
[2, None, None],
[None, None, None]]

将被视为匹配,因为在第一行中,两个只用“无”分隔。\ n'但是像

这样的东西
[[2, None, None],
[2, None, None],
[None, None, 2]] 

必须返回False.我写的程序在很多情况下都能正常工作,但是有一些错误。我有:

def check_rows(matrix):
    for i in range(len(matrix)):
        for j in range(len(matrix) - 2):
            if (matrix[i][j] != None and matrix[i][j] == matrix[i][j+1]):
                return True

            if (matrix[i][j] != matrix[i][j+1] and matrix[i][j+1] == None) and matrix[i][j] == matrix[i][j+2]:
                return True

            if matrix[i][j+1] != None and matrix[i][j+1] == matrix[i][j+2]:
                return True

            else:
                return False

但如果我申请

[[4, None, None],
[4, None, None],
[2, 2, None]]

结果是False,这是不正确的(最后一行有匹配)。此外,该程序必须适用于任何维度的矩阵。有人能指出我的错误在哪里吗?因为我没有看到它。

提前致谢。

1 个答案:

答案 0 :(得分:1)

坦率地说,我宁愿以一种基本上无索引的方式重写函数,而不是使用所有这些索引,我更喜欢这样:

import itertools

def check_rows(matrix):
    for row in matrix:
        # Strip out the Nones from the row
        filtered = filter(lambda x: x is not None, row)
        # Copy the iterator for the filtered row
        f1, f2 = itertools.tee(filtered)
        # Advance the second one by one step, if possible
        try:
            next(f2)
        except StopIteration:
            # If there's nothing in the filtered row, then clearly there are
            # no duplicates. Move on to the next row.
            continue
        # Look at the elements of f1 and the corresponding "off-by-one" elements
        # of f2. If they are ever equal, we know that we have identical elements
        # adjacent to one another, so we return True early.
        if any(a == b for a, b in zip(f1, f2)):
            return True
    return False

请注意,因为这个函数没有对索引进行任何明确的操作,所以它几乎必须在任何大小的矩阵上工作(事实上,确实有效)。