-2

Here is my list:

List = [[1,2,4,5], [1,2,3,4,5,7], [1,4,5,6], [2,3,5], [1,2,3]]

From this how to find all the smallest missing numbers?

Edit:

  • The "smallest missing number" is the first integer (> 0) that is not in the list.
  • The expected output for the example input is 3, 6, 2, 1 and 4.
  • The input lists are always sorted.
Falko
  • 17,076
  • 13
  • 60
  • 105
user458766
  • 35
  • 6

3 Answers3

2

An approach without any built-in functions:

Lists = [[1,2,4,5],[1,2,3,4,5,7],[1,4,5,6]]

for List in Lists:
    i = 1
    while i <= List[-1] + 1:
        if i in List:
            i += 1
        else:
            break
    print i

Basically it processes each List separately (is that what you want?). It iterates a counter i starting at 1 (assuming you look for integers > 0) and stops, as soon as List doesn't contain i.

Output:

3
6
2
Falko
  • 17,076
  • 13
  • 60
  • 105
1

If the sublists are already sorted like you input, just compare the previous to the current element, if the prev +1 is not equal to the current ele add prev + 1 to the output list:

List = [[1, 2, 4, 5], [1, 2, 3, 4, 5, 7], [1, 4, 5, 6]]
out = []
for sub in List:
    prev = sub[0]
    for  ele in sub[1:]:
        if prev + 1 != ele:
            out.append(prev +1)
            break
        prev = ele
print(out)
[3, 6, 2]

It will work for any sublists that are ordered not just lists starting with 1:

List = [[3, 4, 5,7], [10,13,14,15], [100,101,104,105]]

Output:

[6, 11, 102]

And without slicing:

out = []
for sub in List:
    prev = sub[0]
    i = 0
    for ele in sub:
        if i == 0:
            i += 1
            continue
        if prev + 1 != ele:
            out.append(prev +1)
            break
        prev = ele
print(out)

If you always want to find the first missing number starting at 1 and can have 0 or negative numbers, only check each ele and increase i if the ele is > 0:

out = []
for sub in Lists:
    i = 1
    for ele in sub:
        if ele > 0:
            if ele != i:
                out.append(i)
                break
            i += 1
print(out)

That means at worst you do a single pass over each sublist as opposed to O(n^2) approach using in

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

Inspired by this answer:

List = [[1,2,4,5],[1,2,3,4,5,7],[1,4,5,6]]
print [sorted(set(range(1,max(l)+2)).difference(l))[0] for l in List]

Output:

[3, 6, 2]

Sure, this approach uses built-in functions. But you can start from here and break it down by replacing forbidden functions by your own implementations.

Community
  • 1
  • 1
Falko
  • 17,076
  • 13
  • 60
  • 105