如果列表在多个方向上有 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]

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

如果我们可以将这些数据表示为网格结构,每个点都有 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

这是你要找的吗?

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]
limit = 4
flag = False
oldValue = ''
newValue = ''
counter = 0
for i in range(0, len(List)):
  newValue = List[i]
  if (newValue == oldValue):
    counter += 1
  oldValue = newValue
  if (counter >= 4):
    flag = True
    break

print 'Result is' + str(flag)

最新更新