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

时间:2011-10-30 22:48:51

标签: python list jython

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

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时它不起作用。任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

查看maximum subsequence问题。

答案 1 :(得分:1)

在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])