查找整数游程

Finding runs of integers

我有一个问题要求我编写一个程序,该程序具有一个已定义的列表(作为参数),然后将找到所有增加或减少 1 的 Y 连续数字的运行。然后它将return 每次运行的第一个元素的索引列表。

例如,如果Y = 3,则l1 = [1,2,3,5,10,9,8,9,10,11,7,8,7] returns [0,4,6,7]。我的代码有点工作,但它只在我 'hard code' 我正在检查多少个数字时才有效。例如,如果 Y = 3,那么我的 IF 语句正在检查 l1[i]l1[i] + 1l1[i] + 2)。无论我将 Y 设置为什么,我都需要它动态工作。

下面是我的代码 'base logic':

A = [1,2,3,5,10,9,8,9,10,11,7,8,7]

new_indices = []
for index, number in enumerate(A[:-2]):
    urgent_number = abs(A[index + 1])
    next_number = abs(A[index + 2])
    if (number + 1 == urgent_number and number + 2 == next_number) or (number - 1 == urgent_number and number - 2 == next_number):
        new_indices.append(index)

print(new_indices)

下面是我尝试合并一个 while 循环来动态执行此操作的尝试。我很接近,但我似乎无法弄清楚:

A = [1,2,3,5,10,9,8,9,10,11,7,8,7]
Y = 3  #length of list

new_indices = []
for index, number in enumerate(A[:-2]):
    urgent_number = abs(A[index + 1])
    next_number = abs(A[index + 2])
    x = 0
    while x < Y:
        if (number + 1 == urgent_number and number + 2 == next_number) or (number - 1 == urgent_number and number - 2 == next_number):
            new_indices.append(index)
        x += 1

print(new_indices)

打印出 [0,0,0,4,4,4,6,6,6,7,7,7]。但是,我正在寻找 [0,4,6,7].

既然你已经得到了所有的起始索引,只需要删除重复项,你可以这样做:

from itertools import groupby

original_result = [0,0,0,4,4,4,6,6,6,7,7,7]
final_result = [key for key, _ in groupby(original_result)]
[key for key, _ in groupby(original_result)]

以获得所需的输出。

这输出:

[0, 4, 6, 7]

如果你需要专门处理变量运行的长度,你可以找到所有可以组成一个运行的有效列表切片,然后验证这些切片是否组成一个运行:

A = [1,2,3,5,10,9,8,9,10,11,7,8,7]
RUN_LENGTH = 3
indices = []
for s in range(len(A) - RUN_LENGTH):
    is_incrementally_increasing = \
        all(i2 - i1 == 1 for i1, i2 in zip(A[s:s+RUN_LENGTH], A[s+1:s+RUN_LENGTH]))
    is_incrementally_decreasing = \
        all(i1 - i2 == 1 for i1, i2 in zip(A[s:s+RUN_LENGTH], A[s+1:s+RUN_LENGTH]))
    if is_incrementally_increasing or is_incrementally_decreasing:
        indices.append(s)

print(indices)

这也输出:

[0, 4, 6, 7]

这也有效:

def dynamical(A):
    new_indices = []
    for index, number in enumerate(A[:-2]):
        urgent_number = abs(A[index + 1])
        next_number = abs(A[index + 2])
        if (number + 1 == urgent_number and number + 2 == next_number) or (number - 1 == urgent_number and number - 2 == next_number):
            new_indices.append(index)

    return new_indices