查找不包含特定数字的最长序列

时间:2019-05-12 04:38:35

标签: python python-3.x algorithm

我有一个数组,我想从不包含3的数组中找到最长的数字序列:

#array
x=[1,2,3,4,5,6,5,4,3,3,4,5,2,3,7]

我期望结果如下:

[4, 5, 6, 5, 4]

2 个答案:

答案 0 :(得分:2)

如果我这样做的话,我会与itertools.groupby组成小组,参加最长的小组:

from itertools import groupby

a = [1,2,3,4,5,6,5,4,3,3,4,5,2,3,7] 

groups = [list(g) for k, g in groupby(a, key=lambda x: x!=3) if k]
max(groups, key = len)

# [4, 5, 6, 5, 4]

当然还有许多其他方法。如果您想手动循环浏览列表,则可以跟踪当前最长的记录:

a = [1,2,3,4,5,6,5,4,3,3,4,5,2,3,7] 

cur = []
longest = cur
for n in a:
    if n != 3:
        cur.append(n)
        if len(cur) > len(longest):
            longest = cur
    else:
        cur = []

print(longest) #[4, 5, 6, 5, 4]

答案 1 :(得分:0)

如果要查找序列(特别是子序列),则将取非3以外的所有元素作为结果。

但是似乎您想找到子数组。以下是我在python中相同的实现

def findLargestSubArray(arr, k):
    # collect all the index position of k in arr
    kPos = [i for i in range(len(arr)) if arr[i] == k]
    largest = 0
    left = -1
    right = -1
    # size of subarray to the left of 1st instance of k
    if len(kPos) > 0:
        largest = kPos[0] - 1
        left = 0
        right = kPos[0]
    for i in range(1, len(kPos)):
        # size of subarray between ith & (i-1)th instance of k
        currSize = kPos[i] - kPos[i-1] - 1
        if largest < currSize:
            largest = currSize
            left = kPos[i-1] + 1
            right = kPos[i]
    # size of subarry to the right of last instance of k
    if largest < len(arr) - kPos[-1] - 1:
        largest = len(arr) - kPos[-1] - 1
        left = kPos[-1] + 1
        right = len(arr)
    return arr[left: right]


x = [3,3]
print(findLargestSubArray(x, 3))