返回列表中的连续正数序列

发布于 2024-12-12 10:37:55 字数 540 浏览 2 评论 0原文

我需要返回列表中最长的正数序列。 目前我有:

def longestSequencePos(nums):
    longest_sequence = []
    current_sequence = []

    for obj in nums:
        if current_sequence and current_sequence[-1]+1 == obj:
            current_sequence.append(obj)
        else:
            current_sequence = [obj]
        if len(current_sequence) > len(longest_sequence):
            longest_sequence = current_sequence
    return sum(1 for obj in longest_sequence if obj > 0)

这只返回随后出现的正数总数,因此当序列类似于 5、8、12 时它不起作用。任何帮助将不胜感激。

I need to return the longest sequence of positive numbers in a list.
currently I have:

def longestSequencePos(nums):
    longest_sequence = []
    current_sequence = []

    for obj in nums:
        if current_sequence and current_sequence[-1]+1 == obj:
            current_sequence.append(obj)
        else:
            current_sequence = [obj]
        if len(current_sequence) > len(longest_sequence):
            longest_sequence = current_sequence
    return sum(1 for obj in longest_sequence if obj > 0)

This only returns the total number of positive numbers which appear consequentially, so it doesn't work when a sequence is something like 5, 8, 12. Any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌上芳菲 2024-12-19 10:37:55

查看最大子序列问题。

Look into the maximum subsequence problem.

弱骨蛰伏 2024-12-19 10:37:55

在Python中你可以:

def find_longest_sequence(source_list):
    longest_sequence = []
    current_sequence = []

    for obj in source_list:
            if current_sequence and current_sequence[-1]+1 == obj:
                current_sequence.append(obj)
            else:
                current_sequence = [obj]
            if len(current_sequence) > len(longest_sequence):
                longest_sequence = current_sequence
    return longest_sequence
print "Longest sequence:", find_longest_sequence([1,5,6,7,3,4,1,2,3,4,5,5,6,7])

In python you could:

def find_longest_sequence(source_list):
    longest_sequence = []
    current_sequence = []

    for obj in source_list:
            if current_sequence and current_sequence[-1]+1 == obj:
                current_sequence.append(obj)
            else:
                current_sequence = [obj]
            if len(current_sequence) > len(longest_sequence):
                longest_sequence = current_sequence
    return longest_sequence
print "Longest sequence:", find_longest_sequence([1,5,6,7,3,4,1,2,3,4,5,5,6,7])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文