返回列表中的连续正数序列
我需要返回列表中最长的正数序列。 目前我有:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看最大子序列问题。
Look into the maximum subsequence problem.
在Python中你可以:
In python you could: