Home > other >  Find consecutive missing numbers from list
Find consecutive missing numbers from list

Time:06-18

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]]

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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

  • Related