簡體   English   中英

在整數列表中找到最長的 0 序列

[英]Find longest sequence of 0's in the integer list

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代碼index.Please幫助。

我試過:

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

返回8作為最大長度。

現在,如何找到最長序列的開始和結束索引?

您可以先使用enumerate用索引壓縮項目,

然后itertools.groupby(list,operator.itemgetter(1))按項目分組,

list(y) for (x,y) in list if x == 0list(y) for (x,y) in list if x == 0使用list(y) for (x,y) in list if x == 0僅過濾0 s,

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

一個不錯的簡潔的原生 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

你可以試試這個:

 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

現在您有了長度,在原始列表中找到 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

你現在能把它包裝成一個單一的語句嗎?

好吧,作為一長串惡心!

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

是的,它非常丑陋,您應該選擇其他答案之一,但我想分享

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
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
        }
    }

如果你想完全避免 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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM