在整数列表中找到0的最长序列

时间:2016-10-21 00:23:16

标签: python list python-3.x

A = [1,2,0,0,3,4,5,-1,0,2,-1,-3,0,0,0,0,0,0,0,0,-2,-3,-4,-5,0,0,0]

返回列表中0的最长序列的初始和结束索引。 因为,上面列表中0的最长序列是0,0,0,0,0,0,0,0所以它应该返回12,19作为开始和结束索引。请帮助使用一行python代码。

我试过了:

k = max(len(list(y)) for (c,y) in itertools.groupby(A) if c==0)
print(k)

返回8作为最大长度。

现在,如何找到最长序列的起始和结束索引?

8 个答案:

答案 0 :(得分:4)

您可以先使用enumerate压缩带索引的项目

然后itertools.groupby(list,operator.itemgetter(1))逐项分组,

仅使用0

过滤list(y) for (x,y) in list if x == 0

并在最后max(list, key=len)获得最长的序列。

import itertools,operator
r = max((list(y) for (x,y) in itertools.groupby((enumerate(A)),operator.itemgetter(1)) if x == 0), key=len)
print(r[0][0]) # prints 12
print(r[-1][0]) # prints 19

答案 1 :(得分:1)

一种简洁的本机python方法

target = 0
A = [1,2,0,0,3,4,5,-1,0,2,-1,-3,0,0,0,0,0,0,0,0,2,-3,-4,-5,0,0,0]

def longest_seq(A, target):
    """ input list of elements, and target element, return longest sequence of target """
    cnt, max_val = 0, 0 # running count, and max count
    for e in A: 
        cnt = cnt + 1 if e == target else 0  # add to or reset running count
        max_val = max(cnt, max_val) # update max count
    return max_val

答案 2 :(得分:0)

你可以试试这个:

 A = [1,2,0,0,3,4,5,-1,0,2,-1,-3,0,0,0,0,0,0,0,0,2,-3,-4,-5,0,0,0]

count = 0
prev = 0
indexend = 0
for i in range(0,len(A)):
    if A[i] == 0:
        count += 1
    else:            
      if count > prev:
        prev = count
        indexend = i
      count = 0

print("The longest sequence of 0's is "+str(prev))
print("index start at: "+ str(indexend-prev))
print("index ends at: "+ str(indexend-1))

输出:

  

0的最长序列是8

index start at: 12

index ends at: 19

答案 3 :(得分:0)

现在您有了长度,在原始列表中找到0的k长度序列。扩展您最终将工作的内容扩展到一行:

# k is given in your post
k_zeros = [0]*k
for i in range(len(A)-k):
    if A[i:i+k] == k_zeros:
        break
# i is the start index; i+k-1 is the end

现在可以将它包装成一个单独的语句吗?

答案 4 :(得分:0)

好吧,作为一条长长的令人厌恶的路线!

"-".join([sorted([list(y) for c,y in itertools.groupby([str(v)+"_"+str(i) for i,v in enumerate(A)], lambda x: x.split("_")[0]) if c[0] == '0'],key=len)[-1][a].split("_")[1] for a in [0,-1]])

通过将[1,2,0...]转换为["1_0","2_1","0_2",..]然后进行一些拆分和解析来跟踪索引。

是的,它非常难看,你应该选择其中一个答案,但我想分享

答案 5 :(得分:0)

针对上述问题的初学者的完整解决方案是:

A = [1,2,0,0,3,4,5,-1,0,2,-1,-3,0,0,0,2,-3,-4,-5,0,0,0,0]

count = 0
prev = 0
indexend = 0
indexcount = 0
for i in range(0,len(A)):
    if A[i] == 0:
       count += 1
       indexcount = i
    else:            
       if count > prev:
       prev = count
       indexend = i
       count = 0

if count > prev:
   prev = count
   indexend = indexcount

print("The longest sequence of 0's is "+str(prev))
print("index start at: "+ str(indexend-prev))
print("index ends at: "+ str(indexend-1))

还要考虑最长0的序列是否在末尾。

输出

 The longest sequence of 0's is 4
 index start at: 18
 index ends at: 21

答案 6 :(得分:0)

This solution i submitted in Codility with 100 percent efficieny.
    class Solution {
        public int solution(int N) {
            int i = 0;
                int gap = 0;
                `bool startZeroCount = false;
                List<int> binaryArray = new List<int>();
                while (N > 0)
                {
                    binaryArray.Add(N % 2);
                    N = N / 2;
                    i++;
                }
                
                List<int> gapArr = new List<int>();
                for (int j = i-1; j >= 0; j--)
                {
                    if (binaryArray[j] == 1)
                    {
                        if(startZeroCount)
                        {
                            gapArr.Add(gap);
                            gap = 0;
                           
                        }
                        startZeroCount = true;
                    }
                    else if(binaryArray[j] == 0)
                    {
                        if (startZeroCount)
                            gap++;
                    }                
                }
                gapArr.Sort();            
                if (gapArr.Count != 0)
                    return gapArr[gapArr.Count - 1];
                else return 0;enter code here
        }
    }

答案 7 :(得分:0)

如果你想完全避免 Python 迭代,你可以用 Numpy 来实现。例如,对于很长的序列,使用 for 循环可能相对较慢。此方法将在后台使用预编译的 C for 循环。缺点是这里有多个 for 循环。尽管如此,总的来说,下面的算法应该是对较长序列的速度增益。

austin-tui -p <pid>