【问题标题】:Find longest sequence of 0's in the integer list在整数列表中查找最长的 0 序列
【发布时间】:2016-10-21 00:23:16
【问题描述】:

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 作为最大长度。

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

【问题讨论】:

  • 所以,你有一种方法,可能是一些代码,可能是运行该代码的一些结果。你有什么问题?
  • 我需要用一行python代码写这个
  • 这不是问题,这是作业。
  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只有在发布者已经尝试自己解决问题时才会提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • 请检查我的代码

标签: python list python-3.x


【解决方案1】:

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

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

使用list(y) for (x,y) in list if x == 0 仅过滤0s,

最后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

【讨论】:

    【解决方案2】:

    你可以试试这个:

     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的最长序列ist 8

    index start at: 12
    
    index ends at: 19
    

    【讨论】:

    • 如果最长序列包含列表中的最后一项,您的解决方案将失败。这当然可以通过在 for 循环之后直接添加 final(如果 count > prev ....)来轻松解决。
    【解决方案3】:

    一个不错的简洁的原生 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
    

    【讨论】:

      【解决方案4】:

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

      # 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
      

      你现在能把它包装成一个语句吗?

      【讨论】:

        【解决方案5】:

        好吧,就像一条长长的恶心的台词!

        "-".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",..] 然后进行一些拆分和解析来跟踪索引。

        是的,它非常丑陋,您应该选择其他答案之一,但我想分享

        【讨论】:

          【解决方案6】:
          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】:
            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
            

            【讨论】:

              【解决方案8】:

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

              import numpy as np
              def longest_sequence(bool_array):
                  where_not_true = np.where(~bool_array)[0]
                  lengths_plus_1 = np.diff(np.hstack((-1,where_not_true,len(bool_array))))
                  index          = np.cumsum(np.hstack((0,lengths_plus_1)))
                  start_in_lngth = np.argmax(lengths_plus_1)
                  start          = index[         start_in_lngth]
                  length         = lengths_plus_1[start_in_lngth] - 1
                  return start, length
              
              t = np.array((0,1,0,1,1,1,0,0,1,1,0,1))
              print(longest_sequence(t==0))
              print(longest_sequence(t==1))
              p = np.array((0,0,0,1,0,1,1,1,0,0,0,1,1,0,1,1,1,1))
              print(longest_sequence(p==0))
              print(longest_sequence(p==1))
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2021-06-23
                • 1970-01-01
                • 2022-01-16
                • 2018-09-10
                • 1970-01-01
                • 1970-01-01
                • 2020-07-17
                相关资源
                最近更新 更多