Longest distinct consecutive list in Python
I have a list:
a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16,开发者_高级运维 17, 18, 20, 21]
Is it possible to make a function that shows the longest list of distinct, consecutive elements?
Please, show how to do it
In this case the answer should be:
13, 14, 15, 16, 17, 18
Assuming your list is sorted:
>>> from itertools import groupby
>>> z = zip(a, a[1:])
>>> tmp = [list(j) for i, j in groupby(z, key=lambda x: (x[1] - x[0]) <= 1)]
>>> max(tmp, key=len)
[(13, 14), (14, 15), (15, 16), (16, 16), (16, 17), (17, 18)]
>>> list(range(_[0][0], _[-1][-1]+1))
[13, 14, 15, 16, 17, 18]
ETA: fixed last step;
The simplest thing to do seems to be to loop through the list once, building any sequences you can find and then print the longest one.
a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]
seqlist = [] # List of Sequences
seq = [] # Current Sequence
last = -1
for item in a:
# Start a new sequence if the gap from the last item is too big
if item - last > 1:
seqlist.append(seq)
seq = []
# only add item to the sequence if it's not the same as the last
if item != last:
seq.append(item)
last = item
# Print longest sequence found
print max(seqlist)
There is probably a more pythonic way, but I can't think of it right now, so here a very basic solution:
def longestDistinctConsecutiveList ( lst ):
lst = list( set( lst ) ) # get rid of duplicated elements
lst.sort() # sort
s, l = 0, 0
for i in range( len( lst ) ):
for j in range( i, len( lst ) ):
if lst[j] - lst[i] == len( lst[i:j] ) > l:
l = 1 + a[j] - a[i]
s = i
return lst[s:s+l]
精彩评论