Reputation: 3
How can I find consecutive missing numbers from the list below:
get_user_input_list = [1,2,3,4,5,7,8,11,12,13,14,15,17,21]
missing_item_in_list = []
start = get_user_input_list[0]
stop = get_user_input_list[-1]
for i in range(start,stop+1):
if i not in get_user_input_list:
missing_item_in_list.append(i)
The ouput I currently get:
[6,9,10,16,18,19,20]
The ouput I would need :
[[6],[9,10],[16],[18,19,20]]
Upvotes: 0
Views: 265
Reputation: 11
Here is how I did it:
get_user_input_list = [1,2,3,4,5,7,8,11,12,13,14,15,17,21]
missing_item_in_list = []
for i in range(len(get_user_input_list)-1):
if (n := get_user_input_list[i]+1) not in get_user_input_list:
missing_item_in_list.append(list(range(n, get_user_input_list[i+1])))
print(missing_item_in_list)
Output
[[6], [9, 10], [16], [18, 19, 20]]
Upvotes: 1
Reputation: 26976
Here's a very straightforward solution:
lst = [1,2,3,4,5,7,8,11,12,13,14,15,17,21]
missing = []
for i, e in enumerate(lst[:-1]):
if (n := lst[i+1]) - e > 1:
missing.append(list(range(e+1, n)))
print(missing)
Output:
[[6], [9, 10], [16], [18, 19, 20]]
Note:
There's an implicit assumption here that the input list is sorted ascending
Upvotes: 4
Reputation: 1205
get_user_input_list = [1,2,3,4,5,7,8,11,12,13,14,15,17,21]
missing_item_in_list = []
start = get_user_input_list[0]
stop = get_user_input_list[-1]
temp = []
for i in range(start,stop+1):
if i not in get_user_input_list:
if not temp:
temp.append(i)
elif i-1 == temp[-1]:
temp.append(i)
continue
else:
missing_item_in_list.append(temp)
temp=[i]
#print(i)
#missing_item_in_list.append(i)
missing_item_in_list.append(temp)
print(missing_item_in_list)
edited your code to accommodate the change in one loop itself
Upvotes: 1
Reputation: 36
get_user_input_list = [1, 2, 3, 4, 5, 7, 8, 11, 12, 13, 14, 15, 17, 21]
missing_item_in_list = []
start = get_user_input_list[0]
stop = get_user_input_list[-1]
sublist = []
for i in range(start, stop+1):
if i not in get_user_input_list:
sublist.append(i)
else:
if len(sublist) > 0:
missing_item_in_list.append(sublist)
sublist = []
print(missing_item_in_list)
Upvotes: 0
Reputation: 54148
You need a temporary list that will hold the number if they are consecutives, save it in the main list when there is a break
tmp_list = []
for i in range(start, stop + 1):
if i not in get_user_input_list:
if not tmp_list or tmp_list[-1] + 1 == i:
tmp_list.append(i)
else:
missing_item_in_list.append(tmp_list)
tmp_list = [i]
if tmp_list:
missing_item_in_list.append(tmp_list)
Upvotes: 1