首页 > 解决方案 > 如果列表在多个方向上有 4 个连续数字,则获取真假结果测试

问题描述

我正在制作一个列表,我想在任何方向连续测试 4 个或更多的阳性结果(我正在测试 B 和 E),例如:

List = [N, N, B, N, N, E, B, E, N,
        N, E, B, N, E, E, E, B, N,
        N, N, N, N, N, E, B, E, N,
        N, E, B, N, E, E, E, B, N]

它更长,但你明白了,无论如何我希望它返回为 True forE因为连续有四个 forE但没有 for B。我也想测试对角线,但我正在努力弄清楚如何尝试这样做。我没有示例代码,因为我不知道如何解决这个问题。如果我需要以不同的方式解释,请告诉我。

标签: pythonpython-3.x

解决方案


如果我们可以将这些数据表示为每个点的 x、y 坐标的网格结构,那就更容易了。我们可以使用一个类以这种方式设置数据。班级需要知道您希望网格有多宽才能做到这一点。要找到一系列项目,我们可以遍历行和列,每次找到项目的匹配项时,我们检查每个方向上的相邻方格是否也包含相同的项目。

class Grid(object):
    def __init__(self, data, width):
        self.data = data
        self.width = width
        self.height = len(L) / width

    def get(self, x, y):
        """ Find the item in the grid at the given coordinates """
        if 0 <= x < self.width and 0 <= y < self.height:
            return self.data[y * self.width + x]

    def find_sequence(self, item, times):
        """ Check for a sequence of item occuring at least the specified 
        number of times. Checks right, down, down-right, and down-left. """

        for y in range(self.height):
            for x in range(self.width):
                # if we find the item at x, y...
                if self.get(x, y) == item:
                    # ... then look at adjacent items in each direction
                    for dx, dy in [(1, 0), (0, 1), (1, 1), (-1, 1)]:
                        if all(self.get(x + i*dx, y + i*dy) == item 
                               for i in range(1, times)):
                            return True
        return False

N, B, E = "N", "B", "E"
data = [N, N, B, N, N, E, B, E, N,
        N, E, B, N, E, E, E, B, N,
        N, N, N, N, N, E, B, E, N,
        N, E, B, N, E, E, E, B, N]
grid = Grid(data, width=9)
grid.get(3, 3)   # N
grid.find_sequence(B, 4)  # False
grid.find_sequence(N, 4)  # True
grid.find_sequence(E, 4)  # True

推荐阅读