简体   繁体   English

如何在列表中找到特定模式?

[英]How can I find a specific pattern in a list?

Given a list of numbers containing either 0's, 1's, or -1's, how can I find the longest portion of the list that starts with a +1 and ends with a -1.给定一个包含 0、1 或 -1 的数字列表,如何找到列表中以 +1 开头并以 -1 结尾的最长部分。

For example, [0,0,1,1,1,-1,-1,-1,0] : The longest portion is 6 due to the portion of the list [1,1,1,-1,-1,-1].例如, [0,0,1,1,1,-1,-1,-1,0] :由于列表 [1,1,1,-1,-1 的部分,最长的部分是 6 ,-1]。

For example, [1,-1,0,1,-1,-1,-1] : The longest portion is 4 due to the portion of the list [1,-1,-1,-1].例如, [1,-1,0,1,-1,-1,-1] :由于列表 [1,-1,-1,-1] 的部分,最长的部分是 4。 Note that had the original list only been the first 3 elements (eg, [1,-1,0]), then the correct answer would have been 2 [1,-1].请注意,如果原始列表只有前 3 个元素(例如 [1,-1,0]),那么正确答案应该是 2 [1,-1]。

Also, the list cannot be broken with a 0 and it can only alternate from +1 to -1 once.此外,列表不能被 0 打破,它只能从 +1 到 -1 交替一次。 In other words [+1,-1,+1,-1] is still only 2.换句话说 [+1,-1,+1,-1] 仍然只有 2。

Thank you谢谢

You need has two bool(previous_has_one exist, previous_has_neg_one) to record them exist or not.您需要有两个 bool(previous_has_one 存在,previous_has_neg_one) 来记录它们是否存在。

def getLongestPortion(l):
    maxx = 0
    curMax = 0
    JustHadOne = False
    JustHadNeg = False
    for i in range(len(l)):
        if(l[i]==1):
            if(JustHadNeg):
                curMax = 0
            curMax += 1
            JustHadOne = True
            JustHadNeg = False
        elif(l[i]==-1 and JustHadOne):
            curMax += 1
            maxx = max(maxx,curMax)
            JustHadNeg = True
        else:
            JustHadOne = False
            JustHadNeg = False
            curMax=0
    return maxx

l = [1,-1,-1,0,1,1,-1,-1]
print(getLongestPortion(l))

Here's a regex solution.这是一个正则表达式解决方案。 First I change a list like [1, -1, 0, 1, -1, -1, -1] to a string like 'ab abbb' , then I search for 'a+b+' , then take the maximum length of the matches:首先,我将[1, -1, 0, 1, -1, -1, -1]类的列表更改为'ab abbb'类的字符串,然后搜索'a+b+' ,然后取最大长度比赛:

import re

max(map(len, re.findall('a+b+', ''.join(' ab'[i] for i in l))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM