Pick First And Last Int Value From And List And Continue The Sequence Till The End Of List
Input: l1 = [1,2,3,5,7,9,10,11,12,15] Expected output: l2 = [[1,3],[5],[7],[9,12],[15]] In l2, the first nested list is the sequence from 1 to 3, so the first and last values are
Solution 1:
You could use a library, intspan, to get results like what you want.
from intspan import intspan
l1 = [1,2,3,5,7,9,10,11,12,15]
M = []
for tpl in intspan(l1).ranges():
M.append(tpl)
print(M)
Prints:
[(1, 3), (5, 5), (7, 7), (9, 12), (15, 15)]
To get the same data structure as posted originally:
for a,b in intspan(l1).ranges():
if a != b:
M.append([a,b])
else:
M.append([a])
[[1, 3], [5], [7], [9, 12], [15]]
Solution 2:
Try this:
l=[]
cnt=0
a+=[-1] #added dummy value
for i in range(1,len(a)):
if a[i] == a[i-1]+1:
cnt+=1
else:
if cnt > 0 :
l.append([a[i-1]-cnt,a[i-1]])
else:
l.append([a[i-1]])
cnt=0
a=a[:-1] #remove the dummy value
Dummy value is added so that the iteration will loop through all the element of the original list
Solution 3:
This solution is not perfect but it works.
l1 = [1,2,3,5,7,9,10,11,12,15]
l2 = []
start_ind = Nonefor x inrange(len(l1)-1):
"""
Lets asign a start index from where to make the slice
"""if start_ind == None:
start_ind = x
"""
Check the two nearest numbers
"""ifabs(l1[x] - l1[x+1]) != 1:
"""
If the start index is the same as the end index:
add first and last values
Else:
Only add the first value
"""if start_ind != x:
l2.append([l1[start_ind], l1[x]])
else:
l2.append([l1[start_ind]])
start_ind = None"""
This is for the last value if it hasn't been added
"""if l1[-1] != l2[-1][-1]:
l2.append([l1[-1]])
print(l2)
Solution 4:
And another solution :-)
l1 = [1,2,3,5,7,9,10,11,12,15]
l2 = []
sequence = []
for i in range(1, len(l1)+1):
sequence.append(l1[i-1])
if i >= len(l1):
l2.append(sequence)
breakif l1[i-1] != l1[i] - 1:
l2.append(sequence)
sequence = []
print(l2)
Solution 5:
Your problem is the Gaps and Islands problem
.
l1 = [1, 2, 3, 5, 7, 9, 43, 44, 10, 11, 12, 1, 1, 7, 9, 42, 170, 170, 170]
l1.sort()
prev_elem = l1[0]
dense_rank = 1
curr_group = prev_elem - dense_rank
islands = [[prev_elem]]
for elem in l1[1:]:
if elem != prev_elem:
dense_rank += 1
group = elem - dense_rank
if group != curr_group:
if islands[-1][0] != prev_elem:
islands[-1].append(prev_elem)
islands.append([elem])
curr_group = group
prev_elem = elem
print(islands)
Output:
[[1, 3], [5], [7], [9, 12], [42, 44], [170]]
Post a Comment for "Pick First And Last Int Value From And List And Continue The Sequence Till The End Of List"