在布尔数组中查找特定模式

Finding a specific pattern in a boolean array

我正在做一个项目,但遇到了以下问题:我有一个布尔数组,我想确定该数组中是否存在特定模式。

例如,假设我有这个布尔数组:[True, False, False, True, False, False, True, False, True, True, True] 我想知道它是否包含以下内容模式[假,假,真,假]。

我的第一个想法是遍历布尔数组的所有值,定义一个变量来计算连续“False”的数量,然后再次循环以查找“True”是否遵循该序列,等等......但是这似乎有点乏味,我想有更好的方法来做到这一点...

非常欢迎任何建议! 谢谢

一种方法是将数组转换为 ft 字符的字符串,然后使用字符串搜索来查找所需的模式。例如:

def bool_list_to_str(bool_list):
    return ''.join('ft'[i] for i in bool_list)

您可以调用此函数将数组和搜索模式都转换为字符串。然后你可以使用 s.find(p) 在字符串 s.

中搜索模式 p

请注意,每个 bool 值使用一个字符,因此字符串将与 bool 列表具有相同的长度,并且索引将匹配。它还使用最少量的字符串内存。

您可以将它们作为字符串加入并检查子字符串:

super_list = [True, False, False, True, False, False, True, False, True, True, True]
sub_list = [False, False, True, False]

super_list_as_str = ''.join(map(str, super_list))
sub_list_as_str = ''.join(map(str, sub_list))

if sub_list_as_str in super_list_as_str:
    print('Sub string')

我刚开始编程,然后我的代码没有优化。但是很容易理解:

1.- 创建一个列表,其中包含长度为 n

的数组的所有组合

2.- 将模式与您创建的列表进行比较。

# a is the array you want to check with
a = [True, False, False, True, False, False, True, False, True, True, True]
# b is the array you want to check
b = [False, True, False, False]
# patterns is the list with all the patterns in the array
patterns = []
for i in range(len(a)-(len(b)-1)):
    patterns.append((a[i:(len(b)+i)]))

# Check if b is in the list you have create.
b in patterns