一个列表中全是自然数,是无序的,计算这个列表中最大长度的连续自然数。比如[1,5,7,9,12,17,,6,6],返回结果为 [5,6,7]
def get_longest_num(list1): longest_num = [] long_tmp = [] flag = True longth = 1 last_longest = 0 list1 = sorted(list1) for j, i in enumerate(list1): if(flag): num_start = i flag = False if(i == list1[j-1] and j!=len(list1)-1): continue elif(list1[j-1] == i-1): long_tmp.append(i) if(list1[j-1] != i-1 or j == len(list1)-1): if(longth>last_longest): longest_num = [] longest_num.append(long_tmp) elif(longth==last_longest and longth != 0): longest_num.append(long_tmp) long_tmp = [] long_tmp.append(i) last_longest = longth if(longth>last_longest) else last_longest longth = 1 num_start = i longth = longth + 1 print(longest_num) get_longest_num([0,1,2,5,6,6,6,7,7])