python - 如果列表在多个方向上有 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
。我也想测试对角线,但我正在努力弄清楚如何尝试这样做。我没有示例代码,因为我不知道如何解决这个问题。如果我需要以不同的方式解释,请告诉我。
解决方案
如果我们可以将这些数据表示为每个点的 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
推荐阅读
- amazon-ami - 在本地环境中存储 Packer 烘焙图像
- c# - 并行循环中的静态与实例在内存和性能方面更好
- python - 在数据框中创建一个新列,从现有的 dd/mm/yy 列显示星期几?Python
- postgresql - 子查询中的列总和产生奇怪的结果
- sum - 按元素分组并求和 XSLT
- java - 设置复选框的限制
- c++ - 拥有一个不需要创建对象的类是不好的做法吗?
- flutter - 宽度超过时 Flutter TextFormField 文本裁剪
- c# - 无法在 GetAwaiter().GetResult() 上将类型“void”隐式转换为“object”
- android - 如何在android studio中将现有的java类排列到不同的包中?