确定二维数组中最长连续值范围的最快方法

Quickest way to determine the longest consecutive value range in a 2D-Array

问题

假设我们正在处理一个大型数据集,为了简单起见,我们在这个问题中使用这个较小的数据集:

dataset = [["PLANT", 4,11],
           ["PLANT", 4,12],
           ["PLANT", 34,4],
           ["PLANT", 6,5],
           ["PLANT", 54,45],
           ["ANIMAL", 5,76],
           ["ANIMAL", 7,33],
           ["Animal", 11,1]]

我们想找出哪一列的连续值范围最长,找出哪一列最好的最快方法是什么?

天真的做法

我很快发现它可以按每列排序

sortedDatasets = []
for i in range(1,len(dataset[0]):
    sortedDatasets.append(sorted(dataset,key=lambda x: x[i]))

但是这里出现了滞后的部分:我们可以从这里继续并为每个排序的数据集做一个 for loop,并计算连续的元素但是当涉及到处理时 for loops python 很慢。

现在我的问题:有没有比这种天真的方法更快的方法,这些 2D 容器是否有内置函数?


更新:

这个伪算法可以更准确地描述范围的含义——这包括递增 if current value == next value:

if nextValue > current Value +1: 
     {reset counter} 
else: 
     {increment counter}

您可以使用 groupby 以合理的效率完成此操作。我将分阶段执行此操作,以便您了解其工作原理。

from itertools import groupby

dataset = [
    ["PLANT", 4, 11],
    ["PLANT", 4, 12],
    ["PLANT", 34, 4],
    ["PLANT", 6, 5],
    ["PLANT", 54, 45],
    ["ANIMAL", 5, 76],
    ["ANIMAL", 7, 33],
    ["ANIMAL", 11, 1],
]

# Get numeric columns & sort them in-place
sorted_columns = [sorted(col) for col in zip(*dataset)[1:]]
print sorted_columns
print

# Check if tuple `t` consists of consecutive numbers
keyfunc = lambda t: t[1] == t[0] + 1

# Search for runs of consecutive numbers in each column
for col in sorted_columns:
    #Create tuples of adjacent pairs of numbers in this column
    pairs = zip(col, col[1:])
    print pairs
    for k,g in groupby(pairs, key=keyfunc):
        print k, list(g)
    print

输出

[[4, 4, 5, 6, 7, 11, 34, 54], [1, 4, 5, 11, 12, 33, 45, 76]]

[(4, 4), (4, 5), (5, 6), (6, 7), (7, 11), (11, 34), (34, 54)]
False [(4, 4)]
True [(4, 5), (5, 6), (6, 7)]
False [(7, 11), (11, 34), (34, 54)]

[(1, 4), (4, 5), (5, 11), (11, 12), (12, 33), (33, 45), (45, 76)]
False [(1, 4)]
True [(4, 5)]
False [(5, 11)]
True [(11, 12)]
False [(12, 33), (33, 45), (45, 76)]

现在,攻击你的实际问题:

from itertools import groupby

dataset = [
    ["PLANT", 4, 11],
    ["PLANT", 4, 12],
    ["PLANT", 34, 4],
    ["PLANT", 6, 5],
    ["PLANT", 54, 45],
    ["ANIMAL", 5, 76],
    ["ANIMAL", 7, 33],
    ["ANIMAL", 11, 1],
]

# Get numeric columns & sort them in-place
sorted_columns = [sorted(col) for col in zip(*dataset)[1:]]

# Check if tuple `t` consists of consecutive numbers
keyfunc = lambda t: t[1] == t[0] + 1

#Search for the longest run of consecutive numbers in each column
runs = []
for i, col in enumerate(sorted_columns, 1):
    pairs = zip(col, col[1:])
    m = max(len(list(g)) for k,g in groupby(pairs, key=keyfunc) if k)
    runs.append((m, i))

print runs
#Print the highest run length found and the column it was found in
print max(runs)

输出

[(3, 1), (1, 2)]
(3, 1)

FWIW,这可以压缩成一行。由于它使用几个生成器表达式而不是列表理解,因此效率更高一些,但它的可读性不是特别好:

print max((max(len(list(g)) 
    for k,g in groupby(zip(col, col[1:]), key=lambda t: t[1] == t[0] + 1) if k), i)
        for i, col in enumerate((sorted(col) for col in zip(*dataset)[1:]), 1))

更新

我们可以通过做一些小改动来处理您新的连续序列定义。

首先,我们需要一个关键函数 returns True 如果排序列中相邻的一对数字之间的差异 <= 1.

def keyfunc(t):
    return t[1] - t[0] <= 1

现在,我们不再获取与该关键函数匹配的序列的长度,而是通过一些简单的算术来查看序列中值范围的大小。

def runlen(seq):
    return 1 + seq[-1][1] - seq[0][0]

综合起来:

def keyfunc(t):
    return t[1] - t[0] <= 1

def runlen(seq):
    return 1 + seq[-1][1] - seq[0][0]

# Get numeric columns & sort them in-place
sorted_columns = [sorted(col) for col in zip(*dataset)[1:]]

#Search for the longest run of consecutive numbers in each column
runs = []
for i, col in enumerate(sorted_columns, 1):
    pairs = zip(col, col[1:])
    m = max(runlen(list(g)) for k,g in groupby(pairs, key=keyfunc) if k)
    runs.append((m, i))

print runs
#Print the highest run length found and the column it was found in
print max(runs)

更新 2

如评论中所述,如果 max 的 arg 是空序列,则引发 ValueError。一种简单的处理方法是将 max 调用包装在 try..except 块中。如果异常很少发生,这是非常有效的, try..except 实际上比未引发异常时等效的 if...else 逻辑更快。所以我们可以做这样的事情:

run = (runlen(list(g)) for k,g in groupby(pairs, key=keyfunc) if k)
try:
    m = max(run)
except ValueError:
    m = 0
runs.append((m, i))

但是如果这种异常经常发生,最好使用另一种方法。

这是一个新版本,它使用成熟的生成器函数 find_runs 代替生成器表达式。 find_runs 在开始处理列数据之前只需 yield 一个零,这样 max 将始终至少有一个值要处理。我内联了 runlen 计算以节省额外函数调用的开销。这种重构还使得在列表理解中构建 runs 列表变得更加容易。

from itertools import groupby

dataset = [
    ["PLANT", 4, 11, 3],
    ["PLANT", 4, 12, 5],
    ["PLANT", 34, 4, 7],
    ["PLANT", 6, 5, 9],
    ["PLANT", 54, 45, 11],
    ["ANIMAL", 5, 76, 13],
    ["ANIMAL", 7, 33, 15],
    ["ANIMAL", 11, 1, 17],
]

def keyfunc(t):
    return t[1] - t[0] <= 1

def find_runs(col):
    pairs = zip(col, col[1:])
    #This stops `max` from choking if we don't find any runs
    yield 0
    for k, g in groupby(pairs, key=keyfunc):
        if k:
            #Determine run length
            seq = list(g)
            yield 1 + seq[-1][1] - seq[0][0]

# Get numeric columns & sort them in-place
sorted_columns = [sorted(col) for col in zip(*dataset)[1:]]

#Search for the longest run of consecutive numbers in each column
runs = [(max(find_runs(col)), i) for i, col in enumerate(sorted_columns, 1)]
print runs

#Print the highest run length found and the column it was found in
print max(runs)

输出

[(4, 1), (2, 2), (0, 3)]
(4, 1)