简体   繁体   中英

Find consecutive missing numbers from list

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM