查找容差级别内最大的数字子串

时间:2017-11-06 19:28:17

标签: python arrays longest-substring

我有以下输入:

  • 公差等级T
  • 数量N
  • N个数字

任务是找到这N个数字内的最长时间段,使它们在容差范围内。更确切地说,给定子串lr的左边界和右边界以及两个边界之间的两个不同元素a1a2,它必须保持{|a1 - a1| <= T 1}}。我怎样才能以有效的方式做到这一点?我的方法是:

def getLength(T, N, numbers):

    max_length = 1

    for i in range(0, N-1):
        start = numbers[i]
        numlist = [start]

        for j in range(i+1, N):
            end = numbers[j]
            numlist.append(end)

            if (max(numlist) - min(numlist)) > T:
                break

            if (j-i+1) > max_length:
                max_length = j-i+1

    return max_length

编辑:说清楚。代码按预期工作。但是,它不够有效。我想更有效率地做到这一点。

1 个答案:

答案 0 :(得分:0)

首先,我不确定您的代码是否符合您在问题中描述的内容。其次,处理12,000个随机数需要(很多)小于秒。

无论何时,每次添加新元素时,{em>都不会在min()上调用max()numlist来加快速度。相反,您只需使用几个if语句更新当前的最小和最大变量。

这里的代码显示已完成,以及我为时序性能编写的简单框架:

def getLength(T, N, numbers):
    max_length = 1

    for i in range(N-1):
        start = numbers[i]
        numlist = [start]
        min_numlist = max_numlist = start  # Added variables.

        for j in range(i+1, N):
            end = numbers[j]
            numlist.append(end)

# Inefficient - replaced.
#            if (max(numlist) - min(numlist)) > T:
#                break

            # Update extremities.
            if end > max_numlist:
                max_numlist = end
            if end < min_numlist:
                min_numlist = end

            if max_numlist-min_numlist > T:
                break

            if j-i+1 > max_length:
                max_length = j-i+1

    return max_length


if __name__ == '__main__':
    import random
    import time

    random.seed(42)  # Use hardcoded seed to get same numbers each time run.
    T = 100
    N = 12000
    numbers = [random.randrange(1000) for _ in range(N)]
    starttime = time.time()
    max_length = getLength(T, N, numbers)
    stoptime = time.time()
    print('max length: {}'.format(max_length))
    print('processing {:,d} elements took {:.5f} secs'.format(N, stoptime-starttime))